Choice Cards
Cards to compare and pick, on real radio buttons or checkboxes, with a title, a line and an optional price. The picked card's ink border draws itself around it from the corner while a check draws in its mark. Pure CSS.
View codeA box to sign with a finger, a mouse or a stylus: the ink thins as the pen speeds up, Undo backs the last stroke out along its path, and a typed name signs too. The form gets a trimmed PNG.
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 Signature Pad to my page.
claude mcp add -t http kodza https://kodza.dev/api/mcp
<div class="kodza-signature">
<div class="kodza-signature__pad">
<label class="kodza-signature__write">
<span class="kodza-signature__label">Signature, quote #2048</span>
<input class="kodza-signature__type" type="text" name="signed-by" autocomplete="name" spellcheck="false" required>
<span class="kodza-signature__prompt" aria-hidden="true"><span class="kodza-signature__say">Sign here</span></span>
</label>
<div class="kodza-signature__tools">
<button class="kodza-signature__undo" type="button">Undo</button>
<button class="kodza-signature__clear" type="button">Clear</button>
</div>
</div>
<input class="kodza-signature__value" type="hidden" name="signature">
<p class="kodza-signature__note">
<span class="kodza-signature__hint">Finger, mouse or stylus. Keyboard? Type your name.</span>
<span class="kodza-signature__error" aria-live="polite"></span>
</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 — Signature Pad
A box to sign in, over a line with its little cross. The ink thins as the pen speeds up, like
a real nib, with finger, mouse or stylus. Undo makes the last stroke back out along its own
path; Clear wipes the box from left to right. With a keyboard, the name typed on the line is
the signature, in the display font. The form gets a trimmed PNG (data URL) under the hidden
input's name, printed in black whatever the theme. Without JS, the name field stays.
Same box as Text Field. Everything is tuned with the --kz-signature-* variables; the words
and timings, at the top of the script. */
.kodza-signature {
--kz-signature-bg: #ffffff;
--kz-signature-fg: #0a0a0a;
--kz-signature-muted: rgba(10, 10, 10, 0.6);
--kz-signature-line: rgba(10, 10, 10, 0.14);
--kz-signature-line-hover: rgba(10, 10, 10, 0.3);
--kz-signature-soft: rgba(10, 10, 10, 0.06);
--kz-signature-error: #0a0a0a; /* a message, never colour alone: set a red here if you want one */
--kz-signature-ink: #0a0a0a; /* the ink on screen */
--kz-signature-print: #0a0a0a; /* the ink in the image the form gets, for a white page */
--kz-signature-pen-min: 0.8px; /* the thinnest line, at full speed (read by the script) */
--kz-signature-pen-max: 3.2px; /* the thickest, when the pen slows down */
--kz-signature-name-size: 34px; /* the name typed on the line */
--kz-signature-height: 200px;
--kz-signature-width: var(--kz-field-width, 480px);
--kz-signature-radius: calc(12px * var(--kz-radius-scale, 1));
--kz-signature-duration: 0.35s;
--kz-signature-ease: cubic-bezier(0.22, 1, 0.36, 1);
display: grid;
gap: 8px;
width: 100%;
max-width: var(--kz-signature-width);
color: var(--kz-signature-fg);
}
/* The box: the label on top, the tools on the right, the line near the bottom */
.kodza-signature__pad {
position: relative;
display: block;
height: var(--kz-signature-height);
margin: 0;
padding: 0;
border-radius: var(--kz-signature-radius);
background: var(--kz-signature-bg);
box-shadow: inset 0 0 0 1px var(--kz-signature-line);
transition: box-shadow calc(0.25s * var(--kz-motion-scale, 1)) ease;
}
.kodza-signature__pad:hover {
box-shadow: inset 0 0 0 1px var(--kz-signature-line-hover);
}
.kodza-signature.is-invalid .kodza-signature__pad {
box-shadow: inset 0 0 0 1.5px var(--kz-signature-error);
}
/* The line to sign on, and its cross */
.kodza-signature__pad::before {
content: "";
position: absolute;
right: 24px;
bottom: 52px;
left: 40px;
height: 1px;
background: var(--kz-signature-line-hover);
}
.kodza-signature__pad::after {
content: "";
position: absolute;
bottom: 58px;
left: 20px;
width: 9px;
height: 9px;
background: var(--kz-signature-muted);
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M1 1l8 8M9 1L1 9' stroke='black' stroke-width='1.4' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M1 1l8 8M9 1L1 9' stroke='black' stroke-width='1.4' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat;
}
/* The ink, drawn by the script over the line */
.kodza-signature__ink {
position: absolute;
z-index: 1;
inset: 0;
display: block;
width: 100%;
height: 100%;
border-radius: inherit;
color: var(--kz-signature-ink); /* read by the script */
cursor: crosshair;
touch-action: none;
}
/* The name field, over the whole box. Once the script runs the pointer goes through it to the
ink; the keyboard still reaches the field, and a name already typed takes the pointer back */
.kodza-signature__write {
position: absolute;
z-index: 2;
inset: 0;
display: block;
margin: 0;
padding: 0;
border-radius: inherit;
cursor: text;
}
.kodza-signature.is-ready .kodza-signature__write {
pointer-events: none;
}
.kodza-signature.is-ready.is-typed .kodza-signature__type {
pointer-events: auto;
}
/* Typing: the box is the one in use */
.kodza-signature__write::after {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
box-shadow: inset 0 0 0 1.5px transparent, 0 0 0 4px transparent;
pointer-events: none;
transition: box-shadow calc(0.25s * var(--kz-motion-scale, 1)) ease;
}
.kodza-signature__write:focus-within::after {
box-shadow: inset 0 0 0 1.5px var(--kz-signature-fg), 0 0 0 4px var(--kz-signature-soft);
}
.kodza-signature.is-invalid .kodza-signature__write:focus-within::after {
box-shadow: inset 0 0 0 1.5px var(--kz-signature-error), 0 0 0 4px var(--kz-signature-soft);
}
.kodza-signature__label {
position: absolute;
top: 14px;
left: 16px;
color: var(--kz-signature-muted);
font-size: 12px;
line-height: 1.2;
white-space: nowrap;
}
/* The name typed on the line, in the display font */
.kodza-signature__type {
position: absolute;
right: 24px;
bottom: 42px;
left: 40px;
box-sizing: border-box;
width: auto;
height: 50px;
margin: 0;
padding: 0;
border: 0;
border-radius: 0;
outline: none;
background: transparent;
box-shadow: none;
color: var(--kz-signature-ink);
caret-color: var(--kz-signature-fg);
font-family: var(--kz-font-display, inherit);
font-size: calc(var(--kz-signature-name-size) * var(--kz-font-display-scale, 1));
font-style: italic;
font-weight: var(--kz-font-display-weight, 400);
letter-spacing: var(--kz-font-display-tracking, -0.02em);
line-height: 50px;
text-transform: var(--kz-font-display-case, none);
appearance: none;
}
/* Under the line: what to do now, then when it was signed */
.kodza-signature__prompt {
position: absolute;
bottom: 24px;
left: 40px;
display: grid;
overflow: hidden;
color: var(--kz-signature-muted);
font-family: var(--kz-font-label, inherit);
font-size: var(--kz-font-label-size, 12px);
font-weight: var(--kz-font-label-weight, inherit);
letter-spacing: var(--kz-font-label-tracking, inherit);
line-height: var(--kz-font-label-leading, 1.4);
text-transform: var(--kz-font-label-case, inherit);
white-space: nowrap;
pointer-events: none;
}
.kodza-signature__say {
grid-area: 1 / 1;
}
/* Undo once there is ink, Clear once there is a signature, drawn or typed */
.kodza-signature__tools {
position: absolute;
z-index: 3;
top: 10px;
right: 10px;
display: flex;
gap: 2px;
}
.kodza-signature__undo,
.kodza-signature__clear {
display: inline-flex;
align-items: center;
box-sizing: border-box;
height: 28px;
margin: 0;
padding: 0 11px;
border: 0;
border-radius: var(--kz-radius-pill, 999px);
outline: none;
background: transparent;
color: var(--kz-signature-muted);
font-family: var(--kz-font-label, inherit);
font-size: var(--kz-font-label-size, 12px);
font-weight: var(--kz-font-label-weight, 500);
letter-spacing: var(--kz-font-label-tracking, revert);
line-height: 1;
text-transform: var(--kz-font-label-case, revert);
cursor: pointer;
opacity: 0;
transform: translateY(-6px);
visibility: hidden;
transition:
opacity calc(var(--kz-signature-duration) * 0.625 * var(--kz-motion-scale, 1)) ease,
transform calc(var(--kz-signature-duration) * var(--kz-motion-scale, 1)) var(--kz-signature-ease),
visibility 0s linear calc(var(--kz-signature-duration) * var(--kz-motion-scale, 1)),
background-color calc(0.2s * var(--kz-motion-scale, 1)) ease,
color calc(0.2s * var(--kz-motion-scale, 1)) ease;
}
.kodza-signature.is-inked .kodza-signature__undo,
.kodza-signature.is-filled .kodza-signature__clear {
opacity: 1;
transform: none;
visibility: visible;
transition-delay: 0s;
}
.kodza-signature__undo:hover,
.kodza-signature__clear:hover {
background: var(--kz-signature-soft);
color: var(--kz-signature-fg);
}
.kodza-signature__undo:focus-visible,
.kodza-signature__clear:focus-visible {
background: var(--kz-signature-soft);
box-shadow: inset 0 0 0 1.5px var(--kz-signature-fg);
color: var(--kz-signature-fg);
}
/* Hint and error share one line: the hint steps out upward as the error rises in */
.kodza-signature__note {
display: grid;
margin: 0;
padding: 0 2px;
overflow: hidden;
font-family: var(--kz-font-label, inherit);
font-size: var(--kz-font-label-size, 13px);
font-weight: var(--kz-font-label-weight, inherit);
letter-spacing: var(--kz-font-label-tracking, inherit);
line-height: var(--kz-font-label-leading, 1.4);
text-transform: var(--kz-font-label-case, inherit);
}
.kodza-signature__hint,
.kodza-signature__error {
grid-area: 1 / 1;
transition:
opacity calc(var(--kz-signature-duration) * 0.625 * var(--kz-motion-scale, 1)) ease,
transform calc(var(--kz-signature-duration) * var(--kz-motion-scale, 1)) var(--kz-signature-ease);
}
.kodza-signature__hint {
color: var(--kz-signature-muted);
}
.kodza-signature__error {
display: flex;
align-items: center;
gap: 6px;
color: var(--kz-signature-error);
font-weight: var(--kz-font-label-weight, 500);
opacity: 0;
transform: translateY(100%);
}
.kodza-signature__error::before {
content: "";
flex: none;
width: 14px;
height: 14px;
background: currentColor;
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='6.5' fill='none' stroke='black' stroke-width='1.5'/%3E%3Cpath d='M8 4.5v4.2M8 10.9v.1' stroke='black' stroke-width='1.6' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='6.5' fill='none' stroke='black' stroke-width='1.5'/%3E%3Cpath d='M8 4.5v4.2M8 10.9v.1' stroke='black' stroke-width='1.6' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat;
}
.kodza-signature.is-invalid .kodza-signature__hint {
opacity: 0;
transform: translateY(-100%);
}
.kodza-signature.is-invalid .kodza-signature__error {
opacity: 1;
transform: none;
}
/* What screen readers hear: a stroke undone, the box cleared */
.kodza-signature__live {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@media (prefers-reduced-motion: reduce) {
.kodza-signature__pad,
.kodza-signature__write::after,
.kodza-signature__undo,
.kodza-signature__clear,
.kodza-signature__hint,
.kodza-signature__error {
transition-duration: 0.01ms !important;
transition-delay: 0s !important;
}
}
/* Theming example — on a dark background:
.dark-section .kodza-signature {
--kz-signature-bg: #161616;
--kz-signature-fg: #f2f2f0;
--kz-signature-muted: rgba(242, 242, 240, 0.62);
--kz-signature-line: rgba(255, 255, 255, 0.14);
--kz-signature-line-hover: rgba(255, 255, 255, 0.3);
--kz-signature-soft: rgba(255, 255, 255, 0.08);
--kz-signature-error: #f2f2f0;
--kz-signature-ink: #f2f2f0;
}
*/
/* kodza-guard 8694a0e5a488 — 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-signature__undo):not(#_),
:where(.kodza-signature__clear):not(#_) {
box-shadow: revert;
}
/* What the browser gives, on everything the component leaves to it */
.kodza-signature:not(#_),
.kodza-signature__pad:not(#_),
.kodza-signature__ink:not(#_),
.kodza-signature__label:not(#_),
.kodza-signature__prompt:not(#_),
.kodza-signature__say:not(#_),
.kodza-signature__tools:not(#_),
.kodza-signature__hint:not(#_),
.kodza-signature__error:not(#_),
.kodza-signature__live:not(#_) {
box-sizing: revert;
}
.kodza-signature__write:not(#_) {
border: revert;
outline: revert;
text-decoration: revert;
transition: revert;
list-style: revert;
box-sizing: revert;
float: 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-signature__type:not(#_) {
text-decoration: revert;
transition: revert;
list-style: revert;
float: revert;
outline-offset: revert;
max-width: revert;
max-height: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
white-space: revert;
min-height: revert;
}
.kodza-signature__undo:not(#_),
.kodza-signature__clear:not(#_) {
text-decoration: revert;
list-style: revert;
float: revert;
position: 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;
white-space: revert;
min-height: revert;
}
.kodza-signature__value:not(#_) {
border: revert;
margin: 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;
white-space: revert;
min-height: revert;
}
.kodza-signature__note: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-style: revert;
text-underline-offset: revert;
text-align: revert;
text-indent: revert;
text-shadow: revert;
vertical-align: revert;
}
.kodza-signature__type:not(#_):where(:not([hidden])),
.kodza-signature__value:not(#_):where(:not([hidden])) {
display: revert;
}
.kodza-signature__type:not(#_):where([hidden]),
.kodza-signature__value:not(#_):where([hidden]) {
display: none;
}
.kodza-signature__pad:not(#_)::before,
.kodza-signature__pad:not(#_)::after,
.kodza-signature__write:not(#_)::after,
.kodza-signature__error: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-signature:not(#_) {
width: min(100%, var(--kz-signature-width));
}
.kodza-signature__write:not(#_) {
position: absolute;
display: block;
margin: 0;
padding: 0;
border-radius: inherit;
}
.kodza-signature.is-ready.is-typed .kodza-signature__type:not(#_) {
pointer-events: auto;
}
.kodza-signature__type:not(#_) {
position: absolute;
right: 24px;
bottom: 42px;
left: 40px;
box-sizing: border-box;
width: auto;
height: 50px;
margin: 0;
padding: 0;
border: 0;
border-radius: 0;
outline: none;
background: transparent;
box-shadow: none;
color: var(--kz-signature-ink);
caret-color: var(--kz-signature-fg);
font-family: var(--kz-font-display, inherit);
font-size: calc(var(--kz-signature-name-size) * var(--kz-font-display-scale, 1));
font-style: italic;
font-weight: var(--kz-font-display-weight, 400);
letter-spacing: var(--kz-font-display-tracking, -0.02em);
line-height: 50px;
text-transform: var(--kz-font-display-case, none);
appearance: none;
}
.kodza-signature__undo:not(#_),
.kodza-signature__clear:not(#_) {
display: inline-flex;
align-items: center;
box-sizing: border-box;
height: 28px;
margin: 0;
padding: 0 11px;
border: 0;
border-radius: var(--kz-radius-pill, 999px);
outline: none;
background: transparent;
color: var(--kz-signature-muted);
font-family: var(--kz-font-label, inherit);
font-size: var(--kz-font-label-size, 12px);
font-weight: var(--kz-font-label-weight, 500);
letter-spacing: var(--kz-font-label-tracking, revert);
line-height: 1;
text-transform: var(--kz-font-label-case, revert);
cursor: pointer;
opacity: 0;
transform: translateY(-6px);
visibility: hidden;
transition: opacity calc(var(--kz-signature-duration) * 0.625 * var(--kz-motion-scale, 1)) ease,
transform calc(var(--kz-signature-duration) * var(--kz-motion-scale, 1)) var(--kz-signature-ease),
visibility 0s linear calc(var(--kz-signature-duration) * var(--kz-motion-scale, 1)),
background-color calc(0.2s * var(--kz-motion-scale, 1)) ease,
color calc(0.2s * var(--kz-motion-scale, 1)) ease;
}
.kodza-signature.is-inked .kodza-signature__undo:not(#_),
.kodza-signature.is-filled .kodza-signature__clear:not(#_) {
opacity: 1;
transform: none;
visibility: visible;
transition-delay: 0s;
}
.kodza-signature__undo:hover:not(#_),
.kodza-signature__clear:hover:not(#_) {
background: var(--kz-signature-soft);
color: var(--kz-signature-fg);
}
.kodza-signature__undo:focus-visible:not(#_),
.kodza-signature__clear:focus-visible:not(#_) {
background: var(--kz-signature-soft);
box-shadow: inset 0 0 0 1.5px var(--kz-signature-fg);
color: var(--kz-signature-fg);
}
.kodza-signature__note:not(#_) {
display: grid;
margin: 0;
padding: 0 2px;
font-family: var(--kz-font-label, inherit);
font-size: var(--kz-font-label-size, 13px);
font-weight: var(--kz-font-label-weight, inherit);
letter-spacing: var(--kz-font-label-tracking, inherit);
line-height: var(--kz-font-label-leading, 1.4);
text-transform: var(--kz-font-label-case, inherit);
}
@media (prefers-reduced-motion: reduce) {
.kodza-signature__undo:not(#_),
.kodza-signature__clear: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 — Signature Pad
// A box to sign in with a finger, a mouse or a stylus. The ink thins as the pen speeds up and
// thickens as it slows, like a nib. Undo makes the last stroke back out along its own path; Clear
// wipes the box from left to right. With a keyboard, the name typed on the line is the signature.
// Under the line, "Sign here" rolls to "Signed 4 Nov 2026" once signed. The form gets a trimmed
// PNG (a data URL) from the hidden input, printed in --kz-signature-print on a transparent ground,
// and the typed name under the field's own name; a required field asks for one or the other.
// Settings: --kz-signature-* in the CSS (the pen widths too), data-locale (the language of the
// date, else the page's). The words and timings are below; each word can be set per pad with
// data-text-<name> (data-text-sign="…"), {date} is filled in.
(() => {
const SELECTOR = '.kodza-signature';
const WORDS = {
sign: 'Sign here', // under the line, before anything
type: 'Type your name', // under the line, while the name field has the focus
signed: 'Signed {date}', // under the line, once signed
required: 'Sign first. Or type your name.',
undone: 'Last stroke removed', // read out
cleared: 'Signature cleared', // read out
};
const UNDO = 400; // ms, the last stroke backing out
const SWEEP = 600; // ms, Clear wiping the box
const SWEEP_EASE = 'cubic-bezier(0.65, 0, 0.35, 1)';
const ROLL = 420; // ms, the words under the line rolling
const SMOOTHING = 0.7; // how much the newest pen speed counts against the one before (0 to 1)
const MIN_STEP = 1.5; // px, a point closer than this to the last one is skipped
const STEP = 0.5; // px between two dabs of ink along a stroke
const MARGIN = 8; // px around the signature in the image the form gets
const ease = 'cubic-bezier(0.22, 1, 0.36, 1)';
// SWEEP_EASE for a stroke drawn frame by frame
const easeInOut = (t) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// The site's pace, --kz-motion-scale (set on :root, read on the instance): every duration of the
// script times it, and 0 moves nothing, like reduced motion
const paceOf = (el) => {
const pace = parseFloat(getComputedStyle(el).getPropertyValue('--kz-motion-scale'));
return pace >= 0 ? pace : 1;
};
const mid = (p, q) => ({ x: (p.x + q.x) / 2, y: (p.y + q.y) / 2 });
// Dabs of ink along a quadratic curve from a to c, bent by b, the width going the same way
const curve = (out, a, b, c, wa, wb, wc) => {
const length = Math.hypot(b.x - a.x, b.y - a.y) + Math.hypot(c.x - b.x, c.y - b.y);
const steps = Math.max(1, Math.ceil(length / STEP));
for (let i = 1; i <= steps; i++) {
const t = i / steps;
const u = 1 - t;
out.push(u * u * a.x + 2 * u * t * b.x + t * t * c.x, u * u * a.y + 2 * u * t * b.y + t * t * c.y, u * u * wa + 2 * u * t * wb + t * t * wc);
}
};
// The pieces of a stroke its points now settle: a dab at the start, a line to the first
// midpoint, one curve per point from midpoint to midpoint, and the last line once the pen lifts
const extend = (line, ended) => {
const { points: p, samples } = line;
const n = p.length;
if (!samples.length && n) samples.push(p[0].x, p[0].y, p[0].w);
for (; line.pieces < n - 1; line.pieces++) {
const k = line.pieces;
if (!k) {
const m = mid(p[0], p[1]);
curve(samples, p[0], mid(p[0], m), m, p[0].w, (3 * p[0].w + p[1].w) / 4, (p[0].w + p[1].w) / 2);
} else curve(samples, mid(p[k - 1], p[k]), p[k], mid(p[k], p[k + 1]), (p[k - 1].w + p[k].w) / 2, p[k].w, (p[k].w + p[k + 1].w) / 2);
}
if (ended && n > 1) {
const m = mid(p[n - 2], p[n - 1]);
curve(samples, m, mid(m, p[n - 1]), p[n - 1], (p[n - 2].w + p[n - 1].w) / 2, (p[n - 2].w + 3 * p[n - 1].w) / 4, p[n - 1].w);
}
};
// One round dab per sample, filled at once: [x, y, width, x, y, width, …]
const paint = (context, samples, from = 0, to = samples.length) => {
context.beginPath();
for (let i = from; i < to; i += 3) {
const r = samples[i + 2] / 2;
context.moveTo(samples[i] + r, samples[i + 1]);
context.arc(samples[i], samples[i + 1], r, 0, Math.PI * 2);
}
context.fill();
};
let uid = 0;
// One instance. Everything it starts is tied to `signal`, so kodza:destroy stops it all
function mount(root, signal) {
const pad = root.querySelector('.kodza-signature__pad');
const type = root.querySelector('.kodza-signature__type');
const prompt = root.querySelector('.kodza-signature__prompt');
const undo = root.querySelector('.kodza-signature__undo');
const clear = root.querySelector('.kodza-signature__clear');
const value = root.querySelector('.kodza-signature__value');
const hint = root.querySelector('.kodza-signature__hint');
const error = root.querySelector('.kodza-signature__error');
if (!pad || !type) return;
const id = `kodza-signature-${++uid}`;
const word = (key) => root.dataset[`text${key[0].toUpperCase()}${key.slice(1)}`] || WORDS[key];
const lang = root.dataset.locale || root.closest('[lang]')?.lang || navigator.language || 'en';
const today = () => {
try {
return new Intl.DateTimeFormat(lang, { dateStyle: 'medium' }).format(new Date());
} catch {
return new Date().toLocaleDateString();
}
};
const described = [];
if (hint) described.push((hint.id = `${id}-hint`));
if (error) described.push((error.id = `${id}-error`));
if (described.length) type.setAttribute('aria-describedby', described.join(' '));
// Required means a drawing or a name: the script checks for either one
const required = type.required;
if (required) {
type.required = false;
type.setAttribute('aria-required', 'true');
}
const canvas = document.createElement('canvas');
canvas.className = 'kodza-signature__ink';
canvas.setAttribute('aria-hidden', 'true');
pad.prepend(canvas);
const ctx = canvas.getContext('2d');
// The strokes that stay, drawn once while the last one backs out over them
const base = document.createElement('canvas');
const baseCtx = base.getContext('2d');
const live = document.createElement('span');
live.className = 'kodza-signature__live';
live.setAttribute('aria-live', 'polite');
root.append(live);
let width = 0;
let height = 0;
let ratio = 0;
let strokes = []; // each { points: [{ x, y, t, w }], samples: [x, y, w, …], pieces }
let stroke = null; // the one being drawn
let pointer = null;
let velocity = 0;
let pens = [0.8, 3.2];
let backing = 0; // the frame of the stroke backing out
let textGoing = false; // the typed name is being wiped
const wipes = new Set();
let shown = prompt?.querySelector('.kodza-signature__say');
const style = () => getComputedStyle(root);
const inkOf = () => getComputedStyle(canvas).color;
const typed = () => !textGoing && type.value.trim() !== '';
const redraw = () => {
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = inkOf();
strokes.forEach((line) => paint(ctx, line.samples));
};
// The canvas at the box's size, in device pixels (times the scale of a parent's transform);
// the strokes follow a new width, held on the line near the bottom
const size = () => {
const w = canvas.offsetWidth;
const h = canvas.offsetHeight;
if (!w || !h) return;
const r = (window.devicePixelRatio || 1) * (canvas.getBoundingClientRect().width / w || 1);
if (w === width && h === height && r === ratio) return;
if (width && w !== width) {
const k = w / width;
strokes.forEach((line) => {
line.points.forEach((point) => {
point.x *= k;
point.y = h - (height - point.y) * k;
});
line.samples = [];
line.pieces = 0;
extend(line, true);
});
}
width = w;
height = h;
ratio = r;
[canvas, base].forEach((each) => {
each.width = Math.round(w * r);
each.height = Math.round(h * r);
});
ctx.setTransform(r, 0, 0, r, 0, 0);
baseCtx.setTransform(r, 0, 0, r, 0, 0);
redraw();
};
// Under the line, the old words go up as the new ones come in from below
const roll = (text, animate = true) => {
if (!shown || shown.textContent === text) return;
const pace = paceOf(root);
if (!animate || reduceMotion || !pace) {
shown.textContent = text;
return;
}
const old = shown;
shown = old.cloneNode();
shown.textContent = text;
prompt.append(shown);
const timing = { duration: ROLL * pace, easing: ease };
const gone = () => old.remove();
old.animate([{ transform: 'none', opacity: 1 }, { transform: 'translateY(-100%)', opacity: 0 }], { ...timing, fill: 'forwards' }).finished.then(gone, gone);
shown.animate([{ transform: 'translateY(100%)', opacity: 0 }, { transform: 'none', opacity: 1 }], timing);
};
// Hint and error share the line under the box
const say = (text) => {
if (!error) return;
error.textContent = text;
root.classList.add('is-invalid');
type.setAttribute('aria-invalid', 'true');
};
const clearError = () => {
root.classList.remove('is-invalid');
type.removeAttribute('aria-invalid');
};
// A tool that hides under the keyboard's focus hands it on: to Clear while it shows, else to
// the name field. Under the mouse it is let go
const handOn = (tool) => {
if (!tool || document.activeElement !== tool || !tool.matches(':focus-visible')) return;
(tool !== clear && clear && root.classList.contains('is-filled') ? clear : type).focus({ preventScroll: true });
};
const sync = (animate = true) => {
const inked = strokes.length > 0;
const signed = inked || typed();
root.classList.toggle('is-inked', inked);
root.classList.toggle('is-typed', typed());
root.classList.toggle('is-filled', signed);
if (!inked) handOn(undo);
if (!signed) handOn(clear);
roll(signed ? word('signed').replace('{date}', today()) : document.activeElement === type ? word('type') : word('sign'), animate);
if (required) type.setCustomValidity(signed ? '' : word('required'));
if (signed) clearError();
};
// The image the form gets: the ink, or the typed name in the field's font, trimmed to it, at
// twice the size. A hidden input sends no event of its own: "change" bubbles from it
const output = () => {
if (!value) return;
const name = typed() ? type.value.trim() : '';
let data = '';
if (strokes.length || name) {
const sheet = document.createElement('canvas');
const pen = sheet.getContext('2d');
let left = Infinity;
let top = Infinity;
let right = -Infinity;
let bottom = -Infinity;
let metrics = null;
const font = getComputedStyle(type);
const text = font.textTransform === 'uppercase' ? name.toUpperCase() : font.textTransform === 'lowercase' ? name.toLowerCase() : name;
const setFont = () => {
pen.font = `${font.fontStyle} ${font.fontWeight} ${font.fontSize} ${font.fontFamily}`;
if ('letterSpacing' in pen) pen.letterSpacing = font.letterSpacing === 'normal' ? '0px' : font.letterSpacing;
};
if (strokes.length) {
strokes.forEach(({ samples }) => {
for (let i = 0; i < samples.length; i += 3) {
const r = samples[i + 2] / 2;
left = Math.min(left, samples[i] - r);
right = Math.max(right, samples[i] + r);
top = Math.min(top, samples[i + 1] - r);
bottom = Math.max(bottom, samples[i + 1] + r);
}
});
} else {
setFont();
metrics = pen.measureText(text);
left = -metrics.actualBoundingBoxLeft;
right = metrics.actualBoundingBoxRight;
top = -metrics.actualBoundingBoxAscent;
bottom = metrics.actualBoundingBoxDescent;
}
sheet.width = Math.ceil((right - left + MARGIN * 2) * 2);
sheet.height = Math.ceil((bottom - top + MARGIN * 2) * 2);
pen.setTransform(2, 0, 0, 2, (MARGIN - left) * 2, (MARGIN - top) * 2);
pen.fillStyle = '#0a0a0a';
pen.fillStyle = style().getPropertyValue('--kz-signature-print').trim() || '#0a0a0a';
if (metrics) {
setFont();
pen.fillText(text, 0, 0);
} else strokes.forEach(({ samples }) => paint(pen, samples));
data = sheet.toDataURL('image/png');
}
if (value.value === data) return;
value.value = data;
value.dispatchEvent(new Event('change', { bubbles: true }));
};
// Clear's sweep, from left to right, on the ink or the typed name; `done` runs underneath it
// just before it lifts, at its end or as soon as something new starts
const wipe = (el, done) => {
const pace = paceOf(root);
if (reduceMotion || !pace) return done();
const anim = el.animate([{ clipPath: 'inset(0 0 0 0)' }, { clipPath: 'inset(0 0 0 100%)' }], { duration: SWEEP * pace, easing: SWEEP_EASE, fill: 'forwards' });
const entry = { anim, finish: () => {
if (!wipes.delete(entry)) return;
done();
anim.cancel();
sync();
output();
} };
wipes.add(entry);
anim.finished.then(entry.finish, () => {});
};
const settle = () => [...wipes].forEach((entry) => entry.finish());
const stopBacking = () => {
if (!backing) return;
cancelAnimationFrame(backing);
backing = 0;
redraw();
};
const dropInk = () => {
if (!strokes.length) return;
stopBacking();
strokes = [];
wipe(canvas, redraw);
};
const dropName = () => {
if (!typed()) return;
textGoing = true;
wipe(type, () => {
type.value = '';
textGoing = false;
});
};
// Drawing. The pointer's place is divided by the scale of a parent's transform
const at = (event, rect) => {
const scale = rect.width / canvas.offsetWidth || 1;
return { x: (event.clientX - rect.left) / scale, y: (event.clientY - rect.top) / scale, t: event.timeStamp };
};
// The width from the pen's speed (px/ms), smoothed: fast and thin, slow and full
const add = (point) => {
const points = stroke.points;
const last = points[points.length - 1];
if (last) {
const distance = Math.hypot(point.x - last.x, point.y - last.y);
if (distance < MIN_STEP) return;
velocity = SMOOTHING * (distance / Math.max(point.t - last.t, 1)) + (1 - SMOOTHING) * velocity;
point.w = Math.max(pens[1] / (velocity + 1), pens[0]);
} else {
velocity = 0;
point.w = (pens[0] + pens[1]) / 2;
}
points.push(point);
const from = stroke.samples.length;
extend(stroke, false);
paint(ctx, stroke.samples, from);
};
canvas.addEventListener('pointerdown', (event) => {
if (event.button !== 0 || stroke || type.matches(':disabled')) return;
event.preventDefault();
settle();
stopBacking();
size();
if (document.activeElement === type) type.blur();
dropName();
pointer = event.pointerId;
try {
canvas.setPointerCapture(pointer);
} catch {}
const css = style();
const min = parseFloat(css.getPropertyValue('--kz-signature-pen-min'));
const max = parseFloat(css.getPropertyValue('--kz-signature-pen-max'));
pens = [min > 0 ? min : 0.8, max > 0 ? max : 3.2];
ctx.fillStyle = inkOf();
stroke = { points: [], samples: [], pieces: 0 };
strokes.push(stroke);
add(at(event, canvas.getBoundingClientRect()));
}, { signal });
canvas.addEventListener('pointermove', (event) => {
if (!stroke || event.pointerId !== pointer) return;
const rect = canvas.getBoundingClientRect();
const events = event.getCoalescedEvents?.() || [];
(events.length ? events : [event]).forEach((each) => add(at(each, rect)));
}, { signal });
const end = (event) => {
if (!stroke || event.pointerId !== pointer) return;
const line = stroke;
stroke = null;
pointer = null;
const from = line.samples.length;
extend(line, true);
paint(ctx, line.samples, from);
sync();
output();
};
['pointerup', 'pointercancel', 'lostpointercapture'].forEach((name) => canvas.addEventListener(name, end, { signal }));
// Undo: the last stroke runs back along its own path, over the ones that stay
undo?.addEventListener('click', () => {
if (stroke || !strokes.length) return;
settle();
stopBacking();
const line = strokes.pop();
live.textContent = word('undone');
sync();
output();
const pace = paceOf(root);
if (reduceMotion || !pace) return redraw();
baseCtx.clearRect(0, 0, width, height);
baseCtx.fillStyle = inkOf();
strokes.forEach((other) => paint(baseCtx, other.samples));
ctx.fillStyle = baseCtx.fillStyle;
const count = line.samples.length / 3;
const start = performance.now();
const frame = (now) => {
const progress = Math.min((now - start) / (UNDO * pace), 1);
ctx.clearRect(0, 0, width, height);
ctx.drawImage(base, 0, 0, width, height);
const keep = Math.round(count * (1 - easeInOut(progress)));
if (keep) paint(ctx, line.samples, 0, keep * 3);
backing = progress < 1 ? requestAnimationFrame(frame) : 0;
};
backing = requestAnimationFrame(frame);
}, { signal });
clear?.addEventListener('click', () => {
if (stroke || !root.classList.contains('is-filled')) return;
settle();
dropInk();
dropName();
live.textContent = word('cleared');
sync();
output();
}, { signal });
// Typing: a key first settles a sweep still running; a name wipes the ink away
type.addEventListener('beforeinput', settle, { signal });
type.addEventListener('input', () => {
if (type.value.trim()) dropInk();
sync();
output();
}, { signal });
type.addEventListener('focus', () => sync(), { signal });
type.addEventListener('blur', () => sync(), { signal });
// Sent empty: the message goes under the box, and the focus to the field when it is the
// first one the form stops on
type.addEventListener('invalid', (event) => {
event.preventDefault();
say(word('required'));
const firstInvalid = type.form && [...type.form.elements].find((el) => el.willValidate && !el.validity.valid);
if (!type.form || firstInvalid === type) type.focus();
}, { signal });
// A form reset empties the field after this event: the pad follows on the next turn
type.form?.addEventListener('reset', () => setTimeout(() => {
if (signal.aborted) return;
settle();
stopBacking();
strokes = [];
redraw();
clearError();
sync();
output();
}), { signal });
const observer = new ResizeObserver(size);
observer.observe(canvas);
signal.addEventListener('abort', () => {
observer.disconnect();
cancelAnimationFrame(backing);
wipes.forEach(({ anim }) => anim.cancel());
wipes.clear();
});
size();
sync(false);
}
// 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 — Signature Pad, for React. From https://kodza.dev/components/signature-pad/
// 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: signature-pad.css and signature-pad.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 './signature-pad.css';
export type SignaturePadProps = Omit<ComponentPropsWithoutRef<'div'>, "children" | "vars"> & {
/** Settings, as CSS variables on the root */
vars?: {
/** default: #ffffff */
"--kz-signature-bg"?: string | number;
/** default: #0a0a0a */
"--kz-signature-fg"?: string | number;
/** default: rgba(10, 10, 10, 0.6) */
"--kz-signature-muted"?: string | number;
/** default: rgba(10, 10, 10, 0.14) */
"--kz-signature-line"?: string | number;
/** default: rgba(10, 10, 10, 0.3) */
"--kz-signature-line-hover"?: string | number;
/** default: rgba(10, 10, 10, 0.06) */
"--kz-signature-soft"?: string | number;
/** a message, never colour alone: set a red here if you want one — default: #0a0a0a */
"--kz-signature-error"?: string | number;
/** the ink on screen — default: #0a0a0a */
"--kz-signature-ink"?: string | number;
/** the ink in the image the form gets, for a white page — default: #0a0a0a */
"--kz-signature-print"?: string | number;
/** the thinnest line, at full speed (read by the script) — default: 0.8px */
"--kz-signature-pen-min"?: string | number;
/** the thickest, when the pen slows down — default: 3.2px */
"--kz-signature-pen-max"?: string | number;
/** the name typed on the line — default: 34px */
"--kz-signature-name-size"?: string | number;
/** default: 200px */
"--kz-signature-height"?: string | number;
/** default: var(--kz-field-width, 480px) */
"--kz-signature-width"?: string | number;
/** default: calc(12px * var(--kz-radius-scale, 1)) */
"--kz-signature-radius"?: string | number;
/** default: 0.35s */
"--kz-signature-duration"?: string | number;
/** default: cubic-bezier(0.22, 1, 0.36, 1) */
"--kz-signature-ease"?: string | number;
};
className?: string;
};
export function SignaturePad({ vars, className, style, ...rest }: SignaturePadProps) {
const ref = useRef<ComponentRef<'div'>>(null);
const classes = ["kodza-signature", 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('./signature-pad.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 key={key} {...rest} className={classes} data-kodza-manual style={{ ...vars, ...style } as CSSProperties} ref={ref}>
<div className="kodza-signature__pad">
<label className="kodza-signature__write">
<span className="kodza-signature__label">Signature, quote #2048</span>
{' '}
<input className="kodza-signature__type" type="text" name="signed-by" autoComplete="name" spellCheck="false" required />
{' '}
<span className="kodza-signature__prompt" aria-hidden="true">
<span className="kodza-signature__say">Sign here</span>
</span>
</label>
<div className="kodza-signature__tools">
<button className="kodza-signature__undo" type="button">Undo</button>
{' '}
<button className="kodza-signature__clear" type="button">Clear</button>
</div>
</div>
<input className="kodza-signature__value" type="hidden" name="signature" />
<p className="kodza-signature__note">
<span className="kodza-signature__hint">Finger, mouse or stylus. Keyboard? Type your name.</span>
{' '}
<span className="kodza-signature__error" aria-live="polite" />
</p>
</div>
);
}
Checked
Robots poked at it before you did. Every component goes through the same checks, and again each time it changes.