glyphline

Selection and marks

Draw the reader's selection as one shape, snap it to words and keep it as a mark.

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.

Drawing the selection

const hl = createHighlighter(svg, source, {
  trackSelection: {
    snapToWords: true,
    onChange: (range, text) => showToolbar(range, text),
  },
});

glyphline listens to selectionchange, converts the selection inside its source to a character range and draws it with the sentence outline. Selections elsewhere on the page are ignored. Hide the browser's own colour on the selectable element with the gl-native-selection-hidden class; the selection itself still works, so copy, the context menu and keyboard selection behave as usual.

snapToWords changes what is drawn and reported, not the browser's selection: copy still copies what the browser selected.

Without trackSelection you can draw any range yourself: hl.update({ selection: { start, end } }).

Keeping a mark

A mark is a character range plus an id and an optional class:

const marks = [
  { id: "n1", start: 120, end: 168, className: "note-yellow" },
  { id: "n2", start: 402, end: 431, className: "note-green" },
];
hl.update({ marks });
.gl-mark.note-yellow {
  fill: oklch(0.9 0.15 95 / 0.75);
}

Each mark path has data-id. Store start and end with the document; they redraw at any zoom or width. For HTML that changes, store some surrounding text too and re-anchor it.

A toolbar over the selection

onChange gives you the range; the selection's position on screen comes from the browser:

const rect = document.getSelection()?.getRangeAt(0).getBoundingClientRect();

Prevent mousedown on the toolbar buttons (e.preventDefault()) so pressing one does not clear the selection.

Made by Lucas Piera

On this page