Skip to content

Commit

Permalink
šŸ› Fixed kg-html-to-lexical creating unwanted text alignment and invā€¦
Browse files Browse the repository at this point in the history
ā€¦alid nesting

refs TryGhost/Ghost#18448

- extracted our aligment stripping and denesting transforms to a new `kg-default-transforms` package
- updated `kg-html-to-lexical` so it adds the transforms to the headless editor ensuring the output matches what we'd get if the same content was pasted directly into the editor
  • Loading branch information
kevinansfield committed Oct 18, 2023
1 parent 65663bc commit 170d03a
Show file tree
Hide file tree
Showing 21 changed files with 465 additions and 103 deletions.
7 changes: 7 additions & 0 deletions packages/kg-default-transforms/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
parser: '@typescript-eslint/parser',
plugins: ['ghost'],
extends: [
'plugin:ghost/ts'
]
};
2 changes: 2 additions & 0 deletions packages/kg-default-transforms/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
build
tsconfig.tsbuildinfo
21 changes: 21 additions & 0 deletions packages/kg-default-transforms/LICENSE
Original file line number Diff line number Diff line change
@@ -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.
35 changes: 35 additions & 0 deletions packages/kg-default-transforms/README.md
Original file line number Diff line number Diff line change
@@ -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).
40 changes: 40 additions & 0 deletions packages/kg-default-transforms/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
1 change: 1 addition & 0 deletions packages/kg-default-transforms/src/decs.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module '@tryghost/kg-default-nodes';
26 changes: 26 additions & 0 deletions packages/kg-default-transforms/src/default-transforms.ts
Original file line number Diff line number Diff line change
@@ -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()))
);
}
1 change: 1 addition & 0 deletions packages/kg-default-transforms/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './default-transforms.js';
67 changes: 67 additions & 0 deletions packages/kg-default-transforms/src/transforms/denest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {ElementNode, $createParagraphNode, LexicalEditor, LexicalNode, Klass} from 'lexical';

export type CreateNodeFn<T extends LexicalNode> = (originalNode: T) => T;

export function denestTransform<T extends ElementNode>(node: T, createNode: CreateNodeFn<T>) {
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<T extends ElementNode>(editor: LexicalEditor, klass: Klass<T>, createNode: CreateNodeFn<T>): () => void {
if (editor.hasNodes([klass])) {
return editor.registerNodeTransform(klass, (node) => {
denestTransform(node, createNode);
});
}

return () => {};
}
16 changes: 16 additions & 0 deletions packages/kg-default-transforms/src/transforms/remove-alignment.ts
Original file line number Diff line number Diff line change
@@ -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<T extends ElementNode>(editor: LexicalEditor, klass: Klass<T>) {
if (editor.hasNodes([klass])) {
return editor.registerNodeTransform(klass, removeAlignmentTransform);
}

return () => {};
}
7 changes: 7 additions & 0 deletions packages/kg-default-transforms/test/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
parser: '@typescript-eslint/parser',
plugins: ['ghost'],
extends: [
'plugin:ghost/test'
]
};
8 changes: 8 additions & 0 deletions packages/kg-default-transforms/test/hello.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import assert from 'assert/strict';

describe('Hello world', function () {
it('Runs a test', function () {
// TODO: Write me!
assert.ok(require('../'));
});
});
Loading

0 comments on commit 170d03a

Please sign in to comment.