diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6ede4a0..a6fa4b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,3 +26,4 @@ jobs: - run: pnpm test - run: pnpm test:perf - run: pnpm build + - run: pnpm --filter overlapmark-site test:e2e diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 94678aa..1437590 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -1,6 +1,6 @@ name: Pages -# Builds the demo (examples/vanilla) and deploys it to GitHub Pages at +# Builds the site (site/: the demo and the docs) and deploys it to GitHub Pages at # https://edonghyun.github.io/overlapmark/. Off until the repository # variable PAGES_ENABLED is 'true' and Pages is set to deploy from Actions. on: @@ -33,9 +33,9 @@ jobs: - run: corepack enable - run: pnpm install --frozen-lockfile # The site is served from the /overlapmark/ subpath. - - run: pnpm --filter vanilla-example build --base /overlapmark/ + - run: pnpm --filter overlapmark-site build --base /overlapmark/ - uses: actions/upload-pages-artifact@v5 with: - path: examples/vanilla/dist + path: site/dist - id: deployment uses: actions/deploy-pages@v5 diff --git a/.gitignore b/.gitignore index dda3455..8072463 100644 --- a/.gitignore +++ b/.gitignore @@ -32,7 +32,12 @@ __screenshots__ # local-only planning docs docs/ +!site/docs/ # acceptance-test working files acceptance/.work/ packages/*/LICENSE + +# Playwright output of the site e2e suite +site/test-results/ +site/playwright-report/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3a5328e..c41a543 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,15 +14,15 @@ pnpm exec playwright install chromium # browser tests The repository is a pnpm workspace: -| Path | What it is | -| --------------------------------- | ---------------------------------------------------------------------------------------------- | -| `packages/core` | `@overlapmark/core`: segments, render contract, DOM helpers, `styles.css` | -| `packages/dom` | `@overlapmark/dom`, the vanilla JS adapter | -| `packages/vue`, `react`, `svelte` | The framework adapters | -| `packages/adapter-contract` | Private: the browser test suite every adapter runs | -| `acceptance` | End-to-end tests of apps installed from the packed tarballs | -| `examples/vanilla` | The [live demo](https://edonghyun.github.io/overlapmark/): `pnpm --filter vanilla-example dev` | -| `docs-assets` | README images, rendered from the demo by `pnpm docs:images` | +| Path | What it is | +| --------------------------------- | -------------------------------------------------------------------------------------------------------- | +| `packages/core` | `@overlapmark/core`: segments, render contract, DOM helpers, `styles.css` | +| `packages/dom` | `@overlapmark/dom`, the vanilla JS adapter | +| `packages/vue`, `react`, `svelte` | The framework adapters | +| `packages/adapter-contract` | Private: the browser test suite every adapter runs | +| `acceptance` | End-to-end tests of apps installed from the packed tarballs | +| `site` | The [live demo and docs](https://edonghyun.github.io/overlapmark/): `pnpm --filter overlapmark-site dev` | +| `docs-assets` | README images, rendered from the site by `pnpm docs:images` | ## Checks diff --git a/README.md b/README.md index d936a74..8a7603e 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # overlapmark -A paragraph with overlapping highlights in different colors: the spots several analyses cover are darker, and a panel lists the highlights covering the clicked phrase. +The overlapmark demo: a sentence with three overlapping highlights in yellow, orange and pink, darker where they overlap, under an Add a highlight button. [![npm](https://img.shields.io/npm/v/@overlapmark/core?label=npm)](https://www.npmjs.com/package/@overlapmark/core) [![CI](https://github.com/edonghyun/overlapmark/actions/workflows/ci.yml/badge.svg)](https://github.com/edonghyun/overlapmark/actions/workflows/ci.yml) [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/edonghyun/overlapmark/blob/main/LICENSE) -**[Live demo](https://edonghyun.github.io/overlapmark/)** +**[Live demo](https://edonghyun.github.io/overlapmark/)** · **[Docs](https://edonghyun.github.io/overlapmark/docs/)** Overlapping text highlights for Vue, React, Svelte and plain JS. The more highlights cover a spot, the darker it gets, even when every highlight has its own color, and a click tells you exactly which highlights cover that spot. @@ -101,7 +101,7 @@ highlights = findMatches(text, 'highlights').map((m, i) => ({ hl.update({ highlights }); ``` -The [live demo](https://edonghyun.github.io/overlapmark/) lives in [`examples/vanilla`](examples/vanilla): `pnpm --filter vanilla-example dev`. +The [live demo and docs](https://edonghyun.github.io/overlapmark/) live in [`site`](site): `pnpm --filter overlapmark-site dev`. ## Quick start (Vue) @@ -221,7 +221,7 @@ With the default `layers` strategy, each highlight covering a segment is its own ### `multiply` (default) -The demo paragraph in multiply mode: every nested highlight darkens the spot it covers. +A sentence with three nested highlights in multiply mode: every nested highlight darkens the spot it covers. Each nested layer multiplies with the layers under it (`mix-blend-mode: multiply`), like a highlighter pen drawn over itself, so every highlight covering a spot darkens it, for any color except pure white (a white layer multiplies to no change). The root is an isolated group (`isolation: isolate`), so the layers never blend with the page behind the root. @@ -229,7 +229,7 @@ Each nested layer multiplies with the layers under it (`mix-blend-mode: multiply ### `darken` -The demo paragraph in darken mode: nested highlights are their own color mixed toward black. +The same sentence in darken mode: nested highlights are their own color mixed toward black. Each nested layer takes its own color mixed toward `--om-depth-ink` (default `black`) by `--om-depth-step` (default `12%`) per nesting level, up to `--om-max-depth`, and is painted at `--om-alpha`. It uses no blend mode: the layers are translucent over the page, and the text is not tinted. @@ -237,7 +237,7 @@ Each nested layer takes its own color mixed toward `--om-depth-ink` (default `bl ### `none` -The demo paragraph in none mode: plain translucent layers. +The same sentence in none mode: plain translucent layers. Plain translucent layers, each at `--om-alpha`, with no depth effect. Overlaps of light colors may look the same as, or lighter than, a single highlight. diff --git a/RELEASING.md b/RELEASING.md index 6944b04..81e5300 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -25,7 +25,7 @@ Never run `npm publish` or `changeset publish` from a laptop. The demo links to the npm packages, which return 404 until they are published, and the README images need these files on `main`. So these come last: -2. **Demo site.** Settings, Pages: set the source to GitHub Actions, then add the repository variable `PAGES_ENABLED` with the value `true`. The next push to `main`, or a manual run of the Pages workflow, deploys the demo to . +2. **Demo and docs site.** Settings, Pages: set the source to GitHub Actions, then add the repository variable `PAGES_ENABLED` with the value `true`. The next push to `main`, or a manual run of the Pages workflow, deploys the demo to and the docs to . 3. **Repository homepage.** Set the repository website (the About box) to . 4. **Deprecate the old package.** The root README says `vue-easy-highlight` is replaced; make npm say so: diff --git a/acceptance/scripts/check-readme.ts b/acceptance/scripts/check-readme.ts index a7e1d68..76a9ab1 100644 --- a/acceptance/scripts/check-readme.ts +++ b/acceptance/scripts/check-readme.ts @@ -1,12 +1,13 @@ import { existsSync, readFileSync } from 'node:fs'; import { dirname, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { QUICK_STARTS } from '../../site/src/quick-starts.ts'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); interface Framework { /** As in the root README heading `## Quick start ()`. */ - heading: string; + heading: keyof typeof QUICK_STARTS; pkg: string; /** The acceptance app's quick-start file. */ file: string; @@ -72,6 +73,12 @@ for (const { heading, pkg, file } of frameworks) { `${pkgReadme}: quick start differs from README.md (${heading})`, ); + const site = QUICK_STARTS[heading]; + if (normalized(site.code).join('\n') !== lines.join('\n')) + problems.push( + `site/src/quick-starts.ts: quick start differs from README.md (${heading})`, + ); + const app = join(root, 'acceptance/apps', file); if (!existsSync(app)) { problems.push(`${relative(root, app)} does not exist (${heading})`); @@ -87,4 +94,6 @@ if (problems.length > 0) { console.error(problems.join('\n')); process.exit(1); } -console.log('README quick starts match the package READMEs and the apps'); +console.log( + 'README quick starts match the package READMEs, the site and the apps', +); diff --git a/docs-assets/hero.png b/docs-assets/hero.png index d08948e..deb02e7 100644 Binary files a/docs-assets/hero.png and b/docs-assets/hero.png differ diff --git a/docs-assets/overlap-darken.png b/docs-assets/overlap-darken.png index 6a4ad85..c84d663 100644 Binary files a/docs-assets/overlap-darken.png and b/docs-assets/overlap-darken.png differ diff --git a/docs-assets/overlap-multiply.png b/docs-assets/overlap-multiply.png index 0777819..d80c8c8 100644 Binary files a/docs-assets/overlap-multiply.png and b/docs-assets/overlap-multiply.png differ diff --git a/docs-assets/overlap-none.png b/docs-assets/overlap-none.png index 2c77c84..543e16b 100644 Binary files a/docs-assets/overlap-none.png and b/docs-assets/overlap-none.png differ diff --git a/examples/vanilla/index.html b/examples/vanilla/index.html deleted file mode 100644 index 620c670..0000000 --- a/examples/vanilla/index.html +++ /dev/null @@ -1,300 +0,0 @@ - - - - - - - overlapmark: overlapping text highlights - - - - -
-
- -
-

overlapmark

-

- Highlights that overlap get darker, and a click names every - highlight under it. For vanilla JS, Vue, React and Svelte. -

-
- npm install @overlapmark/dom @overlapmark/core - -
- -
- -
-
-

- Analyses of a passage -

-
-
- Overlap -
- - - -
-

-
-
- Strategy -
- - -
-

-
-
- -
-
-

-
    -
    - - -
    -
    - -
    -

    Make it yours

    -

    - The look is plain CSS. Set the theme variables, pick a - preset class or your own, and decorate segments with markup - such as a count. -

    -
    -
    -
    -

    -
    -

    - This sample uses overlap: 'darken', so - the depth step shows. The variables go on - .om-root or any ancestor: -

    -
    -
    -
    -
    - Class -
    - - - - - -
    -

    -
    - - - - -
    -
    -
    - -
    -

    Same DOM in every framework

    -
    - - - - -
    -
    -
    -
    - - - - - - - diff --git a/examples/vanilla/main.ts b/examples/vanilla/main.ts deleted file mode 100644 index 45ff4e0..0000000 --- a/examples/vanilla/main.ts +++ /dev/null @@ -1,579 +0,0 @@ -import '@fontsource/literata/latin-400.css'; -import '@fontsource/literata/latin-600.css'; -import '@fontsource/instrument-sans/latin-400.css'; -import '@fontsource/instrument-sans/latin-500.css'; -import '@fontsource/instrument-sans/latin-600.css'; -import '@overlapmark/core/styles.css'; -import type { Highlight, Overlap, Strategy } from '@overlapmark/core'; -import { createHighlighter } from '@overlapmark/dom'; -import { PASSAGE, ownColor, seedAnalyses } from './passage'; -import type { Analysis, AnalysisRange } from './passage'; -import { SNIPPETS } from './snippets'; - -const $ = (id: string): T => { - const el = document.getElementById(id); - if (!el) throw new Error(`#${id} not found`); - return el as T; -}; - -const radios = (name: string): HTMLInputElement[] => [ - ...document.querySelectorAll(`input[name="${name}"]`), -]; - -function esc(s: string): string { - return s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`); -} - -function excerpt(s: string, max: number): string { - const flat = s.replace(/\s+/g, ' ').trim(); - return flat.length > max ? `${flat.slice(0, max - 1).trimEnd()}…` : flat; -} - -// ---- theme ---------------------------------------------------------------- - -type ThemeChoice = 'auto' | 'light' | 'dark'; - -function storedTheme(): ThemeChoice { - try { - const v = localStorage.getItem('om-demo-theme'); - return v === 'light' || v === 'dark' ? v : 'auto'; - } catch { - return 'auto'; - } -} - -let themeChoice: ThemeChoice = storedTheme(); - -// ---- the passage ------------------------------------------------------------ - -const OVERLAP_EXPLAIN: Record = { - multiply: - 'The default. Each layer multiplies with the ones under it, like a highlighter pen drawn over itself, so every extra analysis darkens the spot whatever its color. On a dark background it would also tint light text, which is why the reading cards stay paper-colored in the dark theme.', - darken: 'Each nested layer mixes its own color toward --om-depth-ink by --om-depth-step per level and never blends with the page: predictable for colors of similar lightness, but a pale color inside a saturated one comes out lighter.', - none: 'Plain translucent layers without a depth effect, for when you only need to show where analyses are, not how many.', -}; - -const STRATEGY_EXPLAIN: Record = { - layers: 'Every analysis keeps its own color as a nested layer, and the overlap mode decides how the layers combine.', - depth: 'Each stretch of text gets one color, its first analysis’s, darkened by how many analyses cover it; the overlap mode does not apply.', -}; - -let analyses: AnalysisRange[] = seedAnalyses(); -let ownCount = 0; -let emphasized: string | null = null; -let overlap: Overlap = 'multiply'; -let strategy: Strategy = 'layers'; - -/** What the inspector shows: the analyses under a spot, or a hint. */ -type Inspected = - | { kind: 'none' } - | { kind: 'spot'; start: number; end: number; ids: string[] } - | { kind: 'one'; id: string; added?: boolean }; -let inspected: Inspected = { kind: 'none' }; - -const passageEl = $('passage'); -const legendEl = $('legend'); -const inspectorEl = $('inspector'); -const statusEl = $('status'); -const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)'); -const oneColumn = matchMedia('(max-width: 860px)'); - -/** Says `message` to screen readers through the short live status line. */ -function announce(message: string): void { - statusEl.textContent = message; -} - -/** - * On one column the inspector sits below the passage, often off screen: - * bring its answer into view after a click, Enter or selection. - */ -function revealInspector(): void { - if (!oneColumn.matches) return; - const { top } = inspectorEl.getBoundingClientRect(); - if (top >= 0 && top < innerHeight - 120) return; - inspectorEl.scrollIntoView({ - block: 'start', - behavior: reducedMotion.matches ? 'auto' : 'smooth', - }); -} -const peek = $('peek'); - -function passageHighlights(): Highlight[] { - return analyses.map((a) => ({ - ...a, - color: a.data.color, - className: a.id === emphasized ? 'is-emph' : undefined, - })); -} - -const passage = createHighlighter(passageEl, { - text: PASSAGE, - highlights: passageHighlights(), - overlap, - strategy, - // Screen readers hear the analyses' names after the text. - describe: (covering) => covering.map((h) => h.data?.label).join(', '), -}); - -const byId = (id: string): AnalysisRange | undefined => - analyses.find((a) => a.id === id); - -function swatch(color: string): string { - return ``; -} - -function covered(): Set { - if (inspected.kind === 'spot') return new Set(inspected.ids); - if (inspected.kind === 'one') return new Set([inspected.id]); - return new Set(); -} - -function renderLegend(): void { - const on = covered(); - legendEl.innerHTML = analyses - .map( - (a) => - `
  • `, - ) - .join(''); -} - -function card(a: AnalysisRange): string { - const own = a.data.own - ? `
    ` + - `
    ` - : ''; - return ( - `
  • ${swatch(a.data.color)}${esc(a.data.label)}` + - `

    “${esc(excerpt(PASSAGE.slice(a.start, a.end), 110))}”

    ${own}
  • ` - ); -} - -function renderInspector(): void { - if (inspected.kind === 'none') { - inspectorEl.innerHTML = - '

    Inspector

    Click or tap any highlighted words to see every analysis that covers them.

    '; - return; - } - if (inspected.kind === 'one') { - const a = byId(inspected.id); - if (!a) { - inspected = { kind: 'none' }; - renderInspector(); - return; - } - inspectorEl.innerHTML = - `

    ${esc(a.data.label)}

    ` + - (inspected.added - ? '

    Added from your selection. Rename it or remove it here.

    ' - : '') + - `
      ${card(a)}
    `; - return; - } - const list = inspected.ids - .map(byId) - .filter((a): a is AnalysisRange => a !== undefined); - inspectorEl.innerHTML = - `

    “${esc(excerpt(spotText(inspected), 48))}”

    ` + - `

    ${coverage(list.length)}, outermost first.

    ` + - `
      ${list.map(card).join('')}
    `; -} - -function coverage(n: number): string { - if (n === 0) return 'No analysis covers this spot'; - return n === 1 - ? '1 analysis covers this spot' - : `${n} analyses cover this spot`; -} - -/** - * The text of a clicked spot. A spot of only spaces (between two sentences) - * is widened to the words on either side, so the heading is never empty. - */ -function spotText({ start, end }: { start: number; end: number }): string { - if (PASSAGE.slice(start, end).trim()) return PASSAGE.slice(start, end); - while (start > 0 && /\S/.test(PASSAGE[start - 1]!)) start -= 1; - while (end < PASSAGE.length && /\S/.test(PASSAGE[end]!)) end += 1; - return PASSAGE.slice(start, end); -} - -function sync(): void { - passage.update({ highlights: passageHighlights() }); - renderLegend(); - renderInspector(); -} - -passage.on('click', ({ highlights, segment }) => { - inspected = { - kind: 'spot', - start: segment.start, - end: segment.end, - ids: highlights.map((h) => h.id), - }; - // The inspector now answers; no preview until the pointer moves on. - peekMuted = true; - hidePeek(); - renderLegend(); - renderInspector(); - announce(`${coverage(highlights.length)}.`); - revealInspector(); -}); - -passage.on('select', ({ start, end, text }) => { - window.getSelection()?.removeAllRanges(); - if (!text.trim()) return; - const same = analyses.find((a) => a.start === start && a.end === end); - if (same) { - inspected = { kind: 'one', id: same.id }; - renderLegend(); - renderInspector(); - announce(`${same.data.label} already covers this selection.`); - revealInspector(); - return; - } - ownCount += 1; - const id = `own-${ownCount}`; - analyses = [ - ...analyses, - { - id, - start, - end, - data: { - label: `Your note ${ownCount}`, - color: ownColor(ownCount), - own: true, - }, - }, - ]; - inspected = { kind: 'one', id, added: true }; - sync(); - announce(`Added Your note ${ownCount}.`); - revealInspector(); -}); - -// Hover preview: a small tooltip naming the analyses under the pointer. -let peekMuted = false; -function hidePeek(): void { - peek.hidden = true; -} - -function placePeek(x: number, y: number): void { - const pad = 14; - const { width, height } = peek.getBoundingClientRect(); - const left = Math.min(x + pad, innerWidth - width - 8); - // Above the pointer, so the line being read stays visible. - const top = y - pad - height < 8 ? y + pad : y - pad - height; - peek.style.left = `${Math.max(8, left)}px`; - peek.style.top = `${top}px`; -} - -passage.on('hover', (d) => { - if (d.type === 'leave') { - peekMuted = false; - hidePeek(); - return; - } - if (peekMuted || d.event.buttons) return; - peek.innerHTML = d.highlights - .map( - (h) => - `
    ${h.data ? swatch(h.data.color) : ''}${esc(h.data?.label ?? h.id)}
    `, - ) - .join(''); - peek.hidden = false; - placePeek(d.event.clientX, d.event.clientY); -}); - -passageEl.addEventListener('pointerdown', hidePeek); -passageEl.addEventListener('pointermove', (e) => { - if (!peek.hidden) placePeek(e.clientX, e.clientY); -}); - -// Legend chips: pointing at one outlines its analysis in the text. -function emphasize(id: string | null): void { - if (emphasized === id) return; - emphasized = id; - passage.update({ highlights: passageHighlights() }); -} - -const chipId = (e: Event): string | null => - (e.target as HTMLElement).closest('.chip')?.dataset.id ?? null; - -legendEl.addEventListener('pointerover', (e) => emphasize(chipId(e))); -legendEl.addEventListener('pointerleave', () => emphasize(null)); -legendEl.addEventListener('focusin', (e) => emphasize(chipId(e))); -legendEl.addEventListener('focusout', () => emphasize(null)); -legendEl.addEventListener('click', (e) => { - const id = chipId(e); - if (!id) return; - inspected = { kind: 'one', id }; - renderLegend(); - renderInspector(); - legendEl.querySelector(`[data-id="${id}"]`)?.focus(); -}); - -inspectorEl.addEventListener('click', (e) => { - const id = (e.target as HTMLElement).dataset.remove; - if (!id) return; - const removed = byId(id); - analyses = analyses.filter((a) => a.id !== id); - if (removed) announce(`Removed ${removed.data.label}.`); - if (inspected.kind === 'spot') - inspected = { - ...inspected, - ids: inspected.ids.filter((i) => i !== id), - }; - sync(); -}); - -inspectorEl.addEventListener('input', (e) => { - const input = e.target as HTMLInputElement; - const id = input.dataset.rename; - const a = id && byId(id); - if (!a) return; - a.data = { ...a.data, label: input.value || 'Untitled' }; - // Keep the input (and its caret) alive: refresh everything else. - passage.update({ highlights: passageHighlights() }); - renderLegend(); - const label = input.closest('.card')?.querySelector('.label'); - if (label) label.textContent = a.data.label; - const heading = inspectorEl.querySelector('h3'); - if (heading && inspected.kind === 'one') heading.textContent = a.data.label; -}); - -$('reset').addEventListener('click', () => { - analyses = seedAnalyses(); - ownCount = 0; - inspected = { kind: 'none' }; - sync(); - announce('Analyses reset.'); -}); - -// ---- overlap and strategy toggles -------------------------------------------- - -function renderModes(): void { - $('overlap-explain').textContent = OVERLAP_EXPLAIN[overlap]; - $('strategy-explain').textContent = STRATEGY_EXPLAIN[strategy]; - $('overlap-control').classList.toggle('is-off', strategy === 'depth'); -} - -for (const input of radios('overlap')) - input.addEventListener('change', () => { - overlap = input.value as Overlap; - passage.update({ overlap }); - renderModes(); - }); - -for (const input of radios('strategy')) - input.addEventListener('change', () => { - strategy = input.value as Strategy; - passage.update({ strategy }); - renderModes(); - }); - -// ---- the wordmark: the library drawing its own name ------------------------ - -createHighlighter($('wordmark'), { - text: 'overlapmark', - highlights: [ - { id: 'overlap', start: 0, end: 7, color: '#bcd6ff' }, - { id: 'lapmark', start: 4, end: 11, color: '#ffcadd' }, - ], - focusable: false, -}); - -// ---- styling showcase ---------------------------------------------------------- - -const SAMPLE = - 'Read it once for the argument, again for the evidence, and a third time for what the author leaves out.'; - -const SAMPLE_RANGES: { id: string; part: string; color: string }[] = [ - { id: 's1', part: SAMPLE, color: '#5b9cff' }, - { - id: 's2', - part: 'for the argument, again', - color: '#ff8fb8', - }, - { - id: 's3', - part: 'again for the evidence, and a third time for what the author leaves out', - color: '#4fd49b', - }, - { - id: 's4', - part: 'a third time for what the author leaves out', - color: '#b49bff', - }, - { - id: 's5', - part: 'what the author leaves out', - color: '#ffa64d', - }, - { - id: 's6', - part: 'leaves out', - color: '#ff7a7a', - }, -]; - -const PRESET_EXPLAIN: Record = { - '': 'The stylesheet’s default: a translucent fill per layer.', - 'om-style-marker': - 'om-style-marker paints a brush stroke from --om-brush (the brush option).', - 'om-style-underline': - 'om-style-underline: each nesting level’s underline sits 4px lower.', - 'om-style-box': - 'om-style-box: each nesting level’s box reaches 3px further.', - squiggle: - '.squiggle is a rule of this page: a wavy underline in --om-color, offset by --om-level. Your class rules always win over the stylesheet.', -}; - -let preset = ''; -let badge = true; - -function sampleHighlights(): Highlight[] { - return SAMPLE_RANGES.map(({ id, part, color }) => { - const start = SAMPLE.indexOf(part); - return { - id, - start, - end: start + part.length, - color, - className: preset || undefined, - }; - }); -} - -function countBadge(segment: { depth: number }): Node | null { - if (!badge || segment.depth < 2) return null; - const el = document.createElement('span'); - el.className = 'badge'; - el.textContent = String(segment.depth); - return el; -} - -const sampleEl = $('sample'); -const sample = createHighlighter(sampleEl, { - text: SAMPLE, - highlights: sampleHighlights(), - overlap: 'darken', - decorate: countBadge, -}); - -const knobs: { id: string; prop: string; unit: string }[] = [ - { id: 'alpha', prop: '--om-alpha', unit: '%' }, - { id: 'step', prop: '--om-depth-step', unit: '%' }, - { id: 'max-depth', prop: '--om-max-depth', unit: '' }, -]; - -function renderKnobs(): void { - const lines: string[] = []; - for (const { id, prop, unit } of knobs) { - const input = $(id); - const value = `${input.value}${unit}`; - sampleEl.style.setProperty(prop, value); - const out = input.parentElement?.querySelector('output'); - if (out) out.textContent = value; - lines.push(` ${prop}: ${value};`); - } - $('css-out').textContent = `.om-root {\n${lines.join('\n')}\n}`; -} - -for (const { id } of knobs) $(id).addEventListener('input', renderKnobs); - -for (const input of radios('preset')) - input.addEventListener('change', () => { - preset = input.value; - $('preset-explain').textContent = PRESET_EXPLAIN[preset] ?? ''; - sample.update({ highlights: sampleHighlights() }); - }); - -$('badge').addEventListener('change', (e) => { - badge = (e.target as HTMLInputElement).checked; - // decorate runs on every render: re-render to add or drop the badges. - sample.update({ decorate: countBadge }); -}); - -// ---- framework snippets --------------------------------------------------------- - -// A tablist with roving tabindex: Tab enters at the selected tab, the -// arrow keys, Home and End move between tabs and select them. -const tabs = [...document.querySelectorAll('[role="tab"]')]; -const tabPanel = $('snippet-panel'); - -function showTab(index: number, focus = false): void { - tabs.forEach((tab, i) => { - const selected = i === index; - tab.setAttribute('aria-selected', String(selected)); - tab.tabIndex = selected ? 0 : -1; - if (!selected) return; - tabPanel.setAttribute('aria-labelledby', tab.id); - $('snippet').textContent = SNIPPETS[tab.dataset.tab ?? ''] ?? ''; - if (focus) tab.focus(); - }); -} - -tabs.forEach((tab, i) => { - tab.addEventListener('click', () => showTab(i)); - tab.addEventListener('keydown', (e) => { - const last = tabs.length - 1; - const next = - e.key === 'ArrowRight' - ? (i + 1) % tabs.length - : e.key === 'ArrowLeft' - ? (i + last) % tabs.length - : e.key === 'Home' - ? 0 - : e.key === 'End' - ? last - : -1; - if (next < 0) return; - e.preventDefault(); - showTab(next, true); - }); -}); - -// ---- install line, theme --------------------------------------------------------- - -$('copy').addEventListener('click', async () => { - const button = $('copy'); - try { - await navigator.clipboard.writeText($('install-cmd').textContent ?? ''); - button.textContent = 'Copied'; - } catch { - button.textContent = 'Select and copy'; - } - setTimeout(() => (button.textContent = 'Copy'), 1600); -}); - -function applyTheme(): void { - const root = document.documentElement; - if (themeChoice === 'auto') delete root.dataset.theme; - else root.dataset.theme = themeChoice; - $('theme').textContent = `Theme: ${themeChoice}`; -} - -$('theme').addEventListener('click', () => { - themeChoice = - themeChoice === 'auto' - ? 'light' - : themeChoice === 'light' - ? 'dark' - : 'auto'; - try { - localStorage.setItem('om-demo-theme', themeChoice); - } catch { - // private mode: the choice lasts for this page only - } - applyTheme(); -}); - -renderModes(); -renderKnobs(); -$('preset-explain').textContent = PRESET_EXPLAIN[''] ?? ''; -showTab(0); -applyTheme(); -renderLegend(); -renderInspector(); diff --git a/examples/vanilla/passage.ts b/examples/vanilla/passage.ts deleted file mode 100644 index ba8a2bc..0000000 --- a/examples/vanilla/passage.ts +++ /dev/null @@ -1,118 +0,0 @@ -// The demo's passage and the reader's analyses of it. Every analysis covers -// whole sentences or phrases inside them, so they nest (a key term inside a -// comparison inside the evidence inside the argument) and cross (the -// trade-off starts inside the argument and ends after it). - -export const PASSAGE = - 'Cities that plant trees along their streets tend to report cooler summers. ' + - 'In one survey of forty neighbourhoods, blocks with a full canopy were up to four degrees cooler at street level than bare ones. ' + - 'The effect is not only about shade: leaves release water as they breathe, and that evaporation pulls heat out of the air. ' + - 'Critics point out that a young tree takes decades to mature, so the benefit arrives slowly. ' + - 'Still, few other measures lower the temperature, the energy bill and the noise at once.'; - -export interface Analysis { - label: string; - color: string; - /** Added by the visitor, so it can be renamed and removed. */ - own?: boolean; -} - -interface Seed { - id: string; - label: string; - from: string; - to?: string; - color: string; -} - -const SEEDS: Seed[] = [ - { - id: 'argument', - label: 'Argument', - from: 'Cities that plant', - to: 'out of the air.', - color: '#8dbdff', - }, - { - id: 'hedge', - label: 'Hedge', - from: 'tend to', - color: '#ffc6d9', - }, - { - id: 'evidence', - label: 'Evidence', - from: 'In one survey', - to: 'than bare ones.', - color: '#4fd49b', - }, - { - id: 'comparison', - label: 'Comparison', - from: 'blocks with a full canopy', - to: 'than bare ones', - color: '#b49bff', - }, - { - id: 'term', - label: 'Key term', - from: 'full canopy', - color: '#fff27a', - }, - { - id: 'mechanism', - label: 'Mechanism', - from: 'The effect is', - to: 'out of the air.', - color: '#3fcfe0', - }, - { - id: 'tradeoff', - label: 'Trade-off', - from: 'that evaporation', - to: 'arrives slowly.', - color: '#ffa64d', - }, - { - id: 'objection', - label: 'Objection', - from: 'Critics point out', - to: 'arrives slowly.', - color: '#ff7a7a', - }, - { - id: 'conclusion', - label: 'Conclusion', - from: 'Still, few', - to: 'at once.', - color: '#b5e550', - }, -]; - -/** `[start, end)` of the passage from the start of `from` to the end of `to`. */ -function range(from: string, to = from): { start: number; end: number } { - const start = PASSAGE.indexOf(from); - const last = PASSAGE.indexOf(to, start); - if (start < 0 || last < 0) throw new Error(`"${from}" not in the passage`); - return { start, end: last + to.length }; -} - -export interface AnalysisRange { - id: string; - start: number; - end: number; - data: Analysis; -} - -export function seedAnalyses(): AnalysisRange[] { - return SEEDS.map(({ id, label, from, to, color }) => ({ - id, - ...range(from, to), - data: { label, color }, - })); -} - -/** A fresh, well-spread hue for the visitor's n-th analysis. */ -export function ownColor(n: number): string { - return `hsl(${Math.round((n * 137.5 + 200) % 360)} 90% 72%)`; -} diff --git a/examples/vanilla/style.css b/examples/vanilla/style.css deleted file mode 100644 index f7b0312..0000000 --- a/examples/vanilla/style.css +++ /dev/null @@ -1,634 +0,0 @@ -:root { - --bg: #eef1f6; - --paper: #ffffff; - --ink: #1a1f2b; - --muted: #586174; - --line: #d9dee8; - --soft: #e4e8f0; - --focus: #2453c4; - --code-bg: #f5f7fa; - --serif: 'Literata', Georgia, 'Times New Roman', serif; - --sans: 'Instrument Sans', system-ui, -apple-system, 'Segoe UI', sans-serif; - --mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace; - /* the reading cards' paper, light in both themes (see .page) */ - --sheet: #ffffff; - color-scheme: light; -} - -@media (prefers-color-scheme: dark) { - :root:not([data-theme='light']) { - --bg: #11141a; - --paper: #1a1e26; - --ink: #e6e9ef; - --muted: #9ba4b4; - --line: #2c323d; - --soft: #252a34; - --focus: #8fb0ff; - --code-bg: #151920; - --sheet: #eef0f4; - color-scheme: dark; - } -} - -:root[data-theme='dark'] { - --bg: #11141a; - --paper: #1a1e26; - --ink: #e6e9ef; - --muted: #9ba4b4; - --line: #2c323d; - --soft: #252a34; - --focus: #8fb0ff; - --code-bg: #151920; - --sheet: #eef0f4; - color-scheme: dark; -} - -* { - box-sizing: border-box; -} - -body { - margin: 0; - background: var(--bg); - color: var(--ink); - font: 16px/1.55 var(--sans); - -webkit-text-size-adjust: 100%; -} - -a { - color: inherit; - text-decoration-color: var(--muted); - text-underline-offset: 3px; -} - -a:hover { - text-decoration-color: currentColor; -} - -:focus-visible { - outline: 2px solid var(--focus); - outline-offset: 2px; -} - -code, -pre { - font-family: var(--mono); - font-size: 0.875em; -} - -h2 { - font-size: 1.5rem; - line-height: 1.25; - font-weight: 600; - margin: 0 0 0.5rem; -} - -.visually-hidden { - position: absolute; - width: 1px; - height: 1px; - overflow: hidden; - clip-path: inset(50%); - white-space: nowrap; -} - -button { - font: inherit; - color: inherit; - cursor: pointer; -} - -.quiet { - background: transparent; - border: 1px solid var(--line); - border-radius: 6px; - padding: 0.3rem 0.7rem; - font-size: 0.875rem; -} - -.quiet:hover { - background: var(--soft); -} - -/* ---- intro ------------------------------------------------------------ */ - -.intro, -main, -.foot { - max-width: 1120px; - margin: 0 auto; - padding: 0 16px; -} - -.intro { - position: relative; - padding-top: 3rem; - padding-bottom: 2rem; -} - -.theme { - position: absolute; - top: 1rem; - right: 16px; -} - -.wordmark { - /* every letter is under a light mark, so the ink stays dark in both themes */ - color: #1a1f2b; - font-family: var(--serif); - font-weight: 600; - font-size: clamp(2.75rem, 9vw, 4.75rem); - line-height: 1.1; - letter-spacing: -0.02em; - margin: 0 0 1rem; -} - -.wordmark { - /* opaque marks: they read as paper stickers on either theme */ - --om-alpha: 100%; -} - -.wordmark .om-hl { - padding: 0 0.03em; - border-radius: 0.06em; - cursor: default; -} - -.pitch { - font-size: clamp(1.125rem, 2.4vw, 1.375rem); - line-height: 1.45; - max-width: 36em; - margin: 0 0 1.25rem; -} - -.install { - display: inline-flex; - max-width: 100%; - align-items: center; - gap: 0.75rem; - background: var(--paper); - border: 1px solid var(--line); - border-radius: 8px; - padding: 0.5rem 0.5rem 0.5rem 0.9rem; - margin-bottom: 1.25rem; -} - -.install code { - overflow-x: auto; - white-space: nowrap; -} - -.links { - display: flex; - flex-wrap: wrap; - gap: 0.4rem 1.25rem; - font-size: 0.9375rem; -} - -/* ---- controls ----------------------------------------------------------- */ - -.controls { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 1rem 2rem; - margin-bottom: 1.25rem; -} - -.control { - border: 0; - padding: 0; - margin: 0; - min-width: 0; -} - -.control legend { - font-weight: 600; - font-size: 0.9375rem; - padding: 0; - margin-bottom: 0.4rem; -} - -.segmented { - display: inline-flex; - background: var(--soft); - border-radius: 8px; - padding: 3px; - gap: 2px; -} - -.segmented.wrap { - flex-wrap: wrap; -} - -.segmented label { - position: relative; -} - -.segmented input { - position: absolute; - opacity: 0; - inset: 0; - margin: 0; - cursor: pointer; -} - -.segmented span { - display: block; - padding: 0.35rem 0.85rem; - border-radius: 6px; - font-size: 0.9375rem; - color: var(--muted); -} - -.segmented input:checked + span { - background: var(--paper); - color: var(--ink); - font-weight: 500; - box-shadow: 0 0 0 1px var(--line); -} - -.segmented input:focus-visible + span { - outline: 2px solid var(--focus); - outline-offset: 1px; -} - -.control.is-off .segmented { - opacity: 0.55; -} - -.explain { - color: var(--muted); - font-size: 0.9375rem; - margin: 0.5rem 0 0; - max-width: 38em; -} - -/* ---- the reader ------------------------------------------------------------ */ - -.layout { - display: grid; - grid-template-columns: minmax(0, 1fr) 320px; - gap: 1.5rem; - align-items: start; -} - -/* - * The reading cards are paper in both themes: multiply darkens on a light - * backdrop, and on a dark one it would also tint the light text. Inside a - * card the tokens take their light values. - */ -.page { - --ink: #1a1f2b; - --muted: #586174; - --line: #d9dee8; - --soft: #e4e8f0; - --focus: #2453c4; - --paper: var(--sheet); - color-scheme: light; - color: var(--ink); - background: var(--paper); - border: 1px solid var(--line); - border-radius: 10px; - padding: 1.75rem 2rem; -} - -.passage { - font-family: var(--serif); - font-size: 1.25rem; - line-height: 1.75; - margin: 0; - max-width: 36em; -} - -/* a softer focus ring than the stylesheet's currentColor one */ -.om-root .om-hl:focus-visible { - outline: 2px solid var(--focus); - outline-offset: 2px; -} - -/* the analysis a legend chip points at */ -.om-root .om-hl.is-emph { - outline: 2px solid var(--ink); - outline-offset: 1px; -} - -.legend { - list-style: none; - padding: 0; - margin: 1.5rem 0 0; - display: flex; - flex-wrap: wrap; - gap: 0.4rem; -} - -.chip { - display: inline-flex; - align-items: center; - gap: 0.45rem; - border: 1px solid var(--line); - border-radius: 999px; - background: transparent; - padding: 0.2rem 0.7rem 0.2rem 0.45rem; - font-size: 0.875rem; -} - -.chip:hover { - background: var(--soft); -} - -.chip.is-covering { - border-color: var(--ink); - background: var(--soft); -} - -.swatch { - flex: none; - width: 0.9rem; - height: 0.9rem; - border-radius: 4px; - box-shadow: inset 0 0 0 1px rgb(0 0 0 / 0.12); -} - -.inspector { - scroll-margin-top: 12px; - background: var(--paper); - border: 1px solid var(--line); - border-radius: 10px; - padding: 1.25rem; -} - -.inspector h3 { - font-size: 1rem; - margin: 0 0 0.75rem; -} - -.inspector .empty { - color: var(--muted); - margin: 0; -} - -.cards { - list-style: none; - margin: 0; - padding: 0; - display: grid; - gap: 0.75rem; -} - -.card { - display: grid; - grid-template-columns: auto minmax(0, 1fr); - gap: 0.15rem 0.6rem; - align-items: baseline; -} - -.card .swatch { - align-self: center; -} - -.card .label { - font-weight: 600; -} - -.card .quote { - grid-column: 2; - color: var(--muted); - font-family: var(--serif); - font-size: 0.9375rem; - line-height: 1.45; - margin: 0; -} - -.card .own { - grid-column: 2; - display: flex; - gap: 0.5rem; - margin-top: 0.35rem; -} - -.card .own input { - flex: 1; - min-width: 0; - font: inherit; - font-size: 0.875rem; - color: inherit; - background: var(--bg); - border: 1px solid var(--line); - border-radius: 6px; - padding: 0.25rem 0.5rem; -} - -.note { - margin: 0 0 0.75rem; - font-size: 0.9375rem; -} - -.hint { - color: var(--muted); - font-size: 0.875rem; - border-top: 1px solid var(--line); - margin: 1.25rem 0 0.75rem; - padding-top: 0.9rem; -} - -.touch-only { - display: none; -} - -@media (hover: none) { - .pointer-only { - display: none; - } - .touch-only { - display: inline; - } -} - -.peek { - position: fixed; - z-index: 10; - pointer-events: none; - background: var(--ink); - color: var(--paper); - border-radius: 6px; - padding: 0.35rem 0.6rem; - font-size: 0.8125rem; - line-height: 1.5; - max-width: 260px; -} - -.peek .row { - display: flex; - align-items: center; - gap: 0.4rem; -} - -.peek .swatch { - width: 0.7rem; - height: 0.7rem; - box-shadow: none; -} - -/* ---- styling showcase --------------------------------------------------- */ - -.styling, -.code { - margin-top: 4rem; -} - -.lede { - color: var(--muted); - max-width: 38em; - margin: 0 0 1.5rem; -} - -.styling-grid { - display: grid; - grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); - gap: 1.5rem; - align-items: start; -} - -.sample { - font-family: var(--serif); - font-size: 1.25rem; - line-height: 2.1; - margin: 0; -} - -.knobs, -.sample-col { - display: grid; - gap: 0.9rem; -} - -.slider { - display: grid; - grid-template-columns: 9.5rem minmax(0, 1fr) 3rem; - align-items: center; - gap: 0.75rem; - font-family: var(--mono); - font-size: 0.875rem; -} - -.slider input { - width: 100%; - accent-color: var(--focus); -} - -.slider output { - text-align: right; -} - -.check { - display: flex; - align-items: center; - gap: 0.5rem; - font-size: 0.9375rem; -} - -.check input { - accent-color: var(--focus); - width: 1rem; - height: 1rem; -} - -.css, -.snippet { - margin: 0; - background: var(--code-bg); - border: 1px solid var(--line); - border-radius: 8px; - padding: 0.9rem 1rem; - overflow-x: auto; - line-height: 1.55; -} - -/* the count badge from decorate */ -.badge { - display: inline-block; - font-family: var(--sans); - font-size: 0.6em; - font-weight: 600; - line-height: 1; - vertical-align: super; - margin: 0 0.25em 0 0.15em; - padding: 0.15em 0.35em; - border-radius: 999px; - background: var(--ink); - color: var(--paper); -} - -/* "Your class": any class you pass in highlight.className */ -.om-root .om-hl.squiggle { - background: none; - text-decoration: underline wavy var(--om-color); - text-decoration-thickness: 2px; - text-underline-offset: calc(4px + var(--om-level) * 5px); -} - -/* ---- code tabs -------------------------------------------------------------- */ - -.tabs { - display: flex; - flex-wrap: wrap; - gap: 0.25rem; - margin: 1rem 0 0.75rem; -} - -.tabs button { - background: transparent; - border: 1px solid transparent; - border-radius: 6px; - padding: 0.3rem 0.8rem; - color: var(--muted); -} - -.tabs button[aria-selected='true'] { - color: var(--ink); - border-color: var(--line); - background: var(--paper); - font-weight: 500; -} - -.foot { - color: var(--muted); - font-size: 0.875rem; - padding-top: 3rem; - padding-bottom: 3rem; -} - -/* ---- narrow screens ------------------------------------------------------ */ - -@media (max-width: 860px) { - .layout, - .styling-grid { - grid-template-columns: minmax(0, 1fr); - } -} - -@media (max-width: 640px) { - .intro { - padding-top: 3.5rem; - } - .controls { - grid-template-columns: minmax(0, 1fr); - } - .page { - padding: 1.25rem; - } - .install code { - white-space: normal; - } - .passage, - .sample { - font-size: 1.125rem; - } - .slider { - grid-template-columns: minmax(0, 1fr) 3rem; - } - .slider input { - grid-column: 1 / -1; - grid-row: 2; - } -} diff --git a/examples/vanilla/tsconfig.json b/examples/vanilla/tsconfig.json deleted file mode 100644 index de3c6fd..0000000 --- a/examples/vanilla/tsconfig.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": [ - "../../tsconfig.base.json", - "../../tsconfig.workspace-paths.json" - ], - "compilerOptions": { - "types": ["vite/client"] - }, - "include": ["*.ts"] -} diff --git a/examples/vanilla/vite.config.ts b/examples/vanilla/vite.config.ts deleted file mode 100644 index c1aa6fd..0000000 --- a/examples/vanilla/vite.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { defineConfig } from 'vite'; -import { workspaceAliases } from '../../vitest.workspace-aliases.ts'; - -// The workspace packages resolve to their sources, so the demo runs without -// building them first. The Pages build serves it from a subpath with -// `vite build --base /overlapmark/` (see .github/workflows/pages.yml); every -// other build keeps the default base. -export default defineConfig({ - resolve: { alias: workspaceAliases }, -}); diff --git a/packages/core/README.md b/packages/core/README.md index 3ffa23e..cd964ed 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -1,6 +1,6 @@ # @overlapmark/core -Framework-agnostic core of [overlapmark](https://github.com/edonghyun/overlapmark#readme): segment computation, text search, the types and event details, DOM offset helpers and the default stylesheet. Overlapping highlights get darker, and a click reports every highlight covering that spot. **[Live demo](https://edonghyun.github.io/overlapmark/)** +Framework-agnostic core of [overlapmark](https://github.com/edonghyun/overlapmark#readme): segment computation, text search, the types and event details, DOM offset helpers and the default stylesheet. Overlapping highlights get darker, and a click reports every highlight covering that spot. **[Live demo](https://edonghyun.github.io/overlapmark/)** · **[Docs](https://edonghyun.github.io/overlapmark/docs/)** Most apps want [`@overlapmark/dom`](https://www.npmjs.com/package/@overlapmark/dom) or a framework adapter ([`@overlapmark/vue`](https://www.npmjs.com/package/@overlapmark/vue), [`@overlapmark/react`](https://www.npmjs.com/package/@overlapmark/react), [`@overlapmark/svelte`](https://www.npmjs.com/package/@overlapmark/svelte)) and install this package next to it for the stylesheet and the types. diff --git a/packages/dom/README.md b/packages/dom/README.md index 3b19767..2190aaf 100644 --- a/packages/dom/README.md +++ b/packages/dom/README.md @@ -1,6 +1,6 @@ # @overlapmark/dom -Vanilla JS adapter for [overlapmark](https://github.com/edonghyun/overlapmark#readme): render overlapping text highlights into any element and listen to selections and clicks. Overlapping highlights get darker, and a click reports every highlight covering that spot. Depends only on [`@overlapmark/core`](https://www.npmjs.com/package/@overlapmark/core). **[Live demo](https://edonghyun.github.io/overlapmark/)** +Vanilla JS adapter for [overlapmark](https://github.com/edonghyun/overlapmark#readme): render overlapping text highlights into any element and listen to selections and clicks. Overlapping highlights get darker, and a click reports every highlight covering that spot. Depends only on [`@overlapmark/core`](https://www.npmjs.com/package/@overlapmark/core). **[Live demo](https://edonghyun.github.io/overlapmark/)** · **[Docs](https://edonghyun.github.io/overlapmark/docs/)** Install `@overlapmark/core` next to it: you import its stylesheet and types yourself. diff --git a/packages/react/README.md b/packages/react/README.md index 5a6f245..deda832 100644 --- a/packages/react/README.md +++ b/packages/react/README.md @@ -1,6 +1,6 @@ # @overlapmark/react -React component for overlapmark: render overlapping text highlights and listen to selections, clicks and hovers. Built on [`@overlapmark/core`](https://www.npmjs.com/package/@overlapmark/core); renders the same DOM as [`@overlapmark/dom`](https://www.npmjs.com/package/@overlapmark/dom). Overlapping highlights get darker, and a click reports every highlight covering that spot: see the [overlapmark README](https://github.com/edonghyun/overlapmark#readme) and the **[live demo](https://edonghyun.github.io/overlapmark/)**. +React component for overlapmark: render overlapping text highlights and listen to selections, clicks and hovers. Built on [`@overlapmark/core`](https://www.npmjs.com/package/@overlapmark/core); renders the same DOM as [`@overlapmark/dom`](https://www.npmjs.com/package/@overlapmark/dom). Overlapping highlights get darker, and a click reports every highlight covering that spot: see the [overlapmark README](https://github.com/edonghyun/overlapmark#readme) the **[live demo](https://edonghyun.github.io/overlapmark/)** and the **[docs](https://edonghyun.github.io/overlapmark/docs/)**. ```sh npm install @overlapmark/react @overlapmark/core diff --git a/packages/svelte/README.md b/packages/svelte/README.md index 5fa909c..4bec208 100644 --- a/packages/svelte/README.md +++ b/packages/svelte/README.md @@ -1,6 +1,6 @@ # @overlapmark/svelte -Svelte 5 component for overlapmark: render overlapping text highlights and listen to selections, clicks and hovers. Built on [`@overlapmark/core`](https://www.npmjs.com/package/@overlapmark/core); renders the same DOM as [`@overlapmark/dom`](https://www.npmjs.com/package/@overlapmark/dom). Overlapping highlights get darker, and a click reports every highlight covering that spot: see the [overlapmark README](https://github.com/edonghyun/overlapmark#readme) and the **[live demo](https://edonghyun.github.io/overlapmark/)**. +Svelte 5 component for overlapmark: render overlapping text highlights and listen to selections, clicks and hovers. Built on [`@overlapmark/core`](https://www.npmjs.com/package/@overlapmark/core); renders the same DOM as [`@overlapmark/dom`](https://www.npmjs.com/package/@overlapmark/dom). Overlapping highlights get darker, and a click reports every highlight covering that spot: see the [overlapmark README](https://github.com/edonghyun/overlapmark#readme) the **[live demo](https://edonghyun.github.io/overlapmark/)** and the **[docs](https://edonghyun.github.io/overlapmark/docs/)**. ```sh npm install @overlapmark/svelte @overlapmark/core diff --git a/packages/vue/README.md b/packages/vue/README.md index c43d7c8..1d779cf 100644 --- a/packages/vue/README.md +++ b/packages/vue/README.md @@ -1,6 +1,6 @@ # @overlapmark/vue -Vue 3 component for overlapmark: render overlapping text highlights and listen to selections, clicks and hovers. Built on [`@overlapmark/core`](https://www.npmjs.com/package/@overlapmark/core); renders the same DOM as [`@overlapmark/dom`](https://www.npmjs.com/package/@overlapmark/dom). Overlapping highlights get darker, and a click reports every highlight covering that spot: see the [overlapmark README](https://github.com/edonghyun/overlapmark#readme) and the **[live demo](https://edonghyun.github.io/overlapmark/)**. +Vue 3 component for overlapmark: render overlapping text highlights and listen to selections, clicks and hovers. Built on [`@overlapmark/core`](https://www.npmjs.com/package/@overlapmark/core); renders the same DOM as [`@overlapmark/dom`](https://www.npmjs.com/package/@overlapmark/dom). Overlapping highlights get darker, and a click reports every highlight covering that spot: see the [overlapmark README](https://github.com/edonghyun/overlapmark#readme) the **[live demo](https://edonghyun.github.io/overlapmark/)** and the **[docs](https://edonghyun.github.io/overlapmark/docs/)**. ```sh npm install @overlapmark/vue @overlapmark/core diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b72d67f..b71d0d6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -78,25 +78,6 @@ importers: specifier: ^5.0.5 version: 5.0.5(@types/node@22.20.5)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(yaml@2.9.1)) - examples/vanilla: - dependencies: - '@overlapmark/core': - specifier: workspace:* - version: link:../../packages/core - '@overlapmark/dom': - specifier: workspace:* - version: link:../../packages/dom - devDependencies: - '@fontsource/instrument-sans': - specifier: ^5.3.0 - version: 5.3.0 - '@fontsource/literata': - specifier: ^5.3.0 - version: 5.3.0 - vite: - specifier: ^8 - version: 8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(yaml@2.9.1) - packages/adapter-contract: dependencies: vitest: @@ -188,6 +169,25 @@ importers: specifier: ^3.3.13 version: 3.3.13(typescript@6.0.3) + site: + dependencies: + '@overlapmark/core': + specifier: workspace:* + version: link:../packages/core + '@overlapmark/dom': + specifier: workspace:* + version: link:../packages/dom + devDependencies: + '@fontsource/inter': + specifier: ^5.3.0 + version: 5.3.0 + '@fontsource/jetbrains-mono': + specifier: ^5.3.0 + version: 5.3.0 + vite: + specifier: ^8 + version: 8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(yaml@2.9.1) + packages: '@andrewbranch/untar.js@1.0.4': @@ -499,11 +499,11 @@ packages: resolution: {integrity: sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} - '@fontsource/instrument-sans@5.3.0': - resolution: {integrity: sha512-QwXc4hb/px3XvSPS2CPAOgey8nyrQFxgxrmXQQ+pN+P51hKdAcchxpg8rSbjANFfPu6VKXhDqkVDucXMZ9CM5g==} + '@fontsource/inter@5.3.0': + resolution: {integrity: sha512-RofMylZmjlJEfELXeNHFWBRcSs75rGU/6bV2S2jfnvv/3rPXPGe0LgUJTklcHZ9lM4OZmAVFhcJPnACfb91A3g==} - '@fontsource/literata@5.3.0': - resolution: {integrity: sha512-9JGMT5+YfBK49thoMq9ASaMRJErHT4V4QuMhAEwKHRLreOsIMP2xP6ZRLhPJ0e6YlET+kjWTJuN7LAxt9/gWGQ==} + '@fontsource/jetbrains-mono@5.3.0': + resolution: {integrity: sha512-fqDfB5I9f1p1TV486aUgB9t8zP84P0O1FtQR5Ol9vjwPy+S+EIGlVYm1cvj2W5shcZMTg2nZFdVMoH5wFu8a1A==} '@humanfs/core@0.19.2': resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} @@ -2489,9 +2489,9 @@ snapshots: '@eslint/core': 1.2.1 levn: 0.4.1 - '@fontsource/instrument-sans@5.3.0': {} + '@fontsource/inter@5.3.0': {} - '@fontsource/literata@5.3.0': {} + '@fontsource/jetbrains-mono@5.3.0': {} '@humanfs/core@0.19.2': dependencies: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index f65dc03..5287661 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,3 +1,3 @@ packages: - 'packages/*' - - 'examples/*' + - 'site' diff --git a/scripts/render-doc-images.ts b/scripts/render-doc-images.ts index b5869e8..f2418b9 100644 --- a/scripts/render-doc-images.ts +++ b/scripts/render-doc-images.ts @@ -1,6 +1,6 @@ -// Renders the README images into docs-assets/ from the built demo -// (examples/vanilla): one per overlap mode and a hero of the inspector. -// Run with `pnpm docs:images`. The pages are captured in the light theme at +// Renders the README images into docs-assets/ from the built site (site/): +// one per overlap mode, from the docs page's overlap examples, and a hero of +// the demo's opening. Run with `pnpm docs:images`. The pages are captured at // twice the pixel density. The mode images are white cards on a transparent // page and the hero carries the page's own background, so both read on // GitHub's light and dark themes; each is re-encoded as a palette PNG. @@ -14,12 +14,12 @@ import { preview } from 'vite'; import { toPalettePng } from './palette-png.ts'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); -const demo = join(root, 'examples/vanilla'); +const demo = join(root, 'site'); const out = join(root, 'docs-assets'); const MODES = ['multiply', 'darken', 'none'] as const; -execFileSync('pnpm', ['--filter', 'vanilla-example', 'build'], { +execFileSync('pnpm', ['--filter', 'overlapmark-site', 'build'], { cwd: root, stdio: 'inherit', }); @@ -36,7 +36,7 @@ if (!url) throw new Error('the demo preview server has no local URL'); const browser = await chromium.launch(); const errors: string[] = []; -async function open(width: number): Promise { +async function open(path: string, width: number): Promise { const page = await browser.newPage({ viewport: { width, height: 1200 }, deviceScaleFactor: 2, @@ -46,7 +46,7 @@ async function open(width: number): Promise { if (m.type() === 'error') errors.push(m.text()); }); page.on('pageerror', (e) => errors.push(e.message)); - await page.goto(url!, { waitUntil: 'networkidle' }); + await page.goto(new URL(path, url).href, { waitUntil: 'networkidle' }); await page.evaluate(async () => { await document.fonts.ready; // Transparent around the cards, so their rounded corners show. @@ -65,58 +65,35 @@ async function save(name: string, png: Buffer): Promise { mkdirSync(out, { recursive: true }); try { - const page = await open(760); + const docs = await open('docs/', 760); for (const mode of MODES) { - await page - .locator(`input[name="overlap"][value="${mode}"]`) - .check({ force: true }); - // A caption naming the mode, inside the card the image shows. - await page.evaluate((mode) => { - const card = document.getElementById('page')!; - let caption = card.querySelector('.shot-caption'); - if (!caption) { - caption = document.createElement('p'); - caption.className = 'shot-caption'; - caption.style.cssText = - 'margin:0 0 1rem;font:600 0.9375rem/1.4 var(--sans);color:var(--muted)'; - card.prepend(caption); - } - caption.textContent = `overlap: '${mode}'`; - }, mode); await save( `overlap-${mode}.png`, - await page - .locator('#page') + await docs + .locator(`#ex-modes [data-mode="${mode}"]`) .screenshot({ omitBackground: true, animations: 'disabled' }), ); } - await page.close(); + await docs.close(); - // Hero: the wordmark, the pitch and the inspector naming the four - // analyses under "full canopy", on the page's own background. - const hero = await open(1100); + // Hero: the title, the pitch, the buttons and the seeded sentence with + // its status line, on the page's own background. + const hero = await open('', 1100); await hero.evaluate(() => { document.documentElement.style.background = ''; document.body.style.background = ''; - for (const el of document.querySelectorAll( - '.theme, .install, .links, .controls, .hint, #reset', - )) - el.style.display = 'none'; }); - await hero.locator('#passage .om-seg', { hasText: 'full canopy' }).click(); - await hero.mouse.move(0, 0); - await hero.waitForSelector('#inspector .cards'); const top = (await hero.locator('.intro').boundingBox())!; - const bottom = (await hero.locator('.layout').boundingBox())!; + const bottom = (await hero.locator('#hero-status').boundingBox())!; await save( 'hero.png', await hero.screenshot({ animations: 'disabled', clip: { - x: 0, - y: top.y + 8, - width: 1100, - height: bottom.y + bottom.height + 32 - (top.y + 8), + x: top.x - 24, + y: top.y + 32, + width: top.width + 48, + height: bottom.y + bottom.height + 24 - (top.y + 32), }, }), ); diff --git a/site/docs/index.html b/site/docs/index.html new file mode 100644 index 0000000..f34b3a8 --- /dev/null +++ b/site/docs/index.html @@ -0,0 +1,535 @@ + + + + + + overlapmark docs + + + + +
    + overlapmark + +
    + +
    + + +
    +

    Docs

    +

    + overlapmark renders a text once, cut into segments, with one + nested <mark> per highlight. The more + highlights cover a spot, the darker it gets, and a click + reports every highlight under it. The same options and + events work in vanilla JS, Vue, React and Svelte. +

    + +
    +

    Usage

    +

    + Install the adapter for your framework, plus core for + the stylesheet and types: +

    +
    +
    npm install @overlapmark/dom @overlapmark/core      # vanilla JS
    +npm install @overlapmark/vue @overlapmark/core      # Vue 3.3+
    +npm install @overlapmark/react @overlapmark/core    # React 18+
    +npm install @overlapmark/svelte @overlapmark/core   # Svelte 5+
    +
    +

    + Then render the text with its highlights. A selection + adds a highlight; a click lists the highlights under it. +

    +
    +

    + The quick starts use crypto.randomUUID() + for ids, which browsers only offer on HTTPS or + localhost. To highlight search results + instead of selections, + findMatches(text, query) from + @overlapmark/core returns + { start, end }[]. +

    +

    + In Vue the events are @select, + @click, @dblclick and + @hover; in React onSelect, + onClick, onDblClick and + onHover; in Svelte onselect, + onclick, ondblclick and + onhover. Each receives the same detail + object as in vanilla JS, not a framework or DOM event. +

    +
    + +
    +

    Highlight

    +

    + A highlight is a plain object, + Highlight<T> from + @overlapmark/core: +

    +
    +
    +
    +

    + Ranges are normalised before rendering: a non-integer, + empty or reversed range is dropped, and a range outside + the text is clamped to it, each with a dev warning. A + range that splits a surrogate pair is widened to the + whole character. Duplicate ids and ids with whitespace + also get a warning. +

    +

    + findMatches(text, query, options?) finds + literal occurrences of a string or an array of strings. + Options: caseSensitive (default + false), overlapping (default + true) and wholeWord (default + false). +

    +
    + +
    +

    createHighlighter

    +
    +
    createHighlighter<T>(el: HTMLElement, options: HighlighterOptions<T>): Highlighter<T>
    +
    +

    + From @overlapmark/dom. It replaces the + content of el with the rendered text, adds + the om-root class and sets + data-om-strategy and + data-om-overlap. The Vue, React and Svelte + Highlighter components take the same + options as props. +

    +
    +
    +
    +

    + update() restores a selection at the same + text offsets, unless the text changed, and gives a + focused highlight its focus back on the re-rendered + element. +

    +
    + +
    +

    Options

    +

    + Options of createHighlighter, or props of + the components: +

    +
    +
    +
    +
    + +
    +

    Events

    +
    +
    +
    +

    + The detail types are SelectDetail, + PointDetail and + HoverDetail from + @overlapmark/core. + highlights in every event follow the + library order: start ascending, then longer + first, then input order. Try it: hover, click, + double-click or select below. +

    +
    +
    +
      +
      +
      + +
      +

      Overlap modes

      +

      + With the default layers strategy, each + highlight covering a segment is its own nested + <mark>. The overlap + option decides how those layers combine. It only sets + data-om-overlap on the root; the stylesheet + does the rest. The depth strategy paints + one color per segment, darkened by its overlap count, + and ignores overlap. +

      +
      +
      +
      + overlap: 'multiply' +
      +
      +
      +
      +
      + overlap: 'darken' +
      +
      +
      +
      +
      overlap: 'none'
      +
      +
      +
      +
      +
      multiply (default)
      +
      + Each layer multiplies with the layers under it + (mix-blend-mode: multiply), like a + highlighter pen drawn over itself, so every + highlight darkens the spot it covers, for any color + except pure white. The root is isolated, so layers + never blend with the page behind it. Use it on a + light background. A nested layer also tints its own + text and decorations, and on a dark background + pastels fade and light text loses contrast. Mixing + hues from opposite sides of the color wheel turns + stacks gray-brown, so prefer neighbouring hues for + highlights that overlap. +
      +
      darken
      +
      + Each layer takes its own color mixed toward + --om-depth-ink by + --om-depth-step per nesting level, up + to --om-max-depth, painted at + --om-alpha. No blend mode, so text is + never tinted. It darkens reliably only when the + colors have similar lightness: a pale color nested + in a saturated one still comes out lighter. Use it + for dark themes or wherever blending is unwanted. +
      +
      none
      +
      + Plain translucent layers with no depth effect. Use + it when the overlap should not stand out, or when + you draw depth yourself from + [data-om-depth] or + --om-level. +
      +
      +

      + For dark themes, keep a light reading surface, or switch + to darken with deeper colors: +

      +
      +
      /* Option 1: the default multiply mode on a light reading surface. */
      +.article {
      +    background: #fbf8f1;
      +    color: #1d1d1f;
      +}
      +
      +/* Option 2: overlap: 'darken' with deeper colors on the dark page. */
      +@media (prefers-color-scheme: dark) {
      +    .article {
      +        --om-default-color: #6d5bd0;
      +        --om-alpha: 70%;
      +        --om-depth-ink: black;
      +    }
      +}
      +
      +
      + +
      +

      Styling

      +

      + Import @overlapmark/core/styles.css, then + style at three levels. Every library selector is wrapped + in :where(), so your own class rules always + win. You can also skip the stylesheet and style the DOM + yourself; keep a visible focus style if you do. +

      +

      1. Theme variables

      +

      Set them on .om-root or any ancestor:

      +
      +
      +
      +

      2. Per highlight

      +

      + Give a highlight a color and a + className, such as a preset: +

      +
      +

      + The presets are made for the layers + strategy, where nesting shows. Write your own CSS + against these classes and attributes: +

      +
      +
      +
      +

      3. Decorations

      +

      + Add presentational markup after the text of each + highlighted segment, such as an overlap count. It goes + in + <span data-om-skip aria-hidden="true">, stays out of offsets, selections and copies, and must + not contain anything focusable. +

      +
      +
      createHighlighter(el, {
      +    text,
      +    highlights,
      +    decorate: (segment) => (segment.depth > 1 ? `×${segment.depth}` : null),
      +});
      +
      +
      + +
      +

      Accessibility

      +
        +
      • + Keyboard. With + focusable: true, the default, every + highlighted segment is a Tab stop, and Enter or + Space reports click. Tab stops are per + segment, not per highlight, so for densely annotated + text set focusable: false + and offer another way in, such as a list. +
      • +
      • + Screen readers. A focusable segment + is role="button" with an + aria-description from + describe, "2 highlights" by default. It + is an attribute, so it never enters the text or the + offsets. aria-description is from the + ARIA 1.3 draft; older Safari with VoiceOver may not + announce it. +
      • +
      • + Decorations are + aria-hidden: put what matters in + describe. +
      • +
      • + Forced colors. Highlights are + painted in the system Mark colors with + an outline, and depth shows through the outlines of + nested highlights. +
      • +
      +
      + +
      +

      Server rendering

      +

      + The main entry of @overlapmark/core reads + no window or document, so it + runs on the server. The Vue, React and Svelte components + render the same markup on the server as on the client + and hydrate on it. Import + @overlapmark/core/styles.css on both sides. +

      +

      + @overlapmark/react starts with + 'use client'. In React Server Components, a + Server Component can render + Highlighter with plain props, but when you + pass functions (handlers, describe, + brush, renderDecoration), + render it from a Client Component of your own. +

      +
      + +
      +

      Shadow DOM and iframes

      +

      + The root may sit inside an open shadow root or in an + iframe's document: selection, focus and offsets are read + from the root's own tree and window. +

      +
        +
      • + In a closed shadow root in Chromium, a drag that + starts on a focusable highlight's first character + selects nothing. Closed shadow roots are not tested. +
      • +
      • Slotted content in the root is not supported.
      • +
      +
      + +
      +

      Limitations

      +
        +
      • + Browsers. The stylesheet needs + color-mix(): Chrome and Edge 111, + Firefox 113, Safari 16.2. Without it highlights have + no fill. The acceptance tests run in Playwright's + Chromium, Firefox and WebKit, desktop and emulated + Pixel 7 and iPhone 15; no real device is tested. +
      • +
      • + Framework versions. React 18+, Vue + 3.3+ and Svelte 5+. The lowest versions run a + reduced suite. On Svelte 5.0, esrap 1.4 or later + fails to compile TypeScript components (Not implemented type annotation); the tests pin esrap to 1.2.3 for Svelte 5.0.5, + so pin it if you see that error. +
      • +
      • + Ctrl+drag that starts on a + focusable highlight's first character selects + nothing in Chromium. Start the drag elsewhere, or + set focusable: false. +
      • +
      • + Modules. The Vue, React and Svelte + adapters ship ES modules only; core and dom ship ES + modules and CommonJS. +
      • +
      • + Svelte. Every highlighted segment + gets a decoration container when a + decoration snippet is given, and + highlights held in deep $state arrive + in events as state proxies; use + $state.raw to compare with + ===. +
      • +
      +

      + The full list is in the + README. +

      +
      + +
      +

      Migrating from vue-easy-highlight

      +

      + overlapmark replaces vue-easy-highlight. In + Vue, render Highlighter from + @overlapmark/vue, compute the ranges + yourself and pass them as highlights with + ids. +

      +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      vue-easy-highlight 0.1.14overlapmark
      texttext
      + textsToHighlight (a Set) + + highlights from + findMatches(text, [...set], { + overlapping: false }), each with an id +
      baseColor + defaultColor, or + --om-default-color +
      textsBaseColorMap + color on each highlight +
      + selectedTextColor, + selectedTextBackgroundColor + + Your CSS: + .om-root ::selection { … } +
      @text:selected + @select="({ text, rect, start, end + }) => …" +
      @text:clicked + @click="({ event, offset, segment, + highlights }) => …" +
      +
      +

      + The old one-color-per-character darkening is closest to + strategy="depth". The old + text:selected skipped selections shorter + than 2 characters: use + :min-selection-length="2". +

      +
      +
      +
      + + + + diff --git a/site/e2e/demo.spec.ts b/site/e2e/demo.spec.ts new file mode 100644 index 0000000..7237b43 --- /dev/null +++ b/site/e2e/demo.spec.ts @@ -0,0 +1,193 @@ +import { expect, test, type Page } from '@playwright/test'; +import { QUICK_STARTS } from '../src/quick-starts'; + +/** Distinct highlight ids rendered inside `selector`. */ +const highlightCount = (page: Page, selector: string) => + page.$$eval( + `${selector} [data-om-id]`, + (els) => + new Set(els.map((el) => (el as HTMLElement).dataset.omId)).size, + ); + +const maxDepth = (page: Page, selector: string) => + page.$$eval(`${selector} [data-om-depth]`, (els) => + Math.max( + 0, + ...els.map((el) => Number((el as HTMLElement).dataset.omDepth)), + ), + ); + +/** Viewport rect of `phrase` inside the text of `selector`. */ +const phraseRect = (page: Page, selector: string, phrase: string) => + page.evaluate( + ([selector, phrase]) => { + const root = document.querySelector(selector!)!; + const walker = document.createTreeWalker( + root, + NodeFilter.SHOW_TEXT, + { + acceptNode: (n) => + n.parentElement?.closest('[data-om-skip]') + ? NodeFilter.FILTER_REJECT + : NodeFilter.FILTER_ACCEPT, + }, + ); + const nodes: Text[] = []; + let text = ''; + while (walker.nextNode()) { + nodes.push(walker.currentNode as Text); + text += (walker.currentNode as Text).data; + } + const at = (offset: number): [Text, number] => { + for (const node of nodes) { + if (offset <= node.data.length) return [node, offset]; + offset -= node.data.length; + } + throw new Error('offset out of range'); + }; + const start = text.indexOf(phrase!); + if (start < 0) throw new Error(`"${phrase}" not found`); + const range = document.createRange(); + range.setStart(...at(start)); + range.setEnd(...at(start + phrase!.length)); + const r = range.getBoundingClientRect(); + return { x: r.x, y: r.y, width: r.width, height: r.height }; + }, + [selector, phrase], + ); + +test.beforeEach(async ({ page }) => { + await page.goto('./'); +}); + +test('Add a highlight adds one highlight and updates the status', async ({ + page, +}) => { + const before = await highlightCount(page, '#hero'); + await page.click('#add'); + expect(await highlightCount(page, '#hero')).toBe(before + 1); + await expect(page.locator('#hero-status')).toContainText( + `${before + 1} highlights`, + ); + expect(before).toBe(3); +}); + +test('selecting words in the hero adds a highlight', async ({ page }) => { + const r = await phraseRect(page, '#hero', 'the page should'); + const y = r.y + r.height / 2; + await page.mouse.move(r.x + 1, y); + await page.mouse.down(); + await page.mouse.move(r.x + r.width - 1, y, { steps: 8 }); + await page.mouse.up(); + await expect.poll(() => highlightCount(page, '#hero')).toBe(4); + await expect(page.locator('#hero-status')).toContainText('4 highlights'); +}); + +test('Reset clears the hero', async ({ page }) => { + expect(await page.locator('#hero .om-hl').count()).toBeGreaterThan(0); + await page.click('#reset'); + await expect(page.locator('#hero .om-hl')).toHaveCount(0); +}); + +test('the layers slider sets the deepest depth', async ({ page }) => { + for (const n of [1, 6, 3]) { + await page.locator('#layers').fill(String(n)); + expect(await maxDepth(page, '#layers-stage')).toBe(n); + } +}); + +test('clicking a stacked word lists every layer', async ({ page }) => { + const deepest = await maxDepth(page, '#click-stage'); + expect(deepest).toBeGreaterThan(1); + await page + .locator(`#click-stage [data-om-depth="${deepest}"]`) + .first() + .click(); + await expect(page.locator('#click-out .chip')).toHaveCount(deepest); +}); + +test('Enter on a focused highlight lists its layers', async ({ page }) => { + await expect(page.locator('#click-out .chip')).toHaveCount(0); + for (let i = 0; i < 60; i++) { + await page.keyboard.press('Tab'); + const inside = await page.evaluate( + () => !!document.activeElement?.closest('#click-stage'), + ); + if (inside) break; + } + await page.keyboard.press('Enter'); + expect( + await page.locator('#click-out .chip').count(), + ).toBeGreaterThanOrEqual(1); +}); + +test('style presets set the highlight class', async ({ page }) => { + const marks = page.locator('#style-stage .om-hl'); + await page.locator('#style-presets button', { hasText: 'Marker' }).click(); + const total = await marks.count(); + expect(total).toBeGreaterThan(0); + await expect( + page.locator('#style-stage .om-hl.om-style-marker'), + ).toHaveCount(total); + await page.locator('#style-presets button', { hasText: 'Fill' }).click(); + await expect( + page.locator('#style-stage .om-hl.om-style-marker'), + ).toHaveCount(0); +}); + +test('framework tabs switch the code', async ({ page }) => { + await page + .locator('#frameworks [role="tab"]', { hasText: 'React' }) + .click(); + expect(await page.locator('#frameworks pre').textContent()).toBe( + QUICK_STARTS.React.code, + ); +}); + +test('docs links point at ./docs/', async ({ page }) => { + const hrefs = await page.$$eval('a', (as) => + as + .filter((a) => /docs/i.test(a.textContent ?? '')) + .map((a) => (a as HTMLAnchorElement).href), + ); + expect(hrefs.length).toBeGreaterThanOrEqual(2); + for (const href of hrefs) expect(href).toMatch(/\/overlapmark\/docs\/$/); +}); + +test('no horizontal scroll at 390px', async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + expect( + await page.evaluate(() => document.documentElement.scrollWidth), + ).toBeLessThanOrEqual(390); +}); + +test('stages stay light under a dark OS theme', async ({ page }) => { + await page.emulateMedia({ colorScheme: 'dark' }); + expect( + await page + .locator('#hero') + .evaluate((el) => getComputedStyle(el).backgroundColor), + ).toBe('rgb(255, 255, 255)'); +}); + +test('hero highlights are not Tab stops', async ({ page }) => { + expect( + await page.locator('#click-stage [tabindex="0"]').count(), + ).toBeGreaterThan(0); + await expect(page.locator('#hero [tabindex]')).toHaveCount(0); +}); + +test('a second copy click keeps the install command', async ({ + page, + context, +}) => { + await context.grantPermissions(['clipboard-read', 'clipboard-write']); + const chip = page.locator('#install'); + await chip.click(); + await expect(chip).toHaveText('Copied'); + await chip.click(); + await expect(chip).toHaveText('npm i @overlapmark/dom'); + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe( + 'npm i @overlapmark/dom', + ); +}); diff --git a/site/e2e/docs.spec.ts b/site/e2e/docs.spec.ts new file mode 100644 index 0000000..a6a2495 --- /dev/null +++ b/site/e2e/docs.spec.ts @@ -0,0 +1,95 @@ +import { expect, test } from '@playwright/test'; +import { EVENTS, OPTIONS } from '../src/api-data'; +import { QUICK_STARTS } from '../src/quick-starts'; + +const SECTIONS = [ + 'usage', + 'highlight', + 'create-highlighter', + 'options', + 'events', + 'overlap-modes', + 'styling', + 'accessibility', + 'ssr', + 'shadow-dom', + 'limitations', + 'migrating', +]; + +test.beforeEach(async ({ page }) => { + await page.goto('./docs/'); +}); + +test('every TOC link targets a section on the page', async ({ page }) => { + const hrefs = await page.$$eval('#toc a', (as) => + as.map((a) => a.getAttribute('href')), + ); + expect(hrefs).toEqual(SECTIONS.map((id) => `#${id}`)); + for (const id of SECTIONS) + await expect(page.locator(`#${id}`)).toHaveCount(1); +}); + +test('tables list every option and event', async ({ page }) => { + await expect(page.locator('#options tbody tr')).toHaveCount( + Object.keys(OPTIONS).length, + ); + await expect(page.locator('#events tbody tr')).toHaveCount( + Object.keys(EVENTS).length, + ); +}); + +test('the overlap examples render each mode', async ({ page }) => { + for (const mode of ['multiply', 'darken', 'none']) { + const root = page.locator(`#ex-modes [data-mode="${mode}"] .om-root`); + await expect(root).toHaveAttribute('data-om-overlap', mode); + expect(await root.locator('.om-hl').count()).toBeGreaterThan(0); + } +}); + +test('clicking in the events example logs it', async ({ page }) => { + const log = page.locator('#ex-events-log li'); + await expect(log).toHaveCount(0); + await page.locator('#ex-events [data-om-depth]').first().click(); + await expect(log.first()).toHaveText(/^click/); +}); + +test('the TOC marks the section in view', async ({ page }) => { + await page.locator('#events').scrollIntoViewIfNeeded(); + await page.evaluate(() => + document.getElementById('events')!.scrollIntoView({ block: 'start' }), + ); + await expect(page.locator('#toc a[href="#events"]')).toHaveAttribute( + 'aria-current', + 'true', + ); + await expect(page.locator('#toc a[aria-current="true"]')).toHaveCount(1); +}); + +test('the TOC collapses at 390px without horizontal scroll', async ({ + page, +}) => { + await page.setViewportSize({ width: 390, height: 844 }); + await expect(page.locator('#toc details')).not.toHaveAttribute( + 'open', + /.*/, + ); + expect( + await page.evaluate(() => document.documentElement.scrollWidth), + ).toBeLessThanOrEqual(390); +}); + +test('quick-start tabs show the README code', async ({ page }) => { + await page.locator('#usage [role="tab"]', { hasText: 'Svelte' }).click(); + expect(await page.locator('#usage pre').last().textContent()).toBe( + QUICK_STARTS.Svelte.code, + ); +}); + +test('the events log is not a live region', async ({ page }) => { + await expect(page.locator('#ex-events-log')).toHaveCount(1); + await expect(page.locator('#ex-events-log')).not.toHaveAttribute( + 'aria-live', + /.*/, + ); +}); diff --git a/site/e2e/pages.spec.ts b/site/e2e/pages.spec.ts new file mode 100644 index 0000000..28539d4 --- /dev/null +++ b/site/e2e/pages.spec.ts @@ -0,0 +1,47 @@ +import { expect, test } from '@playwright/test'; + +const PAGES = ['./', './docs/']; + +for (const path of PAGES) { + test(`${path} loads under /overlapmark/ without console errors`, async ({ + page, + }) => { + const errors: string[] = []; + page.on('console', (m) => { + if (m.type() === 'error') errors.push(m.text()); + }); + page.on('pageerror', (e) => errors.push(e.message)); + const response = await page.goto(path); + expect(response?.status()).toBe(200); + await page.waitForLoadState('networkidle'); + expect(errors).toEqual([]); + }); + + test(`every same-origin link and asset on ${path} resolves`, async ({ + page, + request, + }) => { + await page.goto(path); + const urls = await page.evaluate(() => { + const out = new Set(); + const attr = (sel: string, name: string) => + document.querySelectorAll(sel).forEach((el) => { + const value = el.getAttribute(name); + if (!value) return; + const url = new URL(value, location.href); + url.hash = ''; + if (url.origin === location.origin) out.add(url.href); + }); + attr('a[href]', 'href'); + attr('link[href]', 'href'); + attr('script[src]', 'src'); + attr('img[src]', 'src'); + return [...out]; + }); + expect(urls.length).toBeGreaterThan(0); + const statuses = await Promise.all( + urls.map(async (url) => [url, (await request.get(url)).status()]), + ); + expect(statuses.filter(([, status]) => status !== 200)).toEqual([]); + }); +} diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..3c8fc4f --- /dev/null +++ b/site/index.html @@ -0,0 +1,126 @@ + + + + + + overlapmark + + + + +
      + overlapmark + +
      + +
      +
      +

      overlapmark

      +

      + Overlapping highlights that get darker where they stack. +

      +
      + + + +
      +
      +
      +
      +

      +
      + + + +
      +

      01Overlap gets darker

      +

      + Each layer multiplies with the ones under it, whatever its + color. +

      +
      +
      + + +
      +
      +
      +
      + +
      +

      02Click to see every layer

      +

      + A click, or Enter on a focused highlight, reports every + highlight under it, not only the top one. +

      +
      +
      +
      + Click a highlighted word. +
      +
      +
      + +
      +

      03Style it with CSS

      +

      + Pick a preset class or write your own. Overlap still reads + as depth. +

      +
      +
      + className +
      +
      +
      +
      +
      + +
      +

      04Any framework

      +

      The same DOM from vanilla JS, Vue, React and Svelte.

      +
      +
      + +

      + Read the docs → +

      +
      + + + + diff --git a/examples/vanilla/package.json b/site/package.json similarity index 59% rename from examples/vanilla/package.json rename to site/package.json index db1037c..6216fed 100644 --- a/examples/vanilla/package.json +++ b/site/package.json @@ -1,5 +1,5 @@ { - "name": "vanilla-example", + "name": "overlapmark-site", "private": true, "version": "0.0.0", "type": "module", @@ -7,15 +7,17 @@ "dev": "vite", "build": "vite build", "preview": "vite preview", - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "test": "vitest run --passWithNoTests", + "test:e2e": "playwright test" }, "dependencies": { "@overlapmark/core": "workspace:*", "@overlapmark/dom": "workspace:*" }, "devDependencies": { - "@fontsource/instrument-sans": "^5.3.0", - "@fontsource/literata": "^5.3.0", + "@fontsource/inter": "^5.3.0", + "@fontsource/jetbrains-mono": "^5.3.0", "vite": "^8" } } diff --git a/site/playwright.config.ts b/site/playwright.config.ts new file mode 100644 index 0000000..8252b9d --- /dev/null +++ b/site/playwright.config.ts @@ -0,0 +1,18 @@ +import { defineConfig, devices } from '@playwright/test'; + +// The site as Pages serves it: a production build under /overlapmark/. +export default defineConfig({ + testDir: 'e2e', + retries: 0, + forbidOnly: !!process.env.CI, + reporter: process.env.CI ? 'list' : 'line', + use: { baseURL: 'http://localhost:4179/overlapmark/' }, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], + webServer: { + command: + 'pnpm exec vite build --base /overlapmark/ && pnpm exec vite preview --base /overlapmark/ --port 4179 --strictPort', + url: 'http://localhost:4179/overlapmark/', + reuseExistingServer: !process.env.CI, + timeout: 120_000, + }, +}); diff --git a/site/src/api-data.test.ts b/site/src/api-data.test.ts new file mode 100644 index 0000000..b1dbe7f --- /dev/null +++ b/site/src/api-data.test.ts @@ -0,0 +1,68 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, test } from 'vitest'; +import { + CSS_CLASSES, + CSS_VARIABLES, + EVENTS, + HIGHLIGHT_FIELDS, + HIGHLIGHTER_METHODS, + OPTIONS, +} from './api-data'; + +const core = (file: string) => + readFileSync( + new URL(`../../packages/core/src/${file}`, import.meta.url), + 'utf8', + ); +const styles = core('styles.css'); +const render = core('render.ts'); + +describe.each([ + ['OPTIONS', OPTIONS], + ['HIGHLIGHT_FIELDS', HIGHLIGHT_FIELDS], +])('%s', (_, rows) => { + test('gives every row a type and a description', () => { + for (const row of Object.values(rows)) { + expect(row.type).not.toBe(''); + expect(row.description).not.toBe(''); + } + }); +}); + +test('every event and method is described', () => { + for (const e of Object.values(EVENTS)) { + expect(e.payload).not.toBe(''); + expect(e.description).not.toBe(''); + } + for (const m of Object.values(HIGHLIGHTER_METHODS)) { + expect(m.signature).not.toBe(''); + expect(m.description).not.toBe(''); + } +}); + +test('every documented CSS variable is in the stylesheet', () => { + expect(CSS_VARIABLES.length).toBeGreaterThan(0); + for (const { name } of CSS_VARIABLES) expect(styles).toContain(name); +}); + +test('every documented class is rendered or styled by core', () => { + expect(CSS_CLASSES.length).toBeGreaterThan(0); + for (const { name } of CSS_CLASSES) expect(styles + render).toContain(name); +}); + +test('a name core lacks is caught', () => { + expect(styles + render).not.toContain('--om-nope'); + expect(styles + render).not.toContain('om-style-nope'); +}); + +test('every custom property core styles with is documented', () => { + const used = new Set(styles.match(/--om-[a-z-]+/g)); + expect(used.size).toBeGreaterThan(0); + expect(new Set(CSS_VARIABLES.map((v) => v.name))).toEqual(used); +}); + +test('data-om-id is documented as layers-only', () => { + const hl = CSS_CLASSES.find((c) => c.name === 'om-hl')!; + expect(hl.description).toContain('data-om-id'); + expect(hl.description).toContain('`layers` strategy'); +}); diff --git a/site/src/api-data.ts b/site/src/api-data.ts new file mode 100644 index 0000000..73e7043 --- /dev/null +++ b/site/src/api-data.ts @@ -0,0 +1,264 @@ +// The docs page's reference tables. Each table is keyed by the library's own +// types, so `pnpm typecheck` fails when an option, field, event or method is +// missing here or does not exist. Text in backticks renders as code. +import type { Highlight } from '@overlapmark/core'; +import type { Highlighter, HighlighterOptions } from '@overlapmark/dom'; + +export interface Row { + name: string; + type: string; + default: string; + description: string; +} + +type Table = { [P in K]-?: Row }; + +export const HIGHLIGHT_FIELDS: Table = { + id: { + name: 'id', + type: 'string', + default: 'required', + description: + 'Unique among the highlights you pass, and without whitespace: the ids covering a segment are written space-separated in its `data-om-ids`.', + }, + start: { + name: 'start', + type: 'number', + default: 'required', + description: 'Integer UTF-16 index of the first character.', + }, + end: { + name: 'end', + type: 'number', + default: 'required', + description: + 'Integer UTF-16 index after the last character (exclusive).', + }, + color: { + name: 'color', + type: 'string', + default: '`defaultColor`', + description: + "CSS color, set as `--om-color` on the highlight's element.", + }, + className: { + name: 'className', + type: 'string', + default: '—', + description: + "Class for the highlight's element, such as a preset: `om-style-marker`, `om-style-underline` or `om-style-box`.", + }, + data: { + name: 'data', + type: 'T', + default: '—', + description: + 'A payload of your own. Events hand your highlight objects back, so you read it from there.', + }, +}; + +export const OPTIONS: Table = { + text: { + name: 'text', + type: 'string', + default: 'required', + description: 'The source text.', + }, + highlights: { + name: 'highlights', + type: 'Highlight[]', + default: '`[]`', + description: 'The highlights to render. See Highlight.', + }, + strategy: { + name: 'strategy', + type: "'layers' | 'depth'", + default: "`'layers'`", + description: + '`layers`: one nested element per highlight. `depth`: one element per segment, darkened by its overlap count.', + }, + overlap: { + name: 'overlap', + type: "'multiply' | 'darken' | 'none'", + default: "`'multiply'`", + description: + 'How nested layers combine with the `layers` strategy; `depth` ignores it. See Overlap modes.', + }, + focusable: { + name: 'focusable', + type: 'boolean', + default: '`true`', + description: + 'Make highlighted segments Tab stops (`tabindex="0"`, `role="button"`). Enter or Space reports `click`.', + }, + describe: { + name: 'describe', + type: '(highlights: readonly Highlight[]) => string', + default: 'count', + description: + "The accessible description of a focusable segment: `'1 highlight'` / `'n highlights'` by default. Return `''` for none.", + }, + defaultColor: { + name: 'defaultColor', + type: 'string', + default: '`#ddd6ff`', + description: + 'Color of highlights without `color`. When given, it is also set as `--om-default-color` on the root.', + }, + brush: { + name: 'brush', + type: '(color: string) => string', + default: 'built-in', + description: + 'Returns a CSS image for `--om-brush`, which `om-style-marker` paints.', + }, + minSelectionLength: { + name: 'minSelectionLength', + type: 'number', + default: '`1`', + description: 'Shorter selections do not report `select`.', + }, + touchSelectionDelay: { + name: 'touchSelectionDelay', + type: 'number', + default: '`500`', + description: + 'Milliseconds without a selection change before a touch selection reports `select`.', + }, + decorate: { + name: 'decorate', + type: '(segment: Segment) => Node | string | null', + default: '—', + description: + "Presentational markup after the text of each highlighted segment, such as a count. Return `null` or `''` for none. In Vue, React and Svelte this is the `decoration` slot, `renderDecoration` prop and `decoration` snippet.", + }, +}; + +type EventName = Parameters[0]; + +export const EVENTS: { + [K in EventName]: { payload: string; description: string }; +} = { + select: { + payload: '{ start, end, text, rect, highlights }', + description: + 'A selection inside the root is finished: on the next task after the mouse button or key is released, or after `touchSelectionDelay` on touch. `highlights` are those overlapping the selection; `rect` is the bounding rect of the selected text inside the root.', + }, + click: { + payload: '{ offset, segment, highlights, event }', + description: + 'A click or tap with no active selection, or Enter/Space on a focused highlight. `offset` is the character index; `highlights` lists every highlight covering it, `[]` on plain text.', + }, + dblclick: { + payload: '{ offset, segment, highlights, event }', + description: + "A double-click. The browser's own word selection stays in place.", + }, + hover: { + payload: "{ type: 'enter' | 'leave', segment, highlights, event }", + description: + 'A mouse pointer enters or leaves a highlighted segment. Every `enter` is followed by one `leave`; a `leave` not caused by the pointer (destroy, or an update that removes the segment) has `event: null`. Touch and pen do not hover.', + }, +}; + +export const HIGHLIGHTER_METHODS: { + [K in keyof Highlighter]: { signature: string; description: string }; +} = { + update: { + signature: 'update(partial: Partial>): void', + description: + 'Merge new options and re-render, keeping the selection (unless the text changed) and keyboard focus.', + }, + on: { + signature: 'on(type, fn): () => void', + description: + 'Subscribe to `select`, `click`, `dblclick` or `hover`. Returns a function that removes this subscription.', + }, + getSegments: { + signature: 'getSegments(): readonly Segment[]', + description: + 'The current segments: `{ start, end, text, highlights, depth }`.', + }, + destroy: { + signature: 'destroy(): void', + description: + 'Remove the listeners and restore the element to plain text.', + }, +}; + +export const CSS_VARIABLES = [ + { + name: '--om-default-color', + default: '#ddd6ff', + description: 'Color of highlights that have no `color`.', + }, + { + name: '--om-alpha', + default: '55%', + description: 'Opacity of each layer (layers strategy).', + }, + { + name: '--om-depth-step', + default: '12%', + description: 'How much darker per level (darken mode, depth strategy).', + }, + { + name: '--om-depth-ink', + default: 'black', + description: 'What the darken mode mixes toward.', + }, + { + name: '--om-max-depth', + default: '6', + description: + 'The level at which darkening stops, and the furthest nested underlines and boxes are offset.', + }, + { + name: '--om-color', + default: 'per highlight', + description: + 'Set from `highlight.color` and reset on every `.om-hl`, so setting it on the root has no effect; set it in a class instead.', + }, + { + name: '--om-level', + default: 'per layer', + description: 'Layer index, 0 for the outermost (layers strategy).', + }, + { + name: '--om-depth', + default: 'per segment', + description: 'Overlap count of a segment (depth strategy).', + }, + { + name: '--om-brush', + default: 'per highlight', + description: + 'The image `om-style-marker` paints, from the `brush` option.', + }, +] as const; + +export const CSS_CLASSES = [ + { name: 'om-root', description: 'The root element.' }, + { + name: 'om-seg', + description: + 'Outermost element of a segment. A highlighted one carries `data-om-depth` and `data-om-ids`.', + }, + { + name: 'om-hl', + description: + 'A highlight element (``). With the `layers` strategy it carries `data-om-id`; with `depth`, one per segment, it is also the `om-seg`.', + }, + { + name: 'om-style-marker', + description: 'Preset: a marker stroke from `--om-brush`.', + }, + { + name: 'om-style-underline', + description: 'Preset: an underline; nested underlines stack 4px apart.', + }, + { + name: 'om-style-box', + description: 'Preset: a box; nested boxes reach 3px further per level.', + }, +] as const; diff --git a/site/src/demo.css b/site/src/demo.css new file mode 100644 index 0000000..84e00d6 --- /dev/null +++ b/site/src/demo.css @@ -0,0 +1,133 @@ +.demo { + max-width: 680px; + margin: 0 auto; + padding: 0 24px 96px; +} + +.intro { + padding: 72px 0 40px; + text-align: center; +} + +.intro h1 { + font-size: 44px; + font-weight: 600; + letter-spacing: -0.035em; + line-height: 1.1; + margin: 0; +} + +.tagline { + color: var(--muted); + margin: 10px 0 28px; + font-size: 17px; +} + +.actions { + display: flex; + gap: 10px; + justify-content: center; + flex-wrap: wrap; +} + +.hero-card { + margin-top: 40px; + text-align: left; +} + +.hero-card .stage { + padding: 36px 32px; + font-size: 22px; + min-height: 150px; +} + +.status { + margin: 12px 0 0; + min-height: 1.6em; +} + +.toc { + display: flex; + gap: 18px; + justify-content: center; + flex-wrap: wrap; + font-size: 13px; + margin: 8px 0 8px; +} + +.toc a { + text-decoration: none; +} + +.toc a:hover { + color: var(--ink); +} + +.spec { + padding-top: 64px; + scroll-margin-top: 16px; +} + +.spec h2 { + font-size: 15px; + font-weight: 600; + margin: 0 0 4px; + display: flex; + gap: 12px; +} + +.spec h2 span { + font: 400 13px var(--mono); + color: var(--muted); + padding-top: 1px; +} + +.spec > p { + color: var(--muted); + margin: 0 0 18px; +} + +.bar b { + color: var(--ink); + font-weight: 500; +} + +.out { + border-top: 1px solid var(--rule); + border-bottom: 0; + justify-content: flex-start; + min-height: 38px; +} + +.out .layer { + display: inline-flex; + align-items: center; + gap: 6px; + color: var(--ink); +} + +.next { + text-align: center; + margin: 72px 0 0; +} + +.next .btn { + display: inline-block; + text-decoration: none; +} + +@media (max-width: 520px) { + .demo { + padding: 0 16px 72px; + } + .intro { + padding-top: 40px; + } + .intro h1 { + font-size: 36px; + } + .hero-card .stage { + padding: 24px 20px; + font-size: 19px; + } +} diff --git a/site/src/demo.ts b/site/src/demo.ts new file mode 100644 index 0000000..43e6be3 --- /dev/null +++ b/site/src/demo.ts @@ -0,0 +1,160 @@ +import './fonts'; +import '@overlapmark/core/styles.css'; +import './site.css'; +import './demo.css'; +import type { Highlight } from '@overlapmark/core'; +import { createHighlighter } from '@overlapmark/dom'; +import { PALETTES } from './palette'; +import { QUICK_STARTS } from './quick-starts'; +import { SAMPLES, type Label } from './samples'; +import { mountTabs } from './tabs'; +import { randomWordRange, wordRanges } from './words'; + +const byId = (id: string) => + document.getElementById(id) as E; + +// Hero: every press or selection adds one more mark. + +const heroText = SAMPLES.hero.text; +const words = wordRanges(heroText); +let heroMarks = [...SAMPLES.hero.highlights]; +let added = 0; +const hero = createHighlighter