a tool for shared writing and social publishing
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

handle keypress when things are selected

+30 -7
+30 -7
components/Blocks.tsx
··· 25 25 value: string; 26 26 type: Fact<"block/type">["data"]["value"]; 27 27 }; 28 + interface ReplayedKeyboardEvent extends KeyboardEvent { 29 + replayed: boolean; 30 + } 28 31 export function Blocks(props: { entityID: string }) { 29 32 let rep = useReplicache(); 30 33 let ref = useRef<HTMLDivElement | null>(null); 31 34 let previous = useRef("none"); 32 35 useEffect(() => { 33 - let cb = () => { 36 + let selectionChangeHandler = () => { 34 37 let selection = window.getSelection(); 38 + let ranges; 35 39 if (previous.current !== selection?.type) { 36 - let ranges = saveSelection(); 37 - requestAnimationFrame(() => { 38 - restoreSelection(ranges); 39 - }); 40 + ranges = saveSelection(); 40 41 } 41 42 if (selection?.type === "Range") { 42 43 if (ref.current) ref.current.contentEditable = "true"; ··· 55 56 } else { 56 57 if (ref.current) ref.current.contentEditable = "false"; 57 58 } 59 + if (previous.current !== selection?.type) { 60 + if (ranges) restoreSelection(ranges); 61 + } 58 62 previous.current = selection?.type || "None"; 59 63 }; 60 - document.addEventListener("selectionchange", cb); 64 + let keyDownHandler = (e: KeyboardEvent) => { 65 + let selection = window.getSelection(); 66 + if (selection?.type !== "Range") return; 67 + if ((e as ReplayedKeyboardEvent).replayed) { 68 + return; 69 + } 70 + e.stopPropagation(); 71 + 72 + let ranges = saveSelection(); 73 + if (ref.current) ref.current.contentEditable = "false"; 74 + restoreSelection(ranges); 75 + let newEvent = new KeyboardEvent(e.type, { 76 + ...e, 77 + }) as ReplayedKeyboardEvent; 78 + newEvent.replayed = true; 79 + e.target?.dispatchEvent(newEvent); 80 + }; 81 + document.addEventListener("selectionchange", selectionChangeHandler); 82 + document.addEventListener("keydown", keyDownHandler, true); 61 83 let pointerUp = () => { 62 84 if (useUIState.getState().selectedBlock.length > 1) 63 85 window.getSelection()?.removeAllRanges(); ··· 65 87 window.addEventListener("pointerup", pointerUp); 66 88 return () => { 67 89 window.removeEventListener("pointerup", pointerUp); 68 - document.removeEventListener("selectionchange", cb); 90 + document.removeEventListener("keydown", keyDownHandler, true); 91 + document.removeEventListener("selectionchange", selectionChangeHandler); 69 92 }; 70 93 }, []); 71 94 let initialValue = useMemo(