@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.
420 lines (418 loc) • 13.6 kB
JavaScript
import { anchorYear, dateIn, digitRuns, digitSetOf } from "./weekYearText.js";
// src/internal/weekYearSynth.ts
/** Option names of the time fields. */
const TIME_KEYS = [
"hour",
"minute",
"second",
"fractionalSecondDigits",
"dayPeriod",
"timeZoneName",
"timeStyle"
];
const LETTER = /\p{L}|\p{M}/u;
const DIGIT = /\p{Nd}/u;
/** Part types a twin supplies by digit run, not by text. */
const NUMERIC_TYPES = /* @__PURE__ */ new Set([
"literal",
"day",
"hour",
"minute",
"second",
"fractionalSecond",
"year",
"relatedYear",
"yearName"
]);
/** The widths a text field is printed in: the formatter's own, unless a style could print any. */
function widthsOf(options, key, all) {
const styled = options.dateStyle !== void 0 || options.timeStyle !== void 0;
const own = options[key];
return !styled && own !== void 0 ? [own] : all;
}
/** Twins for the weekday, month and era fields, in every width the options can print. */
function textTwinOptions(options) {
const out = [];
for (const weekday of widthsOf(options, "weekday", ["long", "short"])) out.push({ weekday }, {
weekday,
month: "long",
day: "numeric"
});
for (const month of widthsOf(options, "month", ["long", "short"])) if (month !== "numeric" && month !== "2-digit") out.push({ month }, {
month,
day: "numeric"
});
for (const era of options.era === void 0 ? [
"long",
"short",
"narrow"
] : [options.era]) out.push({
era,
month: "numeric",
day: "numeric"
});
for (const width of ["long", "short"]) {
if (!out.some((o) => o.month === width && o.day !== void 0)) out.push({
month: width,
day: "numeric"
});
if (!out.some((o) => o.weekday === width && o.month === void 0)) out.push({ weekday: width });
}
out.push({
month: "numeric",
day: "numeric"
}, {
month: "2-digit",
day: "2-digit"
});
return out;
}
/** The twin for the time fields of a formatter, or `null` when it prints none. */
function timeTwinOptions(options, hourCycle) {
if (!TIME_KEYS.some((key) => options[key] !== void 0)) return null;
const time = {};
for (const key of TIME_KEYS) if (options[key] !== void 0 && key !== "timeStyle") Object.assign(time, { [key]: options[key] });
if (options.timeStyle !== void 0) {
time.hour = "numeric";
time.minute = "numeric";
if (options.timeStyle === "long" || options.timeStyle === "full") time.timeZoneName = options.timeStyle === "full" ? "long" : "short";
}
if (hourCycle !== void 0) time.hourCycle = hourCycle;
if (TIME_KEYS.slice(0, 5).every((key) => time[key] === void 0)) {
time.month = "numeric";
time.day = "numeric";
}
return time;
}
/** The twin options for a formatter: its text fields, in every width its options can print. */
function twinOptions(options, hourCycle) {
const time = timeTwinOptions(options, hourCycle);
return time === null ? textTwinOptions(options) : [...textTwinOptions(options), time];
}
/**
* The twins of a formatter that print no year. A twin that prints a year could hold `Y`, so it is
* never asked for parts.
*/
function buildTwins(options, resolved) {
const twins = [];
const common = {
calendar: resolved.calendar,
numberingSystem: resolved.numberingSystem,
timeZone: resolved.timeZone
};
for (const [index, own] of twinOptions(options, resolved.hourCycle).entries()) try {
const format = new Intl.DateTimeFormat(resolved.locale, {
...common,
...own
});
if (format.resolvedOptions().year === void 0) twins.push({
format,
index,
numeric: (own.month === "numeric" || own.month === "2-digit") && own.era === void 0
});
} catch {}
return twins;
}
/** Every text and numeric value the twins print at `ms`, longest first. */
function candidatesFrom(twins, ms) {
const out = [];
for (const { format, index, numeric } of twins) for (const part of format.formatToParts(ms)) {
if (part.type === "literal" || part.value.trim() === "") continue;
const isNumber = numeric && (part.type === "month" || part.type === "day");
if (isNumber || !NUMERIC_TYPES.has(part.type)) out.push({
type: part.type,
key: `${index}:${part.type}`,
value: part.value,
numeric: isNumber
});
}
return out.sort((a, b) => b.value.length - a.value.length);
}
/**
* Whether `value` at `at` in `span` starts and ends on a field boundary: one or two characters may
* not begin or end inside a run of letters (the `d` of `de`).
*/
function fits(span, at, value) {
if (!span.startsWith(value, at)) return false;
if (value.length > 2) return true;
const last = value.at(-1) ?? "";
const first = value[0] ?? "";
return !(LETTER.test(last) && LETTER.test(span[at + value.length] ?? "") || LETTER.test(first) && LETTER.test(span[at - 1] ?? ""));
}
/**
* The template of a span: the text fields in order, found greedily from the candidates. `null`
* when two field types claim the same longest text at one place: a type chosen on a tie would be
* a guess, so a date where the names differ decides it (CORE-112 tie-break).
*/
function segment(spans, candidates) {
const plan = [];
for (const span of spans) {
const fields = [];
for (let at = 0; at < span.length;) {
const hits = candidates.filter((c) => fits(span, at, c.value));
const longest = hits[0]?.value.length;
if (longest === void 0) {
at++;
continue;
}
const best = hits.filter((c) => c.value.length === longest);
if (new Set(best.map((c) => c.type)).size > 1) return null;
fields.push({
type: best[0]?.type ?? "literal",
keys: best.map((c) => c.key)
});
at += longest;
}
plan.push(fields);
}
return plan;
}
/**
* The extent of a numeric run widened to a twin's wider value for it (`1` printed as `01`), or
* `null` when no twin value covers it.
*/
function widenRun(text, run, label, candidates, position) {
for (const c of candidates) {
if (!c.numeric || c.type !== label || c.value === run.text) continue;
const inside = c.value.indexOf(run.text);
const from = run.start - inside;
if (inside >= 0 && from >= position && text.slice(from, from + c.value.length) === c.value) return {
start: from,
end: from + c.value.length
};
}
return null;
}
/**
* The keys of the twin fields whose names hold a digit on some dates and none on others: lg `Lw3`
* beside `Sab`, an Islamic month `Jum. 2` beside `Rajab`, he `Adar 1` beside `Tevet`. Read over a
* week and over every month of three years, which hold a Hebrew and a Chinese leap month.
*/
function varyingNames(twins, calendar, timeZone, isDigit) {
const anchor = anchorYear(calendar);
const start = dateIn(calendar, anchor, 1, 15);
const dates = [
1,
2,
3,
4,
5,
6
].map((days) => start.add({ days }));
for (let year = anchor; year < anchor + 3; year++) {
const months = dateIn(calendar, year, 1, 15).monthsInYear;
for (let month = 1; month <= months; month++) dates.push(dateIn(calendar, year, month, 15));
}
const withDigit = /* @__PURE__ */ new Map();
const varying = /* @__PURE__ */ new Set();
for (const date of dates) {
const ms = date.toZonedDateTime({
timeZone,
plainTime: "12:00"
}).epochMilliseconds;
for (const { key, value, numeric } of candidatesFrom(twins, ms)) {
const has = [...value].some(isDigit);
if (!numeric && withDigit.get(key) === !has) varying.add(key);
withDigit.set(key, has);
}
}
return varying;
}
/**
* A formatter's text at a time value with the digits of each name in `varyingNames` hidden, the
* length kept: its digit runs are then the same on every date, which `analyse` and `repairText`
* need. A name is found where no digit touches it (ksb narrow weekday `3` beside a day `13`).
*
* @param options the options the formatter was built with
* @param resolved its resolved options
*/
function createNameMask(options, resolved) {
const digits = digitSetOf(resolved.numberingSystem);
const isDigit = (character) => digits.has(character) || DIGIT.test(character);
let twins;
let varying;
return (text, ms) => {
twins ??= buildTwins(options, resolved);
varying ??= varyingNames(twins, resolved.calendar, resolved.timeZone, isDigit);
let out = text;
const hidden = /* @__PURE__ */ new Set();
for (const { type, key, value } of varying.size === 0 ? [] : candidatesFrom(twins, ms)) {
const name = `${type}:${value}`;
if (!varying.has(key) || hidden.has(name)) continue;
hidden.add(name);
for (let at = out.indexOf(value); at >= 0; at = out.indexOf(value, at + 1)) {
const end = at + value.length;
if (!isDigit(/.$/u.exec(out.slice(0, at))?.[0] ?? "") && !isDigit(/^./u.exec(out.slice(end))?.[0] ?? "")) {
const masked = [...value].map((character) => isDigit(character) ? "_".repeat(character.length) : character).join("");
out = out.slice(0, at) + masked + out.slice(end);
break;
}
}
}
return out;
};
}
/** The repaired text cut at its numeric runs, and the numeric parts between. */
function spansOf(analysis, repaired, candidates, ms) {
const runs = digitRuns(analysis.mask(repaired.text, ms), analysis.digits);
if (runs.length !== analysis.count) return null;
const spans = [];
const numbers = [];
let position = 0;
for (const [index, run] of runs.entries()) {
const label = analysis.labels[index];
if (label === void 0 || label === "literal" || label === "text") continue;
const year = analysis.yearRuns.indexOf(index);
const extent = (year < 0 ? void 0 : repaired.edits[year]) ?? widenRun(repaired.text, run, label, candidates, position) ?? run;
spans.push(repaired.text.slice(position, extent.start));
numbers.push({
type: label,
value: repaired.text.slice(extent.start, extent.end)
});
position = extent.end;
}
spans.push(repaired.text.slice(position));
return {
spans,
numbers
};
}
/** The first dates the template is tried on: a month, a day and a time each. */
const TEMPLATE_DATES = [
[
1,
15,
"10:20:30.456"
],
[
1,
15,
"22:20:30.456"
],
[
3,
9,
"22:20:30.456"
],
[
5,
20,
"03:20:30.456"
],
[
8,
3,
"15:20:30.456"
]
];
/** The time value of a template date in the formatter's calendar and zone. */
function templateMs(analysis, anchor, [month, day, time]) {
return dateIn(analysis.calendar, anchor, month, day).toZonedDateTime({
timeZone: analysis.timeZone,
plainTime: time
}).epochMilliseconds;
}
/**
* Finds a field's value in a span at or after `position`: the earliest hit, the longer on a tie.
* `null` when none of its keys finds one.
*/
function placeField(span, position, field, values) {
let best = null;
for (const key of field.keys) {
const value = values.get(key);
if (value === void 0) continue;
for (let i = span.indexOf(value, position); i >= 0; i = span.indexOf(value, i + 1)) if (fits(span, i, value)) {
if (best === null || i < best.at || i === best.at && value.length > best.found.length) best = {
at: i,
found: value
};
break;
}
}
return best;
}
/** One span's parts: its template fields, the literals between, and the numeric part after. */
function partsOfSpan(span, fields, values, number) {
const parts = [];
let position = 0;
for (const field of fields) {
const hit = placeField(span, position, field, values);
if (hit === null) return null;
if (hit.at > position) parts.push({
type: "literal",
value: span.slice(position, hit.at)
});
parts.push({
type: field.type,
value: hit.found
});
position = hit.at + hit.found.length;
}
if (position < span.length) parts.push({
type: "literal",
value: span.slice(position)
});
if (number !== void 0) parts.push(number);
return parts;
}
/** Adjacent literals joined into one. */
function mergeLiterals(parts) {
const merged = [];
for (const part of parts) {
const last = merged.at(-1);
if (last?.type === "literal" && part.type === "literal") last.value += part.value;
else merged.push({ ...part });
}
return merged;
}
/**
* Parts of one flagged formatter, from its repaired `format` text and its twins.
*
* @param options the options the formatter was built with
* @param resolved its resolved options
* @param analysis what was read from its text
* @param repair the formatter's repaired text at a time value, or `null`
* @returns a function from a time value to its parts, or `null` where no answer is known
*/
function createPartsSynth(options, resolved, analysis, repair) {
let twins;
let plan;
const candidatesAt = (ms) => {
twins ??= buildTwins(options, resolved);
return candidatesFrom(twins, ms);
};
const spansAt = (ms, candidates) => {
const repaired = repair(ms);
return repaired === null ? null : spansOf(analysis, repaired, candidates, ms);
};
const templateOf = () => {
if (plan !== void 0) return plan;
plan = null;
const anchor = anchorYear(analysis.calendar);
for (const date of TEMPLATE_DATES) {
const ms = templateMs(analysis, anchor, date);
const candidates = candidatesAt(ms);
const spans = spansAt(ms, candidates);
if (spans === null) continue;
plan = segment(spans.spans, candidates.filter((c) => !c.numeric));
if (plan !== null) break;
}
return plan;
};
return (ms) => {
const template = templateOf();
if (template === null) return null;
const candidates = candidatesAt(ms);
const spans = spansAt(ms, candidates);
if (spans === null) return null;
const values = new Map(candidates.map((c) => [c.key, c.value]));
const parts = [];
for (const [n, span] of spans.spans.entries()) {
const next = partsOfSpan(span, template[n] ?? [], values, spans.numbers[n]);
if (next === null) return null;
parts.push(...next);
}
return mergeLiterals(parts);
};
}
export { createNameMask, createPartsSynth };