json-joy
Version:
Collection of libraries for building collaborative editing apps.
40 lines (39 loc) • 1.59 kB
JavaScript
import { SliceTypeName } from '../slice';
import { toText as _toHtml } from 'very-small-parser/lib/html/toText';
import { toHast as _toHast } from 'very-small-parser/lib/html/json-ml/toHast';
import { toBase64 } from '@jsonjoy.com/base64/lib/toBase64';
export const toJsonMl = (json) => {
if (typeof json === 'string')
return json;
const [tag, attr, ...children] = json;
const namedTag = tag === '' ? tag : SliceTypeName[tag];
const htmlTag = namedTag ?? (attr?.inline ? 'span' : 'div');
const htmlAttr = attr && attr.data !== void 0 ? { 'data-attr': JSON.stringify(attr.data) } : null;
const htmlNode = [htmlTag, htmlAttr];
const length = children.length;
for (let i = 0; i < length; i++)
htmlNode.push(toJsonMl(children[i]));
return htmlNode;
};
export const toHast = (json) => {
const jsonml = toJsonMl(json);
// console.log(jsonml);
const hast = _toHast(jsonml);
return hast;
};
export const toHtml = (json, tab, indent) => _toHtml(toHast(json), tab, indent);
const base64Str = (str) => toBase64(new TextEncoder().encode(str));
export const exportHtml = (view, node) => {
const data = { view };
const json = JSON.stringify(data);
const jsonBase64 = base64Str(json);
const html = toHtml(node) + '<b data-json-joy-peritext="' + jsonBase64 + '"/>';
return html;
};
export const exportStyle = (style) => {
const data = { style };
const json = JSON.stringify(data);
const jsonBase64 = base64Str(json);
const html = '<b data-json-joy-peritext="' + jsonBase64 + '"/>';
return html;
};