From 353dc835427a2522295c445808557464aa53d757 Mon Sep 17 00:00:00 2001 From: "Timothy J. Baek" Date: Fri, 18 Oct 2024 22:16:18 -0700 Subject: [PATCH] enh: rich text input space behaviour --- .../components/common/RichTextInput.svelte | 48 ++++++++++++++++++- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/src/lib/components/common/RichTextInput.svelte b/src/lib/components/common/RichTextInput.svelte index 2989a4852..5d1e30494 100644 --- a/src/lib/components/common/RichTextInput.svelte +++ b/src/lib/components/common/RichTextInput.svelte @@ -104,6 +104,48 @@ // Initialize Editor State and View + function handleSpace(state, dispatch) { + let { from, to, empty } = state.selection; + console.log('Space key pressed', from, to, empty); + if (dispatch) { + let tr = state.tr.insertText(' ', state.selection.from, state.selection.to); + + // // After inserting space, check for any active marks at `from + 1` + const storedMarks = state.storedMarks || state.selection.$from.marks(); + + const hasBold = storedMarks.some((mark) => mark.type === state.schema.marks.strong); + const hasItalic = storedMarks.some((mark) => mark.type === state.schema.marks.em); + + console.log('Stored marks:', storedMarks, hasBold, hasItalic); + + // Step 2: Remove marks only for the space character inserted + if (hasBold) { + tr = tr.removeMark(from, from + 1, state.schema.marks.strong); + } + if (hasItalic) { + tr = tr.removeMark(from, from + 1, state.schema.marks.em); + } + + // Final step: Dispatch the transaction + dispatch(tr); + } + + return false; + } + + function toggleMark(markType) { + return (state, dispatch) => { + const { from, to } = state.selection; + if (state.doc.rangeHasMark(from, to, markType)) { + if (dispatch) dispatch(state.tr.removeMark(from, to, markType)); + return true; + } else { + if (dispatch) dispatch(state.tr.addMark(from, to, markType.create())); + return true; + } + }; + } + function isInList(state) { const { $from } = state.selection; return ( @@ -122,7 +164,6 @@ onMount(() => { const initialDoc = markdownToProseMirrorDoc(value || ''); // Convert the initial content - // const initialDoc = state = EditorState.create({ doc: initialDoc, @@ -143,6 +184,7 @@ ...baseKeymap, 'Mod-z': undo, 'Mod-y': redo, + Space: handleSpace, Enter: chainCommands( (state, dispatch, view) => { if (isEmptyListItem(state)) { @@ -174,7 +216,9 @@ return liftListItem(schema.nodes.list_item)(state, dispatch); } return true; // Prevent Shift-Tab from moving the focus - } + }, + 'Mod-b': toggleMark(schema.marks.strong), + 'Mod-i': toggleMark(schema.marks.em) }) ] });