Skip to content

Commit

Permalink
Merge pull request #36 from contentstack/development
Browse files Browse the repository at this point in the history
add missing target attribute when parsing anchor tags and reducing bundle size
  • Loading branch information
Jayesh2812 committed Jan 10, 2024
2 parents ec4585d + 4a005ce commit 27cf70b
Show file tree
Hide file tree
Showing 10 changed files with 2,632 additions and 6,544 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2022-2023 Contentstack
Copyright (c) 2023-2024 Contentstack

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
8,868 changes: 2,350 additions & 6,518 deletions package-lock.json

Large diffs are not rendered by default.

31 changes: 23 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
{
"name": "@contentstack/json-rte-serializer",
"version": "2.0.5",
"version": "2.0.6",
"description": "This Package converts Html Document to Json and vice-versa.",
"main": "lib/index.js",
"module": "lib/index.mjs",
"types": "lib/index.d.ts",
"scripts": {
"test": "jest",
"prepare": "npm run build",
"build": "tsc"
"build:cjs": "esbuild src/index.tsx --bundle --outdir=lib --platform=node --minify",
"build:esm": "esbuild src/index.tsx --bundle --outdir=lib --format=esm --out-extension:.js=.mjs --minify",
"build": "npm run build:cjs && npm run build:esm && tsc --emitDeclarationOnly --outDir lib"
},
"repository": {
"type": "git",
Expand All @@ -24,11 +27,19 @@
},
"homepage": "https://github.com/contentstack/json-rte-serializer#readme",
"devDependencies": {
"@types/jest": "^26.0.23",
"@types/jest": "^27.0.3",
"@types/jsdom": "^16.2.12",
"@types/lodash": "^4.14.168",
"@types/lodash.clonedeep": "^4.5.9",
"@types/lodash.flatten": "^4.4.9",
"@types/lodash.isempty": "^4.4.9",
"@types/lodash.isequal": "^4.5.8",
"@types/lodash.isobject": "^3.0.9",
"@types/lodash.isplainobject": "^4.0.9",
"@types/lodash.isundefined": "^3.0.9",
"@types/lodash.kebabcase": "^4.1.9",
"@types/omit-deep-lodash": "^1.1.1",
"@types/uuid": "^8.3.0",
"esbuild": "0.19.11",
"jest": "^27.5.1",
"jest-html-reporter": "^3.7.0",
"jsdom": "^16.6.0",
Expand All @@ -38,10 +49,14 @@
},
"dependencies": {
"array-flat-polyfill": "^1.0.1",
"lodash": "^4.17.21",
"slate": "^0.72.0",
"slate-hyperscript": "^0.62.0",
"tslib": "^2.3.1",
"lodash.clonedeep": "^4.5.0",
"lodash.flatten": "^4.4.0",
"lodash.isempty": "^4.4.0",
"lodash.isequal": "^4.5.0",
"lodash.isobject": "^3.0.2",
"lodash.isplainobject": "^4.0.6",
"lodash.isundefined": "^3.0.1",
"lodash.kebabcase": "^4.1.1",
"uuid": "^8.3.2"
},
"files": [
Expand Down
30 changes: 20 additions & 10 deletions src/fromRedactor.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { jsx } from 'slate-hyperscript'
import { v4 } from 'uuid'
import kebabCase from "lodash/kebabCase"
import isEmpty from "lodash/isEmpty"
Expand All @@ -7,6 +6,8 @@ import isObject from "lodash/isObject"
import cloneDeep from "lodash/cloneDeep"
import isUndefined from "lodash/isUndefined"

import { jsx } from './utils/jsx'

import {IHtmlToJsonElementTags,IHtmlToJsonOptions, IHtmlToJsonTextTags, IAnyObject} from './types'

const generateId = () => v4().split('-').join('')
Expand All @@ -15,13 +16,22 @@ const isVoid = ['img', 'embed']


const ELEMENT_TAGS: IHtmlToJsonElementTags = {
A: (el: HTMLElement) => ({
type: 'a',
attrs: {
url:
el.getAttribute('href') ? el.getAttribute('href') : '#'
A: (el: HTMLElement) => {
const attrs: Record<string, string> = {}
const target = el.getAttribute('target');
const href = el.getAttribute('href');

attrs.url = href ? href : '#';

if(target && target !== '') {
attrs.target = target;
}
}),

return {
type: "a",
attrs: attrs,
};
},
BLOCKQUOTE: () => ({ type: 'blockquote', attrs: {} }),
H1: () => ({ type: 'h1', attrs: {} }),
H2: () => ({ type: 'h2', attrs: {} }),
Expand Down Expand Up @@ -225,20 +235,20 @@ export const fromRedactor = (el: any, options?:IHtmlToJsonOptions) : IAnyObject
const thead = el.querySelector('thead')

if (!tbody && !thead) {
el.innerHTML += "<tbody></tbody>"
el.append(el.ownerDocument.createElement('tbody'))
}
}
else if (['TBODY', 'THEAD'].includes(el.nodeName)) {
const row = el.querySelector('tr')
if (!row) {
el.innerHTML += "<tr></tr>"
el.append(el.ownerDocument.createElement('tr'))
}
}
else if (el.nodeName === 'TR') {
const cell = el.querySelector('th, td')
if (!cell) {
const cellType = el.parentElement.nodeName === 'THEAD' ? 'th' : 'td'
el.innerHTML += `<${cellType}></${cellType}>`
el.append(el.ownerDocument.createElement(cellType))

}
}
Expand Down
8 changes: 4 additions & 4 deletions src/toRedactor.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import kebbab from 'lodash/kebabCase'
import isEmpty from 'lodash/isEmpty'
import kebbab from 'lodash.kebabcase'
import isEmpty from 'lodash.isempty'

import {IJsonToHtmlElementTags, IJsonToHtmlOptions, IJsonToHtmlTextTags} from './types'
import { isPlainObject } from 'lodash'
import isPlainObject from 'lodash.isplainobject'

const ELEMENT_TYPES: IJsonToHtmlElementTags = {
'blockquote': (attrs: string, child: string) => {
Expand Down Expand Up @@ -229,7 +229,7 @@ export const toRedactor = (jsonValue: any,options?:IJsonToHtmlOptions) : string
text = `<span id=${jsonValue['id']}>${text}</span>`
}
}
if (jsonValue.text.includes('\n')) {
if (jsonValue.text.includes('\n') && !jsonValue['break']) {
text = text.replace(/\n/g, '<br/>')
}
Object.entries(jsonValue).forEach(([key, value]) => {
Expand Down
180 changes: 180 additions & 0 deletions src/utils/jsx.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import isPlainObject from "lodash.isplainobject";
import isEqual from "lodash.isequal";

const resolveDescendants = (children: any[]) => {
const nodes: any[] = [];

const addChild = (child: any): void => {
if (child == null) {
return;
}

const prev = nodes[nodes.length - 1];

if (typeof child === "string") {
const text = { text: child };
STRINGS.add(text);
child = text;
}

if (isText(child)) {
const c = child; // HACK: fix typescript complaining

if (
isText(prev) &&
STRINGS.has(prev) &&
STRINGS.has(c) &&
textEquals(prev, c, { loose: true })
) {
prev.text += c.text;
} else {
nodes.push(c);
}
} else if (isElement(child)) {
nodes.push(child);
} else {
throw new Error(`Unexpected hyperscript child object: ${child}`);
}
};

for (const child of children.flat(Infinity)) {
addChild(child);
}

return nodes;
};

/**
* Create an `Element` object.
*/

export function createElement(
tagName: string,
attributes: { [key: string]: any },
children: any[]
) {
return { ...attributes, children: resolveDescendants(children) };
}

/**
* Create a fragment.
*/

export function createFragment(
tagName: string,
attributes: { [key: string]: any },
children: any[]
) {
return resolveDescendants(children);
}

/**
* Create a `Text` object.
*/

export function createText(
tagName: string,
attributes: { [key: string]: any },
children: any[]
) {
const nodes = resolveDescendants(children);

if (nodes.length > 1) {
throw new Error(
`The <text> hyperscript tag must only contain a single node's worth of children.`
);
}

let [node] = nodes;

if (node == null) {
node = { text: "" };
}

if (!isText(node)) {
throw new Error(`
The <text> hyperscript tag can only contain text content as children.`);
}

// COMPAT: If they used the <text> tag we want to guarantee that it won't be
// merge with other string children.
STRINGS.delete(node);

Object.assign(node, attributes);
return node;
}

const STRINGS = new WeakSet();

function isText(value: any) {
return isPlainObject(value) && typeof value.text === "string";
}

function textEquals(
text: any,
another: any,
options: { loose?: boolean } = {}
): boolean {
const { loose = false } = options;

function omitText(obj: Record<any, any>) {
const { text, ...rest } = obj;

return rest;
}

return isEqual(
loose ? omitText(text) : text,
loose ? omitText(another) : another
);
}

const isElement = (value: any): boolean => {
return (
isPlainObject(value) &&
isNodeList(value.children)
// && !Editor.isEditor(value) // value cannot be editor
)
};

export const jsx = (
tagName: string,
attributes?: Object,
...children: any[]
) => {
const creators = {
element: createElement,
fragment: createFragment,
text: createText,
};
const creator = creators[tagName];

if (!creator) {
throw new Error(`No hyperscript creator found for tag: <${tagName}>`);
}

if (attributes == null) {
attributes = {};
}

if (!isPlainObject(attributes)) {
children = [attributes].concat(children);
attributes = {};
}

children = children.filter((child) => Boolean(child)).flat();
const ret = creator(tagName, attributes, children);
return ret;
};


function isNodeList (value: any[]) {
return value.every(val => isNode(val))
}

function isNode(value: any){
return (
isText(value) || isElement(value)
// || Editor.isEditor(value) // // value cannot be editor
)
}
Loading

0 comments on commit 27cf70b

Please sign in to comment.