Selection and marks
Draw the selection, snap it to words and keep it as marks, in React.
Down the Rabbit-Hole
Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, “and what is the use of a book,” thought Alice “without pictures or conversations?”
So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.
A mark is a character range of the source text, so it can be stored and redrawn later, at any zoom or width.
import type { Mark, TextRange } from "glyphline";
import { GlyphOverlay, useDomSource } from "glyphline/react";
import { useState } from "react";
export function Annotated() {
const [ref, source] = useDomSource<HTMLDivElement>();
const [selected, setSelected] = useState<{ range: TextRange; text: string } | null>(null);
const [marks, setMarks] = useState<Mark[]>([]);
return (
<>
<button
disabled={!selected}
onMouseDown={(e) => e.preventDefault()} // keep the selection alive
onClick={() => {
if (!selected) return;
setMarks((m) => [...m, { id: crypto.randomUUID(), ...selected.range, className: "note" }]);
document.getSelection()?.removeAllRanges();
}}
>
Highlight
</button>
<div style={{ position: "relative" }}>
<div ref={ref} className="gl-native-selection-hidden">…</div>
<GlyphOverlay
source={source}
marks={marks}
options={{
trackSelection: {
snapToWords: true,
onChange: (range, text) => setSelected(range ? { range, text } : null),
},
}}
/>
</div>
</>
);
}An inline options object is fine: the overlay only redraws when shapes or class names change, and onChange is read when it fires, so the latest closure is used.
Store start, end and className with the document and pass them back as marks. Selection and marks covers the details shared with Svelte.
Made by Lucas Piera