Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement enumerable for has_content module #7

Merged
merged 1 commit into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions lib/tip_tap/has_content.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

module TipTap
module HasContent
include Enumerable

attr_reader :attrs, :content

def self.included(base)
Expand All @@ -20,13 +22,23 @@ def initialize(content = [], **attributes)
yield self if block_given?
end

def find_node(node_type)
content.find { |child| child.is_a?(node_type) }
def each
content.each { |child| yield child }
end

def find_node(type_class_or_name)
node_type = type_class_or_name.is_a?(String) ? TipTap.node_for(type_class_or_name) : type_class_or_name
find { |child| child.is_a?(node_type) }
end

def add_content(node)
@content << node
end
alias_method :<<, :add_content

def size
content.size
end

module ClassMethods
# Create a new instance from a TipTap JSON object.
Expand Down
47 changes: 42 additions & 5 deletions spec/tip_tap/document_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,50 @@
end
end

describe "Enumerable" do
it "iterates over the content for #each" do
json = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Hello World!",
marks: [
{type: "bold"},
{type: "italic"}
]
}
]
}
]
}
document = TipTap::Document.from_json(json)
expect(document.map(&:class)).to eq([TipTap::Nodes::Paragraph])
end
end

describe "find_node" do
it "returns a node" do
document = TipTap::Document.from_json(json_contents)
node = document.find_node(TipTap::Nodes::Paragraph)
context "when passing a string" do
it "returns a node" do
document = TipTap::Document.from_json(json_contents)
node = document.find_node(TipTap::Nodes::Paragraph.type_name)

expect(node).to be_a(TipTap::Nodes::Paragraph)
expect(node.to_plain_text).to eq("Hello World!")
end
end

context "when passing a class" do
it "returns a node" do
document = TipTap::Document.from_json(json_contents)
node = document.find_node(TipTap::Nodes::Paragraph)

expect(node).to be_a(TipTap::Nodes::Paragraph)
expect(node.to_plain_text).to eq("Hello World!")
expect(node).to be_a(TipTap::Nodes::Paragraph)
expect(node.to_plain_text).to eq("Hello World!")
end
end
end

Expand Down