2 Commits
Author SHA1 Message Date
CatoandClaude Sonnet 5.5 a198f6a9f7 fix: icon scales with the field's text; codemod skips comments (0.3.1)
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).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
2026-10-08 14:56:11 +02:00
CatoandClaude Sonnet 5.5 15ed5a9c84 chore: codemod to migrate date inputs to DateInput
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.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
2026-10-08 14:40:38 +02:00
9 changed files with 357 additions and 5 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. request that resolves to `{ startsAt, endsAt }` in the provider's time zone.
```bash ```bash
pnpm add github:bitbaum/whenkit#v0.3.0 pnpm add github:bitbaum/whenkit#v0.3.1
``` ```
```tsx ```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` / state and weekday/month words follow `<html lang>` (or pass `locale` /
`placeholder`). `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 ## Rules it enforces
- Dates are `YYYY-MM-DD`, times `HH:MM` — wall-clock strings. They become an - Dates are `YYYY-MM-DD`, times `HH:MM` — wall-clock strings. They become an
+3
View File
@@ -47,6 +47,9 @@ createRoot(document.getElementById("dialog")!).render(
createRoot(document.getElementById("own-class")!).render( createRoot(document.getElementById("own-class")!).render(
<DateInput className="app-input" defaultValue="2026-10-11" id="own" />, <DateInput className="app-input" defaultValue="2026-10-11" id="own" />,
); );
createRoot(document.getElementById("compact-class")!).render(
<DateInput className="compact-input" defaultValue="2026-10-11" id="compact" />,
);
createRoot(document.getElementById("util-class")!).render( createRoot(document.getElementById("util-class")!).render(
<DateInput className="util-input" defaultValue="2026-10-11" id="util" />, <DateInput className="util-input" defaultValue="2026-10-11" id="util" />,
); );
+7
View File
@@ -54,6 +54,12 @@
border: 3px solid rgb(255, 0, 0); border: 3px solid rgb(255, 0, 0);
border-radius: 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 { @layer utilities {
.util-input { .util-input {
border-width: 5px; border-width: 5px;
@@ -88,6 +94,7 @@
<div class="grid" style="margin-top: 24px"> <div class="grid" style="margin-top: 24px">
<section><div id="own-class"></div></section> <section><div id="own-class"></div></section>
<section><div id="util-class"></div></section> <section><div id="util-class"></div></section>
<section><div id="compact-class"></div></section>
</div> </div>
<div class="dialog-like" id="dialog"></div> <div class="dialog-like" id="dialog"></div>
</main> </main>
+1 -1
View File
@@ -20,7 +20,7 @@ export default tseslint.config(
}, },
{ {
// Tests are plain Node running under `node --test`. // 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. // browser.mjs is Node driving a browser: page.evaluate bodies run there.
languageOptions: { globals: { ...globals.node, ...globals.nodeBuiltin, ...globals.browser } }, languageOptions: { globals: { ...globals.node, ...globals.nodeBuiltin, ...globals.browser } },
}, },
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@bitbaum/whenkit", "name": "@bitbaum/whenkit",
"version": "0.3.0", "version": "0.3.1",
"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.", "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", "license": "MIT",
"author": "Cato", "author": "Cato",
+154
View File
@@ -0,0 +1,154 @@
#!/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;
if (/\{\s*\.\.\./.test(attrs))
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 ")}`);
+4 -2
View File
@@ -281,8 +281,10 @@
} }
.wk-input-icon { .wk-input-icon {
width: 1.25rem; /* em, not rem: the icon scales with the field's own text, so a dense 12px
height: 1.25rem; input is not made taller than its neighbours by a fixed 20px icon. */
width: 1.25em;
height: 1.25em;
flex: 0 0 auto; flex: 0 0 auto;
opacity: 0.7; opacity: 0.7;
} }
+10
View File
@@ -118,6 +118,16 @@ try {
`${name}: a layered utility beats it too (${own.utilWidth} ${own.utilStyle})`, `${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)`,
);
const small = await page.evaluate( const small = await page.evaluate(
() => () =>
[ [
+162
View File
@@ -0,0 +1,162 @@
// 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/);
});