Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,32 @@ euro.format("-12345,6");

Fraction digit limits must be non-negative integers, and the minimum must not exceed the maximum.

## Date formatter

Import `createDateFormatter` from `rifm/date`. It uses the locale's numeric date field order and separators while preserving incomplete input:

```tsx
import { createDateFormatter } from "rifm/date";

const date = createDateFormatter({
locales: "en-US",
year: "long",
});

const rifm = useRifm({
value,
onChange: setValue,
...date,
mask: true,
});
```

The `year` option accepts `"short"` for two digits or `"long"` for four digits and defaults to `"long"`. For example, `120826` becomes `12/08/26` with a short year, while `12082026` becomes `12/08/2026` with a long year.

Leave out `mask` for insertion-style formatting. Set `mask: true` for replacement-style editing of occupied date positions. The formatter is structural and does not validate whether a completed value is a real calendar date.

As with other RIFM inputs, use `type="text"` and `inputMode="numeric"`, not `type="date"`.

## Accepted characters and caret behavior

RIFM restores the caret by tracking the characters matched by `accept`. The formatter may insert, remove, or move separators, but it should preserve the order of those accepted characters.
Expand Down
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,14 @@
"./number": {
"types": "./dist/number.d.ts",
"import": "./dist/number.js"
},
"./date": {
"types": "./dist/date.d.ts",
"import": "./dist/date.js"
}
},
"scripts": {
"build": "tsdown src/index.ts src/number.ts --format esm --target es2022 --platform neutral --dts --clean",
"build": "tsdown src/index.ts src/number.ts src/date.ts --format esm --target es2022 --platform neutral --dts --clean",
"test:unit": "vitest run --project node",
"test:browser": "vitest run --project browser",
"test": "pnpm run test:ts && pnpm run test:unit && pnpm run test:browser",
Expand Down
64 changes: 64 additions & 0 deletions src/date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
export interface DateFormatterOptions {
locales?: string | string[];
year?: "short" | "long";
}

export interface DateFormatter {
format: (value: string) => string;
accept: RegExp;
}

type DatePart = "day" | "month" | "year";

/** Creates locale-aware `format` and `accept` props for RIFM. */
export const createDateFormatter = (options: DateFormatterOptions = {}): DateFormatter => {
const { locales, year = "long" } = options;
const yearLength = year === "short" ? 2 : 4;
const parts = new Intl.DateTimeFormat(locales, {
calendar: "gregory",
numberingSystem: "latn",
day: "2-digit",
month: "2-digit",
year: year === "short" ? "2-digit" : "numeric",
timeZone: "UTC",
}).formatToParts(new Date(Date.UTC(2006, 10, 22)));

const fields: DatePart[] = [];
const separators: string[] = [];
let literal = "";

for (const part of parts) {
if (part.type === "day" || part.type === "month" || part.type === "year") {
if (fields.length > 0) separators.push(literal);
fields.push(part.type);
literal = "";
} else if (fields.length > 0) {
literal += part.value;
}
}

const lengths: Record<DatePart, number> = { day: 2, month: 2, year: yearLength };
const maximumLength = 4 + yearLength;
const accept = /\d/g;

const format = (value: string): string => {
const digits = (value.match(accept) ?? []).join("").slice(0, maximumLength);
const segments: string[] = [];
let offset = 0;

for (const field of fields) {
const segment = digits.slice(offset, offset + lengths[field]);
if (segment === "") break;
segments.push(segment);
offset += lengths[field];
}

return segments.reduce(
(result, segment, index) =>
index === 0 ? segment : `${result}${separators[index - 1]}${segment}`,
"",
);
};

return { format, accept };
};
19 changes: 19 additions & 0 deletions tests/date-formatter.browser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { afterEach, expect, test } from "vitest";
import { createDateFormatter } from "../src/date";
import { BrowserExec, createBrowserExec } from "./utils/browser-exec";

let exec: BrowserExec | null = null;

afterEach(() => {
exec?.cleanup();
exec = null;
});

test("date formatter supports replacement-style mask editing", async () => {
const formatter = createDateFormatter({ locales: "en-US", year: "long" });
exec = createBrowserExec({ ...formatter, mask: true });

expect(await exec({ type: "PUT_SYMBOL", payload: "12082026" })).toBe("12/08/2026|");
expect(await exec({ type: "MOVE_CARET", payload: -4 })).toBe("12/08/|2026");
expect(await exec({ type: "PUT_SYMBOL", payload: "1" })).toBe("12/08/1|026");
});
37 changes: 37 additions & 0 deletions tests/date-formatter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { describe, expect, test } from "vitest";
import { createDateFormatter } from "../src/date";

describe("date formatter", () => {
test("uses locale field order and separators", () => {
const us = createDateFormatter({ locales: "en-US" });
const german = createDateFormatter({ locales: "de-DE" });
const japanese = createDateFormatter({ locales: "ja-JP" });

expect(us.format("12082026")).toBe("12/08/2026");
expect(german.format("12082026")).toBe("12.08.2026");
expect(japanese.format("20261208")).toBe("2026/12/08");
});

test("preserves partial input and limits its length", () => {
const formatter = createDateFormatter({ locales: "en-US" });

expect(formatter.format("1")).toBe("1");
expect(formatter.format("120")).toBe("12/0");
expect(formatter.format("12 / 08 / 202699")).toBe("12/08/2026");
expect(formatter.format(formatter.format("12082026"))).toBe("12/08/2026");
});

test("supports short years", () => {
const formatter = createDateFormatter({ locales: "en-GB", year: "short" });

expect(formatter.format("120826")).toBe("12/08/26");
expect(formatter.format("12082026")).toBe("12/08/20");
});

test("returns an object which can be spread into Rifm options", () => {
const formatter = createDateFormatter();

expect(Object.keys(formatter)).toEqual(["format", "accept"]);
expect("12/08/2026".match(formatter.accept)?.join("")).toBe("12082026");
});
});
6 changes: 5 additions & 1 deletion vitest.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ export default defineConfig({
test: {
name: "node",
environment: "node",
include: ["tests/formatters.test.ts", "tests/test-layout-warn.test.tsx"],
include: [
"tests/formatters.test.ts",
"tests/*-formatter.test.ts",
"tests/test-layout-warn.test.tsx",
],
},
},
{
Expand Down
Loading