@widgetic/file-browser 0.5.25 → 0.5.27

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.
@@ -1,317 +0,0 @@
1
- /**
2
- * The words of the File Browser, as a function.
3
- *
4
- * A message is a template in a flat catalog: `'upload.progress': '{done} of {total} uploaded'`. A page can replace any
5
- * of them (the `messages` option); a key it leaves out keeps the English text, so a partly translated catalog never
6
- * shows a hole.
7
- *
8
- * A template is plain text with two kinds of `{...}`:
9
- *
10
- * {name} the value called `name`; a number is written the way the locale
11
- * writes numbers (1,234 or 1.234)
12
- * {count, plural, =0 {none} one {# file} other {# files}}
13
- * one branch, chosen by the locale's plural rules (`Intl.PluralRules`),
14
- * so a language with more than two forms (Polish, Arabic) can say so.
15
- * `=0` matches exactly 0; `other` is required; `#` is the number
16
- *
17
- * `\{`, `\}`, `\#` and `\\` write the character itself. An apostrophe is just an apostrophe: `Delete '{name}'?` works.
18
- *
19
- * Nothing here knows about Svelte or the DOM: the same code runs in a unit test.
20
- */
21
- /** One line a developer can read in the console about a {@link MessageProblem}. */
22
- export function describeMessageProblem(problem) {
23
- switch (problem.kind) {
24
- case 'unknown-message':
25
- return problem.suggestion
26
- ? `There is no message called "${problem.key}". Did you mean "${problem.suggestion}"? It is ignored.`
27
- : `There is no message called "${problem.key}". It is ignored.`;
28
- case 'not-text':
29
- return `The message "${problem.key}" must be a string. The English text is used.`;
30
- case 'broken-message':
31
- return `The message "${problem.key}" cannot be used (${problem.reason}). The English text is used.`;
32
- case 'unknown-value':
33
- return `The message "${problem.key}" asks for {${problem.name}}, which this message is never given. It would show as written.`;
34
- case 'unknown-locale':
35
- return `"${problem.locale}" is not a language tag (like "de" or "pt-BR"). Numbers and dates use English.`;
36
- }
37
- }
38
- class TemplateSyntaxError extends Error {
39
- }
40
- /** The names of the values a template uses, for checking a replacement against the English one. */
41
- function valueNamesOf(parts, names = new Set()) {
42
- for (const part of parts) {
43
- if (part.kind === 'value')
44
- names.add(part.name);
45
- if (part.kind === 'plural') {
46
- names.add(part.name);
47
- for (const branch of part.branches.values())
48
- valueNamesOf(branch, names);
49
- }
50
- }
51
- return names;
52
- }
53
- const NAME_START = /[A-Za-z_]/;
54
- const NAME_CHARACTER = /[A-Za-z0-9_]/;
55
- /** Reads a template. Throws a {@link TemplateSyntaxError} that says what is wrong, for the console. */
56
- function parseTemplate(source) {
57
- let position = 0;
58
- function skipSpaces() {
59
- while (position < source.length && /\s/.test(source[position]))
60
- position += 1;
61
- }
62
- function readName() {
63
- skipSpaces();
64
- const begin = position;
65
- if (position >= source.length || !NAME_START.test(source[position])) {
66
- throw new TemplateSyntaxError(`a value name was expected at character ${position + 1}`);
67
- }
68
- while (position < source.length && NAME_CHARACTER.test(source[position]))
69
- position += 1;
70
- const name = source.slice(begin, position);
71
- skipSpaces();
72
- return name;
73
- }
74
- /** Reads parts until the end of the text, or (inside a branch) until the `}` that ends it, which it does not consume. */
75
- function readParts(insideBranch) {
76
- const parts = [];
77
- let text = '';
78
- const flushText = () => {
79
- if (text !== '')
80
- parts.push({ kind: 'text', text });
81
- text = '';
82
- };
83
- while (position < source.length) {
84
- const character = source[position];
85
- if (character === '\\') {
86
- const escaped = source[position + 1];
87
- if (escaped === undefined)
88
- throw new TemplateSyntaxError('a backslash at the end');
89
- text += escaped;
90
- position += 2;
91
- }
92
- else if (character === '{') {
93
- flushText();
94
- position += 1;
95
- parts.push(readArgument());
96
- }
97
- else if (character === '}') {
98
- if (insideBranch)
99
- break;
100
- throw new TemplateSyntaxError(`a } at character ${position + 1} closes nothing (write \\} for the character)`);
101
- }
102
- else if (character === '#' && insideBranch) {
103
- flushText();
104
- parts.push({ kind: 'number' });
105
- position += 1;
106
- }
107
- else {
108
- text += character;
109
- position += 1;
110
- }
111
- }
112
- flushText();
113
- return parts;
114
- }
115
- /** After the `{`: `name}` or `name, plural, selector {…} … }`. */
116
- function readArgument() {
117
- const name = readName();
118
- if (source[position] === '}') {
119
- position += 1;
120
- return { kind: 'value', name };
121
- }
122
- if (source[position] !== ',') {
123
- throw new TemplateSyntaxError(`a } or a comma was expected after {${name} at character ${position + 1}`);
124
- }
125
- position += 1;
126
- skipSpaces();
127
- const typeBegin = position;
128
- while (position < source.length && /[a-z]/.test(source[position]))
129
- position += 1;
130
- const type = source.slice(typeBegin, position);
131
- if (type !== 'plural') {
132
- throw new TemplateSyntaxError(`{${name}, ${type || '…'}} is not supported: only plural is`);
133
- }
134
- skipSpaces();
135
- if (source[position] !== ',')
136
- throw new TemplateSyntaxError(`a comma was expected after {${name}, plural`);
137
- position += 1;
138
- const branches = new Map();
139
- for (;;) {
140
- skipSpaces();
141
- if (position >= source.length)
142
- throw new TemplateSyntaxError(`{${name}, plural, … is never closed`);
143
- if (source[position] === '}') {
144
- position += 1;
145
- break;
146
- }
147
- const selectorBegin = position;
148
- while (position < source.length && !/[\s{}]/.test(source[position]))
149
- position += 1;
150
- const selector = source.slice(selectorBegin, position);
151
- if (selector === '' || !/^(=\d+|zero|one|two|few|many|other)$/.test(selector)) {
152
- throw new TemplateSyntaxError(`"${selector}" is not a plural form (use =0, zero, one, two, few, many or other)`);
153
- }
154
- skipSpaces();
155
- if (source[position] !== '{')
156
- throw new TemplateSyntaxError(`a { was expected after "${selector}"`);
157
- position += 1;
158
- if (branches.has(selector))
159
- throw new TemplateSyntaxError(`"${selector}" is given twice`);
160
- const branch = readParts(true);
161
- if (source[position] !== '}')
162
- throw new TemplateSyntaxError(`the text of "${selector}" is never closed with }`);
163
- position += 1;
164
- branches.set(selector, branch);
165
- }
166
- if (!branches.has('other'))
167
- throw new TemplateSyntaxError(`{${name}, plural, …} needs an "other" form`);
168
- return { kind: 'plural', name, branches };
169
- }
170
- return readParts(false);
171
- }
172
- /** The catalog key nearest to `key` by spelling, when it is near enough to be a typo. */
173
- function nearestKey(key, keys) {
174
- let best;
175
- // A key that is up to three edits away is taken for a typo.
176
- let bestDistance = 4;
177
- for (const candidate of keys) {
178
- if (Math.abs(candidate.length - key.length) >= bestDistance)
179
- continue;
180
- let previous = Array.from({ length: candidate.length + 1 }, (_, index) => index);
181
- for (let row = 1; row <= key.length; row += 1) {
182
- const current = [row];
183
- for (let column = 1; column <= candidate.length; column += 1) {
184
- current[column] = Math.min(previous[column] + 1, current[column - 1] + 1, previous[column - 1] + (key[row - 1] === candidate[column - 1] ? 0 : 1));
185
- }
186
- previous = current;
187
- }
188
- const distance = previous[candidate.length];
189
- if (distance < bestDistance) {
190
- best = candidate;
191
- bestDistance = distance;
192
- }
193
- }
194
- return best;
195
- }
196
- /**
197
- * Makes the function that turns keys into text. It never throws for what the page supplied: an unusable message is
198
- * reported through `onProblem` (once) and the English one is used in its place.
199
- */
200
- export function createTranslator(options) {
201
- const { catalog, onProblem } = options;
202
- const reported = new Set();
203
- const report = (problem) => {
204
- const signature = JSON.stringify(problem);
205
- if (reported.has(signature))
206
- return;
207
- reported.add(signature);
208
- onProblem?.(problem);
209
- };
210
- // The locale: a tag this browser has number and plural rules for, or English. A tag that Intl accepts but has no data
211
- // for would silently use the visitor's own language, which would mix two languages on one screen.
212
- let locale = 'en';
213
- if (options.locale !== undefined && options.locale !== null && options.locale !== '') {
214
- try {
215
- const canonical = Intl.getCanonicalLocales(options.locale)[0];
216
- if (canonical !== undefined &&
217
- Intl.NumberFormat.supportedLocalesOf([canonical]).length > 0 &&
218
- Intl.PluralRules.supportedLocalesOf([canonical]).length > 0) {
219
- locale = canonical;
220
- }
221
- else {
222
- report({ kind: 'unknown-locale', locale: String(options.locale) });
223
- }
224
- }
225
- catch {
226
- report({ kind: 'unknown-locale', locale: String(options.locale) });
227
- }
228
- }
229
- const numberFormat = new Intl.NumberFormat(locale);
230
- const pluralRules = new Intl.PluralRules(locale);
231
- const catalogKeys = Object.keys(catalog);
232
- const englishParts = new Map();
233
- const englishPartsOf = (key) => {
234
- let parts = englishParts.get(key);
235
- if (parts === undefined && Object.prototype.hasOwnProperty.call(catalog, key)) {
236
- // The built-in messages are ours; a syntax error in one is a bug the tests catch, so it is allowed to throw.
237
- parts = parseTemplate(catalog[key]);
238
- englishParts.set(key, parts);
239
- }
240
- return parts;
241
- };
242
- // The page's messages, checked once, here: a typo in a key, a value that is not text, a template that does not parse,
243
- // or one that asks for a value the English message is never given.
244
- const replacements = new Map();
245
- const supplied = options.messages;
246
- if (supplied !== undefined && supplied !== null && typeof supplied === 'object') {
247
- for (const key of Object.keys(supplied)) {
248
- if (!Object.prototype.hasOwnProperty.call(catalog, key)) {
249
- report({ kind: 'unknown-message', key, suggestion: nearestKey(key, catalogKeys) });
250
- continue;
251
- }
252
- const text = supplied[key];
253
- if (typeof text !== 'string') {
254
- report({ kind: 'not-text', key });
255
- continue;
256
- }
257
- try {
258
- const parts = parseTemplate(text);
259
- const allowedNames = valueNamesOf(englishPartsOf(key) ?? []);
260
- for (const name of valueNamesOf(parts)) {
261
- if (!allowedNames.has(name))
262
- report({ kind: 'unknown-value', key, name });
263
- }
264
- replacements.set(key, parts);
265
- }
266
- catch (error) {
267
- if (!(error instanceof TemplateSyntaxError))
268
- throw error;
269
- report({ kind: 'broken-message', key, reason: error.message });
270
- }
271
- }
272
- }
273
- function write(parts, values, pluralNumber) {
274
- let output = '';
275
- for (const part of parts) {
276
- if (part.kind === 'text') {
277
- output += part.text;
278
- }
279
- else if (part.kind === 'number') {
280
- output += pluralNumber === null ? '#' : numberFormat.format(pluralNumber);
281
- }
282
- else if (part.kind === 'value') {
283
- const value = values[part.name];
284
- output += value === undefined ? `{${part.name}}` : typeof value === 'number' ? numberFormat.format(value) : String(value);
285
- }
286
- else {
287
- const raw = values[part.name];
288
- const count = typeof raw === 'number' ? raw : Number(raw);
289
- const form = Number.isFinite(count) ? (part.branches.get(`=${count}`) ?? part.branches.get(pluralRules.select(count))) : undefined;
290
- output += write(form ?? part.branches.get('other'), values, Number.isFinite(count) ? count : null);
291
- }
292
- }
293
- return output;
294
- }
295
- const t = (key, values = {}) => {
296
- const parts = replacements.get(key) ?? englishPartsOf(key);
297
- if (parts === undefined) {
298
- report({ kind: 'unknown-message', key, suggestion: nearestKey(key, catalogKeys) });
299
- return key;
300
- }
301
- return write(parts, values, null);
302
- };
303
- return { t, locale };
304
- }
305
- /**
306
- * The names of the values a message asks for: each `{name}` in it, and the number a plural looks at, sorted. For a test
307
- * or a tool that checks the code gives a message everything it needs. Throws when the template does not parse.
308
- */
309
- export function valueNamesOfTemplate(template) {
310
- return [...valueNamesOf(parseTemplate(template))].sort();
311
- }
312
- /** Checks `messages` against a catalog without making a translator: what a test, or a build step, can call. */
313
- export function findMessageProblems(catalog, messages) {
314
- const problems = [];
315
- createTranslator({ catalog, messages, onProblem: (problem) => problems.push(problem) });
316
- return problems;
317
- }