Fix link creation with backward selection (#9986)

Fix link creation with backward selection
This commit is contained in:
Florian Duros 2023-01-26 11:08:23 +01:00 committed by GitHub
parent 222f8a919d
commit 406edfc27d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 65 additions and 5 deletions

View file

@ -20,7 +20,7 @@ import { SubSelection } from "./types";
export function getDefaultContextValue(): { selection: SubSelection } {
return {
selection: { anchorNode: null, anchorOffset: 0, focusNode: null, focusOffset: 0 },
selection: { anchorNode: null, anchorOffset: 0, focusNode: null, focusOffset: 0, isForward: true },
};
}

View file

@ -44,6 +44,7 @@ export function useComposerFunctions(
anchorOffset: anchorOffset + text.length,
focusNode: ref.current.firstChild,
focusOffset: focusOffset + text.length,
isForward: true,
});
setContent(ref.current.innerHTML);
}

View file

@ -23,11 +23,15 @@ function setSelectionContext(composerContext: ComposerContextState): void {
const selection = document.getSelection();
if (selection) {
const range = selection.getRangeAt(0);
const isForward = range.startContainer === selection.anchorNode && range.startOffset === selection.anchorOffset;
composerContext.selection = {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset,
isForward,
};
}
}

View file

@ -19,4 +19,6 @@ export type ComposerFunctions = {
insertText: (text: string) => void;
};
export type SubSelection = Pick<Selection, "anchorNode" | "anchorOffset" | "focusNode" | "focusOffset">;
export type SubSelection = Pick<Selection, "anchorNode" | "anchorOffset" | "focusNode" | "focusOffset"> & {
isForward: boolean;
};

View file

@ -19,9 +19,14 @@ import { SubSelection } from "../types";
export function setSelection(selection: SubSelection): Promise<void> {
if (selection.anchorNode && selection.focusNode) {
const range = new Range();
range.setStart(selection.anchorNode, selection.anchorOffset);
range.setEnd(selection.focusNode, selection.focusOffset);
if (selection.isForward) {
range.setStart(selection.anchorNode, selection.anchorOffset);
range.setEnd(selection.focusNode, selection.focusOffset);
} else {
range.setStart(selection.focusNode, selection.focusOffset);
range.setEnd(selection.anchorNode, selection.anchorOffset);
}
document.getSelection()?.removeAllRanges();
document.getSelection()?.addRange(range);
}