Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CARE-1802] Refactor - Extensions model #504

Draft
wants to merge 55 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
05fb71b
[CARE-1802] Provide infra for extensions definitions
e1himself Sep 7, 2023
d5dc2c8
[CARE-1802] Allow passing multiple extensions to `register()` and `us…
e1himself Sep 7, 2023
0c38071
[CARE-1802] Use shallow compare for registering extensions
e1himself Sep 7, 2023
4770f5f
[CARE-1802] Convert existing extensions to React components
e1himself Sep 19, 2023
07cb9ad
[CARE-1802] Convert `getEnabledExtensions()` to a React component
e1himself Sep 19, 2023
1f636e3
[CARE-1802] Move variables UI markup and state to `VariablesExtension`
e1himself Sep 7, 2023
4164b89
[CARE-1802] Move user mentions UI markup and state to `UserMentionsEx…
e1himself Sep 7, 2023
7d90896
[CARE-1802] Render Extensions inside `<Slate>` context
e1himself Sep 19, 2023
1c6ef3a
[CARE-1802] Simplify `onKeyDown` prop handling
e1himself Sep 7, 2023
8d2a5e3
[CARE-1802] Consolidate Snippets UI and state in the SnippetsExtensio…
e1himself Sep 19, 2023
f52b0a9
[CARE-1802] Solve `onChange` callback for UserMentions & Variables ex…
e1himself Sep 8, 2023
f0f4467
[CARE-1802] Comment out broken code
e1himself Sep 8, 2023
5a93734
[CARE-1802] Improve error message
e1himself Sep 14, 2023
94e5661
[CARE-1802] Move FlashNodes rendering to the FlashNodesExtension
e1himself Sep 14, 2023
f5a05fb
[CARE-1802] Optimize TextStylingExtension by ensuring referential equ…
e1himself Sep 14, 2023
e4f434e
[CARE-1802] Reogranize Extensions manager module
e1himself Sep 15, 2023
8ec34b5
[CARE-1802] Rewrite ExtensionsManager to keep `editor.extensions` up …
e1himself Sep 15, 2023
825e855
[CARE-1802] Move RichFormattingMenu UI into the new `RichFormattingMe…
e1himself Sep 19, 2023
5b48268
[CARE-1802] Finish transitioning of SnippetsExtension to be self-suff…
e1himself Sep 19, 2023
9e02f82
[CARE-1802] Leave comments for later
e1himself Sep 19, 2023
106006e
[CARE-1802] Wire EditableWithExtensions to the editor extensions prop…
e1himself Sep 18, 2023
660332f
[CARE-1802] Move `editor.serialization()` functionality to the Extens…
e1himself Sep 18, 2023
6b36e1b
[CARE-1802] Move `editor.isElementEqual()` functionality to the Exten…
e1himself Sep 18, 2023
9754158
[CARE-1802] Move `editor.isInline()` & `editor.isVoid()` extensions o…
e1himself Sep 18, 2023
bc19448
[CARE-1802] Move `editor.normalizeNode()` extensions overrides to the…
e1himself Sep 18, 2023
77ee360
[CARE-1802] Move `editor.isRichBlock()` extensions checks to the Exte…
e1himself Sep 18, 2023
4c033e4
[CARE-1802] Provide a way for extensions to hook into `editor.insertD…
e1himself Sep 18, 2023
d38af1d
[CARE-1802] Extract Paste event tracking into a separate extension
e1himself Sep 18, 2023
f23d4b9
[CARE-1802] Rewrite Slate Pasting extension to the new `insertData()`…
e1himself Sep 19, 2023
6d2a1a4
[CARE-1802] Deprecate `withOverrides()`
e1himself Sep 18, 2023
1b5485d
[CARE-1802] Convert `withDeserializeHtml` editor mutator function to …
e1himself Sep 19, 2023
0dbf508
[CARE-1802] Rewrite Images & Files pasting to the new `insertData()` …
e1himself Sep 19, 2023
07a8cd6
[CARE-1802] Replace `withResetFormattingOnBreak` editor mutator with …
e1himself Sep 18, 2023
a3627f2
[CARE-1802] Add a todo
e1himself Sep 18, 2023
454673d
[CARE-1802] Rewrite LinksExtension autolinking handling to `insertDat…
e1himself Sep 18, 2023
a5603de
[CARE-1802] Convert `withPastedUrlsUnfurling` mutator to `insertData`…
e1himself Sep 18, 2023
c0846c1
[CARE-1802] Add an extension hook into `editor.insertText()` method
e1himself Sep 18, 2023
698fb74
[CARE-1802] Rewrite `withAutoformat` editor mutator to `insertText()`…
e1himself Sep 18, 2023
b3d6c8a
[CARE-1802] Add a way to hook into `HistoryEditor` `undo()` and `redo…
e1himself Sep 18, 2023
1264170
[CARE-1802] Simplify event-tracking callbacks
e1himself Sep 19, 2023
8a02a3a
[CARE-1802] Add an extension hook into `editor.setFragmentData()` method
e1himself Sep 19, 2023
dfef2fa
[CARE-1802] Convert `withImages()` editor mutator plugin to `setFragm…
e1himself Sep 19, 2023
f5b8b84
Merge branch 'refactor/care-1802-drop-loader-extension' into x/care-1…
e1himself Sep 21, 2023
461f292
[CARE-1802] Change `ListExtension` to work without `withOverrides`
e1himself Sep 22, 2023
7c4f889
[CARE-1802] Add a hook to `Editor.getFragment()` method
e1himself Sep 22, 2023
70418c6
[CARE-1802] Export table plugin's editor overrides as separate parts
e1himself Sep 22, 2023
a5bf2f5
[CARE-1802] Add hooks for Editor `deleteBackward()` and `deleteForwar…
e1himself Sep 22, 2023
de130cd
[CARE-1802] Change `TablesExtension` to work without `withOverrides` …
e1himself Sep 22, 2023
af19597
[CARE-1802] Fix TS type error
e1himself Sep 22, 2023
30c054a
[CARE-1802] Rewrite `FlashNodesExtension` to work without `withOverri…
e1himself Sep 22, 2023
144d476
[CARE-1802] Completely drop `Extension.withOverrides()` feature
e1himself Sep 22, 2023
1f8606a
[CARE-1802] Fix useRegisterExtension effect dependencies
e1himself Sep 22, 2023
9552dac
[CARE-1802] Make ExtensionsEditor code type-strict to catch possible …
e1himself Sep 22, 2023
fff36d8
[CARE-1802] Update editor factory to not require `extensions` or `plu…
e1himself Sep 22, 2023
cf84124
[CARE-1802] Rewrite ExtensionsManager to not trigger a re-render on e…
e1himself Sep 22, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/slate-commons/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"dependencies": {
"@prezly/slate-types": "workspace:*",
"@technically/is-not-null": "^1.0.0",
"@technically/is-not-undefined": "^1.0.0",
"uuid": "^8.3.0"
},
"devDependencies": {
Expand Down
14 changes: 14 additions & 0 deletions packages/slate-commons/src/commands/getCurrentNode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { Node } from 'slate';
import { Editor } from 'slate';

import { isSelectionValid } from './isSelectionValid';

export function getCurrentNode(editor: Editor): Node | null {
if (!editor.selection || !isSelectionValid(editor)) {
return null;
}

const entry = Editor.node(editor, editor.selection, { depth: 1 });

return entry ? entry[0] : null;
}
1 change: 1 addition & 0 deletions packages/slate-commons/src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export { findDescendants } from './findDescendants';
export { focus } from './focus';
export { getCurrentDomNode } from './getCurrentDomNode';
export { getCurrentNodeEntry } from './getCurrentNodeEntry';
export { getCurrentNode } from './getCurrentNode';
export { getEditorRange } from './getEditorRange';
export { getNodePath } from './getNodePath';
export { getPrevChars } from './getPrevChars';
Expand Down
154 changes: 154 additions & 0 deletions packages/slate-commons/src/extensions/ExtensionManager.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import React, {
createContext,
type ReactNode,
RefObject,
useContext,
useEffect,
useState,
} from 'react';
import type { Editor } from 'slate';

import type { Extension } from '../types';
import type {
AdditionalEditorMethods,
EditorMethodsHooks,
EditorRenderHooks,
} from '../types/Extension';

import type { ExtensionsEditor } from './ExtensionsEditor';

export interface ExtensionsManager {
register(
id: Extension['id'],
methodsHooks: RefObject<EditorMethodsHooks & AdditionalEditorMethods>,
propsHooks: EditorRenderHooks,
): void;
unregister(id: Extension['id']): void;
}

/**
* -- CONTEXT --
* =============
*/

function requireExtensionsManagerProvider(): never {
throw new Error(
'It is required to wrap any code using ExtensionsManager into ExtensionsManagerProvider.',
);
}

export const ManagerContext = createContext<ExtensionsManager>({
register: requireExtensionsManagerProvider,
unregister: requireExtensionsManagerProvider,
});

// FIXME: Introduce ManagerSyncContext to only render the Editor itself after all sub-tree extensions are already mounted.

/**
* -- HOOKS --
* ===========
*/

export function useExtensionsManager(): ExtensionsManager {
return useContext(ManagerContext);
}

/**
* -- COMPONENTS --
* ================
*/

interface Props<T extends ExtensionsEditor> {
children: ReactNode;
editor: T;
}

type Entry = {
id: Extension['id'];
methodHooks: RefObject<EditorMethodsHooks & AdditionalEditorMethods>;
renderHooks: EditorRenderHooks;
};

type EntriesMap = Map<Extension['id'], Entry>;

const EDITOR_HOOKS_ENTRIES = new WeakMap<Editor, EntriesMap>();

export function ExtensionsManager<T extends ExtensionsEditor>({ children, editor }: Props<T>) {
const [counter, setCounter] = useState(0);
const [manager] = useState<ExtensionsManager>(() => {
function updateEntries(editor: T, updater: (entries: EntriesMap) => void) {
const entries = EDITOR_HOOKS_ENTRIES.get(editor) ?? new Map();

const prevRenderHooks = [...entries.values()].map((entry) => entry.renderHooks);

updater(entries);

EDITOR_HOOKS_ENTRIES.set(editor, entries);

const methodHooks = [...entries.values()].map((entry) => entry.methodHooks);
const renderHooks = [...entries.values()].map((entry) => entry.renderHooks);

editor.methodHooks = methodHooks;

if (!isRenderHooksEqual(prevRenderHooks, renderHooks)) {
editor.renderHooks = renderHooks;
setCounter((c) => c + 1);
}
}

return {
register(
id: Extension['id'],
methodHooks: RefObject<EditorMethodsHooks & AdditionalEditorMethods>,
renderHooks: EditorRenderHooks,
) {
updateEntries(editor, (entries) => {
entries.set(id, { id, methodHooks, renderHooks });
});
},
unregister(id: Extension['id']) {
updateEntries(editor, (entries) => {
entries.delete(id);
});
},
};
});

/**
* Force editor re-rendering every time the extensions list is changed.
*/
useEffect(() => {
editor.onChange(); // FIXME: Verify this works without causing an infinite update loop.
}, [counter]);

return <ManagerContext.Provider value={manager}>{children}</ManagerContext.Provider>;
}

function isRenderHooksEqual(hooks: Entry['renderHooks'][], prevHooks: Entry['renderHooks'][]) {
if (hooks.length !== prevHooks.length) {
return false;
}

for (let i = 0; i < hooks.length; i++) {
const hooksParts = parts(hooks[i]);
const prevHookParts = parts(prevHooks[i]);
const isEqual = prevHookParts.every((part, index) => part === hooksParts[index]);
if (!isEqual) {
return false;
}
}

return true;
}

function parts(hook: Entry['renderHooks']) {
const { decorate, renderLeaf, renderElement, onDOMBeforeInput, onKeyDown, ...rest } = hook;
if (Object.keys(rest).length > 0) {
throw new Error(
`Logic error: one or more properties are ignored for renderHooks comparison: ${Object.keys(
rest,
).join(', ')}.`,
);
}
return [decorate, renderLeaf, renderElement, onKeyDown, onDOMBeforeInput];
}
Loading