-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathdate-time.ts
222 lines (198 loc) · 8.02 KB
/
date-time.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import {
ICU4XDataProvider,
ICU4XDateLength,
ICU4XDateTime,
ICU4XDateTimeFormatter,
ICU4XLocale,
ICU4XTimeLength,
ICU4XCalendar
} from "icu4x";
import { DataProviderManager } from './data-provider-manager';
import {
Ok,
Result,
result,
unwrap
} from "./index";
export class DateTimeDemo {
#displayFn: (formatted: string) => void;
#dataProvider: ICU4XDataProvider;
#dataProviderManager: DataProviderManager;
#localeStr: string;
#calendarStr: string;
#dateTimeStr: string;
#locale: Result<ICU4XLocale>;
#calendar: Result<ICU4XCalendar>;
#dateLength: ICU4XDateLength;
#timeLength: ICU4XTimeLength;
#formatter: Result<ICU4XDateTimeFormatter>;
#dateTime: Result<ICU4XDateTime> | null;
constructor(displayFn: (formatted: string) => void, dataProviderManager: DataProviderManager) {
this.#displayFn = displayFn;
this.#dataProvider = dataProviderManager.getDataProvider();
this.#dataProviderManager = dataProviderManager;
this.#locale = Ok(ICU4XLocale.create_from_string("en"));
this.#calendar = Ok(ICU4XCalendar.create_for_locale(this.#dataProvider, unwrap(this.#locale)));
this.#dateLength = ICU4XDateLength.Short;
this.#timeLength = ICU4XTimeLength.Short;
this.#dateTime = null;
this.#dateTimeStr = "";
this.#calendarStr = "from-locale";
this.#localeStr = "en";
this.#updateFormatter();
}
setCalendar(calendar: string): void {
this.#calendarStr = calendar;
this.#updateLocaleAndCalendar();
this.#updateFormatter();
}
async setLocale(locid: string): Promise <void> {
this.#locale = result(() => ICU4XLocale.create_from_string(locid));
if (this.#locale.ok == true) {
const locales = this.#dataProviderManager.getLoadedLocales();
const localesFinal: string[] = [];
locales.forEach((item: ICU4XLocale) => {
localesFinal.push(item.to_string)
})
const loadedLocales = new Set(localesFinal);
if (!loadedLocales.has(this.#locale.value.to_string())) {
await this.updateProvider(this.#locale.value);
}
}
this.#updateFormatter()
}
async updateProvider(newLocale: ICU4XLocale) {
this.#dataProvider = await this.#dataProviderManager.loadLocale(newLocale.to_string());
const fallbackLocale = this.#dataProviderManager.getFallbackLocale();
const fallbackLocaleResult = result(() => this.#dataProviderManager.getFallbackLocale());
this.#locale = fallbackLocaleResult
// Logs if there is a fallback and prints the fallback locale
if(newLocale.to_string() != fallbackLocale.to_string()) {
console.log(`Falling back to locale: ${fallbackLocale.to_string()}`);
}
this.#updateFormatter();
}
#updateLocaleAndCalendar(): void {
let locid = this.#localeStr;
if (this.#calendarStr != "from-locale") {
if (locid.indexOf("-u-") == -1) {
locid = `${locid}-u-ca-${this.#calendarStr}`;
} else {
// Don't bother trying to patch up the situation where a calendar
// is already specified; this is GIGO and the current locale parsing behavior
// will just default to the first one (#calendarStr)
locid = locid.replace("-u-", `-u-ca-${this.#calendarStr}-`);
}
}
this.#locale = result(() => ICU4XLocale.create_from_string(locid));
this.#calendar = result(() => ICU4XCalendar.create_for_locale(this.#dataProvider, unwrap(this.#locale) ));
this.#updateDateTime();
}
setDateLength(dateLength: string): void {
this.#dateLength = ICU4XDateLength[dateLength];
this.#updateFormatter()
}
setTimeLength(timeLength: string): void {
this.#timeLength = ICU4XTimeLength[timeLength];
this.#updateFormatter()
}
setDateTime(dateTime: string): void {
this.#dateTimeStr = dateTime;
this.#updateDateTime();
this.#render()
}
#updateDateTime(): void {
const date = new Date(this.#dateTimeStr);
this.#dateTime = result(() => ICU4XDateTime.create_from_iso_in_calendar(
date.getFullYear(),
date.getMonth() + 1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
0,
unwrap(this.#calendar)
));
}
#updateFormatter(): void {
this.#formatter = result(() => ICU4XDateTimeFormatter.create_with_lengths(
this.#dataProvider,
unwrap(this.#locale),
this.#dateLength,
this.#timeLength,
));
this.#render();
}
#render(): void {
try {
const formatter = unwrap(this.#formatter);
if (this.#dateTime !== null) {
const dateTime = unwrap(this.#dateTime);
this.#displayFn(formatter.format_datetime(dateTime));
} else {
this.#displayFn("");
}
} catch (e) {
if (e.error_value) {
this.#displayFn(`ICU4X Error: ${e.error_value}`);
} else {
this.#displayFn(`Unexpected Error: ${e}`);
}
}
}
}
export function setup(dataProvider: ICU4XDataProvider): void {
const formattedDateTime = document.getElementById('dtf-formatted') as HTMLInputElement;
const dateTimeDemo = new DateTimeDemo((formatted) => formattedDateTime.innerText = formatted, dataProvider);
const otherLocaleBtn = document.getElementById('dtf-locale-other') as HTMLInputElement | null;
otherLocaleBtn?.addEventListener('click', () => {
dateTimeDemo.setLocale(otherLocaleInput.value);
});
const otherLocaleInput = document.getElementById('dtf-locale-other-input') as HTMLInputElement | null;
otherLocaleInput?.addEventListener('input', () => {
const otherLocaleBtn = document.getElementById('dtf-locale-other') as HTMLInputElement | null;
if (otherLocaleBtn != null) {
otherLocaleBtn.checked = true;
dateTimeDemo.setLocale(otherLocaleInput.value);
}
});
for (let input of document.querySelectorAll<HTMLInputElement | null>('input[name="dtf-locale"]')) {
if (input?.value !== 'other') {
input.addEventListener('input', () => {
dateTimeDemo.setLocale(input.value)
});
}
}
for (let selector of document.querySelectorAll<HTMLSelectElement | null>('select[name="dtf-calendar"]')) {
// <select> doesn't have oninput
selector?.addEventListener('change', () => {
dateTimeDemo.setCalendar(selector.value)
});
}
for (let input of document.querySelectorAll<HTMLInputElement | null>('input[name="dtf-date-length"]')) {
input?.addEventListener('input', () => {
dateTimeDemo.setDateLength(input.value)
});
}
for (let input of document.querySelectorAll<HTMLInputElement | null>('input[name="dtf-time-length"]')) {
input?.addEventListener('input', () => {
dateTimeDemo.setTimeLength(input.value)
});
}
const inputDateTime = document.getElementById('dtf-input') as HTMLInputElement | null;
inputDateTime?.addEventListener('input', () => {
dateTimeDemo.setDateTime(inputDateTime.value)
});
// Annoyingly `toISOString()` gets us the format we need, but it converts to UTC first
// We instead get the current datetime and recast it to a date that is the current datetime
// when represented in UTC
let now = new Date();
const offset = now.getTimezoneOffset();
now.setMinutes(now.getMinutes() - offset);
const nowISO = now.toISOString().slice(0,16);
if (inputDateTime != undefined) {
// this seems like the best way to get something compatible with inputDateTIme
inputDateTime.value = nowISO;
}
dateTimeDemo.setDateTime(nowISO);
}