@nervure/datetime 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,35 @@
1
+ import type { PickerOptions, PickerValue, Selection } from './types.ts';
2
+ declare const Base: typeof HTMLElement;
3
+ /**
4
+ * `<nv-datetime mode="range" presets locale="fr" zone="Europe/Paris" name="period">`.
5
+ * Draws a text field with its panel, or the calendar itself with `inline`. Light DOM: the CSS of the page applies.
6
+ * `change` fires with the selection in `event.detail`; `value` reads and sets the ISO value.
7
+ */
8
+ export declare class NvDateTime extends Base {
9
+ static readonly observedAttributes: readonly ["mode", "value", "zone", "zones", "locale", "min", "max", "months", "time", "seconds", "minute-step", "hour12", "first-day", "week-numbers", "presets", "inline", "placeholder", "accent", "theme", "name", "disabled"];
10
+ private picker;
11
+ private extra;
12
+ connectedCallback(): void;
13
+ disconnectedCallback(): void;
14
+ attributeChangedCallback(name: string, before: string | null, after: string | null): void;
15
+ /** The ISO value: a text, a list (`multiple`) or `{ start, end }` (`range`). */
16
+ get value(): PickerValue;
17
+ set value(value: PickerValue | Date);
18
+ /** The value, its two instants, its zone and its text. */
19
+ get selection(): Selection | null;
20
+ /** Options an attribute cannot carry: `disable` as a function, `format`, `labels`, your own periods. */
21
+ set options(options: PickerOptions);
22
+ open(): void;
23
+ close(): void;
24
+ private parse;
25
+ private read;
26
+ private render;
27
+ }
28
+ /** Registers `<nv-datetime>` (or another tag name), once. */
29
+ export declare function defineDateTimeElement(tag?: string): void;
30
+ declare global {
31
+ interface HTMLElementTagNameMap {
32
+ 'nv-datetime': NvDateTime;
33
+ }
34
+ }
35
+ export {};
@@ -0,0 +1,160 @@
1
+ import { createDatePicker } from "./core.js";
2
+ const ATTRS = [
3
+ 'mode',
4
+ 'value',
5
+ 'zone',
6
+ 'zones',
7
+ 'locale',
8
+ 'min',
9
+ 'max',
10
+ 'months',
11
+ 'time',
12
+ 'seconds',
13
+ 'minute-step',
14
+ 'hour12',
15
+ 'first-day',
16
+ 'week-numbers',
17
+ 'presets',
18
+ 'inline',
19
+ 'placeholder',
20
+ 'accent',
21
+ 'theme',
22
+ 'name',
23
+ 'disabled',
24
+ ];
25
+ // On the server there is no HTMLElement: the class is defined but never registered.
26
+ const Base = typeof HTMLElement === 'undefined' ? Object : HTMLElement;
27
+ /**
28
+ * `<nv-datetime mode="range" presets locale="fr" zone="Europe/Paris" name="period">`.
29
+ * Draws a text field with its panel, or the calendar itself with `inline`. Light DOM: the CSS of the page applies.
30
+ * `change` fires with the selection in `event.detail`; `value` reads and sets the ISO value.
31
+ */
32
+ export class NvDateTime extends Base {
33
+ static observedAttributes = ATTRS;
34
+ picker = null;
35
+ extra = {};
36
+ connectedCallback() {
37
+ this.render();
38
+ }
39
+ disconnectedCallback() {
40
+ this.picker?.destroy();
41
+ this.picker = null;
42
+ }
43
+ attributeChangedCallback(name, before, after) {
44
+ if (!this.isConnected || before === after)
45
+ return;
46
+ if (name === 'value')
47
+ this.picker?.setValue(this.parse(after));
48
+ else if (name === 'inline' || name === 'name' || name === 'disabled')
49
+ this.render();
50
+ else
51
+ this.picker?.update(this.read());
52
+ }
53
+ /** The ISO value: a text, a list (`multiple`) or `{ start, end }` (`range`). */
54
+ get value() {
55
+ return this.picker?.getValue() ?? null;
56
+ }
57
+ set value(value) {
58
+ this.picker?.setValue(value);
59
+ }
60
+ /** The value, its two instants, its zone and its text. */
61
+ get selection() {
62
+ return this.picker?.getSelection() ?? null;
63
+ }
64
+ /** Options an attribute cannot carry: `disable` as a function, `format`, `labels`, your own periods. */
65
+ set options(options) {
66
+ this.extra = options;
67
+ this.picker?.update({ ...this.read(), ...options });
68
+ }
69
+ open() {
70
+ this.picker?.open();
71
+ }
72
+ close() {
73
+ this.picker?.close();
74
+ }
75
+ parse(text) {
76
+ if (!text)
77
+ return null;
78
+ const t = text.trim();
79
+ if (t.startsWith('{') || t.startsWith('[')) {
80
+ try {
81
+ return JSON.parse(t);
82
+ }
83
+ catch {
84
+ return null;
85
+ }
86
+ }
87
+ // "2026-01-01/2026-03-31" for a range, "2026-01-01,2026-01-05" for several days
88
+ if (t.includes('/')) {
89
+ const [start, end] = t.split('/');
90
+ return { start: start, end: end };
91
+ }
92
+ return t.includes(',') ? t.split(',').map((s) => s.trim()) : t;
93
+ }
94
+ read() {
95
+ const get = (key) => this.getAttribute(key) ?? undefined;
96
+ const flag = (key) => this.hasAttribute(key) ? this.getAttribute(key) !== 'false' : undefined;
97
+ const number = (key) => this.hasAttribute(key) ? Number(this.getAttribute(key)) : undefined;
98
+ return {
99
+ mode: get('mode'),
100
+ zone: get('zone'),
101
+ zones: get('zones')
102
+ ?.split(',')
103
+ .map((z) => z.trim())
104
+ .filter(Boolean),
105
+ locale: get('locale'),
106
+ min: get('min'),
107
+ max: get('max'),
108
+ months: number('months'),
109
+ time: flag('time'),
110
+ seconds: flag('seconds'),
111
+ minuteStep: number('minute-step'),
112
+ hour12: flag('hour12'),
113
+ firstDay: number('first-day'),
114
+ weekNumbers: flag('week-numbers'),
115
+ presets: flag('presets'),
116
+ inline: flag('inline'),
117
+ placeholder: get('placeholder'),
118
+ accent: get('accent'),
119
+ theme: get('theme'),
120
+ };
121
+ }
122
+ render() {
123
+ const value = this.picker ? this.picker.getValue() : this.parse(this.getAttribute('value'));
124
+ this.picker?.destroy();
125
+ this.replaceChildren();
126
+ const inline = this.hasAttribute('inline') && this.getAttribute('inline') !== 'false';
127
+ let field = null;
128
+ if (!inline) {
129
+ const input = this.ownerDocument.createElement('input');
130
+ input.type = 'text';
131
+ input.className = 'nv-datetime-field';
132
+ const name = this.getAttribute('name');
133
+ if (name)
134
+ input.name = name;
135
+ input.disabled = this.hasAttribute('disabled');
136
+ const label = this.getAttribute('aria-label');
137
+ if (label)
138
+ input.setAttribute('aria-label', label);
139
+ this.append(input);
140
+ field = input;
141
+ }
142
+ this.picker = createDatePicker(field ?? this, {
143
+ ...this.read(),
144
+ ...this.extra,
145
+ value,
146
+ onChange: (selection) => {
147
+ this.extra.onChange?.(selection);
148
+ this.dispatchEvent(new CustomEvent('change', { detail: selection, bubbles: true }));
149
+ },
150
+ });
151
+ }
152
+ }
153
+ /** Registers `<nv-datetime>` (or another tag name), once. */
154
+ export function defineDateTimeElement(tag = 'nv-datetime') {
155
+ if (typeof customElements === 'undefined' || customElements.get(tag))
156
+ return;
157
+ customElements.define(tag, tag === 'nv-datetime' ? NvDateTime : class extends NvDateTime {
158
+ });
159
+ }
160
+ defineDateTimeElement();
package/dist/i18n.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import type { PeriodName } from './calendar.ts';
2
+ export interface Labels {
3
+ today: string;
4
+ now: string;
5
+ clear: string;
6
+ apply: string;
7
+ cancel: string;
8
+ from: string;
9
+ to: string;
10
+ time: string;
11
+ /** Short word before a week number: "W" in "W49". */
12
+ week: string;
13
+ /** Short word before a quarter number: "Q" in "Q4", "T" in "T4". */
14
+ quarter: string;
15
+ previous: string;
16
+ next: string;
17
+ zone: string;
18
+ periods: Record<PeriodName, string>;
19
+ }
20
+ /** The languages the words of the picker are written in. Month and day names exist for every language of the platform. */
21
+ export declare const LANGUAGES: readonly string[];
22
+ /** The words of the picker for a locale, with the reader's own replacements. */
23
+ export declare function labelsFor(locale: string, custom?: Partial<Omit<Labels, 'periods'>> & {
24
+ periods?: Partial<Labels['periods']>;
25
+ }): Labels;
26
+ /** Right-to-left scripts (Arabic, Persian, Urdu...). */
27
+ export declare function isRtl(locale: string): boolean;
28
+ /** First day of the week of a locale: 0 Monday to 6 Sunday. */
29
+ export declare function firstDayOf(locale: string): number;
30
+ /** True when the locale writes hours as 1 to 12 with AM and PM. */
31
+ export declare function uses12Hours(locale: string): boolean;
32
+ /** The twelve month names. */
33
+ export declare function monthNames(locale: string, width?: 'long' | 'short'): string[];
34
+ /** The seven day names, from the first day of the week. */
35
+ export declare function weekdayNames(locale: string, firstDay: number, width?: 'long' | 'short' | 'narrow'): string[];
36
+ /** A number in the digits of the locale (Arabic-Indic digits in `ar-EG`). */
37
+ export declare const digits: (n: number, locale: string, minimum?: number) => string;
package/dist/i18n.js ADDED
@@ -0,0 +1,128 @@
1
+ const KEYS = [
2
+ 'today',
3
+ 'now',
4
+ 'clear',
5
+ 'apply',
6
+ 'cancel',
7
+ 'from',
8
+ 'to',
9
+ 'time',
10
+ 'week',
11
+ 'quarter',
12
+ 'previous',
13
+ 'next',
14
+ 'zone',
15
+ ];
16
+ const PERIOD_KEYS = [
17
+ 'yesterday',
18
+ 'last7',
19
+ 'last30',
20
+ 'thisWeek',
21
+ 'lastWeek',
22
+ 'thisMonth',
23
+ 'lastMonth',
24
+ 'thisQuarter',
25
+ 'lastQuarter',
26
+ 'thisYear',
27
+ 'lastYear',
28
+ 'yearToDate',
29
+ ];
30
+ // One line per language, in the order of KEYS then PERIOD_KEYS ("today" is used for both)
31
+ const WORDS = {
32
+ en: 'Today|Now|Clear|Apply|Cancel|From|To|Time|W|Q|Previous|Next|Time zone|Yesterday|Last 7 days|Last 30 days|This week|Last week|This month|Last month|This quarter|Last quarter|This year|Last year|Year to date',
33
+ fr: "Aujourd'hui|Maintenant|Effacer|Appliquer|Annuler|Du|Au|Heure|S|T|Précédent|Suivant|Fuseau horaire|Hier|7 derniers jours|30 derniers jours|Cette semaine|Semaine dernière|Ce mois-ci|Mois dernier|Ce trimestre|Trimestre dernier|Cette année|Année dernière|Depuis le début de l'année",
34
+ de: 'Heute|Jetzt|Löschen|Übernehmen|Abbrechen|Von|Bis|Uhrzeit|KW|Q|Zurück|Weiter|Zeitzone|Gestern|Letzte 7 Tage|Letzte 30 Tage|Diese Woche|Letzte Woche|Dieser Monat|Letzter Monat|Dieses Quartal|Letztes Quartal|Dieses Jahr|Letztes Jahr|Seit Jahresbeginn',
35
+ es: 'Hoy|Ahora|Borrar|Aplicar|Cancelar|Desde|Hasta|Hora|S|T|Anterior|Siguiente|Zona horaria|Ayer|Últimos 7 días|Últimos 30 días|Esta semana|Semana pasada|Este mes|Mes pasado|Este trimestre|Trimestre pasado|Este año|Año pasado|Año hasta la fecha',
36
+ it: "Oggi|Adesso|Cancella|Applica|Annulla|Dal|Al|Ora|S|T|Precedente|Successivo|Fuso orario|Ieri|Ultimi 7 giorni|Ultimi 30 giorni|Questa settimana|Settimana scorsa|Questo mese|Mese scorso|Questo trimestre|Trimestre scorso|Quest'anno|Anno scorso|Da inizio anno",
37
+ pt: 'Hoje|Agora|Limpar|Aplicar|Cancelar|De|Até|Hora|S|T|Anterior|Seguinte|Fuso horário|Ontem|Últimos 7 dias|Últimos 30 dias|Esta semana|Semana passada|Este mês|Mês passado|Este trimestre|Trimestre passado|Este ano|Ano passado|Desde o início do ano',
38
+ nl: 'Vandaag|Nu|Wissen|Toepassen|Annuleren|Van|Tot|Tijd|W|K|Vorige|Volgende|Tijdzone|Gisteren|Laatste 7 dagen|Laatste 30 dagen|Deze week|Vorige week|Deze maand|Vorige maand|Dit kwartaal|Vorig kwartaal|Dit jaar|Vorig jaar|Dit jaar tot nu',
39
+ sv: 'Idag|Nu|Rensa|Använd|Avbryt|Från|Till|Tid|V|K|Föregående|Nästa|Tidszon|Igår|Senaste 7 dagarna|Senaste 30 dagarna|Denna vecka|Förra veckan|Denna månad|Förra månaden|Detta kvartal|Förra kvartalet|I år|Förra året|Hittills i år',
40
+ da: 'I dag|Nu|Ryd|Anvend|Annuller|Fra|Til|Tid|U|K|Forrige|Næste|Tidszone|I går|Seneste 7 dage|Seneste 30 dage|Denne uge|Sidste uge|Denne måned|Sidste måned|Dette kvartal|Sidste kvartal|I år|Sidste år|År til dato',
41
+ nb: 'I dag|Nå|Tøm|Bruk|Avbryt|Fra|Til|Tid|U|K|Forrige|Neste|Tidssone|I går|Siste 7 dager|Siste 30 dager|Denne uken|Forrige uke|Denne måneden|Forrige måned|Dette kvartalet|Forrige kvartal|I år|I fjor|Hittil i år',
42
+ fi: 'Tänään|Nyt|Tyhjennä|Käytä|Peruuta|Alkaen|Asti|Aika|Vk|Q|Edellinen|Seuraava|Aikavyöhyke|Eilen|Viimeiset 7 päivää|Viimeiset 30 päivää|Tämä viikko|Viime viikko|Tämä kuukausi|Viime kuukausi|Tämä neljännes|Viime neljännes|Tämä vuosi|Viime vuosi|Vuoden alusta',
43
+ pl: 'Dzisiaj|Teraz|Wyczyść|Zastosuj|Anuluj|Od|Do|Godzina|Tydz.|Kw.|Poprzedni|Następny|Strefa czasowa|Wczoraj|Ostatnie 7 dni|Ostatnie 30 dni|Ten tydzień|Poprzedni tydzień|Ten miesiąc|Poprzedni miesiąc|Ten kwartał|Poprzedni kwartał|Ten rok|Poprzedni rok|Od początku roku',
44
+ cs: 'Dnes|Nyní|Vymazat|Použít|Zrušit|Od|Do|Čas|T|Q|Předchozí|Další|Časové pásmo|Včera|Posledních 7 dní|Posledních 30 dní|Tento týden|Minulý týden|Tento měsíc|Minulý měsíc|Toto čtvrtletí|Minulé čtvrtletí|Tento rok|Minulý rok|Od začátku roku',
45
+ sk: 'Dnes|Teraz|Vymazať|Použiť|Zrušiť|Od|Do|Čas|T|Q|Predchádzajúci|Ďalší|Časové pásmo|Včera|Posledných 7 dní|Posledných 30 dní|Tento týždeň|Minulý týždeň|Tento mesiac|Minulý mesiac|Tento štvrťrok|Minulý štvrťrok|Tento rok|Minulý rok|Od začiatku roka',
46
+ hu: 'Ma|Most|Törlés|Alkalmaz|Mégse|Ettől|Eddig|Idő|H|N|Előző|Következő|Időzóna|Tegnap|Elmúlt 7 nap|Elmúlt 30 nap|Ez a hét|Múlt hét|Ez a hónap|Múlt hónap|Ez a negyedév|Múlt negyedév|Idén|Tavaly|Év eleje óta',
47
+ ro: 'Astăzi|Acum|Șterge|Aplică|Anulează|De la|Până la|Ora|S|T|Anterior|Următor|Fus orar|Ieri|Ultimele 7 zile|Ultimele 30 de zile|Săptămâna aceasta|Săptămâna trecută|Luna aceasta|Luna trecută|Trimestrul acesta|Trimestrul trecut|Anul acesta|Anul trecut|De la începutul anului',
48
+ bg: 'Днес|Сега|Изчисти|Приложи|Отказ|От|До|Час|С|Тр|Предишен|Следващ|Часова зона|Вчера|Последните 7 дни|Последните 30 дни|Тази седмица|Миналата седмица|Този месец|Миналия месец|Това тримесечие|Миналото тримесечие|Тази година|Миналата година|От началото на годината',
49
+ el: 'Σήμερα|Τώρα|Καθαρισμός|Εφαρμογή|Ακύρωση|Από|Έως|Ώρα|Εβδ|Τρ|Προηγούμενο|Επόμενο|Ζώνη ώρας|Χθες|Τελευταίες 7 ημέρες|Τελευταίες 30 ημέρες|Αυτή την εβδομάδα|Προηγούμενη εβδομάδα|Αυτόν τον μήνα|Προηγούμενος μήνας|Αυτό το τρίμηνο|Προηγούμενο τρίμηνο|Φέτος|Πέρσι|Από την αρχή του έτους',
50
+ hr: 'Danas|Sada|Očisti|Primijeni|Odustani|Od|Do|Vrijeme|T|Kv|Prethodno|Sljedeće|Vremenska zona|Jučer|Zadnjih 7 dana|Zadnjih 30 dana|Ovaj tjedan|Prošli tjedan|Ovaj mjesec|Prošli mjesec|Ovo tromjesečje|Prošlo tromjesečje|Ova godina|Prošla godina|Od početka godine',
51
+ sl: 'Danes|Zdaj|Počisti|Uporabi|Prekliči|Od|Do|Čas|T|Č|Prejšnji|Naslednji|Časovni pas|Včeraj|Zadnjih 7 dni|Zadnjih 30 dni|Ta teden|Prejšnji teden|Ta mesec|Prejšnji mesec|To četrtletje|Prejšnje četrtletje|Letos|Lani|Od začetka leta',
52
+ uk: 'Сьогодні|Зараз|Очистити|Застосувати|Скасувати|Від|До|Час|Тиж|Кв|Попередній|Наступний|Часовий пояс|Вчора|Останні 7 днів|Останні 30 днів|Цей тиждень|Минулий тиждень|Цей місяць|Минулий місяць|Цей квартал|Минулий квартал|Цей рік|Минулий рік|З початку року',
53
+ ru: 'Сегодня|Сейчас|Очистить|Применить|Отмена|С|По|Время|Нед|Кв|Назад|Вперёд|Часовой пояс|Вчера|Последние 7 дней|Последние 30 дней|Эта неделя|Прошлая неделя|Этот месяц|Прошлый месяц|Этот квартал|Прошлый квартал|Этот год|Прошлый год|С начала года',
54
+ tr: 'Bugün|Şimdi|Temizle|Uygula|İptal|Başlangıç|Bitiş|Saat|H|Ç|Önceki|Sonraki|Saat dilimi|Dün|Son 7 gün|Son 30 gün|Bu hafta|Geçen hafta|Bu ay|Geçen ay|Bu çeyrek|Geçen çeyrek|Bu yıl|Geçen yıl|Yıl başından bugüne',
55
+ ca: "Avui|Ara|Esborra|Aplica|Cancel·la|Des de|Fins a|Hora|S|T|Anterior|Següent|Fus horari|Ahir|Últims 7 dies|Últims 30 dies|Aquesta setmana|Setmana passada|Aquest mes|Mes passat|Aquest trimestre|Trimestre passat|Aquest any|Any passat|Des de l'inici de l'any",
56
+ lt: 'Šiandien|Dabar|Išvalyti|Taikyti|Atšaukti|Nuo|Iki|Laikas|Sav|Ketv|Ankstesnis|Kitas|Laiko juosta|Vakar|Paskutinės 7 dienos|Paskutinės 30 dienų|Ši savaitė|Praėjusi savaitė|Šis mėnuo|Praėjęs mėnuo|Šis ketvirtis|Praėjęs ketvirtis|Šie metai|Praėję metai|Nuo metų pradžios',
57
+ lv: 'Šodien|Tagad|Notīrīt|Lietot|Atcelt|No|Līdz|Laiks|Ned|Cet|Iepriekšējais|Nākamais|Laika josla|Vakar|Pēdējās 7 dienas|Pēdējās 30 dienas|Šī nedēļa|Pagājušā nedēļa|Šis mēnesis|Pagājušais mēnesis|Šis ceturksnis|Pagājušais ceturksnis|Šis gads|Pagājušais gads|Kopš gada sākuma',
58
+ et: 'Täna|Praegu|Tühjenda|Rakenda|Tühista|Alates|Kuni|Aeg|Näd|Kv|Eelmine|Järgmine|Ajavöönd|Eile|Viimased 7 päeva|Viimased 30 päeva|See nädal|Eelmine nädal|See kuu|Eelmine kuu|See kvartal|Eelmine kvartal|See aasta|Eelmine aasta|Aasta algusest',
59
+ ar: 'اليوم|الآن|مسح|تطبيق|إلغاء|من|إلى|الوقت|أ|ر|السابق|التالي|المنطقة الزمنية|أمس|آخر 7 أيام|آخر 30 يومًا|هذا الأسبوع|الأسبوع الماضي|هذا الشهر|الشهر الماضي|هذا الربع|الربع الماضي|هذه السنة|السنة الماضية|منذ بداية السنة',
60
+ };
61
+ /** The languages the words of the picker are written in. Month and day names exist for every language of the platform. */
62
+ export const LANGUAGES = Object.keys(WORDS);
63
+ const languageOf = (locale) => locale.toLowerCase().split(/[-_]/)[0];
64
+ /** The words of the picker for a locale, with the reader's own replacements. */
65
+ export function labelsFor(locale, custom = {}) {
66
+ const lang = languageOf(locale);
67
+ const words = (WORDS[lang === 'no' ? 'nb' : lang] ?? WORDS.en).split('|');
68
+ const out = { periods: {} };
69
+ KEYS.forEach((k, i) => (out[k] = words[i]));
70
+ out.periods.today = out.today;
71
+ PERIOD_KEYS.forEach((k, i) => (out.periods[k] = words[KEYS.length + i]));
72
+ const { periods, ...rest } = custom;
73
+ return { ...out, ...rest, periods: { ...out.periods, ...periods } };
74
+ }
75
+ /** Right-to-left scripts (Arabic, Persian, Urdu...). */
76
+ export function isRtl(locale) {
77
+ try {
78
+ const l = new Intl.Locale(locale);
79
+ const info = l.getTextInfo?.() ?? l.textInfo;
80
+ if (info)
81
+ return info.direction === 'rtl';
82
+ }
83
+ catch {
84
+ /* an unknown tag: the language code decides */
85
+ }
86
+ return ['ar', 'fa', 'ur', 'ps', 'dv', 'ckb'].includes(languageOf(locale));
87
+ }
88
+ /** First day of the week of a locale: 0 Monday to 6 Sunday. */
89
+ export function firstDayOf(locale) {
90
+ try {
91
+ const l = new Intl.Locale(locale);
92
+ const info = l.getWeekInfo?.() ?? l.weekInfo;
93
+ if (info)
94
+ return (info.firstDay + 6) % 7; // Intl: 1 Monday to 7 Sunday
95
+ const region = l.maximize().region ?? '';
96
+ if (['US', 'CA', 'MX', 'BR', 'JP', 'KR', 'IL', 'IN', 'PH', 'SA', 'ZA', 'CO', 'PE', 'VE'].includes(region))
97
+ return 6;
98
+ if (['EG', 'DZ', 'MA', 'TN', 'IQ', 'SY', 'JO', 'KW', 'QA', 'BH', 'OM', 'LY', 'AF', 'IR'].includes(region))
99
+ return region === 'MA' || region === 'TN' ? 0 : 5;
100
+ }
101
+ catch {
102
+ /* an unknown tag: Monday */
103
+ }
104
+ return 0;
105
+ }
106
+ /** True when the locale writes hours as 1 to 12 with AM and PM. */
107
+ export function uses12Hours(locale) {
108
+ try {
109
+ return new Intl.DateTimeFormat(locale, { hour: 'numeric' }).resolvedOptions().hour12 === true;
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }
115
+ const noonUtc = (y, m, d) => new Date(Date.UTC(y, m - 1, d, 12));
116
+ /** The twelve month names. */
117
+ export function monthNames(locale, width = 'long') {
118
+ const f = new Intl.DateTimeFormat(locale, { month: width, timeZone: 'UTC' });
119
+ return Array.from({ length: 12 }, (_, i) => f.format(noonUtc(2024, i + 1, 15)));
120
+ }
121
+ /** The seven day names, from the first day of the week. */
122
+ export function weekdayNames(locale, firstDay, width = 'short') {
123
+ const f = new Intl.DateTimeFormat(locale, { weekday: width, timeZone: 'UTC' });
124
+ // 2024-01-01 is a Monday
125
+ return Array.from({ length: 7 }, (_, i) => f.format(noonUtc(2024, 1, 1 + ((firstDay + i) % 7))));
126
+ }
127
+ /** A number in the digits of the locale (Arabic-Indic digits in `ar-EG`). */
128
+ export const digits = (n, locale, minimum = 1) => new Intl.NumberFormat(locale, { useGrouping: false, minimumIntegerDigits: minimum }).format(n);
@@ -0,0 +1,4 @@
1
+ export * from './core.ts';
2
+ export { addDays, addMonths, dateText, isoWeek, monthGrid, parseDate, quarterOf, startOfWeek } from './calendar.ts';
3
+ export { firstDayOf, isRtl, monthNames, weekdayNames } from './i18n.ts';
4
+ export { offsetText, resolveZone, today, zoneLabel } from './zone.ts';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./core.js";
2
+ export { addDays, addMonths, dateText, isoWeek, monthGrid, parseDate, quarterOf, startOfWeek } from "./calendar.js";
3
+ export { firstDayOf, isRtl, monthNames, weekdayNames } from "./i18n.js";
4
+ export { offsetText, resolveZone, today, zoneLabel } from "./zone.js";
@@ -0,0 +1,33 @@
1
+ import { type PlainDate, type PlainTime } from './calendar.ts';
2
+ import type { Labels } from './i18n.ts';
3
+ import type { Mode, PickerOptions, PickerValue, Selection } from './types.ts';
4
+ export declare const MIDNIGHT: PlainTime;
5
+ /** What is picked. `dates` holds one day (date, week, month, quarter, year, time), two (range) or several (multiple). */
6
+ export interface Pick {
7
+ dates: PlainDate[];
8
+ /** Time of the first and of the last day, when the hour is picked. */
9
+ times: [PlainTime, PlainTime];
10
+ }
11
+ export interface Shape {
12
+ mode: Mode;
13
+ time: boolean;
14
+ seconds: boolean;
15
+ zone: string;
16
+ locale: string;
17
+ hour12: boolean | undefined;
18
+ }
19
+ export declare const emptyPick: () => Pick;
20
+ /** True when the pick is whole: a range has its two days. */
21
+ export declare const complete: (pick: Pick, mode: Mode) => boolean;
22
+ /** Reads a value for a mode. An unreadable value gives an empty pick. */
23
+ export declare function readValue(value: PickerValue | Date | undefined, shape: Shape): Pick;
24
+ /** The pick as ISO text, in the form of its mode. */
25
+ export declare function writeValue(pick: Pick, shape: Shape): PickerValue;
26
+ /** First instant of the pick and the instant just after it. */
27
+ export declare function bounds(pick: Pick, shape: Shape): [Date | null, Date | null];
28
+ /** The pick as the field writes it. */
29
+ export declare function textOf(pick: Pick, shape: Shape, labels: Labels, custom?: Intl.DateTimeFormatOptions): string;
30
+ /** The whole selection: value, instants, zone and text. */
31
+ export declare function selectionOf(pick: Pick, shape: Shape, labels: Labels, format?: PickerOptions['format']): Selection;
32
+ /** Last day of a month, for the grids. */
33
+ export declare const lastOfMonth: (y: number, m: number) => PlainDate;
package/dist/model.js ADDED
@@ -0,0 +1,217 @@
1
+ // The pick as data: reading a value, writing it back as ISO text, its two instants and its text. No DOM here.
2
+ import { addDays, addMonths, compare, dateText, daysInMonth, fromIsoWeek, isoWeek, monthText, parseDate, parseTime, quarterOf, quarterText, startOfWeek, timeText, weekText, } from "./calendar.js";
3
+ import { instant, offsetText, wallClock } from "./zone.js";
4
+ export const MIDNIGHT = { h: 0, mi: 0, s: 0 };
5
+ export const emptyPick = () => ({ dates: [], times: [MIDNIGHT, MIDNIGHT] });
6
+ /** True when the pick is whole: a range has its two days. */
7
+ export const complete = (pick, mode) => mode === 'range' ? pick.dates.length === 2 : pick.dates.length > 0;
8
+ // ── Reading a value ────────────────────────────────────────────────────────────────────────────────────────────
9
+ /** One date, with its time when the text has one. A text with an offset or `Z` is an instant, read in the zone. */
10
+ function readMoment(value, zone) {
11
+ if (value instanceof Date) {
12
+ if (Number.isNaN(value.getTime()))
13
+ return null;
14
+ const w = wallClock(value.getTime(), zone);
15
+ return { date: { y: w.y, m: w.m, d: w.d }, time: { h: w.h, mi: w.mi, s: w.s } };
16
+ }
17
+ const text = value.trim();
18
+ const date = parseDate(text);
19
+ if (!date)
20
+ return null;
21
+ const rest = text.slice(10);
22
+ if (!rest)
23
+ return { date, time: null };
24
+ if (/(Z|[+-]\d{2}:?\d{2})$/i.test(rest)) {
25
+ const epoch = Date.parse(text);
26
+ return Number.isNaN(epoch) ? null : readMoment(new Date(epoch), zone);
27
+ }
28
+ const time = parseTime(rest.replace(/^[T ]/, '').replace(/\.\d+$/, ''));
29
+ return time ? { date, time } : null;
30
+ }
31
+ /** Reads a value for a mode. An unreadable value gives an empty pick. */
32
+ export function readValue(value, shape) {
33
+ const pick = emptyPick();
34
+ if (value === null || value === undefined || value === '')
35
+ return pick;
36
+ const { mode, zone } = shape;
37
+ if (mode === 'multiple') {
38
+ const list = Array.isArray(value) ? value : [value];
39
+ for (const v of list) {
40
+ const m = typeof v === 'string' || v instanceof Date ? readMoment(v, zone) : null;
41
+ if (m && !pick.dates.some((d) => compare(d, m.date) === 0))
42
+ pick.dates.push(m.date);
43
+ }
44
+ pick.dates.sort(compare);
45
+ return pick;
46
+ }
47
+ if (mode === 'range') {
48
+ const pair = Array.isArray(value)
49
+ ? value
50
+ : typeof value === 'object' && !(value instanceof Date)
51
+ ? [value.start, value.end]
52
+ : [];
53
+ const a = pair[0] ? readMoment(pair[0], zone) : null;
54
+ const b = pair[1] ? readMoment(pair[1], zone) : null;
55
+ if (a && b) {
56
+ const [first, last] = compare(a.date, b.date) <= 0 ? [a, b] : [b, a];
57
+ pick.dates = [first.date, last.date];
58
+ pick.times = [first.time ?? MIDNIGHT, last.time ?? MIDNIGHT];
59
+ }
60
+ return pick;
61
+ }
62
+ if (value instanceof Date || typeof value !== 'string') {
63
+ const m = value instanceof Date ? readMoment(value, zone) : null;
64
+ if (m) {
65
+ pick.dates = [m.date];
66
+ pick.times = [m.time ?? MIDNIGHT, MIDNIGHT];
67
+ }
68
+ return pick;
69
+ }
70
+ const text = value.trim();
71
+ let m;
72
+ if (mode === 'time') {
73
+ const t = parseTime(text);
74
+ if (t) {
75
+ pick.dates = [{ y: 1970, m: 1, d: 1 }];
76
+ pick.times = [t, MIDNIGHT];
77
+ }
78
+ }
79
+ else if (mode === 'week' && (m = /^(\d{4})-W(\d{1,2})$/i.exec(text)))
80
+ pick.dates = [fromIsoWeek(+m[1], +m[2])];
81
+ else if (mode === 'month' && (m = /^(\d{4})-(\d{2})$/.exec(text)) && +m[2] >= 1 && +m[2] <= 12)
82
+ pick.dates = [{ y: +m[1], m: +m[2], d: 1 }];
83
+ else if (mode === 'quarter' && (m = /^(\d{4})-Q([1-4])$/i.exec(text)))
84
+ pick.dates = [{ y: +m[1], m: (+m[2] - 1) * 3 + 1, d: 1 }];
85
+ else if (mode === 'year' && (m = /^(\d{4})$/.exec(text)))
86
+ pick.dates = [{ y: +m[1], m: 1, d: 1 }];
87
+ else {
88
+ const moment = readMoment(text, zone);
89
+ if (moment) {
90
+ pick.dates = [moment.date];
91
+ pick.times = [moment.time ?? MIDNIGHT, MIDNIGHT];
92
+ }
93
+ }
94
+ return pick;
95
+ }
96
+ // ── Writing the value ──────────────────────────────────────────────────────────────────────────────────────────
97
+ function momentText(date, time, shape) {
98
+ if (!shape.time)
99
+ return dateText(date);
100
+ return `${dateText(date)}T${timeText(time, shape.seconds)}${offsetText(instant(date, time, shape.zone), shape.zone)}`;
101
+ }
102
+ /** The pick as ISO text, in the form of its mode. */
103
+ export function writeValue(pick, shape) {
104
+ const [first, last] = pick.dates;
105
+ if (shape.mode === 'multiple')
106
+ return pick.dates.map(dateText);
107
+ if (!first)
108
+ return null;
109
+ switch (shape.mode) {
110
+ case 'range':
111
+ return last
112
+ ? { start: momentText(first, pick.times[0], shape), end: momentText(last, pick.times[1], shape) }
113
+ : null;
114
+ case 'week':
115
+ return weekText(first);
116
+ case 'month':
117
+ return monthText(first);
118
+ case 'quarter':
119
+ return quarterText(first);
120
+ case 'year':
121
+ return String(first.y).padStart(4, '0');
122
+ case 'time':
123
+ return timeText(pick.times[0], shape.seconds);
124
+ default:
125
+ return momentText(first, pick.times[0], shape);
126
+ }
127
+ }
128
+ /** First instant of the pick and the instant just after it. */
129
+ export function bounds(pick, shape) {
130
+ const [first, last] = pick.dates;
131
+ const { mode, zone } = shape;
132
+ if (!first || mode === 'time' || mode === 'multiple' || (mode === 'range' && !last))
133
+ return [null, null];
134
+ const at = (d, t = MIDNIGHT) => new Date(instant(d, t, zone));
135
+ switch (mode) {
136
+ case 'range':
137
+ return shape.time ? [at(first, pick.times[0]), at(last, pick.times[1])] : [at(first), at(addDays(last, 1))];
138
+ case 'week': {
139
+ const monday = startOfWeek(first, 0);
140
+ return [at(monday), at(addDays(monday, 7))];
141
+ }
142
+ case 'month':
143
+ return [at({ ...first, d: 1 }), at(addMonths({ ...first, d: 1 }, 1))];
144
+ case 'quarter': {
145
+ const start = { y: first.y, m: (quarterOf(first.m) - 1) * 3 + 1, d: 1 };
146
+ return [at(start), at(addMonths(start, 3))];
147
+ }
148
+ case 'year':
149
+ return [at({ y: first.y, m: 1, d: 1 }), at({ y: first.y + 1, m: 1, d: 1 })];
150
+ default:
151
+ return shape.time ? [at(first, pick.times[0]), at(first, pick.times[0])] : [at(first), at(addDays(first, 1))];
152
+ }
153
+ }
154
+ // ── Text for the reader ────────────────────────────────────────────────────────────────────────────────────────
155
+ const noon = (d) => new Date(Date.UTC(d.y, d.m - 1, d.d, 12));
156
+ function momentLabel(date, time, shape, custom) {
157
+ if (!shape.time)
158
+ return new Intl.DateTimeFormat(shape.locale, { ...(custom ?? { dateStyle: 'medium' }), timeZone: 'UTC' }).format(noon(date));
159
+ const options = custom ?? {
160
+ dateStyle: 'medium',
161
+ timeStyle: shape.seconds ? 'medium' : 'short',
162
+ };
163
+ return new Intl.DateTimeFormat(shape.locale, { ...options, hour12: shape.hour12, timeZone: shape.zone }).format(instant(date, time, shape.zone));
164
+ }
165
+ /** The pick as the field writes it. */
166
+ export function textOf(pick, shape, labels, custom) {
167
+ const [first, last] = pick.dates;
168
+ if (!first)
169
+ return '';
170
+ const { locale } = shape;
171
+ switch (shape.mode) {
172
+ case 'multiple':
173
+ return pick.dates.map((d) => momentLabel(d, MIDNIGHT, { ...shape, time: false }, custom)).join(', ');
174
+ case 'range':
175
+ return last
176
+ ? `${momentLabel(first, pick.times[0], shape, custom)} – ${momentLabel(last, pick.times[1], shape, custom)}`
177
+ : '';
178
+ case 'week': {
179
+ const w = isoWeek(first);
180
+ return `${labels.week}${w.week} ${w.year}`;
181
+ }
182
+ case 'month':
183
+ return new Intl.DateTimeFormat(locale, {
184
+ ...(custom ?? { month: 'long', year: 'numeric' }),
185
+ timeZone: 'UTC',
186
+ }).format(noon(first));
187
+ case 'quarter':
188
+ return `${labels.quarter}${quarterOf(first.m)} ${first.y}`;
189
+ case 'year':
190
+ return String(first.y);
191
+ case 'time': {
192
+ const t = pick.times[0];
193
+ return new Intl.DateTimeFormat(locale, {
194
+ ...(custom ?? { timeStyle: shape.seconds ? 'medium' : 'short' }),
195
+ hour12: shape.hour12,
196
+ timeZone: 'UTC',
197
+ }).format(Date.UTC(1970, 0, 1, t.h, t.mi, t.s));
198
+ }
199
+ default:
200
+ return momentLabel(first, pick.times[0], shape, custom);
201
+ }
202
+ }
203
+ /** The whole selection: value, instants, zone and text. */
204
+ export function selectionOf(pick, shape, labels, format) {
205
+ const [start, end] = bounds(pick, shape);
206
+ const base = {
207
+ mode: shape.mode,
208
+ value: writeValue(pick, shape),
209
+ start,
210
+ end,
211
+ zone: shape.zone,
212
+ text: textOf(pick, shape, labels, typeof format === 'object' ? format : undefined),
213
+ };
214
+ return typeof format === 'function' && complete(pick, shape.mode) ? { ...base, text: format(base) } : base;
215
+ }
216
+ /** Last day of a month, for the grids. */
217
+ export const lastOfMonth = (y, m) => ({ y, m, d: daysInMonth(y, m) });
@@ -0,0 +1,19 @@
1
+ import { type CSSProperties, type ReactElement } from 'react';
2
+ import type { Picker, PickerOptions } from './types.ts';
3
+ export type { Mode, Picker, PickerOptions, PickerValue, Selection } from './types.ts';
4
+ export interface DateTimePickerProps extends Omit<PickerOptions, 'class'> {
5
+ /** Classes of the text field, or of the box of an inline calendar. */
6
+ className?: string;
7
+ /** Classes of the panel. */
8
+ panelClassName?: string;
9
+ style?: CSSProperties;
10
+ /** Name of the form value (ISO text). */
11
+ name?: string;
12
+ id?: string;
13
+ disabled?: boolean;
14
+ 'aria-label'?: string;
15
+ /** Receives the picker: `open()`, `close()`, `getSelection()`. */
16
+ pickerRef?: (picker: Picker | null) => void;
17
+ }
18
+ /** `<DateTimePicker mode="range" presets value={value} onChange={(s) => setValue(s.value)} />`. */
19
+ export declare function DateTimePicker(props: DateTimePickerProps): ReactElement;