Skip to content

Commit

Permalink
refactor: add addChildToList helper
Browse files Browse the repository at this point in the history
  • Loading branch information
nperez0111 committed Jan 16, 2025
1 parent 4a3287e commit a04c308
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 10 deletions.
11 changes: 1 addition & 10 deletions src/mappings/blockToNode.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
import { addChild, createNode, createText, type NodeType } from "../utils";
import { addChild, createNode, createText, isListNode } from "../utils";
import type { MapBlockToNodeFn } from "../types";
import type { NodeMapping } from "..";

function isListNode(
node: NodeType | null | undefined
): node is NodeMapping["bulletList"] | NodeMapping["orderedList"] {
return Boolean(
node && (node.type === "bulletList" || node.type === "orderedList")
);
}

/**
* Lists are represented as a tree structure in ProseMirror.
Expand Down
63 changes: 63 additions & 0 deletions src/utils/pm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,3 +263,66 @@ export function isNode(node: unknown): node is NodeType {
node.type !== "text"
);
}

/**
* Check if a node is a list node.
*/
export function isListNode(
node: NodeType | null | undefined
): node is NodeMapping["bulletList"] | NodeMapping["orderedList"] {
return Boolean(
node && (node.type === "bulletList" || node.type === "orderedList")
);
}

/**
* Adds a child to a list node, keeping the list structure intact.
*/
export function addChildToList<TNodeType extends keyof NodeMapping>(
/**
* The list to add the child to
*/
parent: NodeMapping[TNodeType],
/**
* The child to add to the list
*/
child: NodeType,
/**
* If true, append the child to the last list item in the list, if it exists
* If false, add the child as a new list item
* @default false
*/
append = true
) {
// If the parent is not a list node, add the child directly
if (!isListNode(parent)) {
addChild(parent, child);
return;
}

// If already adding a list item, add the child to the list item directly
if (child.type === "listItem") {
addChild(parent, child);
return;
}

// If the child is a list, add it to the list within it's own list item
if (child.type === "orderedList" || child.type === "bulletList") {
if (append && parent.content) {
const lastChild = parent.content[parent.content.length - 1];
if (lastChild) {
addChild(lastChild, child);
return;
}
}
}

if (child.type === "paragraph" && (child.content || []).length === 0) {
// Ignore empty paragraphs
return;
}

// Wrap the child in a list item
child = addChild(createNode("listItem"), child);
addChild(parent, child);
}

0 comments on commit a04c308

Please sign in to comment.