@northguild/gmt
Version:
Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.
239 lines (237 loc) • 9.19 kB
JavaScript
import { Temporal } from "./temporal.js";
import { isIslamicEraCompatNeeded, isJapaneseEraCompatNeeded, isJapaneseTwoDigitYearCompatNeeded, isRelatedYearWidthCompatNeeded } from "./temporalCompat/capabilities.js";
import { nowInstant } from "./temporalCompat/clock.js";
import { markRangeHandled, rangeHooks } from "./rangeHooks.js";
import { digitSetOf, digitsOf } from "./weekYearText.js";
// src/internal/yearPrinting.ts
/** The options that give a formatter a date pattern when none of these is set. */
const FIELD_KEYS = [
"weekday",
"year",
"month",
"day",
"dayPeriod",
"hour",
"minute",
"second",
"fractionalSecondDigits",
"dateStyle",
"timeStyle"
];
/** Whether the formatter can print an era or a year (ECMA-402 CreateDateTimeFormat defaults). */
function showsEraOrYear(options) {
return options.era !== void 0 || options.year !== void 0 || options.dateStyle !== void 0 || FIELD_KEYS.every((key) => options[key] === void 0);
}
/** A time value as `Intl` reads it: a number, a `Date`, or `undefined` for now. */
function toMilliseconds(date) {
if (typeof date === "number") return date;
return date === void 0 ? nowInstant().epochMilliseconds : Number(date);
}
/** The first date the japanese calendar prints a Japanese era for: ISO 1873 (Meiji 6). */
const FIRST_JAPANESE_ERA_YEAR = 1873;
/** The year shifts D27 tries to find an endpoint the same day of the year, at the same time. */
const SHIFTS = [
4,
8,
12,
16,
20,
24,
28,
32,
36,
40
];
/**
* The options a chinese or dangi formatter is built with: `year: "2-digit"` becomes `"numeric"`
* when the engine pads the related year (D28), else the options as given.
*
* @param callerOptions the options the formatter was asked for
* @param calendar the calendar the formatter resolved
* @returns the options to build with
*
* @example widenRelatedYear({ year: "2-digit" }, "chinese") // { year: "numeric" } where the engine pads the related year
* @example widenRelatedYear({ year: "2-digit" }, "gregory") // { year: "2-digit" }
*/
function widenRelatedYear(callerOptions, calendar) {
if (callerOptions.year === "2-digit" && (calendar === "chinese" || calendar === "dangi") && isRelatedYearWidthCompatNeeded()) return {
...callerOptions,
year: "numeric"
};
return callerOptions;
}
/** The ISO year (in the formatter's zone) and the Hijra check of an instant. */
function zonedAt(ms, timeZone) {
return Temporal.Instant.fromEpochMilliseconds(ms).toZonedDateTimeISO(timeZone);
}
/**
* Where a japanese pattern puts its era relative to the year: after it or before it, and the
* literal between them. `null` when the pattern prints no era. Read from the engine's own parts of
* a date after 1873 (the era of a date before it is what the twin supplies).
*/
function eraSeatOf(formatter) {
try {
const parts = formatter.formatToParts(17205696e5);
const era = parts.findIndex((part) => part.type === "era");
const year = parts.findIndex((part) => part.type === "year");
if (era < 0 || year < 0) return null;
const between = parts.slice(Math.min(era, year) + 1, Math.max(era, year));
return {
after: era > year,
glue: between.length === 1 && between[0]?.type === "literal" ? between[0].value : ""
};
} catch {
return null;
}
}
/**
* The formatter itself, or a wrapper that repairs the years of D25, D26 and D27 where the engine
* prints them wrongly.
*
* @param formatter the formatter the week-year guard returned
* @param callerOptions the options it was built with
* @param twinOf the cached formatter for other options and the same locale (a Gregorian twin)
* @returns the formatter, or its wrapper
*
* @example repairYearPrinting(new Intl.DateTimeFormat("en", { year: "numeric" }), { year: "numeric" }, () => new Intl.DateTimeFormat("en")) // the same formatter
* @example repairYearPrinting(new Intl.DateTimeFormat("ja-u-ca-japanese", { year: "2-digit", timeZone: "UTC" }), { year: "2-digit", timeZone: "UTC" }, () => new Intl.DateTimeFormat("ja")).format(Date.UTC(2024, 6, 10)) // "令和06年" where the engine prints 令和6年
*/
function repairYearPrinting(formatter, callerOptions, twinOf) {
let resolved;
try {
resolved = formatter.resolvedOptions();
} catch {
return formatter;
}
const { calendar, timeZone, numberingSystem } = resolved;
const japanese = calendar === "japanese";
const era = japanese && showsEraOrYear(callerOptions) && isJapaneseEraCompatNeeded();
const islamic = calendar.startsWith("islamic") && showsEraOrYear(callerOptions) && isIslamicEraCompatNeeded();
const pad = japanese && callerOptions.year === "2-digit" && new Intl.Locale(resolved.locale).language === "ja" && isJapaneseTwoDigitYearCompatNeeded();
if (!era && !islamic && !pad) return formatter;
const zero = digitsOf(numberingSystem)[0] ?? "0";
const digitSet = digitSetOf(numberingSystem);
const styled = callerOptions.dateStyle !== void 0 || callerOptions.timeStyle !== void 0;
const eraSeat = era && callerOptions.era === void 0 ? eraSeatOf(formatter) : null;
let gregorian;
const twin = () => gregorian ??= twinOf({
...callerOptions,
calendar: "gregory",
...eraSeat !== null && !styled ? { era: "short" } : {}
});
let eraName;
const japaneseForms = [];
const japaneseEraNames = (ms) => {
if (japaneseForms.length === 0) for (const era of [
"long",
"short",
"narrow"
]) japaneseForms.push(twinOf({
calendar: "japanese",
era,
year: "numeric",
timeZone
}));
const names = japaneseForms.flatMap((form) => form.formatToParts(ms).filter((part) => part.type === "era" && part.value !== "").map((part) => part.value));
return [...new Set(names)].toSorted((x, y) => y.length - x.length);
};
const eraPart = (ms) => {
eraName ??= twinOf({
calendar: "gregory",
era: "short",
year: "numeric",
timeZone
});
return eraName.formatToParts(ms).find((part) => part.type === "era");
};
/** The twin's parts of a date before 1873, with the Gregorian era added to a style pattern. */
const twinParts = (ms) => {
const parts = twin().formatToParts(ms);
if (eraSeat === null || !styled) return parts;
const name = eraPart(ms);
const at = parts.findIndex((part) => part.type === "year");
if (name === void 0 || at < 0) return parts;
const extra = eraSeat.after ? [...eraSeat.glue ? [{
type: "literal",
value: eraSeat.glue
}] : [], name] : [name, ...eraSeat.glue ? [{
type: "literal",
value: eraSeat.glue
}] : []];
return parts.toSpliced(eraSeat.after ? at + 1 : at, 0, ...extra);
};
const twinText = (ms) => eraSeat !== null && styled ? twinParts(ms).map((part) => part.value).join("") : twin().format(ms);
/** D25: the instant is before the first Japanese era (ISO year in the formatter's zone). */
const beforeEras = (ms) => era && zonedAt(ms, timeZone).year < FIRST_JAPANESE_ERA_YEAR;
/** D26: the instant is before the Hijra, decided by Temporal (era `bh`, or year 0 or less). */
const beforeHijra = (ms) => {
if (!islamic) return false;
try {
const date = zonedAt(ms, timeZone).withCalendar(calendar);
return date.era === "bh" || date.year <= 0;
} catch {
return false;
}
};
/** D27: an era year printed with one digit gains the formatter's own zero (never 元). */
const padPart = (part) => part.type === "year" && digitSet.has(part.value) && part.value.length === 1 ? {
...part,
value: zero + part.value
} : part;
/** The instants shifted by whole years that keep date and time, or `null` when none does. */
const shiftOf = (ms) => {
const start = zonedAt(ms, timeZone);
for (const years of SHIFTS) {
const moved = start.add({ years });
if (moved.month === start.month && moved.day === start.day && moved.toPlainTime().equals(start.toPlainTime())) return moved.epochMilliseconds;
}
return null;
};
const standIn = {
format(date) {
const ms = toMilliseconds(date);
if (beforeHijra(ms)) return "";
if (beforeEras(ms)) return twinText(ms);
return pad ? formatter.formatToParts(ms).map((part) => padPart(part).value).join("") : formatter.format(ms);
},
formatToParts(date) {
const ms = toMilliseconds(date);
if (beforeHijra(ms)) return [];
if (beforeEras(ms)) return twinParts(ms);
const parts = formatter.formatToParts(ms);
return pad ? parts.map(padPart) : parts;
},
formatRange(start, end) {
const a = toMilliseconds(start);
const b = toMilliseconds(end);
if (beforeHijra(a) || beforeHijra(b)) return "";
const hooks = rangeHooks();
if (hooks === void 0) return formatter.formatRange(a, b);
return hooks.yearRange({
formatter,
options: callerOptions,
resolved,
twin,
eraNameOf: (ms) => eraPart(ms)?.value ?? null,
japaneseEraNames,
twinText,
eraSeat: eraSeat !== null,
styled,
pad,
single: (ms) => standIn.format(ms),
zero,
digitSet,
shiftOf
}, a, b, [beforeEras(a), beforeEras(b)]) ?? "";
},
formatRangeToParts() {
throw new TypeError("formatRangeToParts is not available on a formatter whose years are repaired (CORE-112)");
},
resolvedOptions() {
return resolved;
}
};
markRangeHandled(standIn);
return standIn;
}
export { repairYearPrinting, showsEraOrYear, toMilliseconds, widenRelatedYear };