Curtain Transition
Between two real pages, an ink panel rises with the name of the next page, then lifts off onto it. Back plays it in reverse. Curved edge or from the top. Chrome, Edge, Safari.
View codeBetween two real pages, the picture you click grows into its place on the next page while the rest of it plays its entrance. Back, it shrinks into its card. Chrome, Edge, Safari.
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 Shared Element Morph to my page.
claude mcp add -t http kodza https://kodza.dev/api/mcp
<section class="kodza-shared-element-morph" data-kodza-shared-element-morph>
<p class="kodza-shared-element-morph__label" data-enter="label">Case study · 04 / 12</p>
<div class="kodza-shared-element-morph__split">
<h1 class="kodza-shared-element-morph__title" data-enter="title">The deploy that went out on a Friday</h1>
<div class="kodza-shared-element-morph__intro">
<p class="kodza-shared-element-morph__lead" data-enter>A full redesign, shipped four minutes before the weekend. No rollback, no war room, nobody paged. Here is how a team of three made it boring on purpose.</p>
<dl class="kodza-shared-element-morph__facts">
<div data-enter><dt>Client</dt><dd>Null & Void</dd></div>
<div data-enter><dt>Year</dt><dd>2026</dd></div>
<div data-enter><dt>Shipped</dt><dd>Fri, 17:56</dd></div>
</dl>
</div>
</div>
<figure class="kodza-shared-element-morph__media">
<div class="kodza-shared-element-morph__frame" data-page-morph>
<img class="kodza-shared-element-morph__image" src="https://kodza.dev/media/kz-steps-2400.webp" width="2400" height="1600" alt="Concrete steps climbing through bare grey walls">
</div>
<figcaption data-enter><span>fig. 1 — the release plan, in its final form</span><span>git push, then leave</span></figcaption>
</figure>
</section>
/* Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license */
/* Kodza — Shared Element Morph
A page transition between two real pages (cross-document View Transitions). The image (or
title) you click in a list grows into its place on the next page while the new page comes in
over the one you leave, and plays its arrival: the label, the title rising line by line, the
rest in a cascade (mark them with data-enter="label", "title", or just data-enter). Mark both
ends of the trip with data-page-morph: the same value on the card and on the page it opens,
or leave it empty (the card's link and the page's own address then pair them). Going back,
it shrinks into its card while the arrival plays in reverse. The trip is seamless when the card keeps the whole width of its
picture (a card as wide as the picture, in proportions, or wider) and the page's frame is wider
still: the 3:2 cards and the 21:9 frame here. Without the API (Firefox) or with reduced
motion, navigation stays plain. Tuned with the --kz-shared-element-morph-* variables, on .kodza-shared-element-morph
(or on html, for the pages without the section). */
.kodza-shared-element-morph {
--kz-shared-element-morph-duration: 0.8s; /* the trip of the image, and the pages trading places */
--kz-shared-element-morph-ease: cubic-bezier(0.65, 0, 0.35, 1);
--kz-shared-element-morph-radius: calc(16px * var(--kz-radius-scale, 1)); /* its corners on the way */
--kz-shared-element-morph-backdrop: transparent; /* between the two pages: your page colour shows through */
--kz-shared-element-morph-enter-delay: 0.24s; /* the arrival starts while the image is on its way */
--kz-shared-element-morph-enter-ease: cubic-bezier(0.2, 0.8, 0.1, 1);
--kz-shared-element-morph-bg: #f2f2f0;
--kz-shared-element-morph-fg: #0a0a0a;
--kz-shared-element-morph-muted: rgba(10, 10, 10, 0.62);
--kz-shared-element-morph-line: rgba(10, 10, 10, 0.12);
--kz-shared-element-morph-image-radius: calc(16px * var(--kz-radius-scale, 1));
--kz-shared-element-morph-side: 24px;
box-sizing: border-box;
padding: 64px var(--kz-shared-element-morph-side) 72px;
background: var(--kz-shared-element-morph-bg);
color: var(--kz-shared-element-morph-fg);
font-size: 15px;
line-height: 1.5;
text-align: left;
}
/* ---------- The morph: drawn by the browser between two documents ---------- */
@view-transition {
navigation: auto;
}
/* The script marks the page (kodza-shared-element-morph-on); without it, a page with the section still swaps */
:is(html.kodza-shared-element-morph-on, html:has(.kodza-shared-element-morph):not(.kodza-page-engine))::view-transition {
background: var(--kz-shared-element-morph-backdrop, transparent);
}
:is(html.kodza-shared-element-morph-on, html:has(.kodza-shared-element-morph):not(.kodza-page-engine))::view-transition-group(root) {
animation: none;
}
:is(html.kodza-shared-element-morph-on, html:has(.kodza-shared-element-morph):not(.kodza-page-engine))::view-transition-old(root),
:is(html.kodza-shared-element-morph-on, html:has(.kodza-shared-element-morph):not(.kodza-page-engine))::view-transition-new(root),
html.kodza-shared-element-morph-on::view-transition-group(*.kodza-shared-element-morph-item),
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-item),
html.kodza-shared-element-morph-on::view-transition-new(*.kodza-shared-element-morph-item) {
mix-blend-mode: normal;
animation-duration: var(--kz-shared-element-morph-duration, 0.8s);
animation-timing-function: var(--kz-shared-element-morph-ease, cubic-bezier(0.65, 0, 0.35, 1));
animation-delay: calc(var(--kz-shared-element-morph-at, 0) * var(--kz-shared-element-morph-duration, 0.8s) * -1); /* an interrupted morph goes on from where it was */
animation-fill-mode: both;
}
/* The page you leave holds still, the next one comes in over it, behind the image: never a
moment where both are see-through. Back too: the image always flies (into its card, this time) */
:is(html.kodza-shared-element-morph-on, html:has(.kodza-shared-element-morph):not(.kodza-page-engine))::view-transition-old(root) {
animation-name: none;
}
:is(html.kodza-shared-element-morph-on, html:has(.kodza-shared-element-morph):not(.kodza-page-engine))::view-transition-new(root) {
animation-name: kodza-shared-element-morph-arrive;
}
/* The image, above the pages and under the header. Its group moves and resizes (the browser
animates it from one box to the other); inside, its corners stay round and the picture
keeps its proportions, cropped like an object-fit: cover */
html.kodza-shared-element-morph-on::view-transition-group(*.kodza-shared-element-morph-item) {
z-index: 40;
}
html.kodza-shared-element-morph-on::view-transition-image-pair(*.kodza-shared-element-morph-item) {
overflow: clip;
border-radius: var(--kz-shared-element-morph-radius, calc(16px * var(--kz-radius-scale, 1)));
}
/* The picture you clicked stays until its box has nearly the next one's shape, then the new one
shows over it: a card and a wide picture never trade crops at the click. Going back, the card
frames like the wide picture from the start, so it takes over in the first third */
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-item),
html.kodza-shared-element-morph-on::view-transition-new(*.kodza-shared-element-morph-item) {
width: 100%;
height: 100%;
object-fit: cover;
}
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-item) {
animation-name: none;
}
html.kodza-shared-element-morph-on::view-transition-new(*.kodza-shared-element-morph-item) {
animation-name: kodza-shared-element-morph-show;
animation-timing-function: ease-in-out;
}
html.kodza-shared-element-morph-on.kodza-shared-element-morph-back::view-transition-new(*.kodza-shared-element-morph-item) {
animation-name: kodza-shared-element-morph-show-early;
animation-timing-function: ease-out;
}
/* Nothing to pair it with on the next page: it leaves with its page, or arrives with it */
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-item):only-child {
animation-name: kodza-shared-element-morph-leave;
animation-timing-function: var(--kz-shared-element-morph-ease, cubic-bezier(0.65, 0, 0.35, 1));
}
html.kodza-shared-element-morph-on::view-transition-new(*.kodza-shared-element-morph-item):only-child {
animation-name: kodza-shared-element-morph-arrive;
}
/* Back, the arrival plays in reverse (the script names each part, its kind and rank): the rest
drops away, last part first, the title sinks into its masks line by line from the bottom, the
label goes last. The next page waits until they are gone: the two texts never mix */
html.kodza-shared-element-morph-on::view-transition-group(*.kodza-shared-element-morph-out) {
animation: none;
}
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-out) {
--kz-shared-element-morph-drop: 16px;
animation: kodza-shared-element-morph-drop calc(var(--kz-shared-element-morph-duration, 0.8s) * 0.25) cubic-bezier(0.65, 0, 0.35, 1) both;
animation-delay: calc(var(--kz-shared-element-morph-duration, 0.8s) * (0.03 * var(--kz-shared-element-morph-i, 0) - var(--kz-shared-element-morph-at, 0)));
}
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-out-word) {
animation-name: kodza-shared-element-morph-sink;
animation-timing-function: cubic-bezier(0.32, 0, 0.67, 0);
animation-duration: calc(var(--kz-shared-element-morph-duration, 0.8s) * 0.32);
animation-delay: calc(var(--kz-shared-element-morph-duration, 0.8s) * (0.06 + 0.04 * var(--kz-shared-element-morph-i, 0) - var(--kz-shared-element-morph-at, 0)));
}
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-out-label) {
--kz-shared-element-morph-drop: 8px;
animation-duration: calc(var(--kz-shared-element-morph-duration, 0.8s) * 0.2);
animation-delay: calc(var(--kz-shared-element-morph-duration, 0.8s) * (0.26 - var(--kz-shared-element-morph-at, 0)));
}
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-out-i1) { --kz-shared-element-morph-i: 1; }
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-out-i2) { --kz-shared-element-morph-i: 2; }
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-out-i3) { --kz-shared-element-morph-i: 3; }
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-out-i4) { --kz-shared-element-morph-i: 4; }
html.kodza-shared-element-morph-on::view-transition-old(*.kodza-shared-element-morph-out-i5) { --kz-shared-element-morph-i: 5; }
html.kodza-shared-element-morph-on.kodza-shared-element-morph-back::view-transition-new(root) {
animation-name: kodza-shared-element-morph-arrive-late;
}
/* The header stays: the script names it on both pages, the new one is shown from the start */
:is(html.kodza-shared-element-morph-on, html:has(.kodza-shared-element-morph):not(.kodza-page-engine))::view-transition-group(*.kodza-shared-element-morph-stay) {
z-index: 50;
animation: none;
}
:is(html.kodza-shared-element-morph-on, html:has(.kodza-shared-element-morph):not(.kodza-page-engine))::view-transition-old(*.kodza-shared-element-morph-stay) {
animation: none;
opacity: 0;
}
/* It fills its group: Firefox keeps the proportions of its first capture, so a header that
widens while the page changes (a pill growing back to full width) would grow taller with it */
:is(html.kodza-shared-element-morph-on, html:has(.kodza-shared-element-morph):not(.kodza-page-engine))::view-transition-new(*.kodza-shared-element-morph-stay) {
height: 100%;
mix-blend-mode: normal;
animation: none;
}
@keyframes kodza-shared-element-morph-leave {
0% {
opacity: 1;
}
45%,
100% {
opacity: 0;
}
}
/* The window stays put while the word drops through it: open above (accents) and on the sides */
@keyframes kodza-shared-element-morph-sink {
from {
transform: none;
clip-path: inset(-50% -50% 0 -50%);
}
to {
transform: translateY(130%);
clip-path: inset(-180% -50% 130% -50%);
}
}
@keyframes kodza-shared-element-morph-drop {
to {
opacity: 0;
transform: translateY(var(--kz-shared-element-morph-drop, 16px));
}
}
@keyframes kodza-shared-element-morph-arrive-late {
0%,
40% {
opacity: 0;
}
75%,
100% {
opacity: 1;
}
}
@keyframes kodza-shared-element-morph-arrive {
0%,
10% {
opacity: 0;
}
55%,
100% {
opacity: 1;
}
}
@keyframes kodza-shared-element-morph-show {
0%,
50% {
opacity: 0;
}
75%,
100% {
opacity: 1;
}
}
@keyframes kodza-shared-element-morph-show-early {
0% {
opacity: 0;
}
30%,
100% {
opacity: 1;
}
}
/* ---------- The arrival: hidden from the first paint, until the script plays it ---------- */
@media (prefers-reduced-motion: no-preference) {
html.kodza-shared-element-morph-enter .kodza-shared-element-morph [data-enter] {
opacity: 0;
animation: kodza-shared-element-morph-failsafe 0.5s 2.5s both; /* no script: the page shows anyway */
}
}
@keyframes kodza-shared-element-morph-failsafe {
to {
opacity: 1;
}
}
/* The title, cut into words by the script: each one rises from behind its own edge */
.kodza-shared-element-morph__mask {
display: inline-block;
vertical-align: top;
margin-bottom: -0.16em;
padding-bottom: 0.16em; /* room for the descenders, inside the mask */
}
.kodza-shared-element-morph.is-entering .kodza-shared-element-morph__mask {
clip-path: inset(-0.3em -0.2em 0 -0.2em); /* open above, for the accents */
}
.kodza-shared-element-morph__word {
display: inline-block;
}
/* ---------- The section: a case study opening ---------- */
.kodza-shared-element-morph__label,
.kodza-shared-element-morph__facts dt,
.kodza-shared-element-morph__media figcaption {
margin: 0;
font-family: var(--kz-font-mono, "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace);
font-size: 12px;
font-weight: 400;
line-height: 1.4;
letter-spacing: 0;
color: var(--kz-shared-element-morph-muted);
}
.kodza-shared-element-morph__label {
margin-bottom: 24px;
}
.kodza-shared-element-morph__split {
display: grid;
grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr);
align-items: end;
gap: 32px 64px;
}
.kodza-shared-element-morph__title {
margin: 0;
color: inherit;
font-family: var(--kz-font-display, inherit);
font-size: calc(clamp(44px, 6.6vw, 96px) * var(--kz-font-display-scale, 1));
font-weight: var(--kz-font-display-weight, 600);
line-height: 0.95;
letter-spacing: var(--kz-font-display-tracking, -0.055em);
text-transform: var(--kz-font-display-case, inherit);
text-wrap: balance;
}
.kodza-shared-element-morph__intro {
display: grid;
gap: 32px;
padding-bottom: 6px;
}
.kodza-shared-element-morph__lead {
max-width: 30em;
margin: 0;
color: var(--kz-shared-element-morph-muted);
font-size: clamp(16px, 1.4vw, 18px);
line-height: 1.5;
text-wrap: pretty;
}
.kodza-shared-element-morph__facts {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 16px;
margin: 0;
padding: 0;
}
.kodza-shared-element-morph__facts > div {
padding-top: 12px;
border-top: 1px solid var(--kz-shared-element-morph-line);
}
.kodza-shared-element-morph__facts dd {
margin: 6px 0 0;
font-size: 15px;
font-weight: 500;
letter-spacing: -0.01em;
}
.kodza-shared-element-morph__media {
margin: 56px 0 0;
}
.kodza-shared-element-morph__frame {
overflow: hidden;
aspect-ratio: 21 / 9;
border-radius: var(--kz-shared-element-morph-image-radius);
background: var(--kz-shared-element-morph-line);
}
.kodza-shared-element-morph__image {
display: block;
width: 100%;
height: 100%;
max-width: none;
margin: 0;
object-fit: cover;
}
.kodza-shared-element-morph__media figcaption {
display: flex;
justify-content: space-between;
gap: 16px;
margin-top: 12px;
}
@media (max-width: 860px) {
.kodza-shared-element-morph {
padding-top: 48px;
}
.kodza-shared-element-morph__split {
grid-template-columns: minmax(0, 1fr);
}
.kodza-shared-element-morph__media {
margin-top: 40px;
}
.kodza-shared-element-morph__frame {
aspect-ratio: 3 / 2;
}
}
@media (max-width: 480px) {
.kodza-shared-element-morph__media figcaption span + span {
display: none;
}
}
/* Reduced motion: plain navigation, the page straight away */
@media (prefers-reduced-motion: reduce) {
@view-transition {
navigation: none;
}
}
/* kodza-guard 315023110a5b — 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, on everything the component leaves to it */
.kodza-shared-element-morph__label:not(#_),
.kodza-shared-element-morph__facts dt:where(:is(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))):not(.kodza-shared-element-morph__facts :not(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))) *)):not(#_),
.kodza-shared-element-morph__media figcaption:where(:is(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))):not(.kodza-shared-element-morph__media :not(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))) *)):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-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-shared-element-morph__split:not(#_),
.kodza-shared-element-morph__intro:not(#_),
.kodza-shared-element-morph__frame:not(#_),
.kodza-shared-element-morph__facts div:where(:is(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))):not(.kodza-shared-element-morph__facts :not(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))) *)):not(#_),
.kodza-shared-element-morph__media span:where(:is(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))):not(.kodza-shared-element-morph__media :not(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))) *)):not(#_) {
box-sizing: revert;
}
.kodza-shared-element-morph__title: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-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-shared-element-morph__lead: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-height: revert;
font-family: 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-shared-element-morph__facts:not(#_) {
border: 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;
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-shared-element-morph__media: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;
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-shared-element-morph__image: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-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-shared-element-morph__facts dd:where(:is(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))):not(.kodza-shared-element-morph__facts :not(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))) *)):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;
color: revert;
font-family: revert;
font-style: revert;
line-height: revert;
text-transform: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-shared-element-morph__label:not(#_):where(:not([hidden])),
.kodza-shared-element-morph__title:not(#_):where(:not([hidden])),
.kodza-shared-element-morph__lead:not(#_):where(:not([hidden])),
.kodza-shared-element-morph__media:not(#_):where(:not([hidden])),
.kodza-shared-element-morph__facts dt:where(:is(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))):not(.kodza-shared-element-morph__facts :not(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))) *)):not(#_):where(:not([hidden])),
.kodza-shared-element-morph__facts dd:where(:is(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))):not(.kodza-shared-element-morph__facts :not(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))) *)):not(#_):where(:not([hidden])) {
display: revert;
}
.kodza-shared-element-morph__label:not(#_):where([hidden]),
.kodza-shared-element-morph__title:not(#_):where([hidden]),
.kodza-shared-element-morph__lead:not(#_):where([hidden]),
.kodza-shared-element-morph__media:not(#_):where([hidden]),
.kodza-shared-element-morph__facts dt:where(:is(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))):not(.kodza-shared-element-morph__facts :not(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))) *)):not(#_):where([hidden]),
.kodza-shared-element-morph__facts dd:where(:is(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))):not(.kodza-shared-element-morph__facts :not(:not([class]), [class=""], [class^="is-"]:not([class*="kodza-"]):not([class*=" "]:not([class*=" is-"]))) *)):not(#_):where([hidden]) {
display: none;
}
/* 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-shared-element-morph__label:not(#_),
.kodza-shared-element-morph__facts dt:not(#_),
.kodza-shared-element-morph__media figcaption:not(#_) {
margin: 0;
font-family: var(--kz-font-mono, "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace);
font-size: 12px;
font-weight: 400;
line-height: 1.4;
letter-spacing: 0;
color: var(--kz-shared-element-morph-muted);
}
.kodza-shared-element-morph__label:not(#_) {
margin-bottom: 24px;
}
.kodza-shared-element-morph__title:not(#_) {
margin: 0;
color: inherit;
font-family: var(--kz-font-display, inherit);
font-size: calc(clamp(44px, 6.6vw, 96px) * var(--kz-font-display-scale, 1));
font-weight: var(--kz-font-display-weight, 600);
line-height: 0.95;
letter-spacing: var(--kz-font-display-tracking, -0.055em);
text-transform: var(--kz-font-display-case, inherit);
}
.kodza-shared-element-morph__lead:not(#_) {
max-width: 30em;
margin: 0;
color: var(--kz-shared-element-morph-muted);
font-size: clamp(16px, 1.4vw, 18px);
line-height: 1.5;
}
.kodza-shared-element-morph__facts:not(#_) {
display: grid;
margin: 0;
padding: 0;
}
.kodza-shared-element-morph__facts dd:not(#_) {
margin: 6px 0 0;
font-size: 15px;
font-weight: 500;
letter-spacing: -0.01em;
}
.kodza-shared-element-morph__media:not(#_) {
margin: 56px 0 0;
}
.kodza-shared-element-morph__image:not(#_) {
display: block;
max-width: none;
margin: 0;
}
.kodza-shared-element-morph__media figcaption:not(#_) {
display: flex;
margin-top: 12px;
}
@media (max-width: 860px) {
.kodza-shared-element-morph__media:not(#_) {
margin-top: 40px;
}
}
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Kodza — Shared Element Morph
// The morph itself is CSS: between two real pages the browser draws it (cross-document View
// Transitions). The script names the element clicked and its twin on the next page just before
// each page is captured, gives the transition its direction (back plays it from wherever an
// interrupted one was), keeps the header in place, plays the arrival of the new page, and runs
// the same morph inside one page for sites that swap their content (kodza:page-transition).
(() => {
const SELECTOR = '[data-kodza-shared-element-morph]';
// The two lines that change from one page transition of the family to the next
const NAME = 'shared-element-morph';
const VARS = ['duration', 'ease', 'radius', 'backdrop'];
// ---------- Page engine (begin) ----------
// The same block in every page transition of the family (Page Lift, Curtain, Stairs...),
// copied as is. The page you leave writes a short record (direction, where an interrupted
// transition was, which headers stay); the page that lands reads it before its first paint.
// Pages: data-page-back on a link plays the return (an "All work" link), data-page-stay marks
// what stays in place (the site header by default), data-enter the parts of the arrival.
const html = document.documentElement;
const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
const ON = `kodza-${NAME}-on`;
const BACK = `kodza-${NAME}-back`;
const ENTER = `kodza-${NAME}-enter`;
const STAY = `kodza-${NAME}-stay`;
const KEY = 'kodza-page-engine';
const WAIT = 5000; // ms a turned-round transition can wait for its content swap
const navType = performance.getEntriesByType('navigation')[0]?.type;
const signals = new WeakMap(); // root -> its signal, for its arrival
const entries = new WeakMap(); // root -> its arrival, prepared or playing
const pending = new Set(); // arrivals waiting for their start
let go = null; // when the arrival starts, once the page knows
let current = null; // the transition running
let heading = null; // where it goes: true back, false forward
let local = null; // the one this page runs itself, around a content swap
let turn = null; // the swap waiting for the page on screen to be out of sight
let hold = null; // its animations, kept on until the swap is done
let stayed = [];
let pressed = null;
let revealed = false;
// One engine per page: an earlier one (another transition of the family) steps aside
document.dispatchEvent(new CustomEvent('kodza:page-engine'));
const page = new AbortController();
document.addEventListener('kodza:page-engine', () => {
page.abort();
html.classList.remove(ON, BACK, ENTER);
}, { once: true, signal: page.signal });
html.classList.add(ON, 'kodza-page-engine');
const here = (href) => {
const url = new URL(href, location.href);
url.hash = '';
return url.href;
};
const ms = (value, fallback) => {
const n = parseFloat(value);
return Number.isNaN(n) ? fallback : /ms\s*$/.test(value) ? n : n * 1000;
};
const now = () => document.timeline.currentTime;
const shown = () => [...document.querySelectorAll(SELECTOR)].filter((root) => root.getClientRects().length);
// Where the transition running is, as a share of the way forward (null: none is)
function progress() {
const run = document.getAnimations().find((a) => a.animationName?.startsWith(`kodza-${NAME}`) && a.effect?.pseudoElement?.startsWith('::view-transition'));
if (!run) return null;
const { delay, duration } = run.effect.getTiming();
const t = Math.min(Math.max((run.currentTime ?? 0) - delay, 0), duration) / duration;
return html.classList.contains(BACK) ? 1 - t : t;
}
// Settings of the section that decides (the one that arrives, or the one you leave going back)
function values(root) {
if (!root) return null;
const style = getComputedStyle(root);
const out = {};
VARS.forEach((v) => {
const value = style.getPropertyValue(`--kz-${NAME}-${v}`).trim();
if (value) out[v] = value;
});
return out;
}
const apply = (out) => Object.entries(out || {}).forEach(([v, value]) => html.style.setProperty(`--kz-${NAME}-${v}`, value));
// What stays in place: [data-page-stay], or the site header (and the WordPress admin bar)
// when it sits at the top of the screen. Going back through history, a header that scrolls
// with its page may not be at the top of the next one: only a fixed or sticky one stays.
function candidates() {
const marked = document.querySelectorAll('[data-page-stay]');
if (marked.length) return [...marked];
return [...document.querySelectorAll('header, #wpadminbar')].filter((el) => !el.parentElement?.closest(`header, main, article, section, aside, footer, ${SELECTOR}`));
}
function stays(el, traverse) {
const box = el.getBoundingClientRect();
if (!box.height || box.top < -1 || box.top > 64 || box.height > innerHeight * 0.4) return false;
if (!traverse) return true;
for (let node = el; node && node !== html; node = node.parentElement) {
if (/fixed|sticky/.test(getComputedStyle(node).position)) return true;
}
return false;
}
function release() {
stayed.forEach((el) => {
el.style.removeProperty('view-transition-name');
el.style.removeProperty('view-transition-class');
});
stayed = [];
}
function name(only, traverse) {
release();
const named = [];
candidates().forEach((el, i) => {
if ((only && !only.includes(i)) || !stays(el, traverse)) return;
el.style.setProperty('view-transition-name', `${STAY}-${i}`);
el.style.setProperty('view-transition-class', STAY);
stayed.push(el);
named.push(i);
});
return named;
}
function unturn() {
hold?.forEach((a) => a.playState !== 'idle' && a.finish());
hold = null;
turn = null;
}
function clean() {
unturn();
heading = null;
html.classList.remove(BACK);
html.style.removeProperty(`--kz-${NAME}-at`);
VARS.forEach((v) => html.style.removeProperty(`--kz-${NAME}-${v}`));
release();
}
// The record the page you leave writes, read once by the next one
function read(restored) {
let record = null;
try {
record = JSON.parse(sessionStorage.getItem(KEY));
sessionStorage.removeItem(KEY);
} catch (error) {
record = null;
}
if (record && (Date.now() - record.time > 4000 || (record.to && record.to !== here(location.href)))) record = null;
const activation = window.navigation?.activation;
const from = activation?.from;
const back = record ? record.back
: activation?.navigationType === 'traverse' ? !from || from.index < 0 || activation.entry.index < from.index
: restored || navType === 'back_forward';
// An interrupted transition turned around goes on from where it was
const at = !record || record.p == null || record.was === back ? 0 : back ? 1 - record.p : record.p;
return { back, at, stay: record?.stay || [], vars: record?.vars };
}
// The arrival: label, title line by line from its mask, image uncovering as it tightens, the
// rest in a cascade. Prepared hidden (paused on its first frame), started once the page knows.
// The title is cut into words for it, and put back as it was once they have landed.
function split(title) {
const nodes = [];
const walker = document.createTreeWalker(title, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) nodes.push(walker.currentNode);
const words = [];
nodes.forEach((node) => {
const fragment = document.createDocumentFragment();
node.data.split(/(\s+)/).forEach((piece) => {
if (!piece) return;
if (!piece.trim()) {
fragment.append(piece);
return;
}
const mask = document.createElement('span');
const word = document.createElement('span');
mask.className = `kodza-${NAME}__mask`;
word.className = `kodza-${NAME}__word`;
word.textContent = piece;
mask.append(word);
fragment.append(mask);
words.push(word);
});
node.replaceWith(fragment);
});
return words;
}
function prepare(root) {
const signal = signals.get(root);
if (!signal || signal.aborted || motion.matches) return;
entries.get(root)?.stop();
const parts = [...root.querySelectorAll('[data-enter]')];
if (!parts.length) return;
const style = getComputedStyle(root);
const easing = style.getPropertyValue(`--kz-${NAME}-enter-ease`).trim() || 'cubic-bezier(0.2, 0.8, 0.1, 1)';
const reveal = style.getPropertyValue(`--kz-${NAME}-reveal-ease`).trim() || 'cubic-bezier(0.65, 0, 0.35, 1)';
const delay = ms(style.getPropertyValue(`--kz-${NAME}-enter-delay`), 360);
const title = parts.find((el) => el.dataset.enter === 'title');
const markup = title?.innerHTML;
const words = title ? split(title) : [];
const anims = [];
const add = (el, keyframes, duration, ease = easing) => {
const anim = el.animate(keyframes, { duration, easing: ease, fill: 'both' });
anim.pause();
anims.push(anim);
return anim;
};
root.classList.add('is-entering');
parts.filter((el) => el.dataset.enter === 'label').forEach((el) => add(el, [{ opacity: 0, transform: 'translateY(8px)' }, { opacity: 1, transform: 'none' }], 500));
const lines = words.map((word) => [word, add(word, [{ transform: 'translateY(calc(110% + 0.16em))' }, { transform: 'none' }], 850)]);
const image = parts.filter((el) => el.dataset.enter === 'image').flatMap((el) => {
const media = el.matches('img, video, picture') ? null : el.querySelector('img, video, picture');
const round = getComputedStyle(el).borderTopLeftRadius || '0px';
return [
// A big image uncovers slowly at first: with the entry curve, half of it would show in 100 ms.
// Its lower edge rounds as it reaches the corners (Chrome's compositor draws it so anyway).
add(el, [{ clipPath: 'inset(0 0 100% 0 round 0px)' }, { clipPath: `inset(0 0 0% 0 round ${round})` }], 900, reveal),
...(media ? [add(media, [{ transform: 'scale(1.25)' }, { transform: 'none' }], 1300)] : []),
];
});
const rest = parts.filter((el) => !['label', 'title', 'image'].includes(el.dataset.enter)).map((el) => add(el, [{ opacity: 0, transform: 'translateY(16px)' }, { opacity: 1, transform: 'none' }], 650));
const stop = () => {
anims.forEach((anim) => anim.cancel());
if (title && title.innerHTML !== markup) title.innerHTML = markup;
root.classList.remove('is-entering');
pending.delete(entry);
if (entries.get(root) === entry) entries.delete(root);
};
const entry = {
stop,
start({ time, lifted }) {
// Lines are measured now, in their final font: the words of a line rise together
let top = null;
let line = -1;
lines.forEach(([word, anim]) => {
const y = Math.round(word.parentElement.getBoundingClientRect().top);
if (y !== top) {
top = y;
line += 1;
}
anim.effect.updateTiming({ delay: 60 + line * 90 });
});
image.forEach((anim) => anim.effect.updateTiming({ delay: 120 }));
rest.forEach((anim, i) => anim.effect.updateTiming({ delay: 60 + (line + 1) * 90 + i * 70 }));
const at = Math.max(time + (lifted ? delay : 0), now());
anims.forEach((anim) => {
anim.startTime = at;
});
Promise.all(anims.map((anim) => anim.finished)).then(stop, () => {});
},
};
entries.set(root, entry);
signal.addEventListener('abort', stop, { once: true });
if (go) entry.start(go);
else pending.add(entry);
}
function arrive(time, lifted) {
go = { time, lifted };
pending.forEach((entry) => entry.start(go));
pending.clear();
}
// Inside one page (Swup, an app, the demo): the same transition around a content swap.
// document.dispatchEvent(new CustomEvent('kodza:page-transition', { cancelable: true,
// detail: { update: () => swapTheContent(), back: false } })) || nothing to do
// dispatchEvent() returns true when no engine took it: then run update() yourself.
function swap(update, back) {
const lift = Boolean(document.startViewTransition) && !motion.matches;
if (lift && current && current === local && turn && back === heading) {
const first = turn; // already on its way there: this swap waits its turn too
turn = async () => {
await first();
await update();
};
return;
}
if (lift && current && current === local && !turn && back !== heading && reverse(update, back)) return;
unturn();
const before = shown();
const p = lift ? progress() : null;
const at = p == null || back === heading ? 0 : back ? 1 - p : p;
const stay = lift ? name(null, false) : [];
const run = async () => {
await update();
init();
const after = shown();
const arriving = after.filter((root) => !before.includes(root));
if (lift) {
VARS.forEach((v) => html.style.removeProperty(`--kz-${NAME}-${v}`));
apply(back ? values(before.find((root) => !after.includes(root))) || values(after[0]) : values(arriving[0]) || values(after[0]));
name(stay, false);
}
go = null;
if (!back && !at) arriving.forEach(prepare);
};
if (!lift) {
run().then(() => arrive(now(), false));
return;
}
const vt = document.startViewTransition(run);
current = vt;
local = vt;
heading = back;
html.classList.toggle(BACK, back);
html.style.setProperty(`--kz-${NAME}-at`, at);
vt.ready.then(() => arrive(now(), true), () => arrive(now(), false));
vt.finished.finally(() => {
if (current !== vt) return;
current = null;
clean();
});
}
// Turned round in the middle (back while it lifts, or the other way): the same transition
// plays backwards from where it is, and the content swaps once it is back where it started,
// the page it was showing out of sight. A new one would first show that page whole, a frame.
// It goes back to the page it came from, as a "back" does. Its animations wait at their start
// (a longer delay, the same place) until the swap is done: the transition stays on screen.
function reverse(update, back) {
const runs = document.getAnimations().filter((a) => a.effect?.pseudoElement?.startsWith('::view-transition') && a.playState === 'running');
if (!runs.length) return false;
runs.forEach((a) => {
const time = a.currentTime;
a.effect.updateTiming({ delay: a.effect.getTiming().delay + WAIT });
a.currentTime = time + WAIT;
a.updatePlaybackRate(-a.playbackRate);
});
hold = runs;
heading = back;
turn = update;
const wait = () => {
if (hold !== runs) return;
if (runs.some((a) => a.currentTime > WAIT)) {
requestAnimationFrame(wait);
return;
}
Promise.resolve()
.then(() => turn())
.then(init)
.finally(() => hold === runs && unturn());
};
requestAnimationFrame(wait);
return true;
}
document.addEventListener('kodza:page-transition', (event) => {
if (typeof event.detail?.update !== 'function') return;
event.preventDefault();
swap(event.detail.update, Boolean(event.detail.back));
}, { signal: page.signal });
// Between two documents: the page you leave writes the record...
document.addEventListener('click', (event) => {
const link = event.target.closest?.('a[href]');
pressed = link?.hasAttribute('data-page-back') ? { href: here(link.href), time: Date.now() } : null;
}, { capture: true, signal: page.signal });
// While the pages trade places the browser sends every click to the page itself: one on the
// header that stays goes on to the link under it (back, in the middle of a lift, turns it round).
// After the listener above, which would forget the link pressed.
document.addEventListener('click', (event) => {
if (!current || event.target !== html) return;
const { clientX: x, clientY: y } = event;
const hit = stayed.flatMap((el) => [...el.querySelectorAll('a[href], button')]).find((el) => {
const box = el.getBoundingClientRect();
return x >= box.left && x <= box.right && y >= box.top && y <= box.bottom;
});
hit?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window, detail: 1, clientX: x, clientY: y, ctrlKey: event.ctrlKey, metaKey: event.metaKey, shiftKey: event.shiftKey, altKey: event.altKey }));
}, { capture: true, signal: page.signal });
window.addEventListener('pageswap', (event) => {
if (!event.viewTransition) return;
const activation = event.activation;
const traverse = activation?.navigationType === 'traverse';
const to = activation?.entry?.url ? here(activation.entry.url) : '';
const clicked = Boolean(pressed) && Date.now() - pressed.time < 4000 && (!to || pressed.href === to);
const record = {
to,
back: traverse ? activation.entry.index < activation.from.index : clicked,
p: progress(),
was: heading,
stay: name(null, traverse),
vars: values(shown()[0]),
time: Date.now(),
};
try {
sessionStorage.setItem(KEY, JSON.stringify(record));
} catch (error) {
// no storage: the next page still lifts, forward
}
}, { signal: page.signal });
// ...and the page that lands reads it before its first paint
let landing = read(false);
if (!motion.matches && !landing.back && !landing.at && navType !== 'back_forward' && !performance.getEntriesByType('paint').length) html.classList.add(ENTER);
window.addEventListener('pagereveal', (event) => {
const land = landing || read(true); // later ones: the page comes back from the back/forward cache
landing = null;
revealed = true;
clean();
const vt = event.viewTransition;
if (!vt) {
arrive(now(), false);
return;
}
current = vt;
heading = land.back;
html.classList.toggle(BACK, land.back);
if (land.at) html.style.setProperty(`--kz-${NAME}-at`, land.at);
const own = values(shown()[0]);
apply(land.back ? land.vars || own : own || land.vars);
name(land.stay, false);
vt.ready.then(() => arrive(now(), true), () => arrive(now(), false));
vt.finished.finally(() => {
if (current !== vt) return;
current = null;
clean();
});
}, { signal: page.signal });
// No pagereveal (Firefox, older Safari), or the script came after it: the arrival plays now
requestAnimationFrame(() => {
if (!revealed) arrive(now(), false);
});
// Once the sections of the page are prepared, the class goes: one added later starts shown
const settle = () => requestAnimationFrame(() => html.classList.remove(ENTER));
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', settle, { once: true, signal: page.signal });
else settle();
// ---------- Page engine (end) ----------
// The morph: the element clicked (data-page-morph, or the one inside the link) and its twin on
// the next page get the same name just before the browser captures each page, so it draws one
// flying from one box to the other. Paired by the value of data-page-morph, or, left empty, by
// the address: the card's link on one side, the page's own address on the other.
const ITEM = `kodza-${NAME}-item`;
const OUT = `kodza-${NAME}-out`;
const MORPH = '[data-page-morph]';
const STORE = `kodza-${NAME}`;
let morphed = [];
let clicked = null;
let watching = false;
const active = () => {
try {
return html.matches(':active-view-transition');
} catch (error) {
return false;
}
};
const visible = (el) => {
const box = el.getBoundingClientRect();
return box.width > 0 && box.height > 0 && box.bottom > 0 && box.top < innerHeight && box.right > 0 && box.left < innerWidth;
};
const keyOf = (el) => el.dataset.pageMorph.trim() || here(el.closest('a[href]')?.href || location.href);
let restore = [];
function unmorph() {
morphed.forEach((el) => {
el.style.removeProperty('view-transition-name');
el.style.removeProperty('view-transition-class');
});
morphed = [];
restore.forEach((done) => done());
restore = [];
}
// Back, the arrival plays in reverse before the next page shows: the rest goes first, last part
// first, then the title sinks into its masks line by line from the bottom, and the label goes
// last. Each part gets its own name; its kind and its rank (a class) set its animation.
function leave() {
const parts = [...document.querySelectorAll(`${SELECTOR} [data-enter]`)]
.filter((el) => visible(el) && !el.closest(MORPH) && !el.querySelector(MORPH));
const out = [];
const rank = (n) => `${OUT}-i${Math.min(n, 5)}`;
parts.filter((el) => el.dataset.enter === 'title').forEach((title) => {
if (!title.querySelector(`.kodza-${NAME}__mask`)) {
const markup = title.innerHTML;
split(title);
restore.push(() => {
title.innerHTML = markup;
});
}
const masks = [...title.querySelectorAll(`.kodza-${NAME}__mask`)].filter(visible);
const tops = [...new Set(masks.map((mask) => Math.round(mask.getBoundingClientRect().top)))].sort((a, b) => b - a);
masks.forEach((mask) => out.push([mask, `${OUT}-word ${rank(tops.indexOf(Math.round(mask.getBoundingClientRect().top)))}`]));
});
parts.filter((el) => el.dataset.enter === 'label').forEach((el) => out.push([el, `${OUT}-label`]));
parts.filter((el) => !['label', 'title'].includes(el.dataset.enter) && getComputedStyle(el).display !== 'inline')
.reverse()
.forEach((el, i) => out.push([el, rank(i)]));
out.forEach(([el, kind], i) => {
el.style.setProperty('view-transition-name', `${OUT}-${i}`);
el.style.setProperty('view-transition-class', `${OUT} ${kind}`);
morphed.push(el);
});
}
// els[i] gets the i-th name: a source and its target share an index. null: nothing to pair.
function mark(els, back = false) {
unmorph();
els.forEach((el, i) => {
if (!el) return;
el.style.setProperty('view-transition-name', `${ITEM}-${i}`);
el.style.setProperty('view-transition-class', ITEM);
morphed.push(el);
});
if (back) leave();
if (watching || !morphed.length) return;
watching = true;
// The names go with the transition: a later one never finds them
const watch = () => {
if (active() && !page.signal.aborted) {
requestAnimationFrame(watch);
return;
}
watching = false;
unmorph();
};
requestAnimationFrame(watch);
}
// Forward, what the link pressed holds; back, what is on screen
function sources(back) {
const link = clicked && Date.now() - clicked.time < 4000 ? clicked.el : null;
if (!back && link) return [...(link.matches(MORPH) ? [link] : []), ...link.querySelectorAll(MORPH)].filter(visible);
return [...document.querySelectorAll(MORPH)].filter(visible);
}
const targets = (keys) => keys.map((key) => [...document.querySelectorAll(MORPH)].find((el) => keyOf(el) === key && visible(el)) || null);
page.signal.addEventListener('abort', unmorph, { once: true });
document.addEventListener('click', (event) => {
const el = event.target.closest?.('a[href], button');
clicked = el ? { el, time: Date.now() } : null;
}, { capture: true, signal: page.signal });
// Inside one page: named before the swap, its twin once the content is swapped (before the
// browser captures the new state)
window.addEventListener('kodza:page-transition', (event) => {
const update = event.detail?.update;
if (typeof update !== 'function' || motion.matches || !document.startViewTransition) return;
const from = sources(Boolean(event.detail.back));
const keys = from.map(keyOf);
mark(from, Boolean(event.detail.back));
event.detail.update = async () => {
await update();
mark(targets(keys));
};
}, { capture: true, signal: page.signal });
// Between two documents: the page you leave names its side and writes the keys...
window.addEventListener('pageswap', (event) => {
if (!event.viewTransition || motion.matches) return;
const activation = event.activation;
const link = clicked && Date.now() - clicked.time < 4000 ? clicked.el : null;
const back = activation?.navigationType === 'traverse' ? activation.entry.index < activation.from.index : Boolean(link?.hasAttribute('data-page-back'));
const from = sources(back);
mark(from, back);
try {
sessionStorage.setItem(STORE, JSON.stringify({ keys: from.map(keyOf), time: Date.now() }));
} catch (error) {
// no storage: the pages still trade places, without the morph
}
}, { signal: page.signal });
// ...and the page that lands names its own before the browser captures it
window.addEventListener('pagereveal', (event) => {
unmorph();
let record = null;
try {
record = JSON.parse(sessionStorage.getItem(STORE));
sessionStorage.removeItem(STORE);
} catch (error) {
record = null;
}
if (!event.viewTransition || motion.matches || !record || Date.now() - record.time > 4000) return;
mark(targets(record.keys || []));
}, { signal: page.signal });
// 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) {
signals.set(root, signal);
if (!html.classList.contains(ENTER)) return;
prepare(root); // hidden from the first paint by the CSS, then by its own first frame
queueMicrotask(() => html.classList.remove(ENTER));
}
// 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. Two
// components on one root (a reveal on a stat card) both start, and stop together.
const KODZA = Symbol.for('kodza');
const RUNNING = Symbol.for(`kodza ${SELECTOR}`); // a root this component runs on, for every copy of this script
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) => {
// Already running, maybe from another copy of this script. Marked is-ready with no Kodza component
// running on it, a root is a copy of a started one (a cloned slide): it is left as it is
if (root[RUNNING] || (root.classList.contains('is-ready') && !root[KODZA])) return;
// Rendered by React (data-kodza-manual): React starts it, with an init aimed at that markup once
// it has hydrated it. Any earlier start would change markup React has not taken over yet
const owner = root.closest('[data-kodza-manual]');
if (owner && !(scope && owner.contains(scope))) return;
const controller = new AbortController();
// Another Kodza component already running on this root: its markup as written is kept, and the
// two stop together
const before = root[KODZA];
const saved = { html: before ? before.html : written(root), attrs: before ? before.attrs : attrsOf(root), stop: () => destroy(root) };
if (before) before.above = saved;
instances.set(root, { controller, saved, before });
root[KODZA] = saved;
root[RUNNING] = true;
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);
instance.saved.above?.stop(); // a Kodza component started after it on the same root stops first
// 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[RUNNING];
// Started on top of another one: that one stops next, and puts the markup back
if (instance.before) {
delete instance.before.above;
root[KODZA] = instance.before;
return instance.before.stop();
}
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 — Shared Element Morph, for React. From https://kodza.dev/components/shared-element-morph/
// 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: shared-element-morph.css and shared-element-morph.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.
// data-kodza-manual keeps the script from starting it on its own: the effect below does, once
// React has hydrated the markup (on a page that streams in, the script can load first).
// 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 './shared-element-morph.css';
export type SharedElementMorphProps = Omit<ComponentPropsWithoutRef<'section'>, "children" | "vars" | "onPageEngine" | "onPageTransition"> & {
/** Settings, as CSS variables on the root */
vars?: {
/** the trip of the image, and the pages trading places — default: 0.8s */
"--kz-shared-element-morph-duration"?: string | number;
/** default: cubic-bezier(0.65, 0, 0.35, 1) */
"--kz-shared-element-morph-ease"?: string | number;
/** its corners on the way — default: calc(16px * var(--kz-radius-scale, 1)) */
"--kz-shared-element-morph-radius"?: string | number;
/** between the two pages: your page colour shows through — default: transparent */
"--kz-shared-element-morph-backdrop"?: string | number;
/** the arrival starts while the image is on its way — default: 0.24s */
"--kz-shared-element-morph-enter-delay"?: string | number;
/** default: cubic-bezier(0.2, 0.8, 0.1, 1) */
"--kz-shared-element-morph-enter-ease"?: string | number;
/** default: #f2f2f0 */
"--kz-shared-element-morph-bg"?: string | number;
/** default: #0a0a0a */
"--kz-shared-element-morph-fg"?: string | number;
/** default: rgba(10, 10, 10, 0.62) */
"--kz-shared-element-morph-muted"?: string | number;
/** default: rgba(10, 10, 10, 0.12) */
"--kz-shared-element-morph-line"?: string | number;
/** default: calc(16px * var(--kz-radius-scale, 1)) */
"--kz-shared-element-morph-image-radius"?: string | number;
/** default: 24px */
"--kz-shared-element-morph-side"?: string | number;
};
/** "kodza:page-engine", fired by the script (bubbles from the root) */
onPageEngine?: (event: CustomEvent) => void;
/** "kodza:page-transition", fired by the script (bubbles from the root) */
onPageTransition?: (event: CustomEvent) => void;
className?: string;
};
export function SharedElementMorph({ vars, onPageEngine, onPageTransition, className, style, ...rest }: SharedElementMorphProps) {
const ref = useRef<ComponentRef<'section'>>(null);
const classes = ["kodza-shared-element-morph", 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('./shared-element-morph.js').then(() => {
if (live) document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root } }));
});
return () => {
live = false;
document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } }));
};
}, [key]);
useEffect(() => {
const root = ref.current;
if (!root || !onPageEngine) return;
const listener = (event: Event) => onPageEngine(event as CustomEvent);
root.addEventListener("kodza:page-engine", listener);
return () => root.removeEventListener("kodza:page-engine", listener);
}, [onPageEngine, key]);
useEffect(() => {
const root = ref.current;
if (!root || !onPageTransition) return;
const listener = (event: Event) => onPageTransition(event as CustomEvent);
root.addEventListener("kodza:page-transition", listener);
return () => root.removeEventListener("kodza:page-transition", listener);
}, [onPageTransition, key]);
return (
<section data-kodza-shared-element-morph="" key={key} {...rest} className={classes} data-kodza-manual style={{ ...vars, ...style } as CSSProperties} ref={ref}>
<p className="kodza-shared-element-morph__label" data-enter="label">Case study · 04 / 12</p>
<div className="kodza-shared-element-morph__split">
<h1 className="kodza-shared-element-morph__title" data-enter="title">The deploy that went out on a Friday</h1>
<div className="kodza-shared-element-morph__intro">
<p className="kodza-shared-element-morph__lead" data-enter="">A full redesign, shipped four minutes before the weekend. No rollback, no war room, nobody paged. Here is how a team of three made it boring on purpose.</p>
<dl className="kodza-shared-element-morph__facts">
<div data-enter="">
<dt>Client</dt>
<dd>{"Null & Void"}</dd>
</div>
<div data-enter="">
<dt>Year</dt>
<dd>2026</dd>
</div>
<div data-enter="">
<dt>Shipped</dt>
<dd>Fri, 17:56</dd>
</div>
</dl>
</div>
</div>
<figure className="kodza-shared-element-morph__media">
<div className="kodza-shared-element-morph__frame" data-page-morph="">
<img className="kodza-shared-element-morph__image" src="https://kodza.dev/media/kz-steps-2400.webp" width="2400" height="1600" alt="Concrete steps climbing through bare grey walls" />
</div>
<figcaption data-enter="">
<span>fig. 1 — the release plan, in its final form</span>
<span>git push, then leave</span>
</figcaption>
</figure>
</section>
);
}
Checked
Robots poked at it before you did. Every component goes through the same checks, and again each time it changes.