mirror of
https://github.com/bitbaum/whenkit.git
synced 2026-12-05 06:38:27 +01:00
Compare commits
2
Commits
chore/codemod
...
v0.3.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0072fe68aa | ||
|
|
9fd8b3b11d |
No files matched your search
@@ -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.1
|
||||
```
|
||||
|
||||
```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
|
||||
|
||||
@@ -47,6 +47,9 @@ createRoot(document.getElementById("dialog")!).render(
|
||||
createRoot(document.getElementById("own-class")!).render(
|
||||
<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(
|
||||
<DateInput className="util-input" defaultValue="2026-10-11" id="util" />,
|
||||
);
|
||||
@@ -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;
|
||||
@@ -88,6 +94,7 @@
|
||||
<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>
|
||||
</div>
|
||||
<div class="dialog-like" id="dialog"></div>
|
||||
</main>
|
||||
|
||||
+1
-1
@@ -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
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"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.",
|
||||
"license": "MIT",
|
||||
"author": "Cato",
|
||||
|
||||
@@ -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
@@ -281,8 +281,10 @@
|
||||
}
|
||||
|
||||
.wk-input-icon {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
/* em, not rem: the icon scales with the field's own text, so a dense 12px
|
||||
input is not made taller than its neighbours by a fixed 20px icon. */
|
||||
width: 1.25em;
|
||||
height: 1.25em;
|
||||
flex: 0 0 auto;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
@@ -118,6 +118,16 @@ 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)`,
|
||||
);
|
||||
|
||||
const small = await page.evaluate(
|
||||
() =>
|
||||
[
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
Reference in new issue
Block a user