@garndev/markdown
v0.3.1
Published
Decorative GFM highlighting for fixed-width grids: never emits semantic HTML and never touches a font metric.
Maintainers
Readme
@garndev/markdown
Decorative GFM highlighting for fixed-width grids.
It turns Markdown into spans with classes so you can paint on top of real
text (a <textarea>, a <pre>…) without touching a single metric: no font
size, no line height, no character advance. The caret and selection of the
underlying text stay aligned with what you painted, character by character.
import { highlightDocument } from '@garndev/markdown';
import '@garndev/markdown/tokens.css';
const { html } = highlightDocument(markdown, { width: 40 });
viewer.innerHTML = html;What this is (and is not)
It is a highlighter. It understands blocks (headings, lists, quotes, tables,
fences, reference definitions, HTML) and inline (emphasis, strikethrough, code,
links, images, autolinks, entities) and emits <div class="rline r-KIND"> lines
full of token <span>s.
It is not a Markdown renderer. It never emits <h1>, <strong> or <a>:
- A real
<a>would break alignment with the text underneath (its own focus, selection and scrolling behaviour). - Font sizes would break the fixed grid.
Links are resolved by offset with linkAtOffset / linkRangeAtOffset, so you
can open them on Cmd/Ctrl+click from the outside. Document HTML is always
escaped: it is never interpreted.
Install
npm install @garndev/markdownAPI
highlightDocument(markdown, options?)
The whole pipeline in one call. Returns { lines, realBreaks, highlighted, html }.
| option | type | default | description |
| ---------------- | --------------------- | ------- | ------------------------------------------------------------------ |
| width | number | — | Width in characters. Without it, every \n is a line and there is no soft wrapping. |
| innerClass | string | — | Class of a span wrapping each line's content. |
| lineAttributes | (line, i) => string | — | Extra attributes per div (already escaped). |
highlightLines(lines, realBreaks?)
The lower layer. It takes visual lines (already wrapped to the width) and
returns a HighlightedLine[] of { html, kind }.
realBreaks[i] === 1 means there is a real break in the document between
lines[i] and lines[i+1]; 0 is a soft continuation that inherits the block
(so a list or a quote stays a list or a quote across the wrap). Omit it and
every line becomes a new block.
wrapLines(text, width) / wrapParagraph(paragraph, width)
Wrap to lines of width characters, keeping every space (spaces after a word
hang at the end of the line, the way browsers do with pre-wrap).
toHtml(highlighted, options?)
HighlightedLine[] → HTML.
linkAtOffset(doc, offset, refs?) / linkRangeAtOffset(doc, offset, refs?)
The URL (or { url, start, end } range) of the link under an offset in the
original document. It ignores code and task checkboxes.
collectRefs(doc)
Map of normalised label → destination for every [label]: url definition.
attachLinkHover(options)
The interactive layer: underlines the link under the pointer, shows its URL in a
tooltip that follows the mouse, and opens it on ⌘/Ctrl+click. It renders two
absolute layers (pointer-events: none) inside your container, so it never
touches the text metrics. The container needs position: relative.
const hover = attachLinkHover({
container: wrap, // element holding the rendered lines
text, // the full document
lines, // visible visual lines
lineStart, // document offset where each line starts
charWidth: 7.8,
lineHeight: 32,
padLeft: 48, // left padding of the text inside the container
});| option | type | default |
| ------------- | ------------------------- | --------------------------- |
| container | HTMLElement | — |
| text | string | — |
| lines | string[] | — |
| lineStart | number[] | — |
| charWidth | number | — |
| lineHeight | number | — |
| padLeft | number | 0 |
| hint | string | ⌘-clic para abrir: / Ctrl-clic… |
| openOnClick | boolean | true |
| onOpen | (url) => void | window.open in a new tab |
Returns { update, offsetAt, hide, destroy }: call update() whenever the text,
the visible lines or the metrics change, hide() when the layout moves under the
pointer, and destroy() when the view goes away.
The layers are built with document.createElement and the CSSOM (el.style.left
= …), never with innerHTML or inline style attributes in a string. That
means it works under a strict CSP (default-src 'self', without
style-src 'unsafe-inline'); a test fails the suite if any bundle file brings
HTML-building APIs back.
measureGrid(container, sample?)
Measures the grid from the element itself instead of hardcoding it, so it keeps working after a resize, a zoom or a font change:
const grid = measureGrid(wrap); // { charWidth, lineHeight, padLeft }
attachLinkHover({ container: wrap, ...grid, text, lines, lineStart });charWidth is measured with a 100-character probe in the container's own font;
lineHeight and padLeft come from the computed style. If there is no layout
yet it falls back to 8 and 32.
Geometry helpers
The math behind it, DOM-free and testable in Node:
offsetAtPoint({ lines, lineStart, rect, x, y, charWidth, lineHeight, padLeft })underlineSegments({ lines, lineStart, start, end, charWidth, lineHeight, padLeft, underlineGap })lineIndexAt(lineStart, offset),advance(str, charWidth)(tabs stop every 8 cells)
Block kinds
h1…h6, code, fence, quote, list, hr, thdr, tdelim, trow,
ref, html, and '' for a plain paragraph.
Theming
tokens.css is included and every visible style is a custom property, named
after the Markdown construct rather than the class. Override them wherever you
paint:
.my-notebook {
--inline-code-color: orange;
--inline-code-bg: transparent;
--bold-weight: 600;
--h1-transform: none;
--table-header-bg: transparent;
}Grid and text
| variable | default | what it does |
| -------------------- | ----------- | ----------------------------------------- |
| --rline-height | 32px | line box height (must match the real text) |
| --rline-font-size | 15px | only enforced with .rline-lock |
| --rline-color | inherit | base text colour of the highlighted lines |
Inline
| variable | default |
| ------------------------- | ------------------------ |
| --dim-color | currentColor |
| --dim-opacity | 0.55 |
| --link-color | inherit |
| --link-opacity | 1 |
| --bold-weight | 700 |
| --bold-shadow | 0 0 0.5px currentColor |
| --italic-style | italic |
| --strike-decoration | line-through |
| --inline-code-color | inherit |
| --inline-code-bg | rgba(0,0,0,.07) |
| --inline-code-radius | 3px |
| --task-done-color | #2e7d32 |
Headings
| variable | default |
| ------------------------- | ---------------- |
| --h1-transform | uppercase |
| --h1-literal-transform | none (code/links inside an h1) |
| --h2-weight | 700 |
| --h2-shadow | 0 0 0.5px currentColor |
| --h3-decoration | underline |
| --h3-thickness | 1px |
| --h3-offset | 4px |
| --h4-weight / --h5-weight / --h6-weight | inherit |
| --h4-style / --h5-style / --h6-style | inherit |
| --h4-decoration / --h5-decoration / --h6-decoration | none |
Tables and code blocks
| variable | default |
| ------------------------- | ------------------ |
| --table-header-weight | 700 |
| --table-header-shadow | 0 0 0.5px currentColor |
| --table-header-bg | rgba(0,0,0,.03) |
| --table-header-color | inherit |
| --table-delim-color | inherit |
| --table-row-color | inherit |
| --table-row-bg | transparent |
| --code-block-bg | rgba(0,0,0,.04) |
| --code-block-color | inherit |
Other blocks
| variable | default |
| ------------------- | ------------- |
| --quote-color | inherit |
| --quote-bg | transparent |
| --list-color | inherit |
| --ref-color | inherit |
| --hr-color | inherit |
| --html-color | inherit |
Link hover
| variable | default |
| ------------------------------ | ------------ |
| --link-hover-line | currentColor |
| --link-hover-tip-bg | #34302a |
| --link-hover-tip-color | #fdfcf7 |
| --link-hover-tip-size | 12px |
| --link-hover-tip-line-height | 20px |
| --link-hover-tip-padding | 2px 8px |
| --link-hover-tip-radius | 6px |
| --link-hover-tip-width | 340px |
| --link-hover-hint-opacity | 0.6 |
Compatibility
The old --tok-* names keep working as fallbacks, so upgrading from 0.2.x
changes nothing: --tok-dim-color, --tok-code-bg, --tok-codeblock-bg,
--tok-thdr-bg, --tok-task-done-color.
Recipes
Custom properties inherit, so set them on any ancestor of the painted lines. Three complete examples:
Orange inline code, page ink everywhere else
.notebook {
--inline-code-color: orange;
--inline-code-bg: color-mix(in srgb, orange 14%, transparent);
--inline-code-radius: 4px;
}Quieter emphasis: no uppercase h1, lighter bold
.notebook {
--h1-transform: none;
--bold-weight: 600;
--bold-shadow: none;
}Dark paper
.notebook {
--rline-color: #d8d4cc;
--dim-color: #6f6a63;
--inline-code-bg: rgba(255, 255, 255, 0.09);
--code-block-bg: rgba(255, 255, 255, 0.06);
--table-header-bg: rgba(255, 255, 255, 0.05);
--link-hover-tip-bg: #d8d4cc;
--link-hover-tip-color: #1c1a17;
}tokens.css is tested: if a visible property is hardcoded instead of read from
a variable, the suite fails. If you need something that is not in the tables
above, open an issue rather than hardcoding it in your own CSS — a hardcoded
padding or font-size will misalign the highlight from the text underneath.
Add rline-lock to the container if you want to lock the grid down: no outside
style will be able to change sizes or line height inside the highlight.
The CSS never changes a metric — only colour, opacity, font-weight,
font-style, text-decoration, background, text-transform, text-shadow
and border-radius. Keep that rule in your own overrides: any padding or
font-size will misalign the highlight from the text underneath.
Design notes
- Zero dependencies, zero DOM. The parser is pure regex and string work, so it runs in a worker, on the server, or in a test without a browser.
- Line-oriented by design. It highlights visual lines, not a document tree, because the thing it has to stay aligned with is a fixed grid of characters.
- Escapes everything.
&,<and>are escaped in the output; Markdown syntax characters are wrapped in.tok-dimso they fade without moving. - Strict-CSP friendly. The highlighting HTML only carries classes, never
inline styles, so
innerHTMLon it is safe. The interactive layers are built node by node, so the package itself never usesinnerHTML.
Development
npm install
npm test # tsc + node --test
npm run buildPure ESM, no runtime dependencies, ships its own types.
Releasing
Releases go through CI — nothing is published from a laptop:
npm version patch # or minor / major: bumps package.json, commits, tags
git push --follow-tags # triggers .github/workflows/publish.ymlThe Publish workflow runs the tests, checks that the tag matches
package.json, and publishes with --access public.
It needs the NPM_TOKEN secret (an npm automation token):
gh secret set NPM_TOKEN -R jupegarnica/markdownTo publish without any secret, configure a Trusted Publisher for this repo
and the publish.yml workflow in the npm package settings; npm then validates
GitHub Actions' OIDC token instead.
