| import { removeElement } from 'domutils'; |
| import { |
| type AnyNode, |
| Document, |
| type ParentNode, |
| isDocument as checkIsDocument, |
| } from 'domhandler'; |
| import type { InternalOptions } from './options.js'; |
|
|
| |
| |
| |
| |
| |
| |
| export function getParse( |
| parser: ( |
| content: string, |
| options: InternalOptions, |
| isDocument: boolean, |
| context: ParentNode | null, |
| ) => Document, |
| ) { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| return function parse( |
| content: string | Document | AnyNode | AnyNode[] | Buffer, |
| options: InternalOptions, |
| isDocument: boolean, |
| context: ParentNode | null, |
| ): Document { |
| if (typeof Buffer !== 'undefined' && Buffer.isBuffer(content)) { |
| content = content.toString(); |
| } |
|
|
| if (typeof content === 'string') { |
| return parser(content, options, isDocument, context); |
| } |
|
|
| const doc = content as AnyNode | AnyNode[] | Document; |
|
|
| if (!Array.isArray(doc) && checkIsDocument(doc)) { |
| |
| return doc; |
| } |
|
|
| |
| const root = new Document([]); |
|
|
| |
| update(doc, root); |
|
|
| return root; |
| }; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| export function update( |
| newChilds: AnyNode[] | AnyNode, |
| parent: ParentNode | null, |
| ): ParentNode | null { |
| |
| const arr = Array.isArray(newChilds) ? newChilds : [newChilds]; |
|
|
| |
| if (parent) { |
| parent.children = arr; |
| } else { |
| parent = null; |
| } |
|
|
| |
| for (let i = 0; i < arr.length; i++) { |
| const node = arr[i]; |
|
|
| |
| if (node.parent && node.parent.children !== arr) { |
| removeElement(node); |
| } |
|
|
| if (parent) { |
| node.prev = arr[i - 1] || null; |
| node.next = arr[i + 1] || null; |
| } else { |
| node.prev = node.next = null; |
| } |
|
|
| node.parent = parent; |
| } |
|
|
| return parent; |
| } |
|
|