Skip to main content

Node

Struct Node 

Source
pub struct Node {
    pub node_type: Option<String>,
    pub attrs: Option<Map<String, Value>>,
    pub content: Option<Vec<Node>>,
    pub marks: Option<Vec<Mark>>,
    pub text: Option<String>,
    pub extra: Map<String, Value>,
}
Expand description

A single Tiptap/ProseMirror node.

All structural fields are optional to faithfully distinguish “missing” from “empty” on roundtrip. Unknown top-level keys land in Node::extra.

Fields§

§node_type: Option<String>

Node type, e.g. "doc", "paragraph", "text".

§attrs: Option<Map<String, Value>>

Node attributes.

§content: Option<Vec<Node>>

Child nodes.

§marks: Option<Vec<Mark>>

Marks applied to this node (typically text nodes).

§text: Option<String>

Text payload (text nodes only).

§extra: Map<String, Value>

Any unknown/extra top-level fields, preserved verbatim.

Implementations§

Source§

impl Node

Source

pub fn set_block_type( &mut self, path: &[usize], new_type: impl Into<String>, attrs: Option<Map<String, Value>>, ) -> Result<(), BlockError>

Change the type (and attrs) of the block at path in place, keeping its content — unlike a wholesale Change::Replace. attrs = None clears attrs. The root (&[]) may be retyped.

Source

pub fn split_block( &mut self, path: &[usize], at: usize, depth: usize, ) -> Result<(), BlockError>

Split the block at path at child-boundary index at into two siblings: the left keeps children [..at], a new right sibling takes [at..] (same type/attrs/marks/extra). depth also splits that many ancestors (ProseMirror-style), clamped at the root.

Source

pub fn split_block_at( &mut self, path: &[usize], pos: Position, depth: usize, ) -> Result<(), BlockError>

Split the block at path at an inline Position (materializing a mid-text boundary first), then split like Node::split_block.

Source

pub fn join_blocks( &mut self, parent: &[usize], index: usize, ) -> Result<(), BlockError>

Merge the block at parent[index] into its previous sibling parent[index-1] (appending its content, re-merging inline text at the seam). The previous sibling’s type/attrs win on a mismatch.

Source

pub fn wrap( &mut self, path: &[usize], wrapper_type: impl Into<String>, attrs: Option<Map<String, Value>>, ) -> Result<(), BlockError>

Wrap the single block at path in a new parent of wrapper_type.

Source

pub fn wrap_range( &mut self, range: &BlockRange, wrapper_type: impl Into<String>, attrs: Option<Map<String, Value>>, ) -> Result<(), BlockError>

Wrap a contiguous run of sibling blocks (one level) in a new parent of wrapper_type. Nested structures (e.g. bulletList > listItem) are composed by the caller.

Source

pub fn lift(&mut self, path: &[usize]) -> Result<(), BlockError>

Lift the block at path out of its parent into its grandparent, splitting the parent around it so preceding/following siblings are kept (a sole-child parent simply collapses to the lifted node).

Source§

impl Node

Source

pub fn element(node_type: impl Into<String>) -> Node

Start an element node of node_type (no content/marks/attrs yet).

use tiptap_rusty_parser::Node;
let p = Node::element("paragraph")
    .with_attr("textAlign", "center")
    .with_text("hello");
assert_eq!(p.child_count(), 1);
Source

pub fn text(text: impl Into<String>) -> Node

A text node with the given string.

Source

pub fn text_with_marks( text: impl Into<String>, marks: impl IntoIterator<Item = Mark>, ) -> Node

A text node with text and the given marks.

Source

pub fn with_attr(self, key: impl Into<String>, value: impl Into<Value>) -> Self

Builder: set one attr (consuming).

Source

pub fn with_child(self, node: Node) -> Self

Builder: add a child (consuming).

Source

pub fn with_children(self, nodes: impl IntoIterator<Item = Node>) -> Self

Builder: add several children (consuming).

Source

pub fn with_text(self, text: impl Into<String>) -> Self

Builder: add a text child (consuming).

Source

pub fn with_mark(self, mark: Mark) -> Self

Builder: add a mark (consuming).

Source§

impl Node

Source

pub fn diff(&self, other: &Node) -> Vec<Change>

Structural diff from self to other: a Change list that, when applied to a clone of self, reproduces other.

Source

pub fn apply(&mut self, changes: &[Change]) -> Result<(), ApplyError>

Apply changes to self in order. See apply.

Source

pub fn invert(&self, changes: &[Change]) -> Result<Vec<Change>, ApplyError>

Invert changes relative to self (the pre-image). See invert.

Source§

impl Node

Source

pub fn to_html(&self) -> String

Render this node (and its subtree) to an HTML string with default options.

Source

pub fn to_html_with(&self, opts: &HtmlOptions) -> String

Render to HTML with custom HtmlOptions.

Source§

impl Node

Source

pub fn has_mark(&self, mark_type: &str) -> bool

True if a mark of mark_type is present.

Source

pub fn get_mark(&self, mark_type: &str) -> Option<&Mark>

Reference to the first mark of mark_type.

Source

pub fn add_mark(&mut self, mark: Mark) -> bool

Add mark if no mark of that type exists yet. Returns true if added.

Source

pub fn remove_mark(&mut self, mark_type: &str) -> usize

Remove every mark of mark_type. Returns count removed.

Source

pub fn toggle_mark(&mut self, mark: Mark) -> bool

Toggle a mark: remove if present, else add. Returns true if now present.

Source

pub fn set_mark_attr( &mut self, mark_type: &str, key: impl Into<String>, value: impl Into<Value>, ) -> bool

Set an attr on the (first) mark of mark_type. Returns false if absent.

Source

pub fn clear_marks(&mut self)

Drop all marks.

Source

pub fn attr(&self, key: &str) -> Option<&Value>

Reference to attr key.

Source

pub fn attrs_mut(&mut self) -> &mut Map<String, Value>

Mutable access to the attrs map, creating it if absent.

Source

pub fn set_attr( &mut self, key: impl Into<String>, value: impl Into<Value>, ) -> Option<Value>

Set attr key, returning the previous value if any.

Source

pub fn remove_attr(&mut self, key: &str) -> Option<Value>

Remove attr key, returning its value if present.

Source

pub fn child_count(&self) -> usize

Number of direct children.

Source

pub fn children(&self) -> &[Node]

Direct children slice (empty if none).

Source

pub fn children_mut(&mut self) -> &mut Vec<Node>

Mutable access to children, creating the vec if absent.

Source

pub fn child(&self, i: usize) -> Option<&Node>

Direct child at i.

Source

pub fn child_mut(&mut self, i: usize) -> Option<&mut Node>

Mutable direct child at i.

Source

pub fn push_child(&mut self, node: Node)

Append a child.

Source

pub fn insert_child(&mut self, i: usize, node: Node)

Insert a child at i (clamped to len).

Source

pub fn remove_child(&mut self, i: usize) -> Option<Node>

Remove and return the child at i.

Source

pub fn replace_child(&mut self, i: usize, node: Node) -> Option<Node>

Replace the child at i, returning the old node.

Source

pub fn clear_children(&mut self)

Remove all children.

Source

pub fn retain_children(&mut self, pred: impl FnMut(&Node) -> bool)

Retain only children matching pred.

Source

pub fn get_text(&self) -> Option<&str>

Text payload, if any.

Source

pub fn set_text(&mut self, text: impl Into<String>)

Set text payload.

Source

pub fn replace_all( &mut self, pred: impl FnMut(&Node) -> bool, f: impl FnMut(&mut Node), ) -> usize

Apply f to every node (incl. self) matching pred. Returns count.

Source§

impl Node

Source

pub fn normalize(&mut self)

Normalize this subtree in place with default NormalizeOptions.

Source

pub fn normalize_with(&mut self, opts: &NormalizeOptions)

Normalize this subtree in place with custom NormalizeOptions.

Source§

impl Node

Source

pub fn node_at(&self, path: &[usize]) -> Option<&Node>

Node at path (relative to self), or None if any index is missing.

use tiptap_rusty_parser::Document;
let doc = Document::from_json_str(
    r#"{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"hi"}]}]}"#,
).unwrap();
assert_eq!(doc.node_at(&[0, 0]).unwrap().get_text(), Some("hi"));
assert!(doc.node_at(&[5]).is_none());
Source

pub fn node_at_mut(&mut self, path: &[usize]) -> Option<&mut Node>

Mutable variant of Node::node_at.

Source

pub fn path_to(&self, pred: impl FnMut(&Node) -> bool) -> Option<Vec<usize>>

Path to the first node (incl. self) matching pred, pre-order.

Returns Some(vec![]) when self matches.

use tiptap_rusty_parser::Document;
let doc = Document::from_json_str(
    r#"{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"hi"}]}]}"#,
).unwrap();
let p = doc.path_to(|n| n.node_type.as_deref() == Some("text")).unwrap();
assert_eq!(p, vec![0, 0]);
assert_eq!(doc.node_at(&p).unwrap().get_text(), Some("hi"));
Source

pub fn paths_to(&self, pred: impl FnMut(&Node) -> bool) -> Vec<Vec<usize>>

Paths to every node (incl. self) matching pred, pre-order.

Source§

impl Node

Source

pub fn walk(&self, f: &mut impl FnMut(&Node))

Visit self and every descendant, pre-order.

use tiptap_rusty_parser::Document;
let doc = Document::from_json_str(r#"{"type":"doc","content":[{"type":"paragraph"}]}"#).unwrap();
let mut n = 0;
doc.root().walk(&mut |_| n += 1);
assert_eq!(n, 2);
Source

pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Node))

Mutable pre-order visit of self and every descendant.

Source

pub fn find(&self, pred: impl FnMut(&Node) -> bool) -> Option<&Node>

First node (incl. self) matching pred, pre-order.

Source

pub fn find_mut(&mut self, pred: impl FnMut(&Node) -> bool) -> Option<&mut Node>

Mutable variant of Node::find.

Source

pub fn find_all(&self, pred: impl FnMut(&Node) -> bool) -> Vec<&Node>

All nodes (incl. self) matching pred, pre-order.

Source

pub fn find_all_mut( &mut self, pred: &mut impl FnMut(&Node) -> bool, ) -> Vec<&mut Node>

Mutable variant of Node::find_all. Collects matching &mut Node.

Source

pub fn descendants(&self) -> Descendants<'_>

Lazy pre-order iterator over self and all descendants.

Source§

impl Node

Source

pub fn insert_text( &mut self, pos: Position, text: &str, marks: Option<&[Mark]>, ) -> Result<(), RangeError>

Insert text (with optional marks) at pos in this block’s inline content, splitting the target text node if needed and merging with adjacent equal-mark text afterwards.

Source

pub fn delete_range(&mut self, range: Range) -> Result<(), RangeError>

Delete everything in range, splitting text nodes at the boundaries and removing fully-covered inline nodes. A collapsed range is a no-op.

Source

pub fn replace_range( &mut self, range: Range, text: &str, marks: Option<&[Mark]>, ) -> Result<(), RangeError>

Replace range with text (carrying optional marks).

Source

pub fn add_mark_range( &mut self, range: Range, mark: Mark, ) -> Result<(), RangeError>

Add mark to every text node covered by range (splitting at the boundaries first), then re-merge equal-mark neighbours.

Source

pub fn remove_mark_range( &mut self, range: Range, mark_type: &str, ) -> Result<(), RangeError>

Remove every mark of mark_type from text nodes covered by range.

Source

pub fn toggle_mark_range( &mut self, range: Range, mark: Mark, ) -> Result<(), RangeError>

Toggle mark over range: if every covered text node already has a mark of that type, remove it from all; otherwise add it to all. Mirrors the ProseMirror toggle semantics, range-scoped.

Source§

impl Node

Source

pub fn validate(&self, schema: &Schema) -> Vec<Violation>

Validate against schema, collecting every Violation. An empty result means the document is valid.

use tiptap_rusty_parser::{Document, Schema, NodeSpec};
let schema = Schema::new()
    .node("doc", NodeSpec::new().content(["paragraph"]))
    .node("paragraph", NodeSpec::new())
    .node("heading", NodeSpec::new());
let doc = Document::from_json_str(
    r#"{"type":"doc","content":[{"type":"heading"}]}"#,
).unwrap();
let v = doc.validate(&schema);
assert_eq!(v.len(), 1); // heading is a known type, but not allowed as a child of doc
Source

pub fn is_valid(&self, schema: &Schema) -> bool

True if the document has no schema violations.

use tiptap_rusty_parser::{Document, Schema, NodeSpec};
let schema = Schema::new().node("doc", NodeSpec::new());
let doc = Document::from_json_str(r#"{"type":"doc"}"#).unwrap();
assert!(doc.is_valid(&schema));
Source§

impl Node

Source

pub fn by_type(&self, node_type: &str) -> Vec<&Node>

All descendants (incl. self) whose type equals node_type.

use tiptap_rusty_parser::Document;
let doc = Document::from_json_str(
    r#"{"type":"doc","content":[{"type":"paragraph"},{"type":"paragraph"}]}"#,
).unwrap();
assert_eq!(doc.by_type("paragraph").len(), 2);
Source

pub fn first_by_type(&self, node_type: &str) -> Option<&Node>

First descendant (incl. self) whose type equals node_type, pre-order.

Source

pub fn by_type_mut(&mut self, node_type: &str) -> Vec<&mut Node>

Mutable variant of Node::by_type.

Source

pub fn by_mark(&self, mark_type: &str) -> Vec<&Node>

All descendants (incl. self) carrying a mark of mark_type.

use tiptap_rusty_parser::Document;
let doc = Document::from_json_str(
    r#"{"type":"doc","content":[{"type":"text","text":"a","marks":[{"type":"bold"}]}]}"#,
).unwrap();
assert_eq!(doc.by_mark("bold").len(), 1);
Source

pub fn by_attr(&self, key: &str, value: impl Into<Value>) -> Vec<&Node>

All descendants (incl. self) whose attribute key equals value.

use tiptap_rusty_parser::Document;
let doc = Document::from_json_str(
    r#"{"type":"doc","content":[{"type":"heading","attrs":{"level":1}}]}"#,
).unwrap();
assert_eq!(doc.by_attr("level", 1).len(), 1);
Source§

impl Node

Source

pub fn text_content(&self) -> String

Concatenate all descendant text, with no separators.

Matches ProseMirror’s node.textContent.

use tiptap_rusty_parser::Document;
let doc = Document::from_json_str(
    r#"{"type":"doc","content":[
        {"type":"paragraph","content":[{"type":"text","text":"Hello "},{"type":"text","text":"world"}]}
    ]}"#,
).unwrap();
assert_eq!(doc.text_content(), "Hello world");
Source

pub fn text_content_with_separator(&self, sep: &str) -> String

Concatenate descendant text, inserting sep between adjacent block-level siblings (a node is “block-level” if it has content and is not a text node). Text within a block stays contiguous.

use tiptap_rusty_parser::Document;
let doc = Document::from_json_str(
    r#"{"type":"doc","content":[
        {"type":"paragraph","content":[{"type":"text","text":"Hello"}]},
        {"type":"paragraph","content":[{"type":"text","text":"world"}]}
    ]}"#,
).unwrap();
assert_eq!(doc.text_content_with_separator("\n\n"), "Hello\n\nworld");
Source

pub fn char_count(&self) -> usize

Total number of Unicode scalar values across all descendant text.

Source

pub fn word_count(&self) -> usize

Number of words across all text, via Unicode word segmentation.

Blocks are separated by a space first, so words don’t merge across block boundaries. Correct for CJK and other complex scripts.

use tiptap_rusty_parser::Document;
let doc = Document::from_json_str(
    r#"{"type":"doc","content":[
        {"type":"paragraph","content":[{"type":"text","text":"Hello"}]},
        {"type":"paragraph","content":[{"type":"text","text":"brave world"}]}
    ]}"#,
).unwrap();
assert_eq!(doc.word_count(), 3);
Source§

impl Node

Source

pub fn transform(&mut self) -> Transform<'_>

Begin a Transform over this tree.

Trait Implementations§

Source§

impl Clone for Node

Source§

fn clone(&self) -> Node

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Node

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Node

Source§

fn default() -> Node

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Node

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<Node> for Document

Source§

fn from(root: Node) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for Node

Source§

fn eq(&self, other: &Node) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Node

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Node

Auto Trait Implementations§

§

impl Freeze for Node

§

impl RefUnwindSafe for Node

§

impl Send for Node

§

impl Sync for Node

§

impl Unpin for Node

§

impl UnsafeUnpin for Node

§

impl UnwindSafe for Node

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,