diff --git a/packages/svelte-lexical/src/lib/components/toolbar/Toolbar.svelte b/packages/svelte-lexical/src/lib/components/toolbar/Toolbar.svelte index 20e9062..a1edc47 100644 --- a/packages/svelte-lexical/src/lib/components/toolbar/Toolbar.svelte +++ b/packages/svelte-lexical/src/lib/components/toolbar/Toolbar.svelte @@ -3,14 +3,12 @@ import StateStoreRichTextUpdator from './StateStoreRichTextUpdator.svelte'; import {setContext} from 'svelte'; - import {getEditor} from '$lib/core/composerContext.js'; - import {onMount} from 'svelte'; + import {getEditor, setIsEditable} from '$lib/core/composerContext.js'; import type {NodeKey} from 'lexical'; const editor = getEditor(); - const isEditable = writable(editor.isEditable()); - setContext('isEditable', isEditable); + setIsEditable(editor) const activeEditor = writable(editor); setContext('activeEditor', activeEditor); @@ -36,12 +34,6 @@ setContext('codeLanguage', writable('')); setContext('isLink', writable(false)); setContext('isImageCaption', writable(false)); - - onMount(() => { - return editor.registerEditableListener((editable) => { - $isEditable = editable; - }); - }); diff --git a/packages/svelte-lexical/src/lib/core/composerContext.ts b/packages/svelte-lexical/src/lib/core/composerContext.ts index 7ae5803..309af17 100644 --- a/packages/svelte-lexical/src/lib/core/composerContext.ts +++ b/packages/svelte-lexical/src/lib/core/composerContext.ts @@ -1,7 +1,7 @@ import type {HistoryState} from '@lexical/history'; import type {LexicalEditor} from 'lexical'; import {SvelteComponent, getContext, setContext} from 'svelte'; -import type {Writable} from 'svelte/store'; +import {writable,type Writable} from 'svelte/store'; export function getEditor(): LexicalEditor { return getContext('editor'); @@ -17,6 +17,26 @@ export function getIsEditable(): Writable { return getContext('isEditable'); } +/** + * Writable store that abstracts {@link LexicalEditor.isEditable} and {@link LexicalEditor.setEditable}. + */ +export function setIsEditable(editor: LexicalEditor): Writable { + const isEditable = writable(editor.isEditable(), (set) => { + const unsubscribe = editor.registerEditableListener((editable) => { + set(editable) + }) + return unsubscribe + }); + + // The overridden `set` method will __not__ update the store's state. + // Assume that the editor will emit an update to the store's callback at `registerEditableListener. + isEditable.set = (editable) => { + editor.setEditable(editable) + } + + return setContext('isEditable', isEditable) +} + export function getActiveEditor(): Writable { return getContext('activeEditor'); }