Some checks failed
Verify / Install node dependencies (push) Failing after 2s
Verify / Build packages (push) Has been skipped
Verify / Check linting & formatting (push) Has been skipped
Verify / Run unit tests (push) Has been skipped
Verify / Run e2e tests (shard 1/4) (push) Has been skipped
Verify / Run e2e tests (shard 2/4) (push) Has been skipped
Verify / Run e2e tests (shard 3/4) (push) Has been skipped
Verify / Run e2e tests (shard 4/4) (push) Has been skipped
Publish / Resolve publish config (push) Failing after 2s
Publish / Send notification to Slack (push) Has been skipped
Publish / Send failure notification to Slack (push) Failing after 8s
Verify / Merge e2e reports (push) Has been skipped
Publish / Build (push) Has been skipped
Publish / Bump Versions OR Release to Registry (push) Has been skipped
40 lines
1.5 KiB
TypeScript
40 lines
1.5 KiB
TypeScript
import type { Extensions } from '@tiptap/core'
|
|
import { getSchema } from '@tiptap/core'
|
|
import type { ParseOptions } from '@tiptap/pm/model'
|
|
import { DOMParser } from '@tiptap/pm/model'
|
|
|
|
/**
|
|
* Generates a JSON object from the given HTML string and converts it into a Prosemirror node with content.
|
|
* @param {string} html - The HTML string to be converted into a Prosemirror node.
|
|
* @param {Extensions} extensions - The extensions to be used for generating the schema.
|
|
* @param {ParseOptions} options - The options to be supplied to the parser.
|
|
* @returns {Record<string, any>} - The generated JSON object.
|
|
* @example
|
|
* const html = '<p>Hello, world!</p>'
|
|
* const extensions = [...]
|
|
* const json = generateJSON(html, extensions)
|
|
* console.log(json) // { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Hello, world!' }] }] }
|
|
*/
|
|
export function generateJSON(
|
|
html: string,
|
|
extensions: Extensions,
|
|
options?: ParseOptions,
|
|
): Record<string, any> {
|
|
if (typeof window === 'undefined') {
|
|
throw new Error(
|
|
'generateJSON can only be used in a browser environment\nIf you want to use this in a Node environment, use the `@tiptap/html/server` import instead.',
|
|
)
|
|
}
|
|
|
|
const schema = getSchema(extensions)
|
|
const doc: Document = new window.DOMParser().parseFromString(html, 'text/html')
|
|
|
|
if (!doc) {
|
|
throw new Error('Failed to parse HTML string')
|
|
}
|
|
|
|
return DOMParser.fromSchema(schema)
|
|
.parse(doc.body as Node, options)
|
|
.toJSON()
|
|
}
|