3 Commits
Author SHA1 Message Date
CatoandClaude Sonnet 5.5 f5e0a24208 fix: the date box matches a native input exactly; structure survives an app's display:block (0.3.2) (#7)
- line-height: normal (the font's own, like a native input) instead of 1.3,
  and an icon that fits a normal line: the box is now exactly a native
  input's height (38 vs 38; it was 40 vs 38, a visible step in form rows).
- structure rules on span.wk-input so an app's own unlayered class with
  display:block on the same element cannot collapse the stacked layout.
- codemod: an object spread inside onChange is no longer flagged as a JSX
  prop spread.

Both browser checks were first run failing against the old CSS.

Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-08 06:47:10 -07:00
CatoandClaude Sonnet 5.5 0072fe68aa fix: icon scales with the field's text; codemod skips comments (0.3.1) (#6)
A fixed 20px calendar icon made a dense 12px input taller than its
neighbours (34px vs 30px). The icon is now 1.25em. The browser check has a
compact input and fails on the old icon (it first passed on it — the limit
was exactly the old height; tightened and re-proven).

The codemod no longer edits comments or files already on whenkit (it
rewrote its own shim, whose comment mentioned the tag).

Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-08 05:58:32 -07:00
CatoandClaude Sonnet 5.5 9fd8b3b11d chore: codemod to migrate date inputs to DateInput (#5)
A JSX tag scanner (braces, strings, template literals — not a regex over
attributes) that changes <input type=date|datetime-local> to DateInput and
adds one import. Lists what it will not guess. Tested on tricky fixtures,
including the blank-line-after-imports bug its own test caught; a second run
changes nothing.

Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-08 05:42:11 -07:00
9 changed files with 419 additions and 7 deletions

No files matched your search

+15 -1
View File
@@ -5,7 +5,7 @@ length chips, a readable date field over the native picker, and a booking
request that resolves to `{ startsAt, endsAt }` in the provider's time zone.
```bash
pnpm add github:bitbaum/whenkit#v0.3.0
pnpm add github:bitbaum/whenkit#v0.3.2
```
```tsx
@@ -70,6 +70,20 @@ uncontrolled (`defaultValue` + `name`, e.g. a server-action form). The empty
state and weekday/month words follow `<html lang>` (or pass `locale` /
`placeholder`).
### Migrating a repo
```bash
# one re-export per app: components/ui/date-input.tsx
# "use client"; import "@bitbaum/whenkit/styles.css"; export { DateInput } from "@bitbaum/whenkit/react";
node node_modules/@bitbaum/whenkit/scripts/migrate-date-inputs.mjs src --import "@/components/ui/date-input" # dry run
node node_modules/@bitbaum/whenkit/scripts/migrate-date-inputs.mjs src --import "@/components/ui/date-input" --write # apply
```
It changes the tag and adds one import — nothing else — and lists what it will
not guess (spread props, a dynamic `type={…}`). `--from Input` converts an
app's own wrapper component instead of the raw `<input>`. Tested on tricky
fixtures (`test/codemod.test.js`); a second run changes nothing.
## Rules it enforces
- Dates are `YYYY-MM-DD`, times `HH:MM` — wall-clock strings. They become an
+9
View File
@@ -47,6 +47,15 @@ createRoot(document.getElementById("dialog")!).render(
createRoot(document.getElementById("own-class")!).render(
<DateInput className="app-input" defaultValue="2026-10-11" id="own" />,
);
createRoot(document.getElementById("match-date")!).render(
<DateInput className="match-input" defaultValue="2026-10-11" id="match" />,
);
createRoot(document.getElementById("block-class")!).render(
<DateInput className="block-input" defaultValue="2026-10-11" id="blocked" />,
);
createRoot(document.getElementById("compact-class")!).render(
<DateInput className="compact-input" defaultValue="2026-10-11" id="compact" />,
);
createRoot(document.getElementById("util-class")!).render(
<DateInput className="util-input" defaultValue="2026-10-11" id="util" />,
);
+27
View File
@@ -54,6 +54,12 @@
border: 3px solid rgb(255, 0, 0);
border-radius: 0;
}
/* A dense app input: 12px text, tight padding (e.g. Loki's ui-input-tight). */
.compact-input {
font-size: 12px;
padding: 6px 10px;
line-height: 1.3;
}
@layer utilities {
.util-input {
border-width: 5px;
@@ -61,6 +67,21 @@
border-color: rgb(0, 0, 255);
}
}
/* An app's input, applied to a native input AND to DateInput: they must end up
the same height (a serif so its natural line height differs from 1.3). */
.match-input {
font-family: Georgia, serif;
font-size: 14px;
padding: 10px 14px;
border: 1.5px solid rgb(150, 150, 150);
border-radius: 10px;
width: 100%;
box-sizing: border-box;
}
/* A hostile app class: display:block on the same element (unlayered, later). */
.block-input {
display: block;
}
.resolved {
font-size: 11px;
opacity: 0.5;
@@ -88,6 +109,12 @@
<div class="grid" style="margin-top: 24px">
<section><div id="own-class"></div></section>
<section><div id="util-class"></div></section>
<section><div id="compact-class"></div></section>
<section>
<input id="match-native" class="match-input" value="Bello" />
<div id="match-date" style="margin-top: 8px"></div>
</section>
<section><div id="block-class"></div></section>
</div>
<div class="dialog-like" id="dialog"></div>
</main>
+1 -1
View File
@@ -20,7 +20,7 @@ export default tseslint.config(
},
{
// Tests are plain Node running under `node --test`.
files: ["test/**/*.js", "test/**/*.mjs"],
files: ["test/**/*.js", "test/**/*.mjs", "scripts/**/*.mjs"],
// browser.mjs is Node driving a browser: page.evaluate bodies run there.
languageOptions: { globals: { ...globals.node, ...globals.nodeBuiltin, ...globals.browser } },
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@bitbaum/whenkit",
"version": "0.3.0",
"version": "0.3.2",
"description": "Dates and times people can pick without typing: day chips, time chips, length chips, a readable date field over the native picker, and a low-friction booking request that resolves to {startsAt, endsAt} in the provider's zone.",
"license": "MIT",
"author": "Cato",
+156
View File
@@ -0,0 +1,156 @@
#!/usr/bin/env node
// Replace `<input type="date">` / `<input type="datetime-local">` with whenkit's
// DateInput — a drop-in (same props, same onChange(event)), so only the TAG
// changes. Nothing else in the file is touched except one import line.
//
// node scripts/migrate-date-inputs.mjs <dir> --import "@/components/ui/date-input" [--from input] [--write]
//
// --import module that exports DateInput (a one-line re-export per app that
// also imports "@bitbaum/whenkit/styles.css" once)
// --from tag to replace: `input` (default) or a wrapper such as `Input`
// --write apply; without it, a dry run that only reports
//
// It is a tag scanner, not a regex over attributes: it walks the JSX opening
// tag honouring braces, strings and template literals, so `onChange={(e) => …}`
// and multi-line props cannot confuse it. Anything it will NOT convert safely
// is listed for a human: spread props (`{...register("x")}`) are kept (DateInput
// forwards them) but flagged, and a dynamic `type={…}` is flagged, never guessed.
import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { join, relative } from "node:path";
const args = process.argv.slice(2);
const root = args.find((a) => !a.startsWith("--"));
const opt = (name, fallback) => {
const i = args.indexOf(`--${name}`);
return i >= 0 ? args[i + 1] : fallback;
};
const write = args.includes("--write");
const from = opt("from", "input");
const importFrom = opt("import");
if (!root || !importFrom) {
console.error(
'usage: migrate-date-inputs.mjs <dir> --import "<module>" [--from input|Input] [--write]',
);
process.exit(2);
}
const SKIP =
/(^|\/)(node_modules|\.next|\.claude|dist|build|coverage|__tests__|tests?|e2e|cypress|\.git)(\/|$)/;
const FILE = /\.(tsx|jsx)$/;
const TEST_FILE = /\.(test|spec|stories)\.(tsx|jsx)$/;
function* walk(dir) {
for (const name of readdirSync(dir)) {
const path = join(dir, name);
if (SKIP.test(relative(root, path))) continue;
const st = statSync(path);
if (st.isDirectory()) yield* walk(path);
else if (FILE.test(name) && !TEST_FILE.test(name)) yield path;
}
}
/** End index (exclusive) of the JSX opening tag starting at `start` (`<tag`), or -1. */
function tagEnd(src, start) {
let depth = 0; // braces
let i = start;
while (i < src.length) {
const c = src[i];
if (depth === 0) {
if (c === '"' || c === "'") {
const close = src.indexOf(c, i + 1);
if (close < 0) return -1;
i = close + 1;
continue;
}
if (c === "{") depth++;
else if (c === ">") return i + 1;
} else {
if (c === "{") depth++;
else if (c === "}") depth--;
else if (c === '"' || c === "'" || c === "`") {
// string inside an expression
let j = i + 1;
while (j < src.length && src[j] !== c) j += src[j] === "\\" ? 2 : 1;
i = j + 1;
continue;
}
}
i++;
}
return -1;
}
const TYPE_STATIC =
/\btype=(?:"(date|datetime-local)"|'(date|datetime-local)'|\{\s*["'](date|datetime-local)["']\s*\})/;
const TYPE_ANY = /\btype=\{/;
/** `src` with comments blanked (same length, so indexes still line up). */
function maskComments(src) {
const blank = (m) => m.replace(/[^\n]/g, " ");
return src
.replace(/\/\*[\s\S]*?\*\//g, blank)
.replace(/(^|[^:"'`\\])\/\/[^\n]*/g, (m, lead) => lead + blank(m.slice(lead.length)));
}
let changedFiles = 0;
let changedTags = 0;
const review = [];
for (const file of walk(root)) {
const src = readFileSync(file, "utf8");
// The app's own re-export (and anything already on whenkit) is not a call site.
if (src.includes("@bitbaum/whenkit")) continue;
const code = maskComments(src);
const opening = new RegExp(`<${from}(?=[\\s/>])`, "g");
let out = "";
let last = 0;
let count = 0;
const alias = /\bDateInput\b/.test(src) && !src.includes(`from "${importFrom}"`);
const tag = alias ? "WhenDateInput" : "DateInput";
for (const m of code.matchAll(opening)) {
const end = tagEnd(src, m.index);
if (end < 0) continue;
const attrs = src.slice(m.index, end);
if (TYPE_STATIC.test(attrs)) {
out += src.slice(last, m.index) + `<${tag}`;
last = m.index + m[0].length;
count++;
const line = src.slice(0, m.index).split("\n").length;
// A JSX prop spread is `{...x}` at attribute level; `({ ...form, a })` inside
// an onChange arrow is an object literal and is not worth a human's time.
if (/(^|[\s"'}/])\{\s*\.\.\.[A-Za-z_$]/.test(attrs.replace(/=\{[^}]*\}/g, "=")))
review.push(`${relative(root, file)}:${line} spreads props — check they are input props`);
} else if (TYPE_ANY.test(attrs) && /date/i.test(src.slice(m.index, m.index + 400))) {
const line = src.slice(0, m.index).split("\n").length;
review.push(
`${relative(root, file)}:${line} has a dynamic type={…} near "date" — decide by hand`,
);
}
}
if (count === 0) continue;
out += src.slice(last);
const importLine = alias
? `import { DateInput as WhenDateInput } from "${importFrom}";`
: `import { DateInput } from "${importFrom}";`;
if (!out.includes(`from "${importFrom}"`)) {
// after the last top-level import (or the directive, or the top)
// `[ \t]*$` ends the match at the line, so the blank line after the imports is kept.
const imports = [...out.matchAll(/^import[\s\S]*?;[ \t]*$/gm)];
const at = imports.length
? imports[imports.length - 1].index + imports[imports.length - 1][0].length
: (/^(?:["']use (?:client|server)["'];?\s*)/.exec(out)?.[0].length ?? 0);
out = out.slice(0, at) + (at ? "\n" : "") + importLine + (at ? "" : "\n") + out.slice(at);
}
changedFiles++;
changedTags += count;
console.log(
`${write ? "wrote " : "would change "}${relative(root, file)} (${count} tag${count > 1 ? "s" : ""})`,
);
if (write) writeFileSync(file, out);
}
console.log(
`\n${changedTags} tag(s) in ${changedFiles} file(s)${write ? " migrated" : " (dry run — add --write)"}`,
);
if (review.length) console.log(`\nREVIEW BY HAND:\n ${review.join("\n ")}`);
+11 -4
View File
@@ -225,7 +225,9 @@
looks like the app's other inputs, not like ours. (Unlayered defaults would
have beaten Tailwind's layered utilities.) No min-height: a compact input
stays compact; the picker sets its own 44px where it needs it. */
.wk-input {
/* span.wk-input, not .wk-input: structure must hold even when an app's own
unlayered input class sets display:block on this same element. */
span.wk-input {
position: relative;
display: flex;
align-items: center;
@@ -244,7 +246,9 @@
color: inherit;
font: inherit;
font-size: var(--wk-text);
line-height: 1.3;
/* The font's own line height, exactly like a native input — a fixed 1.3
made the date box a different height from its neighbours. */
line-height: normal;
}
}
@@ -281,8 +285,11 @@
}
.wk-input-icon {
width: 1.25rem;
height: 1.25rem;
/* em, not rem, and no taller than a normal line: the icon scales with the
field's own text, so neither a dense 12px input nor a serif-font one is made
taller than its neighbours by it. */
width: 1.1em;
height: 1.1em;
flex: 0 0 auto;
opacity: 0.7;
}
+27
View File
@@ -118,6 +118,33 @@ try {
`${name}: a layered utility beats it too (${own.utilWidth} ${own.utilStyle})`,
);
// A dense app input stays dense: the icon scales with the text instead of
// forcing a 20px line into a 12px field.
const compactHeight = await page.evaluate(
() => document.querySelector("#compact-class .wk-input").getBoundingClientRect().height,
);
check(
compactHeight <= 32,
`${name}: a 12px compact date input stays compact (${Math.round(compactHeight)}px)`,
);
// The date box is the same height as a native input given the same class —
// so a form row does not step when one field is a date.
const heights = await page.evaluate(() => ({
native: document.getElementById("match-native").getBoundingClientRect().height,
date: document.querySelector("#match-date .wk-input").getBoundingClientRect().height,
}));
check(
Math.abs(heights.native - heights.date) <= 1,
`${name}: date box matches a native input's height (${heights.date} vs ${heights.native})`,
);
// An app class with display:block on the same element must not break the layout.
const stacked = await page.evaluate(() => {
const box = document.querySelector("#block-class .wk-input");
return getComputedStyle(box).display;
});
check(stacked === "flex", `${name}: an app's display:block cannot break the box (${stacked})`);
const small = await page.evaluate(
() =>
[
+172
View File
@@ -0,0 +1,172 @@
// The migration codemod must change the TAG and one import line — nothing else —
// and must never touch an input that is not a date.
import { test } from "node:test";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
const script = fileURLToPath(new URL("../scripts/migrate-date-inputs.mjs", import.meta.url));
const IMPORT = "@/components/ui/date-input";
function project(files) {
const dir = mkdtempSync(join(tmpdir(), "whenkit-codemod-"));
for (const [name, body] of Object.entries(files)) {
const path = join(dir, name);
mkdirSync(join(path, ".."), { recursive: true });
writeFileSync(path, body);
}
return dir;
}
const run = (dir, extra = []) =>
execFileSync("node", [script, dir, "--import", IMPORT, ...extra], { encoding: "utf8" });
const read = (dir, name) => readFileSync(join(dir, name), "utf8");
test("a dry run reports and writes nothing", () => {
const dir = project({
"a.tsx": `import x from "x";\nexport const A = () => <input type="date" value={v} />;\n`,
});
const before = read(dir, "a.tsx");
const out = run(dir);
assert.match(out, /would change a\.tsx/);
assert.match(out, /dry run/);
assert.equal(read(dir, "a.tsx"), before);
});
test("only the tag changes; props, arrows, strings and templates are untouched", () => {
const body = `"use client";
import { useState } from "react";
export function F() {
const [d, setD] = useState("");
return (
<input
type="date"
value={d}
onChange={(e) => setD(e.target.value)}
className={\`ui-input \${d ? "set" : ""}\`}
title="a > b"
min={new Date().toISOString().slice(0, 10)}
/>
);
}
`;
const dir = project({ "f.tsx": body });
run(dir, ["--write"]);
const after = read(dir, "f.tsx");
assert.match(after, /<DateInput\n\s+type="date"/);
assert.match(after, /onChange=\{\(e\) => setD\(e\.target\.value\)\}/);
assert.match(after, /className=\{`ui-input \$\{d \? "set" : ""\}`\}/);
assert.match(after, /title="a > b"/);
// the import goes after the last import, below the directive
assert.match(
after,
/"use client";\nimport \{ useState \} from "react";\nimport \{ DateInput \} from "@\/components\/ui\/date-input";\n/,
);
// and the diff is exactly one tag and one import
assert.equal(
after
.replace('import { DateInput } from "@/components/ui/date-input";\n', "")
.replace("<DateInput", "<input"),
body,
);
});
test("datetime-local, single-quoted and braced types are all converted", () => {
const dir = project({
"a.tsx": `import x from "x";\nexport const A = () => (<><input type='datetime-local' /><input type={"date"} /><input type="date"/></>);\n`,
});
run(dir, ["--write"]);
assert.equal((read(dir, "a.tsx").match(/<DateInput/g) ?? []).length, 3);
});
test("inputs that are not dates are left exactly alone", () => {
const body = `import x from "x";\nexport const A = () => (<><input type="text" /><input type="time" /><input /><input type={kind} /></>);\n`;
const dir = project({ "a.tsx": body });
const out = run(dir, ["--write"]);
assert.equal(read(dir, "a.tsx"), body);
assert.match(out, /0 tag\(s\) in 0 file\(s\)/);
});
test("a name clash gets an alias instead of shadowing the local DateInput", () => {
const dir = project({
"a.tsx": `import x from "x";\nfunction DateInput() { return <input type="date" />; }\nexport { DateInput };\n`,
});
run(dir, ["--write"]);
const after = read(dir, "a.tsx");
assert.match(after, /import \{ DateInput as WhenDateInput \} from/);
assert.match(after, /<WhenDateInput type="date" \/>/);
assert.match(after, /function DateInput\(\)/);
});
test("--from converts a wrapper component and leaves the raw input alone", () => {
const dir = project({
"a.tsx": `import x from "x";\nexport const A = () => (<><Input type="date" /><input type="date" /></>);\n`,
});
run(dir, ["--write", "--from", "Input"]);
const after = read(dir, "a.tsx");
assert.match(after, /<DateInput type="date" \/>/);
assert.match(after, /<input type="date" \/>/);
});
test("a second run changes nothing, and tests, node_modules and non-JSX are skipped", () => {
const dir = project({
"a.tsx": `import x from "x";\nexport const A = () => <input type="date" />;\n`,
"a.test.tsx": `export const T = () => <input type="date" />;\n`,
"node_modules/p/i.tsx": `export const N = () => <input type="date" />;\n`,
"b.ts": `const s = '<input type="date" />';\n`,
});
run(dir, ["--write"]);
const out = run(dir, ["--write"]);
assert.match(out, /0 tag\(s\) in 0 file\(s\)/);
assert.match(read(dir, "a.test.tsx"), /<input type="date"/);
assert.match(read(dir, "node_modules/p/i.tsx"), /<input type="date"/);
assert.match(read(dir, "b.ts"), /<input type="date"/);
});
test("risky shapes are listed for a human, not guessed", () => {
const dir = project({
"a.tsx": `import x from "x";\nexport const A = () => (<><input type="date" {...register("when")} /><input type={isDate ? "date" : "text"} /></>);\n`,
});
const out = run(dir);
assert.match(out, /REVIEW BY HAND/);
assert.match(out, /spreads props/);
assert.match(out, /dynamic type=/);
});
test("comments that mention an input are not call sites, and the app's own whenkit re-export is skipped", () => {
const withComments = `import x from "x";
// <input type="date"> used to be a bare field
/* and <input type="datetime-local" /> here */
export const A = () => (<>{/* <input type="date" /> */}<input type="date" /></>);
`;
const shim = `"use client";\n// the real <input type="date"> stays on top\nimport "@bitbaum/whenkit/styles.css";\nexport { DateInput } from "@bitbaum/whenkit/react";\n`;
const dir = project({ "a.tsx": withComments, "shim.tsx": shim });
run(dir, ["--write"]);
const after = read(dir, "a.tsx");
assert.match(after, /\/\/ <input type="date"> used to be/);
assert.match(after, /\/\* and <input type="datetime-local" \/> here \*\//);
assert.match(after, /\{\/\* <input type="date" \/> \*\/\}<DateInput type="date" \/>/);
assert.equal((after.match(/<DateInput/g) ?? []).length, 1);
assert.equal(read(dir, "shim.tsx"), shim);
});
test("a URL in a string does not hide the rest of the line", () => {
const dir = project({
"a.tsx": `import x from "x";\nexport const A = () => <a href="http://x.y">go</a>;\nexport const B = () => <input type="date" />; // after\n`,
});
run(dir, ["--write"]);
assert.match(read(dir, "a.tsx"), /<DateInput type="date" \/>; \/\/ after/);
});
test("an object spread inside onChange is not flagged; a JSX prop spread still is", () => {
const dir = project({
"a.tsx": `import x from "x";\nexport const A = () => <input type="date" onChange={(e) => set({ ...form, date: e.target.value })} />;\n`,
"b.tsx": `import x from "x";\nexport const B = () => <input type="date" {...register("when")} />;\n`,
});
const out = run(dir);
assert.doesNotMatch(out, /a\.tsx:\d+ spreads props/);
assert.match(out, /b\.tsx:\d+ spreads props/);
});