UNPKG

@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.

130 lines (128 loc) • 6.29 kB
import { isRangeFieldCompatNeeded } from "./temporalCompat/capabilities.js"; import { DATE_KEYS, TIME_KEYS, verdictKey } from "./patternKey.js"; import { rangeVerdict } from "./rangeDetector.js"; import { dayPeriodOf, forgetFieldReaders, localFieldsOf, rangeFieldsEqual } from "./rangeFieldValues.js"; import { fallbackTemplate, joinFallback } from "./rangeFallback.js"; import { formatRangeChecked } from "./weekYearRange.js"; import { ensureRangeHooks } from "./rangeRepairs.js"; // src/internal/rangeFields.ts /** * At most this many verdicts; past it the whole map clears (one `Map#clear`, then each pattern is * judged again on its next range: a cost of one detector run per live pattern, never a wrong text). */ const MAX_VERDICTS = 256; const verdicts = /* @__PURE__ */ new Map(); let verdictsBuiltWith; /** A UTC, zone-free clone of the formatter: the same pattern, with no zone to move an instant. */ function cloneOf(options, resolved) { const twin = { calendar: resolved.calendar, numberingSystem: resolved.numberingSystem, timeZone: "UTC" }; if (resolved.hourCycle !== void 0) twin.hourCycle = resolved.hourCycle; if (options.formatMatcher !== void 0) twin.formatMatcher = options.formatMatcher; for (const key of [...DATE_KEYS, ...TIME_KEYS]) if (options[key] !== void 0) Object.assign(twin, { [key]: options[key] }); return new Intl.DateTimeFormat(resolved.locale, twin); } /** * The class of the greatest field that differs between two instants in the formatter's calendar and * zone, named as the detector's probes are: `G` era, `y` year, `M` month, `d` day, `a` AM or PM, * `B` flexible day period, `h` hour, `m` minute; `null` when only seconds or less differ. The order * is ECMA-402 Table 6. */ function greatestClass(options, resolved, startMs, endMs) { const x = localFieldsOf(resolved, startMs); const y = localFieldsOf(resolved, endMs); const differs = (...types) => types.some((type) => x[type] !== y[type]); if (differs("era")) return "G"; if (differs("year", "relatedYear", "yearName")) return "y"; if (differs("month")) return "M"; if (differs("day")) return "d"; if (Math.floor(Number(x["hour"]) / 12) !== Math.floor(Number(y["hour"]) / 12)) return "a"; if (dayPeriodOf(options, resolved, startMs) !== dayPeriodOf(options, resolved, endMs)) return "B"; if (differs("hour")) return "h"; return differs("minute") ? "m" : null; } /** The classes of range this formatter's pattern gets wrong, kept per pattern. */ function wrongClasses(options, resolved) { if (verdictsBuiltWith !== Intl.DateTimeFormat) { verdicts.clear(); forgetFieldReaders(); verdictsBuiltWith = Intl.DateTimeFormat; } const key = verdictKey(options, resolved); const known = verdicts.get(key); if (known !== void 0) return known; const clone = cloneOf(options, resolved); const { classes } = rangeVerdict({ format: (ms) => clone.format(ms), formatRange: (a, b) => clone.formatRange(a, b), ...options.dayPeriod === void 0 ? {} : { dayPeriod: (ms) => dayPeriodOf(options, { ...resolved, timeZone: "UTC" }, ms) } }, resolved.calendar); if (verdicts.size >= MAX_VERDICTS) verdicts.clear(); verdicts.set(key, classes); return classes; } /** * The range text where the engine's range pattern drops, repeats or garbles a field (defect D29) * for this pair of instants, or `null` when the engine's own range is right and is to be used. * * The verdict is per pattern and per class of the greatest field that differs, because an engine's * interval data is per class: a pattern wrong for a day-apart range prints a same-day range right, * and that range is not replaced. Two instants whose field values are equal in every row ECMA-402 * PartitionDateTimeRangePattern checks are the one single text; printed text is never compared. * * @param formatter the formatter whose range is asked for * @param options the options it was built with * @param startMs the start in epoch milliseconds * @param endMs the end in epoch milliseconds * @returns the repaired text, `""` when the fallback joiner is unavailable, or `null` to use the engine's range * * @example rangeFieldsText(new Intl.DateTimeFormat("en", { dateStyle: "medium", timeZone: "UTC" }), { dateStyle: "medium" }, 0, 86_400_000) // null on an engine whose ranges are right */ function rangeFieldsText(formatter, options, startMs, endMs) { if (!isRangeFieldCompatNeeded()) return null; try { const resolved = formatter.resolvedOptions(); const classes = wrongClasses(options, resolved); if (!classes.length) return null; if (rangeFieldsEqual(options, resolved, startMs, endMs)) return formatter.format(startMs); return classes.includes(greatestClass(options, resolved, startMs, endMs) ?? "") ? rangeFromSingles(formatter, startMs, endMs) : null; } catch { return null; } } /** * The range as the locale's fallback writes it from the formatter's own single texts, or `""` when * the joiner or a single is unavailable (the house value). * * @example rangeFromSingles(new Intl.DateTimeFormat("en", { dateStyle: "medium", timeZone: "UTC" }), 1715731200000, 1715904000000) // "May 15, 2024 – May 17, 2024" */ function rangeFromSingles(formatter, startMs, endMs) { try { const { locale, numberingSystem, calendar } = formatter.resolvedOptions(); const template = fallbackTemplate(locale, numberingSystem, calendar); const first = formatter.format(startMs); const last = formatter.format(endMs); return template === null || first === "" || last === "" ? "" : joinFallback(template, first, last); } catch { return ""; } } /** * The text of a range: the fields repair of D29 where this pair needs it, else the year repair * (`formatRangeChecked`) of the engine's own range. The one call the range functions make. * * @returns the text, or `null` when a flagged formatter's year runs cannot be repaired * * @example formatRangeRepaired(new Intl.DateTimeFormat("en", { dateStyle: "medium", timeZone: "UTC" }), { dateStyle: "medium" }, 1715731200000, 1715904000000) // "May 15 – 17, 2024" */ function formatRangeRepaired(formatter, options, startMs, endMs) { ensureRangeHooks(); return rangeFieldsText(formatter, options, startMs, endMs) ?? formatRangeChecked(formatter, options, startMs, endMs); } export { formatRangeRepaired, rangeFieldsText, rangeFromSingles };