Download Link
A download link that shows the file's type and weight beside its words, read from the file itself. On hover the arrow sinks into its tray; a click sends it through and back from the top.
View codeA # beside every heading. It slides out of the margin when the heading is pointed at, or waits after the last word on a touch screen. Click it, or the heading, to put the section in the bar and copy the link.
With your AI
Say it to your AI. It gets the exact code below, not its best guess, and knows where it goes.
Add the Kodza Heading Anchor to my page.
claude mcp add -t http kodza https://kodza.dev/api/mcp
<div class="kodza-heading-anchor" data-kodza-heading-anchor>
<h2>Install</h2>
<p>Paste the markup, the CSS and the script. That's the install. No package, no build step, no config file to babysit.</p>
<h3>In WordPress</h3>
<p>Leave the block empty and drop it anywhere in the post: it finds the headings of the article around it. Your theme's titles keep their look.</p>
<h2>Behind a sticky header</h2>
<p>The script measures your fixed header and stops each section just below it. Nobody lands on a title hiding under the logo.</p>
<h3>Ids, handled</h3>
<p>Headings without an id get one from their text. It goes away when the script stops, so the HTML you saved stays the HTML you wrote.</p>
</div>
/* Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license */
/* Kodza — Heading Anchor
A link to every heading. With a mouse and room on the left, a # slides out of the margin when
the heading is pointed at or focused; on a touch screen, in a narrow column or under a centred
heading, it waits after the last word. A click on it (with a mouse, on the heading too) puts the
section's address in the bar and copies it: the # rolls up into a check and "Link copied" rolls
in beside it.
Tuned with the --kz-heading-anchor-* variables, on the root (for an empty root, on the article
whose headings it links). By default the mark follows the heading's colour. */
.kodza-heading-anchor {
--kz-heading-anchor-heading: #0a0a0a;
--kz-heading-anchor-text: rgba(10, 10, 10, 0.72);
--kz-heading-anchor-ink: currentColor;
--kz-heading-anchor-muted: color-mix(in srgb, currentColor 50%, transparent);
--kz-heading-anchor-paper: #fff;
--kz-heading-anchor-line: rgba(10, 10, 10, 0.1);
--kz-heading-anchor-gap: 0.3em;
--kz-heading-anchor-size: 0.75em;
--kz-heading-anchor-offset: 24px;
--kz-heading-anchor-duration: 0.24s;
--kz-heading-anchor-ease: cubic-bezier(0.22, 1, 0.36, 1);
display: block;
}
/* The article it holds: its own type, whatever the theme gives to headings and paragraphs (an
empty root leaves the page's own text as it is) */
.kodza-heading-anchor > h2,
.kodza-heading-anchor > h3 {
color: var(--kz-heading-anchor-heading);
font-family: "Geist", system-ui, sans-serif;
font-weight: 600;
text-align: start;
}
.kodza-heading-anchor > h2 {
margin: 56px 0 14px;
font-size: clamp(24px, 4vw, 32px);
line-height: 1.2;
letter-spacing: -0.035em;
}
.kodza-heading-anchor > h3 {
margin: 36px 0 10px;
font-size: 20px;
line-height: 1.3;
letter-spacing: -0.025em;
}
.kodza-heading-anchor > :is(h2, h3):first-child {
margin-top: 0;
}
.kodza-heading-anchor > p {
margin: 0 0 1.1em;
color: var(--kz-heading-anchor-text);
font-family: "Geist", system-ui, sans-serif;
font-size: 17px;
line-height: 1.7;
text-wrap: pretty;
}
.kodza-heading-anchor > p:last-child {
margin-bottom: 0;
}
/* The last word and the mark, kept on one line by the script */
.kodza-heading-anchor__tie {
white-space: nowrap;
}
/* After the last word (touch screens, narrow columns, centred headings, and the default) */
.kodza-heading-anchor__link {
position: relative;
display: inline;
margin: 0 0 0 var(--kz-heading-anchor-gap, 0.3em);
padding: 0;
border: 0;
border-radius: 6px;
background: none;
color: var(--kz-heading-anchor-ink, currentColor);
font: inherit;
letter-spacing: 0;
text-decoration: none;
text-transform: none;
white-space: nowrap;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
.kodza-heading-anchor__link:dir(rtl) {
margin: 0 var(--kz-heading-anchor-gap, 0.3em) 0 0;
}
.kodza-heading-anchor__link:focus-visible {
outline: 2px solid var(--kz-heading-anchor-ink, currentColor);
outline-offset: 3px;
}
/* The mark: the # and the check share one masked cell, and take turns in it */
.kodza-heading-anchor__glyph {
display: inline-grid;
place-items: center;
vertical-align: baseline;
clip-path: inset(0);
}
.kodza-heading-anchor__hash,
.kodza-heading-anchor__check {
grid-area: 1 / 1;
transition: translate var(--kz-heading-anchor-duration, 0.24s) var(--kz-heading-anchor-ease, cubic-bezier(0.22, 1, 0.36, 1));
}
.kodza-heading-anchor__hash {
padding: 0 0.04em;
color: var(--kz-heading-anchor-muted, color-mix(in srgb, currentColor 50%, transparent));
font: 500 var(--kz-heading-anchor-size, 0.75em)/1.15 "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;
transition-property: translate, transform, color;
}
.kodza-heading-anchor__link:hover .kodza-heading-anchor__hash,
.kodza-heading-anchor__link:focus-visible .kodza-heading-anchor__hash {
color: var(--kz-heading-anchor-ink, currentColor);
}
.kodza-heading-anchor__check {
width: calc(var(--kz-heading-anchor-size, 0.75em) * 0.82);
height: calc(var(--kz-heading-anchor-size, 0.75em) * 0.82);
overflow: visible;
fill: none;
stroke: currentColor;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
translate: 0 110%;
}
.kodza-heading-anchor__check path {
stroke-dasharray: 1;
stroke-dashoffset: 1;
transition: stroke-dashoffset 0.2s ease;
}
/* In the margin: level with the first line, its baseline on the heading's baseline. Hidden in its
mask until the heading is pointed at or the link focused, then it slides out of the text. */
.kodza-heading-anchor__link.is-margin {
position: absolute;
top: var(--kz-heading-anchor-top, 0px);
right: calc(100% + var(--kz-heading-anchor-gap, 0.3em));
display: block;
margin: 0;
}
.kodza-heading-anchor__link.is-margin:dir(rtl) {
right: auto;
left: calc(100% + var(--kz-heading-anchor-gap, 0.3em));
}
/* The way from the heading to the mark stays a hover */
.kodza-heading-anchor__link.is-margin::before {
content: "";
position: absolute;
inset: 0 calc(-1 * var(--kz-heading-anchor-gap, 0.3em)) 0 -0.2em;
}
.kodza-heading-anchor__link.is-margin:dir(rtl)::before {
inset: 0 -0.2em 0 calc(-1 * var(--kz-heading-anchor-gap, 0.3em));
}
.kodza-heading-anchor__link.is-margin .kodza-heading-anchor__hash {
translate: 100% 0;
}
.kodza-heading-anchor__link.is-margin:dir(rtl) .kodza-heading-anchor__hash {
translate: -100% 0;
}
@media (hover: hover) {
:is(h1, h2, h3, h4, h5, h6):hover > .kodza-heading-anchor__link.is-margin .kodza-heading-anchor__hash,
:is(h1, h2, h3, h4, h5, h6):hover > .kodza-heading-anchor__tie > .kodza-heading-anchor__link.is-margin .kodza-heading-anchor__hash {
translate: 0 0;
}
}
/* With a mouse the whole heading copies its link: pointing at it shows the hand and inks the # */
@media (hover: hover) and (pointer: fine) {
:is(h1, h2, h3, h4, h5, h6):has(> .kodza-heading-anchor__link, > .kodza-heading-anchor__tie > .kodza-heading-anchor__link) {
cursor: pointer;
}
:is(h1, h2, h3, h4, h5, h6):hover > .kodza-heading-anchor__link .kodza-heading-anchor__hash,
:is(h1, h2, h3, h4, h5, h6):hover > .kodza-heading-anchor__tie > .kodza-heading-anchor__link .kodza-heading-anchor__hash {
color: var(--kz-heading-anchor-ink, currentColor);
}
}
.kodza-heading-anchor__link.is-margin:focus-visible .kodza-heading-anchor__hash {
translate: 0 0;
}
/* Copied: the # rolls up out of its cell, the check comes up behind it, drawing itself on the way */
.kodza-heading-anchor__link.is-copied .kodza-heading-anchor__hash {
transform: translateY(-110%);
}
.kodza-heading-anchor__link.is-copied .kodza-heading-anchor__check {
translate: 0 0;
}
.kodza-heading-anchor__link.is-copied .kodza-heading-anchor__check path {
stroke-dashoffset: 0;
transition: stroke-dashoffset 0.3s var(--kz-heading-anchor-ease, cubic-bezier(0.22, 1, 0.36, 1));
}
/* "Link copied", beside the mark on the side away from the text, its word rolling in its mask.
Centred on the # (in the heading's em: the # sits on the baseline, lower than the box centre) */
.kodza-heading-anchor__label {
position: absolute;
top: 50%;
left: calc(100% + 0.6rem);
display: grid;
clip-path: inset(0 -2px);
color: var(--kz-heading-anchor-ink, currentColor);
white-space: nowrap;
pointer-events: none;
transform: translateY(calc(-50% + 0.075em));
}
.kodza-heading-anchor__link:dir(rtl) .kodza-heading-anchor__label,
.kodza-heading-anchor__link.is-margin .kodza-heading-anchor__label {
right: calc(100% + 0.6rem);
left: auto;
}
.kodza-heading-anchor__link.is-margin:dir(rtl) .kodza-heading-anchor__label {
right: auto;
left: calc(100% + 0.6rem);
}
.kodza-heading-anchor__word {
font: 500 12px/1.5 "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;
letter-spacing: 0;
translate: 0 110%;
transition: translate var(--kz-heading-anchor-duration, 0.24s) var(--kz-heading-anchor-ease, cubic-bezier(0.22, 1, 0.36, 1));
}
.kodza-heading-anchor__link.is-copied .kodza-heading-anchor__word {
translate: 0 0;
transition-delay: 0.06s;
}
/* No room beside it: above the mark, on a small sheet */
.kodza-heading-anchor__link.is-above .kodza-heading-anchor__label,
.kodza-heading-anchor__link.is-above:dir(rtl) .kodza-heading-anchor__label {
top: auto;
right: auto;
bottom: calc(100% + 6px);
left: 50%;
padding: 4px 9px;
border: 1px solid var(--kz-heading-anchor-line, rgba(10, 10, 10, 0.1));
border-radius: 8px;
background: var(--kz-heading-anchor-paper, #fff);
box-shadow: 0 6px 18px rgba(10, 10, 10, 0.08);
color: var(--kz-heading-anchor-ink, #0a0a0a);
clip-path: inset(-1px -1px -1px -1px round 8px);
opacity: 0;
transform: translate(-50%, 4px);
transition: opacity 0.18s ease, transform var(--kz-heading-anchor-duration, 0.24s) var(--kz-heading-anchor-ease, cubic-bezier(0.22, 1, 0.36, 1));
}
.kodza-heading-anchor__link.is-above.is-copied .kodza-heading-anchor__label {
opacity: 1;
transform: translate(-50%, 0);
}
.kodza-heading-anchor__link.is-above .kodza-heading-anchor__word {
translate: 0 0;
transition: none;
}
/* For screen readers: what happened after the click */
.kodza-heading-anchor__status {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@media (prefers-reduced-motion: reduce) {
.kodza-heading-anchor__link *,
.kodza-heading-anchor__link::before {
transition-duration: 0.01ms !important;
transition-delay: 0s !important;
}
}
/* kodza-guard dba5956bf4eb — generated by Kodza, do not edit.
Theme guard: keeps a site's own CSS (WordPress themes, Bootstrap, CSS resets…) off this
component. :not(#_) is always true and weighs as much as an id, so these lines win over
theme rules made of classes and tags. Customise the component through its --kz-* variables. */
/* What the browser gives, where the component sets it only in some states: at the lowest weight, so its own rules below put it back */
:where(.kodza-heading-anchor__link):not(#_) {
outline: revert;
outline-offset: revert;
}
/* What the browser gives, on everything the component leaves to it */
.kodza-heading-anchor:not(#_),
.kodza-heading-anchor__tie:not(#_),
.kodza-heading-anchor__glyph:not(#_),
.kodza-heading-anchor__hash:not(#_),
.kodza-heading-anchor__label:not(#_),
.kodza-heading-anchor__word:not(#_),
.kodza-heading-anchor__status:not(#_) {
box-sizing: revert;
}
.kodza-heading-anchor__link:not(#_) {
transition: revert;
list-style: revert;
box-sizing: revert;
float: revert;
box-shadow: revert;
appearance: revert;
max-width: revert;
max-height: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-heading-anchor__check:not(#_) {
border: revert;
margin: revert;
padding: revert;
border-radius: revert;
outline: revert;
text-decoration: revert;
list-style: revert;
box-sizing: revert;
float: revert;
position: revert;
background-color: revert;
background-image: revert;
box-shadow: revert;
outline-offset: revert;
appearance: revert;
max-width: revert;
max-height: revert;
color: revert;
font-family: revert;
font-size: revert;
font-weight: revert;
font-style: revert;
line-height: revert;
letter-spacing: revert;
text-transform: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-heading-anchor h2:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_),
.kodza-heading-anchor h3:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_) {
border: revert;
padding: revert;
border-radius: revert;
outline: revert;
text-decoration: revert;
transition: revert;
list-style: revert;
box-sizing: revert;
float: revert;
position: revert;
background-color: revert;
background-image: revert;
box-shadow: revert;
outline-offset: revert;
appearance: revert;
max-width: revert;
max-height: revert;
font-style: revert;
text-transform: revert;
text-underline-offset: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-heading-anchor p:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_) {
border: revert;
padding: revert;
border-radius: revert;
outline: revert;
text-decoration: revert;
transition: revert;
list-style: revert;
box-sizing: revert;
float: revert;
position: revert;
background-color: revert;
background-image: revert;
box-shadow: revert;
outline-offset: revert;
appearance: revert;
max-width: revert;
max-height: revert;
font-weight: revert;
font-style: revert;
letter-spacing: revert;
text-transform: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-heading-anchor__check:not(#_):where(:not([hidden])),
.kodza-heading-anchor h2:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where(:not([hidden])),
.kodza-heading-anchor p:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where(:not([hidden])),
.kodza-heading-anchor h3:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where(:not([hidden])) {
display: revert;
}
.kodza-heading-anchor__check:not(#_):where([hidden]),
.kodza-heading-anchor h2:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where([hidden]),
.kodza-heading-anchor p:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where([hidden]),
.kodza-heading-anchor h3:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where([hidden]) {
display: none;
}
.kodza-heading-anchor__link:not(#_)::before {
box-sizing: revert;
}
/* The component's own rules, one step stronger: real buttons and fields, what it sets on tags themes style (links, lists, headings, images…), and the root width (a theme may narrow it, never widen it) */
.kodza-heading-anchor > h2:not(#_),
.kodza-heading-anchor > h3:not(#_) {
color: var(--kz-heading-anchor-heading);
font-family: "Geist", system-ui, sans-serif;
font-weight: 600;
text-align: start;
}
.kodza-heading-anchor > h2:not(#_) {
margin: 56px 0 14px;
font-size: clamp(24px, 4vw, 32px);
line-height: 1.2;
letter-spacing: -0.035em;
}
.kodza-heading-anchor > h3:not(#_) {
margin: 36px 0 10px;
font-size: 20px;
line-height: 1.3;
letter-spacing: -0.025em;
}
.kodza-heading-anchor > :is(h2, h3):first-child:where(h2, p, h3):not(#_) {
margin-top: 0;
}
.kodza-heading-anchor > p:not(#_) {
margin: 0 0 1.1em;
color: var(--kz-heading-anchor-text);
font-family: "Geist", system-ui, sans-serif;
font-size: 17px;
line-height: 1.7;
}
.kodza-heading-anchor > p:last-child:not(#_) {
margin-bottom: 0;
}
.kodza-heading-anchor__link:not(#_) {
position: relative;
display: inline;
margin: 0 0 0 var(--kz-heading-anchor-gap, 0.3em);
padding: 0;
border: 0;
border-radius: 6px;
background: none;
color: var(--kz-heading-anchor-ink, currentColor);
font: inherit;
letter-spacing: 0;
text-decoration: none;
text-transform: none;
}
.kodza-heading-anchor__link:dir(rtl):not(#_) {
margin: 0 var(--kz-heading-anchor-gap, 0.3em) 0 0;
}
.kodza-heading-anchor__link:focus-visible:not(#_) {
outline: 2px solid var(--kz-heading-anchor-ink, currentColor);
outline-offset: 3px;
}
.kodza-heading-anchor__check:not(#_) {
transition: translate var(--kz-heading-anchor-duration, 0.24s) var(--kz-heading-anchor-ease, cubic-bezier(0.22, 1, 0.36, 1));
}
.kodza-heading-anchor__link.is-margin:not(#_) {
position: absolute;
display: block;
margin: 0;
}
@media (prefers-reduced-motion: reduce) {
.kodza-heading-anchor__link *:where(svg):not(#_) {
transition-duration: 0.01ms !important;
transition-delay: 0s !important;
}
}
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Kodza — Heading Anchor
// Gives every heading a link to itself: a # in the margin (after the last word on a touch screen,
// in a narrow column or a centred heading) that puts the section's address in the bar and copies it.
// With a mouse, a click on the heading does the same.
// Headings without an id get one, removed again when the script stops. An empty root works on the
// headings of the article around or beside it (data-target), like a Custom HTML block in WordPress.
(() => {
const SELECTOR = '[data-kodza-heading-anchor]';
const RESET_AFTER = 1800;
const pointer = window.matchMedia('(hover: hover) and (pointer: fine)');
// One link, written once and copied for each heading
const MARK = document.createElement('template');
MARK.innerHTML = '<a class="kodza-heading-anchor__link"><span class="kodza-heading-anchor__glyph" aria-hidden="true"><span class="kodza-heading-anchor__hash">#</span><svg class="kodza-heading-anchor__check" viewBox="0 0 16 16"><path d="M3 8.5l3.2 3L13 4.5" pathLength="1" /></svg></span><span class="kodza-heading-anchor__label" aria-hidden="true"><span class="kodza-heading-anchor__word"></span></span></a>';
const slug = (text) => text.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'section';
async function writeText(text) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
const area = document.createElement('textarea');
area.value = text;
area.setAttribute('readonly', '');
area.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none';
document.body.append(area);
area.select();
let ok = false;
try {
ok = document.execCommand('copy');
} catch {}
area.remove();
return ok;
}
}
// The bottom of what stays at the top of the window (a fixed or sticky header): a section reached
// by its link starts below it, not under it
function headerBottom() {
const width = document.documentElement.clientWidth;
let bottom = 0;
[width / 2, 24, width - 24].forEach((x) => {
for (let el = document.elementFromPoint(x, 1); el && el !== document.body && el !== document.documentElement; el = el.parentElement) {
const { position } = getComputedStyle(el);
if (position !== 'fixed' && position !== 'sticky') continue;
const rect = el.getBoundingClientRect();
if (rect.top <= 1 && rect.height < window.innerHeight / 2) bottom = Math.max(bottom, rect.bottom);
break;
}
});
return bottom;
}
// One instance, with its own state: two copies on a page never interfere. Everything it
// starts is tied to `signal` (listeners get { signal }, observers and timers stop on its
// 'abort' event), so kodza:destroy stops it all.
function mount(root, signal) {
const which = root.dataset.headings || 'h2, h3';
let scope = root;
let headings = [...root.querySelectorAll(which)];
if (!headings.length) {
const selector = root.dataset.target || 'article, main, .entry-content';
scope = root.parentElement?.closest(selector);
for (let up = root.parentElement; !scope && up; up = up.parentElement) scope = up.querySelector(selector);
headings = scope ? [...scope.querySelectorAll(which)] : [];
}
// Not the headings of another component, nor those that already hold a link
headings = headings.filter((heading) => {
const owner = heading.parentElement.closest('[class*="kodza-"]');
return /^H[1-6]$/.test(heading.tagName) && heading.textContent.trim() && (!owner || owner === root)
&& !heading.querySelector('a[href]') && !heading.closest('a[href]');
});
if (!headings.length) return;
const label = root.dataset.label || 'Copy link';
const copied = root.dataset.copied || 'Link copied';
const failed = root.dataset.failed || 'In the address bar';
const status = document.createElement('span');
status.className = 'kodza-heading-anchor__status';
status.setAttribute('role', 'status');
root.append(status);
const items = headings.map((heading) => {
const item = { heading, named: !heading.id, timer: 0 };
if (item.named) {
let id = slug(heading.textContent);
for (let n = 2; document.getElementById(id); n++) id = `${slug(heading.textContent)}-${n}`;
heading.id = id;
}
const link = MARK.content.firstElementChild.cloneNode(true);
link.href = `#${heading.id}`;
link.setAttribute('aria-label', label);
item.link = link;
item.hash = link.querySelector('.kodza-heading-anchor__hash');
item.word = link.querySelector('.kodza-heading-anchor__word');
item.text = link.querySelector('.kodza-heading-anchor__label');
// The mark never starts a line on its own: it is tied to the last word
const last = heading.lastChild;
if (last?.nodeType === Node.TEXT_NODE && /\S\s*$/.test(last.data)) {
const at = last.data.search(/\S+\s*$/);
const word = at > 0 ? last.splitText(at) : last;
const end = word.data.search(/\s*$/);
if (end < word.data.length) word.splitText(end);
item.tie = document.createElement('span');
item.tie.className = 'kodza-heading-anchor__tie';
word.before(item.tie);
item.tie.append(word, link);
} else {
heading.append(link);
}
const style = getComputedStyle(heading);
item.style = { position: heading.style.position, scroll: heading.style.scrollMarginTop };
item.ownScroll = parseFloat(style.scrollMarginTop) > 0;
if (style.position === 'static') heading.style.position = 'relative';
return item;
});
// In the margin on a real pointer, when every heading has room on its start side and starts its
// lines there; after the last word otherwise. The scroll margin follows the header.
const layout = () => {
if (!root.isConnected) return;
const width = document.documentElement.clientWidth;
const was = items.map(({ link, heading }) => {
link.style.setProperty('--kz-heading-anchor-top', getComputedStyle(heading).paddingTop);
const on = link.classList.contains('is-margin');
link.classList.add('is-margin');
return on;
});
const margin = pointer.matches && items.every(({ heading, link }) => {
const style = getComputedStyle(heading);
const ltr = style.direction !== 'rtl';
if (!['start', 'justify', ltr ? 'left' : 'right'].includes(style.textAlign)) return false;
const rect = link.getBoundingClientRect();
return ltr ? rect.left >= 8 : rect.right <= width - 8;
});
// A mark that changes side gets there without sliding
items.forEach(({ link, hash }, i) => {
if (!margin) link.classList.remove('is-margin');
if (was[i] !== margin) hash.getAnimations().forEach((animation) => animation.finish());
});
const padded = parseFloat(getComputedStyle(document.documentElement).scrollPaddingTop) > 0;
const offset = parseFloat(getComputedStyle(items[0].link).getPropertyValue('--kz-heading-anchor-offset')) || 24;
const top = padded ? 0 : Math.round(headerBottom() + offset);
items.forEach(({ heading, ownScroll }) => {
if (!ownScroll && !padded) heading.style.scrollMarginTop = `${top}px`;
});
};
// Beside the mark on the side away from the text when it fits, above it otherwise
const show = (item, ok) => {
const { link, word, text, heading } = item;
clearTimeout(item.timer);
word.textContent = ok ? copied : failed;
link.classList.remove('is-above');
const ltr = getComputedStyle(heading).direction !== 'rtl';
const mark = link.getBoundingClientRect();
const room = text.getBoundingClientRect().width + 12;
const box = heading.getBoundingClientRect();
const fits = link.classList.contains('is-margin')
? (ltr ? mark.left - room >= 8 : mark.right + room <= document.documentElement.clientWidth - 8)
: (ltr ? mark.right + room <= box.right : mark.left - room >= box.left);
link.classList.toggle('is-above', !fits);
text.getAnimations({ subtree: true }).forEach((animation) => animation.finish()); // it changes side without sliding
link.classList.add('is-copied');
status.textContent = ok ? copied : `Couldn't copy. The link is ${failed.toLowerCase()}.`;
item.timer = setTimeout(() => {
link.classList.remove('is-copied');
status.textContent = '';
}, RESET_AFTER);
};
const copy = async (item) => {
history.replaceState(history.state, '', `#${item.heading.id}`);
const ok = await writeText(location.href);
if (!signal.aborted) show(item, ok);
};
const plain = (event) => !event.button && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;
items.forEach((item) => {
item.link.addEventListener('click', (event) => {
if (!plain(event)) return; // a new tab, a new window
event.preventDefault();
copy(item);
}, { signal });
// With a mouse, the heading itself does what its mark does: not while its words are being
// selected, nor from a control written in it
item.heading.addEventListener('click', (event) => {
if (!pointer.matches || !plain(event) || event.defaultPrevented) return;
if (event.target.closest('a, button, input, select, textarea, label, summary')) return;
if (getSelection()?.toString().trim()) return;
copy(item);
}, { signal });
});
let frame = 0;
const later = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(layout);
};
const observer = new ResizeObserver(later);
layout();
observer.observe(scope);
window.addEventListener('resize', later, { signal });
pointer.addEventListener('change', later, { signal });
document.fonts?.ready.then(() => {
if (!signal.aborted) layout();
});
// Arriving on a section named here: the browser looked for it before it had its id
let target = null;
try {
target = items.find(({ heading, named }) => named && `#${heading.id}` === decodeURIComponent(location.hash));
} catch {}
if (target) target.heading.scrollIntoView({ block: 'start' });
signal.addEventListener('abort', () => {
observer.disconnect();
cancelAnimationFrame(frame);
status.remove();
items.forEach((item) => {
clearTimeout(item.timer);
const { heading, link, tie } = item;
link.remove();
if (tie) {
tie.replaceWith(...tie.childNodes);
heading.normalize();
}
heading.style.position = item.style.position;
heading.style.scrollMarginTop = item.style.scroll;
if (!heading.getAttribute('style')) heading.removeAttribute('style');
if (item.named) heading.removeAttribute('id');
});
});
}
// Kodza lifecycle, the same in every component: `kodza:init` starts the instances inside
// event.detail.root (the whole page by default), `kodza:destroy` stops them and puts their
// markup back. For themes and apps that swap content without a page load. Each running root
// keeps its markup as written under KODZA, shared by every Kodza script on the page: a Kodza
// component inside another one is saved as written, not half-started, and stopped with it.
const KODZA = Symbol.for('kodza');
const instances = new WeakMap();
const find = (scope = document) => [scope, ...scope.querySelectorAll(SELECTOR)].filter((el) => el.matches?.(SELECTOR));
const attrsOf = (el) => [...el.attributes].map((a) => [a.name, a.value]);
const put = (el, saved) => {
[...el.attributes].forEach((a) => el.removeAttribute(a.name));
saved.attrs.forEach(([name, value]) => el.setAttribute(name, value));
el.innerHTML = saved.html;
};
// The markup inside a root as written: Kodza components already running in it give back their own
const written = (root) => {
const all = [...root.querySelectorAll('*')];
if (!all.some((el) => el[KODZA])) return root.innerHTML;
const copy = root.cloneNode(true);
const twins = copy.querySelectorAll('*');
let last = null;
all.forEach((el, i) => {
if (!el[KODZA] || last?.contains(el)) return;
last = el;
put(twins[i], el[KODZA]);
});
return copy.innerHTML;
};
const init = (scope) => find(scope).forEach((root) => {
if (root.classList.contains('is-ready')) return; // already running, maybe from another copy of this script
const controller = new AbortController();
const saved = { html: written(root), attrs: attrsOf(root), stop: () => destroy(root) };
instances.set(root, { controller, saved });
root[KODZA] = saved;
mount(root, controller.signal);
root.classList.add('is-ready');
});
const destroy = (scope) => find(scope).forEach((root) => {
const instance = instances.get(root);
if (!instance) return;
instances.delete(root);
// The Kodza components running inside it stop first: once its markup is put back, their own
// script could not find them any more
root.querySelectorAll('*').forEach((el) => el[KODZA]?.stop());
instance.controller.abort();
delete root[KODZA];
put(root, instance.saved);
});
document.addEventListener('kodza:init', (event) => init(event.detail?.root));
document.addEventListener('kodza:destroy', (event) => destroy(event.detail?.root));
init();
// Loaded in <head>, the script runs before the markup exists: once more when it is parsed
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => init(), { once: true });
})();
'use client';
// Kodza — Heading Anchor, for React. From https://kodza.dev/components/heading-anchor/
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Next to this file: heading-anchor.css and heading-anchor.js, the component's CSS and JS from Kodza, as they are.
// Yours to edit: the markup is plain JSX below.
// The script changes this markup once React has rendered it (it adds layers, splits text, moves
// nodes), so React must not patch it afterwards. When a prop changes, the key gives React a fresh
// element: kodza:destroy stops the script on the old one, kodza:init starts it on the new one.
// Built from your data (tabs, rows, options)? Put what the markup is made of in the key, as plain
// values (ids, text, numbers): a change starts the script again on fresh markup. What the visitor
// changes (the open tab, the sort, what they type) is the script's: keep it out of the key, follow
// it with onClick or onInput on the root, and change it from your code as a visitor would (click
// the tab; set the field's value, then dispatch a bubbling input event).
import { useRef, useEffect, type ComponentPropsWithoutRef, type ComponentRef, type CSSProperties } from 'react';
import './heading-anchor.css';
export type HeadingAnchorProps = Omit<ComponentPropsWithoutRef<'div'>, "children" | "vars"> & {
/** Settings, as CSS variables on the root */
vars?: {
/** default: #0a0a0a */
"--kz-heading-anchor-heading"?: string | number;
/** default: rgba(10, 10, 10, 0.72) */
"--kz-heading-anchor-text"?: string | number;
/** default: currentColor */
"--kz-heading-anchor-ink"?: string | number;
/** default: color-mix(in srgb, currentColor 50%, transparent) */
"--kz-heading-anchor-muted"?: string | number;
/** default: #fff */
"--kz-heading-anchor-paper"?: string | number;
/** default: rgba(10, 10, 10, 0.1) */
"--kz-heading-anchor-line"?: string | number;
/** default: 0.3em */
"--kz-heading-anchor-gap"?: string | number;
/** default: 0.75em */
"--kz-heading-anchor-size"?: string | number;
/** default: 24px */
"--kz-heading-anchor-offset"?: string | number;
/** default: 0.24s */
"--kz-heading-anchor-duration"?: string | number;
/** default: cubic-bezier(0.22, 1, 0.36, 1) */
"--kz-heading-anchor-ease"?: string | number;
};
className?: string;
};
export function HeadingAnchor({ vars, className, style, ...rest }: HeadingAnchorProps) {
const ref = useRef<ComponentRef<'div'>>(null);
const classes = ["kodza-heading-anchor", className].filter(Boolean).join(' ');
// Everything the markup is made of: when it changes, React gets a fresh element (see the top)
const key = JSON.stringify([classes, vars, style, rest]);
// Starts the script on this element once React has rendered it, stops it when it goes
useEffect(() => {
const root = ref.current;
let live = true;
// @ts-ignore: a plain script, no types to find
import('./heading-anchor.js').then(() => {
if (live) document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root } }));
});
return () => {
live = false;
document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } }));
};
}, [key]);
return (
<div data-kodza-heading-anchor="" key={key} {...rest} className={classes} style={{ ...vars, ...style } as CSSProperties} ref={ref}>
<h2>Install</h2>
<p>Paste the markup, the CSS and the script. That's the install. No package, no build step, no config file to babysit.</p>
<h3>In WordPress</h3>
<p>Leave the block empty and drop it anywhere in the post: it finds the headings of the article around it. Your theme's titles keep their look.</p>
<h2>Behind a sticky header</h2>
<p>The script measures your fixed header and stops each section just below it. Nobody lands on a title hiding under the logo.</p>
<h3>Ids, handled</h3>
<p>Headings without an id get one from their text. It goes away when the script stops, so the HTML you saved stays the HTML you wrote.</p>
</div>
);
}
Checked
Robots poked at it before you did. Every component goes through the same checks, and again each time it changes.