diff --git a/packages/kg-default-transforms/.eslintrc.js b/packages/kg-default-transforms/.eslintrc.js new file mode 100644 index 000000000..eb6d40613 --- /dev/null +++ b/packages/kg-default-transforms/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + parser: '@typescript-eslint/parser', + plugins: ['ghost'], + extends: [ + 'plugin:ghost/ts' + ] +}; diff --git a/packages/kg-default-transforms/.gitignore b/packages/kg-default-transforms/.gitignore new file mode 100644 index 000000000..61b05babc --- /dev/null +++ b/packages/kg-default-transforms/.gitignore @@ -0,0 +1,2 @@ +build +tsconfig.tsbuildinfo diff --git a/packages/kg-default-transforms/LICENSE b/packages/kg-default-transforms/LICENSE new file mode 100644 index 000000000..fc33a5ece --- /dev/null +++ b/packages/kg-default-transforms/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013-2023 Ghost Foundation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/kg-default-transforms/README.md b/packages/kg-default-transforms/README.md new file mode 100644 index 000000000..f95cd41e5 --- /dev/null +++ b/packages/kg-default-transforms/README.md @@ -0,0 +1,35 @@ +# Koenig Default Transforms + +Default Lexical Node transforms used across our Koenig packages + +## Install + +`npm install @tryghost/kg-default-transforms --save` + +or + +`yarn add @tryghost/kg-default-transforms` + +## Usage + + +## Develop + +This is a monorepo package. + +Follow the instructions for the top-level repo. +1. `git clone` this repo & `cd` into it as usual +2. Run `yarn` to install top-level dependencies. + + + +## Test + +- `yarn lint` run just eslint +- `yarn test` run lint and tests + + + +# Copyright & License + +Copyright (c) 2013-2023 Ghost Foundation - Released under the [MIT license](LICENSE). \ No newline at end of file diff --git a/packages/kg-default-transforms/package.json b/packages/kg-default-transforms/package.json new file mode 100644 index 000000000..1011e4dd8 --- /dev/null +++ b/packages/kg-default-transforms/package.json @@ -0,0 +1,40 @@ +{ + "name": "@tryghost/kg-default-transforms", + "type": "module", + "version": "0.0.0", + "repository": "https://github.com/TryGhost/Koenig/tree/main/packages/kg-default-transforms", + "author": "Ghost Foundation", + "license": "MIT", + "main": "build/index.js", + "types": "build/index.d.ts", + "scripts": { + "dev": "tsc --watch --preserveWatchOutput --sourceMap", + "build": "tsc", + "prepare": "tsc", + "test:unit": "NODE_ENV=testing c8 --src src --all --check-coverage --100 --reporter text --reporter cobertura mocha -r ts-node/register './test/**/*.test.ts'", + "test": "yarn test:types && yarn test:unit", + "test:types": "tsc --noEmit", + "lint:code": "eslint src/ --ext .ts --cache", + "lint": "yarn lint:code && yarn lint:test", + "lint:test": "eslint -c test/.eslintrc.js test/ --ext .ts --cache" + }, + "files": [ + "build" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "c8": "8.0.1", + "mocha": "10.2.0", + "sinon": "16.1.0", + "ts-node": "10.9.1", + "typescript": "5.2.2" + }, + "dependencies": { + "@lexical/rich-text": "^0.12.2", + "@lexical/utils": "^0.12.2", + "@tryghost/kg-default-nodes": "^0.2.3", + "lexical": "^0.12.2" + } +} diff --git a/packages/kg-default-transforms/src/decs.d.ts b/packages/kg-default-transforms/src/decs.d.ts new file mode 100644 index 000000000..804da2ff4 --- /dev/null +++ b/packages/kg-default-transforms/src/decs.d.ts @@ -0,0 +1 @@ +declare module '@tryghost/kg-default-nodes'; diff --git a/packages/kg-default-transforms/src/default-transforms.ts b/packages/kg-default-transforms/src/default-transforms.ts new file mode 100644 index 000000000..69ab842a0 --- /dev/null +++ b/packages/kg-default-transforms/src/default-transforms.ts @@ -0,0 +1,26 @@ +import {LexicalEditor} from 'lexical/LexicalEditor.js'; +import {registerDenestTransform} from './transforms/denest.js'; +import {registerRemoveAlignmentTransform} from './transforms/remove-alignment.js'; +import {mergeRegister} from '@lexical/utils/index.js'; +import {$createParagraphNode, ParagraphNode} from 'lexical/index.js'; +import {$createHeadingNode, $createQuoteNode, HeadingNode, QuoteNode} from '@lexical/rich-text/index.js'; +import {ExtendedHeadingNode} from '@tryghost/kg-default-nodes'; + +export * from './transforms/denest.js'; +export * from './transforms/remove-alignment.js'; + +export function registerDefaultTransforms(editor: LexicalEditor) { + return mergeRegister( + // strip unwanted alignment formats + registerRemoveAlignmentTransform(editor, ParagraphNode), + registerRemoveAlignmentTransform(editor, HeadingNode), + registerRemoveAlignmentTransform(editor, ExtendedHeadingNode), + registerRemoveAlignmentTransform(editor, QuoteNode), + + // fix invalid nesting of nodes + registerDenestTransform(editor, ParagraphNode, () => ($createParagraphNode())), + registerDenestTransform(editor, HeadingNode, node => ($createHeadingNode(node.getTag()))), + registerDenestTransform(editor, ExtendedHeadingNode, node => ($createHeadingNode(node.getTag()))), + registerDenestTransform(editor, QuoteNode, () => ($createQuoteNode())) + ); +} diff --git a/packages/kg-default-transforms/src/index.ts b/packages/kg-default-transforms/src/index.ts new file mode 100644 index 000000000..3a969cf8d --- /dev/null +++ b/packages/kg-default-transforms/src/index.ts @@ -0,0 +1 @@ +export * from './default-transforms.js'; diff --git a/packages/kg-default-transforms/src/transforms/denest.ts b/packages/kg-default-transforms/src/transforms/denest.ts new file mode 100644 index 000000000..fef0d9610 --- /dev/null +++ b/packages/kg-default-transforms/src/transforms/denest.ts @@ -0,0 +1,67 @@ +import {ElementNode, $createParagraphNode, LexicalEditor, LexicalNode, Klass} from 'lexical'; + +export type CreateNodeFn = (originalNode: T) => T; + +export function denestTransform(node: T, createNode: CreateNodeFn) { + const children = node.getChildren(); + + const hasInvalidChild = children.some((child: LexicalNode) => { + return child.isInline && !child.isInline(); + }); + + if (!hasInvalidChild) { + return; + } + + // we need a temporary detached node to hold any moved nodes otherwise + // we can trigger an infinite loop with the transform continually + // re-running on each child move + const tempParagraph = $createParagraphNode(); + + // we need a new node of the current node type to collect inline + // children so we can maintain order when moving the non-inline children + // out. Will be appended and replaced with a new node each time we + // find a non-inline child + let currentElementNode = createNode(node); + + // pull out any non-inline children as we don't support nested element nodes + children.forEach((child: LexicalNode) => { + if (child.isInline && !child.isInline()) { + if (currentElementNode.getChildrenSize() > 0) { + tempParagraph.append(currentElementNode); + currentElementNode = createNode(node); + } + tempParagraph.append(child); + } else { + currentElementNode.append(child); + } + }); + + // append any remaining text nodes + if (currentElementNode.getChildrenSize() > 0) { + tempParagraph.append(currentElementNode); + } + + // reverse because we can only insertAfter the current paragraph + // so we need to insert the first child last to maintain order + tempParagraph.getChildren().reverse().forEach((child) => { + node.insertAfter(child); + }); + + // remove the original paragraph + node.remove(); + + // clean up the temporary paragraph immediately, although it should be + // cleaned up by the reconciler's garbage collection of detached nodes + tempParagraph.remove(); +} + +export function registerDenestTransform(editor: LexicalEditor, klass: Klass, createNode: CreateNodeFn): () => void { + if (editor.hasNodes([klass])) { + return editor.registerNodeTransform(klass, (node) => { + denestTransform(node, createNode); + }); + } + + return () => {}; +} diff --git a/packages/kg-default-transforms/src/transforms/remove-alignment.ts b/packages/kg-default-transforms/src/transforms/remove-alignment.ts new file mode 100644 index 000000000..d94e482c2 --- /dev/null +++ b/packages/kg-default-transforms/src/transforms/remove-alignment.ts @@ -0,0 +1,16 @@ +import {ElementNode, Klass, LexicalEditor} from 'lexical'; + +export function removeAlignmentTransform(node: ElementNode) { + // on element nodes format===text-align in Lexical + if (node.getFormatType() !== '') { + node.setFormat(''); + } +} + +export function registerRemoveAlignmentTransform(editor: LexicalEditor, klass: Klass) { + if (editor.hasNodes([klass])) { + return editor.registerNodeTransform(klass, removeAlignmentTransform); + } + + return () => {}; +} diff --git a/packages/kg-default-transforms/test/.eslintrc.js b/packages/kg-default-transforms/test/.eslintrc.js new file mode 100644 index 000000000..6fe6dc150 --- /dev/null +++ b/packages/kg-default-transforms/test/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + parser: '@typescript-eslint/parser', + plugins: ['ghost'], + extends: [ + 'plugin:ghost/test' + ] +}; diff --git a/packages/kg-default-transforms/test/hello.test.ts b/packages/kg-default-transforms/test/hello.test.ts new file mode 100644 index 000000000..e66b88fad --- /dev/null +++ b/packages/kg-default-transforms/test/hello.test.ts @@ -0,0 +1,8 @@ +import assert from 'assert/strict'; + +describe('Hello world', function () { + it('Runs a test', function () { + // TODO: Write me! + assert.ok(require('../')); + }); +}); diff --git a/packages/kg-default-transforms/tsconfig.json b/packages/kg-default-transforms/tsconfig.json new file mode 100644 index 000000000..56f6ab3b5 --- /dev/null +++ b/packages/kg-default-transforms/tsconfig.json @@ -0,0 +1,110 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": ["es2019"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "Node16", /* Specify what module code is generated. */ + "rootDir": "src", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + "outDir": "build", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "include": ["src/**/*"] +} diff --git a/packages/kg-html-to-lexical/.eslintrc.js b/packages/kg-html-to-lexical/.eslintrc.js index ecc28524e..eb6d40613 100644 --- a/packages/kg-html-to-lexical/.eslintrc.js +++ b/packages/kg-html-to-lexical/.eslintrc.js @@ -2,6 +2,6 @@ module.exports = { parser: '@typescript-eslint/parser', plugins: ['ghost'], extends: [ - 'plugin:ghost/node' + 'plugin:ghost/ts' ] }; diff --git a/packages/kg-html-to-lexical/package.json b/packages/kg-html-to-lexical/package.json index ac94e410b..75b612b22 100644 --- a/packages/kg-html-to-lexical/package.json +++ b/packages/kg-html-to-lexical/package.json @@ -40,7 +40,9 @@ "@lexical/html": "^0.12.2", "@lexical/link": "^0.12.2", "@lexical/list": "^0.12.2", + "@lexical/rich-text": "^0.12.2", "@tryghost/kg-default-nodes": "^0.2.3", + "@tryghost/kg-default-transforms": "^0.0.0", "jsdom": "^22.1.0", "lexical": "^0.12.2" } diff --git a/packages/kg-html-to-lexical/src/html-to-lexical.ts b/packages/kg-html-to-lexical/src/html-to-lexical.ts index defbc132c..431a1b7a5 100644 --- a/packages/kg-html-to-lexical/src/html-to-lexical.ts +++ b/packages/kg-html-to-lexical/src/html-to-lexical.ts @@ -7,6 +7,7 @@ import {ListItemNode, ListNode} from '@lexical/list'; import {LinkNode} from '@lexical/link'; import {DEFAULT_NODES} from '@tryghost/kg-default-nodes'; import {JSDOM} from 'jsdom'; +import {registerDefaultTransforms} from '@tryghost/kg-default-transforms'; export interface htmlToLexicalOptions { editorConfig: CreateEditorArgs @@ -35,6 +36,8 @@ export function htmlToLexical(html: string, options?: htmlToLexicalOptions): Ser const dom = new JSDOM(`${html?.trim()}`); const editor = createHeadlessEditor(editorConfig); + registerDefaultTransforms(editor); + editor.update(() => { const nodes = $generateNodesFromDOM(editor, dom.window.document); diff --git a/packages/kg-html-to-lexical/test/html-to-lexical.test.ts b/packages/kg-html-to-lexical/test/html-to-lexical.test.ts index 94d1f4b39..bab027d63 100644 --- a/packages/kg-html-to-lexical/test/html-to-lexical.test.ts +++ b/packages/kg-html-to-lexical/test/html-to-lexical.test.ts @@ -196,6 +196,113 @@ describe('HTMLtoLexical', function () { assert.deepEqual(lexical, helloWorldDoc); }); + + it('avoids invalid nesting of image nodes', function () { + const lexical = converter.htmlToLexical(` +

Hello

+

+ `, editorConfig); + + assert.deepEqual(lexical, { + root: { + children: [ + { + children: [ + { + detail: 0, + format: 0, + mode: 'normal', + style: '', + text: 'Hello', + type: 'extended-text', + version: 1 + } + ], + direction: null, + format: '', + indent: 0, + type: 'paragraph', + version: 1 + }, + { + alt: '', + detail: 0, + format: 0, + height: 100, + mode: 'normal', + src: 'https://world.com', + style: '', + type: 'image', + version: 1, + width: 100 + } + ], + direction: null, + format: '', + indent: 0, + type: 'root', + version: 1 + } + }); + }); + + it('avoids invalid nesting of header nodes', function () { + // Google Docs uses spans for headings + const lexical = converter.htmlToLexical(` +

World

+

World

+ `, editorConfig); + + assert.deepEqual(lexical, { + root: { + children: [ + { + children: [ + { + detail: 0, + format: 0, + mode: 'normal', + style: '', + text: 'Hello', + type: 'extended-text', + version: 1 + } + ], + direction: null, + format: '', + indent: 0, + tag: 'h1', + type: 'extended-heading', + version: 1 + }, + { + children: [ + { + detail: 0, + format: 0, + mode: 'normal', + style: '', + text: 'World', + type: 'extended-text', + version: 1 + } + ], + direction: null, + format: '', + indent: 0, + tag: 'h1', + type: 'extended-heading', + version: 1 + } + ], + direction: null, + format: '', + indent: 0, + type: 'root', + version: 1 + } + }); + }); }); describe('HTML nodes', function () { diff --git a/packages/kg-lexical-html-renderer/test/render.test.js b/packages/kg-lexical-html-renderer/test/render.test.js index 7a4ba6921..afbaba789 100644 --- a/packages/kg-lexical-html-renderer/test/render.test.js +++ b/packages/kg-lexical-html-renderer/test/render.test.js @@ -59,3 +59,10 @@ describe('Special elements', function () { output: `

Test

a link some text

` })); }); + +describe('Unexpected input', function () { + it('paragraphs with no children', shouldRender({ + input: `{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"Testing Before","type":"text","version":1}],"direction":"ltr","format":"","indent":0,"type":"paragraph","version":1},{"children":[],"direction":"ltr","format":"","indent":0,"type":"paragraph","version":1},{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"Testing After","type":"text","version":1}],"direction":"ltr","format":"","indent":0,"type":"paragraph","version":1}],"direction":"ltr","format":"","indent":0,"type":"root","version":1}}`, + output: `

Testing Before

Testing After

` + })); +}); diff --git a/packages/koenig-lexical/package.json b/packages/koenig-lexical/package.json index f92c26665..8b6aa5566 100644 --- a/packages/koenig-lexical/package.json +++ b/packages/koenig-lexical/package.json @@ -78,6 +78,7 @@ "@tryghost/kg-clean-basic-html": "^3.0.37", "@tryghost/kg-converters": "^0.0.19", "@tryghost/kg-default-nodes": "^0.2.3", + "@tryghost/kg-default-transforms": "^0.0.0", "@tryghost/kg-markdown-html-renderer": "^6.0.12", "@tryghost/kg-simplemde": "^2.0.24", "@types/react": "18.2.29", diff --git a/packages/koenig-lexical/src/plugins/KoenigBehaviourPlugin.jsx b/packages/koenig-lexical/src/plugins/KoenigBehaviourPlugin.jsx index ec57da326..c372ffef8 100644 --- a/packages/koenig-lexical/src/plugins/KoenigBehaviourPlugin.jsx +++ b/packages/koenig-lexical/src/plugins/KoenigBehaviourPlugin.jsx @@ -55,6 +55,7 @@ import {$isListItemNode, $isListNode, INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDE import {$setBlocksType} from '@lexical/selection'; import {MIME_TEXT_HTML, MIME_TEXT_PLAIN, PASTE_MARKDOWN_COMMAND} from './MarkdownPastePlugin.jsx'; import {mergeRegister} from '@lexical/utils'; +import {registerDefaultTransforms, registerDenestTransform, registerStripAlignmentTransform} from '@tryghost/kg-default-transforms'; import {shouldIgnoreEvent} from '../utils/shouldIgnoreEvent'; import {useKoenigSelectedCardContext} from '../context/KoenigSelectedCardContext'; import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext'; @@ -1371,108 +1372,9 @@ function useKoenigBehaviour({editor, containerElem, cursorDidExitAtTop, isNested ); }, [editor]); - // strip text-align formats that can arrive when pasting from external sources - // we don't support text alignment in Koenig + // remove alignment formats and denest invalid node nesting React.useEffect(() => { - function stripAlignmentStyle(node) { - // on element nodes format===text-align in Lexical - if (node.getFormatType() !== '') { - node.setFormat(''); - } - } - - function registerStripAlignmentTransform(nodeType) { - if (editor.hasNodes([nodeType])) { - return editor.registerNodeTransform(nodeType, stripAlignmentStyle); - } - - return () => {}; - } - - return mergeRegister( - registerStripAlignmentTransform(ParagraphNode), - registerStripAlignmentTransform(HeadingNode), - registerStripAlignmentTransform(ExtendedHeadingNode), - registerStripAlignmentTransform(QuoteNode) - ); - }, [editor]); - - // validate child nodes of ParagraphNode - e.g. no headings, lists, horizontal rules, etc - React.useEffect(() => { - function denestNestedElementNodes(node, createNode) { - const children = node.getChildren(); - - const hasInvalidChild = children.some((child) => { - return child.isInline && !child.isInline(); - }); - - if (!hasInvalidChild) { - return; - } - - // we need a temporary detached node to hold any moved nodes otherwise - // we can trigger an infinite loop with the transform continually - // re-running on each child move - const tempParagraph = $createParagraphNode(); - - // we need a new node of the current node type to collect inline - // children so we can maintain order when moving the non-inline children - // out. Will be appended and replaced with a new node each time we - // find a non-inline child - let currentElementNode = createNode(node); - - // pull out any non-inline children as we don't support nested element nodes - children.forEach((child) => { - if (child.isInline && !child.isInline()) { - if (currentElementNode.getChildrenSize() > 0) { - tempParagraph.append(currentElementNode); - currentElementNode = createNode(node); - } - tempParagraph.append(child); - } else { - currentElementNode.append(child); - } - }); - - // append any remaining text nodes - if (currentElementNode.getChildrenSize() > 0) { - tempParagraph.append(currentElementNode); - } - - // reverse because we can only insertAfter the current paragraph - // so we need to insert the first child last to maintain order - tempParagraph.getChildren().reverse().forEach((child) => { - node.insertAfter(child); - }); - - // remove the original paragraph - node.remove(); - - // clean up the temporary paragraph immediately, although it should be - // cleaned up by the reconciler's garbage collection of detached nodes - tempParagraph.remove(); - } - - function registerDenestTransform(nodeType, createNode) { - if (editor.hasNodes([nodeType])) { - return editor.registerNodeTransform(nodeType, (node) => { - denestNestedElementNodes(node, createNode); - }); - } - - return () => {}; - } - - return mergeRegister( - registerDenestTransform(ParagraphNode, $createParagraphNode), - registerDenestTransform(HeadingNode, (node) => { - return $createHeadingNode(node.getTag()); - }), - registerDenestTransform(ExtendedHeadingNode, (node) => { - return $createParagraphNode(node.getTag()); - }), - registerDenestTransform(QuoteNode, $createQuoteNode) - ); + return registerDefaultTransforms(editor); }, [editor]); return null; diff --git a/yarn.lock b/yarn.lock index b3fe359ca..a87933371 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8891,7 +8891,6 @@ eslint-plugin-es-x@^7.1.0: eslint-plugin-filenames@allouis/eslint-plugin-filenames#15dc354f4e3d155fc2d6ae082dbfc26377539a18: version "1.3.2" - uid "15dc354f4e3d155fc2d6ae082dbfc26377539a18" resolved "https://codeload.github.com/allouis/eslint-plugin-filenames/tar.gz/15dc354f4e3d155fc2d6ae082dbfc26377539a18" dependencies: lodash.camelcase "4.3.0"