@craft-cross-cms/rich-text-core
v0.0.5
Published
TipTap-based rich text core for Craft Cross CMS (xcms)
Downloads
577
Readme
@craft-cross-cms/rich-text-core
TipTap-based rich text core for Craft Cross CMS. This library provides HTML to JSON conversion functionality for rich text content.
Getting Started
Installation
npm install @craft-cross-cms/rich-text-coreor
pnpm add @craft-cross-cms/rich-text-coreor
yarn add @craft-cross-cms/rich-text-coreUsage
Import path depends on your environment:
// Node.js (server-side)
import { generateJSON, buildTiptapExtensions } from '@craft-cross-cms/rich-text-core/server';
// Browser
import { generateJSON, buildTiptapExtensions } from '@craft-cross-cms/rich-text-core';The /server subpath uses happy-dom internally to provide the DOM environment that generateJSON / generateHTML require. No additional setup is needed.
const html = '<p>Hello <strong>World</strong>!</p>';
const json = generateJSON(html, buildTiptapExtensions({}));
console.log(json);
// Output:
// {
// type: 'doc',
// content: [
// {
// type: 'paragraph',
// content: [
// { type: 'text', text: 'Hello ' },
// { type: 'text', marks: [{ type: 'bold' }], text: 'World' },
// { type: 'text', text: '!' }
// ]
// }
// ]
// }Image Handling
When converting HTML to JSON, ensure that img tags include the following attributes:
Required Image Attributes
When creating HTML content that will be converted to JSON, set data-asset-id, src, alt, width, and height attributes on the img tag.
import { generateJSON, buildTiptapExtensions } from '@craft-cross-cms/rich-text-core';
// HTML with properly formatted image
const html = `
<img src="https://example.com/image.jpg"
alt="Image description"
width="800"
height="600"
data-asset-id="asset123">
`;
// Build extensions
const extensions = buildTiptapExtensions({});
// Convert HTML to JSON
const json = generateJSON(html, extensions);
// Generated JSON:
// {
// type: 'doc',
// content: [
// {
// type: 'cmsImage',
// attrs: {
// id: 'asset123',
// src: 'https://example.com/image.jpg',
// alt: 'Image description',
// width: 800,
// height: 600,
// },
// },
// ],
// }All five attributes (data-asset-id, src, alt, width, height) are required for proper JSON conversion.
Embed Elements
When using embed elements (e.g., embedded videos, external content), users cannot create the JSON content directly. Embed content must be created manually through the admin interface.
The embed element requires specific attributes that are generated by the admin interface:
{
type: 'embed',
attrs: {
type: 'embed',
url: 'https://example.com/embed-url',
embedHtml: '<iframe src="..."></iframe>', // Generated by admin interface
},
}Note: The
embedHtmlattribute contains the actual embed code and should only be created through the admin interface to ensure proper formatting and security.
