@gramlot/gramlot 0.2.19 → 0.2.20
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.
- package/dist/gramlot.js +960 -79
- package/dist/gramlot.min.js +21 -18
- package/package.json +1 -1
- package/src/binding/inline.js +8 -2
- package/src/binding/installation.js +3 -1
- package/src/binding/pointer.js +199 -0
- package/src/binding/providers.js +7 -4
- package/src/binding/runtime.js +10 -5
- package/src/builder/gramlot-builder.js +4 -0
- package/src/builder/source.js +25 -2
- package/src/date-parser/civil.js +61 -0
- package/src/date-parser/index.d.ts +18 -0
- package/src/date-parser/index.js +196 -0
- package/src/date-parser/locales.js +257 -0
- package/src/format.js +121 -0
- package/src/gramlot.d.ts +21 -0
- package/src/gramlot.js +8 -1
- package/src/index.d.ts +4 -1
- package/src/index.js +2 -0
- package/src/renderer/attributes.js +22 -10
- package/src/renderer/gramlot-renderer.js +4 -2
- package/src/server/gramlot-server.d.ts +2 -0
- package/src/server/gramlot-server.js +6 -3
- package/src/server/page-base.js +2 -0
- package/src/server/page.d.ts +2 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/* @ts-self-types="./index.d.ts" */
|
|
2
|
+
// Copyright 2026 Softwell S.r.l. - SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
// Semantics ported from genro-toolbox dates/period_parser.py; see PORT-0009.
|
|
4
|
+
import {addDays, civil, monday, monthPeriod, parts, daysInMonth} from './civil.js';
|
|
5
|
+
import {localeContext} from './locales.js';
|
|
6
|
+
|
|
7
|
+
const yearPattern = /^(?:\d{4}|\d{2})$/;
|
|
8
|
+
const dayPattern = /^\d{1,2}$/;
|
|
9
|
+
const fail = (code, message) => ({ok: false, error: {code, message}});
|
|
10
|
+
const unrecognized = (code = 'UNRECOGNIZED_EXPRESSION', message = 'Text is not a supported date expression.') => {
|
|
11
|
+
throw Object.assign(new SyntaxError(message), {code});
|
|
12
|
+
};
|
|
13
|
+
const own = (object, key) => Object.hasOwn(object, key);
|
|
14
|
+
|
|
15
|
+
function decodeYear(text, context) {
|
|
16
|
+
if (text.length === 4) return Number(text);
|
|
17
|
+
const lowest = context.year + context.twoDigitYearAhead - 100;
|
|
18
|
+
return lowest + ((Number(text) - lowest) % 100 + 100) % 100;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function boundTexts(text, context) {
|
|
22
|
+
if (text.includes(';')) {
|
|
23
|
+
const bounds = text.split(';').map(part => part.trim());
|
|
24
|
+
if (bounds.length !== 2) return unrecognized('INVALID_RANGE', 'A range must have exactly two endpoints.');
|
|
25
|
+
return {bounds, range: true};
|
|
26
|
+
}
|
|
27
|
+
if (context.phrases('no_period').includes(text)) return {bounds: ['', ''], range: true};
|
|
28
|
+
const to = context.phrases('to'), from = context.phrases('from');
|
|
29
|
+
for (const word of to) {
|
|
30
|
+
if (text.startsWith(`${word} `)) return {bounds: ['', text.slice(word.length + 1).trim()], range: true};
|
|
31
|
+
}
|
|
32
|
+
for (const word of to) {
|
|
33
|
+
const separator = ` ${word} `;
|
|
34
|
+
if (!text.includes(separator)) continue;
|
|
35
|
+
for (const prefix of from) {
|
|
36
|
+
if (text.startsWith(`${prefix} `)) {
|
|
37
|
+
text = text.slice(prefix.length + 1);
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const bounds = text.split(separator).map(part => part.trim());
|
|
42
|
+
if (bounds.length !== 2) return unrecognized('INVALID_RANGE', 'A range must have exactly two endpoints.');
|
|
43
|
+
return {bounds, range: true};
|
|
44
|
+
}
|
|
45
|
+
for (const word of from) {
|
|
46
|
+
if (text.startsWith(`${word} `)) return {bounds: [text.slice(word.length + 1).trim(), ''], range: true};
|
|
47
|
+
}
|
|
48
|
+
return {bounds: [text, text], range: false};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function keywordDate(text, context, isEnd) {
|
|
52
|
+
const candidates = [[text, 0]];
|
|
53
|
+
const offset = /^(.+?)\s*([+-])\s*(\d+)$/.exec(text);
|
|
54
|
+
if (offset) candidates.push([offset[1], Number(offset[2] + offset[3])]);
|
|
55
|
+
const shifts = {today: 0, yesterday: -1, tomorrow: 1,
|
|
56
|
+
this_week: 0, last_week: -1, next_week: 1,
|
|
57
|
+
this_month: 0, last_month: -1, next_month: 1};
|
|
58
|
+
for (const [body, amount] of candidates) {
|
|
59
|
+
for (const [key, shift] of Object.entries(shifts)) {
|
|
60
|
+
if (!context.phrases(key).includes(body)) continue;
|
|
61
|
+
if (key.endsWith('_week')) return addDays(monday(context.workdate), (shift + amount) * 7 + (isEnd ? 6 : 0));
|
|
62
|
+
if (key.endsWith('_month')) {
|
|
63
|
+
const span = monthPeriod(context.year, context.month, shift + amount);
|
|
64
|
+
return isEnd ? span.end : span.start;
|
|
65
|
+
}
|
|
66
|
+
return addDays(context.workdate, shift + amount);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function quarter(text, context, isEnd) {
|
|
73
|
+
const entries = Object.entries(context.dictionary.quarters).sort((a, b) => b[0].length - a[0].length);
|
|
74
|
+
for (const [name, number] of entries) {
|
|
75
|
+
let year;
|
|
76
|
+
if (text === name) year = null;
|
|
77
|
+
else if (text.startsWith(name) && yearPattern.test(text.slice(name.length).trim())) {
|
|
78
|
+
year = decodeYear(text.slice(name.length).trim(), context);
|
|
79
|
+
} else if (text.endsWith(name) && yearPattern.test(text.slice(0, -name.length).trim())) {
|
|
80
|
+
year = decodeYear(text.slice(0, -name.length).trim(), context);
|
|
81
|
+
} else continue;
|
|
82
|
+
return {year, month: isEnd ? number * 3 : number * 3 - 2};
|
|
83
|
+
}
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function monthNumber(token, dictionary) {
|
|
88
|
+
if (own(dictionary.months, token)) return dictionary.months[token];
|
|
89
|
+
const match = /^m(\d{1,2})$/.exec(token);
|
|
90
|
+
return match && Number(match[1]) >= 1 && Number(match[1]) <= 12 ? Number(match[1]) : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function namedMonth(text, context) {
|
|
94
|
+
const tokens = text.split(/\s+/);
|
|
95
|
+
const positions = tokens.map((token, i) => monthNumber(token, context.dictionary) ? i : -1).filter(i => i >= 0);
|
|
96
|
+
if (!positions.length) return null;
|
|
97
|
+
if (positions.length !== 1) return unrecognized();
|
|
98
|
+
const position = positions[0], month = monthNumber(tokens[position], context.dictionary);
|
|
99
|
+
const before = tokens.slice(0, position), after = tokens.slice(position + 1), others = [...before, ...after];
|
|
100
|
+
if (others.length === 1 && context.phrases('last').includes(others[0])) {
|
|
101
|
+
return {year: context.year - (month > context.month ? 1 : 0), month};
|
|
102
|
+
}
|
|
103
|
+
if (others.length === 1 && context.phrases('next').includes(others[0])) {
|
|
104
|
+
return {year: context.year + (month < context.month ? 1 : 0), month};
|
|
105
|
+
}
|
|
106
|
+
if (!others.length) return {year: null, month};
|
|
107
|
+
if (!before.length && after.length === 1 && yearPattern.test(after[0])) return {year: decodeYear(after[0], context), month};
|
|
108
|
+
if (before.length === 1 && dayPattern.test(before[0])) {
|
|
109
|
+
if (!after.length) return civil(context.year, month, Number(before[0]));
|
|
110
|
+
if (after.length === 1 && yearPattern.test(after[0])) return civil(decodeYear(after[0], context), month, Number(before[0]));
|
|
111
|
+
}
|
|
112
|
+
if (!before.length && after.length === 2 && dayPattern.test(after[0]) && yearPattern.test(after[1])) {
|
|
113
|
+
return civil(decodeYear(after[1], context), month, Number(after[0]));
|
|
114
|
+
}
|
|
115
|
+
return unrecognized();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function numericDate(text, context) {
|
|
119
|
+
const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
|
|
120
|
+
if (iso) return civil(...iso.slice(1).map(Number));
|
|
121
|
+
const numeric = /^(\d{1,4})[/\-. ]+(\d{1,4})[/\-. ]+(\d{1,4})$/.exec(text);
|
|
122
|
+
const values = {};
|
|
123
|
+
if (numeric) context.order.split('').forEach((letter, i) => { values[letter] = numeric[i + 1]; });
|
|
124
|
+
else if (/^(?:\d{6}|\d{8})$/.test(text)) {
|
|
125
|
+
const yearWidth = text.length === 8 ? 4 : 2;
|
|
126
|
+
for (const letter of context.order) {
|
|
127
|
+
const width = letter === 'Y' ? yearWidth : 2;
|
|
128
|
+
values[letter] = text.slice(0, width);
|
|
129
|
+
text = text.slice(width);
|
|
130
|
+
}
|
|
131
|
+
} else return null;
|
|
132
|
+
if (!yearPattern.test(values.Y) || values.D.length > 2 || values.M.length > 2) return unrecognized();
|
|
133
|
+
let day = Number(values.D), month = Number(values.M);
|
|
134
|
+
if (numeric && month > 12 && day <= 12) [day, month] = [month, day];
|
|
135
|
+
return civil(decodeYear(values.Y, context), month, day);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function getBound(text, context, isEnd) {
|
|
139
|
+
if (!text) return null;
|
|
140
|
+
const articles = context.phrases('articles');
|
|
141
|
+
text = text.split(/\s+/).filter(token => !articles.includes(token)).join(' ');
|
|
142
|
+
if (!text) return unrecognized();
|
|
143
|
+
if (yearPattern.test(text)) return civil(decodeYear(text, context), isEnd ? 12 : 1, isEnd ? 31 : 1);
|
|
144
|
+
const value = keywordDate(text, context, isEnd) ?? quarter(text, context, isEnd) ?? namedMonth(text, context);
|
|
145
|
+
if (value !== null) return value;
|
|
146
|
+
if (own(context.dictionary.weekdays, text)) return addDays(monday(context.workdate), context.dictionary.weekdays[text]);
|
|
147
|
+
return numericDate(text, context) ?? unrecognized();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function startDate(start, end, context) {
|
|
151
|
+
if (start === null || typeof start === 'string') return start;
|
|
152
|
+
let year = start.year ?? context.year;
|
|
153
|
+
const endYear = typeof end === 'string' ? parts(end)[0] : end?.year;
|
|
154
|
+
const endMonth = typeof end === 'string' ? parts(end)[1] : end?.month;
|
|
155
|
+
if (endYear) {
|
|
156
|
+
if (year > endYear) year = endYear;
|
|
157
|
+
if (year === endYear && start.month > endMonth) year--;
|
|
158
|
+
}
|
|
159
|
+
return civil(year, start.month, 1);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function endDate(end, start, context) {
|
|
163
|
+
if (end === null || typeof end === 'string') return end;
|
|
164
|
+
let year = end.year ?? context.year;
|
|
165
|
+
if (start !== null) {
|
|
166
|
+
const [startYear, startMonth] = parts(start);
|
|
167
|
+
if (year < startYear) year = startYear;
|
|
168
|
+
if (year === startYear && startMonth > end.month) year++;
|
|
169
|
+
}
|
|
170
|
+
return civil(year, end.month, daysInMonth(year, end.month));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Parse a complete date expression using Toolbox semantics and structured JS outcomes. */
|
|
174
|
+
export function parseDateExpression(text, options = {}) {
|
|
175
|
+
if (!options || typeof options !== 'object' || Array.isArray(options)) return fail('INVALID_CONTEXT', 'Options must provide a civil workdate and supported locale.');
|
|
176
|
+
let context;
|
|
177
|
+
try {
|
|
178
|
+
const {locale = 'it-IT', workdate, twoDigitYearAhead = 20} = options;
|
|
179
|
+
const [year, month] = parts(workdate);
|
|
180
|
+
if (!Number.isInteger(twoDigitYearAhead) || twoDigitYearAhead < 0 || twoDigitYearAhead > 99) throw new RangeError('twoDigitYearAhead must be an integer from 0 to 99.');
|
|
181
|
+
context = {...localeContext(locale), workdate, year, month, twoDigitYearAhead};
|
|
182
|
+
} catch (error) { return fail('INVALID_CONTEXT', error.message); }
|
|
183
|
+
if (typeof text !== 'string') return fail('INVALID_INPUT', 'Expression must be a string.');
|
|
184
|
+
try {
|
|
185
|
+
const expression = text.toLowerCase().trim().replaceAll(',', '');
|
|
186
|
+
const {bounds, range} = boundTexts(expression, context);
|
|
187
|
+
const right = getBound(bounds[1], context, true), left = getBound(bounds[0], context, false);
|
|
188
|
+
const start = startDate(left, right, context), end = endDate(right, start, context);
|
|
189
|
+
if (!range && typeof left === 'string' && start === end) return {ok: true, kind: 'date', date: start};
|
|
190
|
+
return {ok: true, kind: 'period', start, end};
|
|
191
|
+
} catch (error) {
|
|
192
|
+
if (error instanceof RangeError) return fail('INVALID_DATE', error.message);
|
|
193
|
+
if (error instanceof SyntaxError) return fail(error.code, error.message);
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// Copyright 2026 Softwell S.r.l. - SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Vocabulary from genro-toolbox dfb7322a53a2f9030d6baaadfbb87028559672fd.
|
|
3
|
+
// Keep the upstream JSON contents unchanged; see PORT-0009 for refresh/fixture provenance.
|
|
4
|
+
const locales = {
|
|
5
|
+
"it": {
|
|
6
|
+
"months": {
|
|
7
|
+
"gennaio": 1,
|
|
8
|
+
"febbraio": 2,
|
|
9
|
+
"marzo": 3,
|
|
10
|
+
"aprile": 4,
|
|
11
|
+
"maggio": 5,
|
|
12
|
+
"giugno": 6,
|
|
13
|
+
"luglio": 7,
|
|
14
|
+
"agosto": 8,
|
|
15
|
+
"settembre": 9,
|
|
16
|
+
"ottobre": 10,
|
|
17
|
+
"novembre": 11,
|
|
18
|
+
"dicembre": 12,
|
|
19
|
+
"gen": 1,
|
|
20
|
+
"feb": 2,
|
|
21
|
+
"mar": 3,
|
|
22
|
+
"apr": 4,
|
|
23
|
+
"mag": 5,
|
|
24
|
+
"giu": 6,
|
|
25
|
+
"lug": 7,
|
|
26
|
+
"ago": 8,
|
|
27
|
+
"set": 9,
|
|
28
|
+
"ott": 10,
|
|
29
|
+
"nov": 11,
|
|
30
|
+
"dic": 12
|
|
31
|
+
},
|
|
32
|
+
"weekdays": {
|
|
33
|
+
"lunedì": 0,
|
|
34
|
+
"martedì": 1,
|
|
35
|
+
"mercoledì": 2,
|
|
36
|
+
"giovedì": 3,
|
|
37
|
+
"venerdì": 4,
|
|
38
|
+
"sabato": 5,
|
|
39
|
+
"domenica": 6,
|
|
40
|
+
"lun": 0,
|
|
41
|
+
"mar": 1,
|
|
42
|
+
"mer": 2,
|
|
43
|
+
"gio": 3,
|
|
44
|
+
"ven": 4,
|
|
45
|
+
"sab": 5,
|
|
46
|
+
"dom": 6
|
|
47
|
+
},
|
|
48
|
+
"quarters": {
|
|
49
|
+
"1º trimestre": 1,
|
|
50
|
+
"2º trimestre": 2,
|
|
51
|
+
"3º trimestre": 3,
|
|
52
|
+
"4º trimestre": 4,
|
|
53
|
+
"1° trimestre": 1,
|
|
54
|
+
"2° trimestre": 2,
|
|
55
|
+
"3° trimestre": 3,
|
|
56
|
+
"4° trimestre": 4,
|
|
57
|
+
"t1": 1,
|
|
58
|
+
"t2": 2,
|
|
59
|
+
"t3": 3,
|
|
60
|
+
"t4": 4,
|
|
61
|
+
"q1": 1,
|
|
62
|
+
"q2": 2,
|
|
63
|
+
"q3": 3,
|
|
64
|
+
"q4": 4
|
|
65
|
+
},
|
|
66
|
+
"keywords": {
|
|
67
|
+
"today": [
|
|
68
|
+
"oggi"
|
|
69
|
+
],
|
|
70
|
+
"yesterday": [
|
|
71
|
+
"ieri"
|
|
72
|
+
],
|
|
73
|
+
"tomorrow": [
|
|
74
|
+
"domani"
|
|
75
|
+
],
|
|
76
|
+
"this_week": [
|
|
77
|
+
"questa settimana",
|
|
78
|
+
"settimana"
|
|
79
|
+
],
|
|
80
|
+
"last_week": [
|
|
81
|
+
"settimana scorsa"
|
|
82
|
+
],
|
|
83
|
+
"next_week": [
|
|
84
|
+
"settimana prossima"
|
|
85
|
+
],
|
|
86
|
+
"this_month": [
|
|
87
|
+
"questo mese",
|
|
88
|
+
"mese"
|
|
89
|
+
],
|
|
90
|
+
"last_month": [
|
|
91
|
+
"mese scorso"
|
|
92
|
+
],
|
|
93
|
+
"next_month": [
|
|
94
|
+
"mese prossimo"
|
|
95
|
+
],
|
|
96
|
+
"last": [
|
|
97
|
+
"scorso",
|
|
98
|
+
"scorsa"
|
|
99
|
+
],
|
|
100
|
+
"next": [
|
|
101
|
+
"prossimo",
|
|
102
|
+
"prossima"
|
|
103
|
+
],
|
|
104
|
+
"articles": [
|
|
105
|
+
"il",
|
|
106
|
+
"lo",
|
|
107
|
+
"la"
|
|
108
|
+
],
|
|
109
|
+
"from": [
|
|
110
|
+
"da",
|
|
111
|
+
"dal",
|
|
112
|
+
"dalla",
|
|
113
|
+
"tra",
|
|
114
|
+
"fra"
|
|
115
|
+
],
|
|
116
|
+
"to": [
|
|
117
|
+
"a",
|
|
118
|
+
"al",
|
|
119
|
+
"alla",
|
|
120
|
+
"e"
|
|
121
|
+
],
|
|
122
|
+
"no_period": [
|
|
123
|
+
"-",
|
|
124
|
+
"senza periodo",
|
|
125
|
+
"sempre"
|
|
126
|
+
]
|
|
127
|
+
},
|
|
128
|
+
"date_order": {
|
|
129
|
+
"default": "DMY"
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
"en": {
|
|
133
|
+
"months": {
|
|
134
|
+
"january": 1,
|
|
135
|
+
"february": 2,
|
|
136
|
+
"march": 3,
|
|
137
|
+
"april": 4,
|
|
138
|
+
"may": 5,
|
|
139
|
+
"june": 6,
|
|
140
|
+
"july": 7,
|
|
141
|
+
"august": 8,
|
|
142
|
+
"september": 9,
|
|
143
|
+
"october": 10,
|
|
144
|
+
"november": 11,
|
|
145
|
+
"december": 12,
|
|
146
|
+
"jan": 1,
|
|
147
|
+
"feb": 2,
|
|
148
|
+
"mar": 3,
|
|
149
|
+
"apr": 4,
|
|
150
|
+
"jun": 6,
|
|
151
|
+
"jul": 7,
|
|
152
|
+
"aug": 8,
|
|
153
|
+
"sep": 9,
|
|
154
|
+
"oct": 10,
|
|
155
|
+
"nov": 11,
|
|
156
|
+
"dec": 12
|
|
157
|
+
},
|
|
158
|
+
"weekdays": {
|
|
159
|
+
"monday": 0,
|
|
160
|
+
"tuesday": 1,
|
|
161
|
+
"wednesday": 2,
|
|
162
|
+
"thursday": 3,
|
|
163
|
+
"friday": 4,
|
|
164
|
+
"saturday": 5,
|
|
165
|
+
"sunday": 6,
|
|
166
|
+
"mon": 0,
|
|
167
|
+
"tue": 1,
|
|
168
|
+
"wed": 2,
|
|
169
|
+
"thu": 3,
|
|
170
|
+
"fri": 4,
|
|
171
|
+
"sat": 5,
|
|
172
|
+
"sun": 6
|
|
173
|
+
},
|
|
174
|
+
"quarters": {
|
|
175
|
+
"1st quarter": 1,
|
|
176
|
+
"2nd quarter": 2,
|
|
177
|
+
"3rd quarter": 3,
|
|
178
|
+
"4th quarter": 4,
|
|
179
|
+
"q1": 1,
|
|
180
|
+
"q2": 2,
|
|
181
|
+
"q3": 3,
|
|
182
|
+
"q4": 4
|
|
183
|
+
},
|
|
184
|
+
"keywords": {
|
|
185
|
+
"today": [
|
|
186
|
+
"today"
|
|
187
|
+
],
|
|
188
|
+
"yesterday": [
|
|
189
|
+
"yesterday"
|
|
190
|
+
],
|
|
191
|
+
"tomorrow": [
|
|
192
|
+
"tomorrow"
|
|
193
|
+
],
|
|
194
|
+
"this_week": [
|
|
195
|
+
"this week",
|
|
196
|
+
"week"
|
|
197
|
+
],
|
|
198
|
+
"last_week": [
|
|
199
|
+
"last week"
|
|
200
|
+
],
|
|
201
|
+
"next_week": [
|
|
202
|
+
"next week"
|
|
203
|
+
],
|
|
204
|
+
"this_month": [
|
|
205
|
+
"this month",
|
|
206
|
+
"month"
|
|
207
|
+
],
|
|
208
|
+
"last_month": [
|
|
209
|
+
"last month"
|
|
210
|
+
],
|
|
211
|
+
"next_month": [
|
|
212
|
+
"next month"
|
|
213
|
+
],
|
|
214
|
+
"last": [
|
|
215
|
+
"last"
|
|
216
|
+
],
|
|
217
|
+
"next": [
|
|
218
|
+
"next"
|
|
219
|
+
],
|
|
220
|
+
"articles": [
|
|
221
|
+
"the"
|
|
222
|
+
],
|
|
223
|
+
"from": [
|
|
224
|
+
"from",
|
|
225
|
+
"between"
|
|
226
|
+
],
|
|
227
|
+
"to": [
|
|
228
|
+
"to",
|
|
229
|
+
"and"
|
|
230
|
+
],
|
|
231
|
+
"no_period": [
|
|
232
|
+
"no period",
|
|
233
|
+
"always"
|
|
234
|
+
]
|
|
235
|
+
},
|
|
236
|
+
"date_order": {
|
|
237
|
+
"default": "MDY",
|
|
238
|
+
"GB": "DMY",
|
|
239
|
+
"AU": "DMY",
|
|
240
|
+
"IE": "DMY",
|
|
241
|
+
"NZ": "DMY",
|
|
242
|
+
"IN": "DMY"
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
export function localeContext(locale) {
|
|
248
|
+
if (typeof locale !== 'string') throw new RangeError('A supported locale is required.');
|
|
249
|
+
const tag = locale.replaceAll('-', '_');
|
|
250
|
+
const split = tag.indexOf('_');
|
|
251
|
+
const language = (split < 0 ? tag : tag.slice(0, split)).toLowerCase();
|
|
252
|
+
const region = (split < 0 ? '' : tag.slice(split + 1)).toUpperCase();
|
|
253
|
+
if (!Object.hasOwn(locales, language)) throw new RangeError(`Unsupported locale: ${locale}`);
|
|
254
|
+
const dictionary = locales[language];
|
|
255
|
+
const phrases = key => [...new Set([...dictionary.keywords[key], ...locales.en.keywords[key]])];
|
|
256
|
+
return {dictionary, phrases, order: dictionary.date_order[region] ?? dictionary.date_order.default};
|
|
257
|
+
}
|
package/src/format.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/** Bounded numeric patterns and temporal styles for Gramlot's formatting contract. */
|
|
2
|
+
|
|
3
|
+
export function validateMask(mask) {
|
|
4
|
+
if (mask != null && (typeof mask !== 'string' || /[{}]/.test(mask.replaceAll('{}', '')))) {
|
|
5
|
+
throw new RangeError('This formatter mask supports only {} placeholders');
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Shared composition for formatted values and plain display text. */
|
|
10
|
+
export function applyMask(text, mask) {
|
|
11
|
+
validateMask(mask);
|
|
12
|
+
return mask == null ? text : mask.replaceAll('{}', () => text);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function inferredType(value) {
|
|
16
|
+
if (value instanceof Date) {
|
|
17
|
+
// Match TYTX's documented inference; dtype can override this ambiguity.
|
|
18
|
+
const epochDay = value.getUTCFullYear() === 1970 && value.getUTCMonth() === 0 && value.getUTCDate() === 1;
|
|
19
|
+
const midnight = value.getUTCHours() === 0 && value.getUTCMinutes() === 0 &&
|
|
20
|
+
value.getUTCSeconds() === 0 && value.getUTCMilliseconds() === 0;
|
|
21
|
+
if (epochDay && !midnight) return 'H';
|
|
22
|
+
if (midnight && !epochDay) return 'D';
|
|
23
|
+
return 'DHZ';
|
|
24
|
+
}
|
|
25
|
+
if (typeof value === 'number') return Number.isInteger(value) ? 'L' : 'R';
|
|
26
|
+
throw new TypeError('Formatting requires finite JavaScript numbers or valid Date objects');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function temporalText(value, dtype, {pattern = 'short', locale, timeZone}) {
|
|
30
|
+
if (!['short', 'medium', 'long', 'full'].includes(pattern)) {
|
|
31
|
+
throw new RangeError('Temporal formatting currently supports short, medium, long and full only');
|
|
32
|
+
}
|
|
33
|
+
if (dtype === 'DHZ' && (typeof timeZone !== 'string' || !timeZone)) {
|
|
34
|
+
throw new TypeError('DHZ formatting currently requires an explicit timeZone');
|
|
35
|
+
}
|
|
36
|
+
// Civil fields are stored in UTC by TYTX; they must not shift with display timezone.
|
|
37
|
+
const options = {timeZone: dtype === 'DHZ' ? timeZone : 'UTC'};
|
|
38
|
+
if (dtype !== 'H') options.dateStyle = pattern;
|
|
39
|
+
if (dtype !== 'D') options.timeStyle = pattern;
|
|
40
|
+
return new Intl.DateTimeFormat(locale, options).format(value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function numericSection(section) {
|
|
44
|
+
// Only decimal skeletons and sign/parenthesis affixes are implemented here.
|
|
45
|
+
const match = /^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(section);
|
|
46
|
+
if (!match || (match[1] === '(') !== (match[4] === ')') || section.endsWith('.')) {
|
|
47
|
+
throw new RangeError(`Unsupported numeric pattern section: ${section}`);
|
|
48
|
+
}
|
|
49
|
+
const fraction = match[3] ?? '';
|
|
50
|
+
return {
|
|
51
|
+
prefix: match[1] ?? '', suffix: match[4] ?? '',
|
|
52
|
+
intl: {
|
|
53
|
+
useGrouping: match[2].startsWith('#,##') ? 'always' : false,
|
|
54
|
+
minimumIntegerDigits: match[2].replace('#,##', '').length,
|
|
55
|
+
minimumFractionDigits: fraction.replaceAll('#', '').length,
|
|
56
|
+
maximumFractionDigits: fraction.length,
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function numericPattern(pattern) {
|
|
62
|
+
const sections = pattern.split(';');
|
|
63
|
+
if (sections.length > 3) throw new RangeError('Numeric patterns support at most three sections');
|
|
64
|
+
const positive = numericSection(sections[0]);
|
|
65
|
+
if (positive.prefix || positive.suffix) throw new RangeError('Positive-section affixes are not implemented');
|
|
66
|
+
const zero = sections.length === 3 ? sections[1] : null;
|
|
67
|
+
// The first slice supports the already agreed literal '-' and empty zero branch.
|
|
68
|
+
if (zero !== null && zero !== '' && zero !== '-') numericSection(zero);
|
|
69
|
+
const negative = sections.length > 1 ? numericSection(sections.at(-1)) : null;
|
|
70
|
+
// Unicode negative sections supply affixes; digit settings come from the positive section.
|
|
71
|
+
return {positive, zero, negative};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Internal implementation; the only public entry point is Gramlot.format. */
|
|
75
|
+
export function formatValue(value, options = {}, context = {}) {
|
|
76
|
+
// A null value bypasses both the pattern and the mask, by contract.
|
|
77
|
+
if (value === null) return '';
|
|
78
|
+
if (typeof options === 'string') options = {pattern: options};
|
|
79
|
+
if (!options || typeof options !== 'object' || Array.isArray(options)) {
|
|
80
|
+
throw new TypeError('Format options must be a pattern string or an options object');
|
|
81
|
+
}
|
|
82
|
+
for (const key of Object.keys(options)) {
|
|
83
|
+
if (!['pattern', 'locale', 'mask', 'dtype', 'timeZone'].includes(key)) throw new RangeError(`Unsupported format option: ${key}`);
|
|
84
|
+
}
|
|
85
|
+
options = {...options, locale: options.locale ?? context.locale, timeZone: options.timeZone ?? context.timeZone};
|
|
86
|
+
const dtype = options.dtype === undefined ? inferredType(value) : options.dtype;
|
|
87
|
+
const temporal = ['D', 'H', 'DHZ'].includes(dtype);
|
|
88
|
+
if (!temporal && !['L', 'R', 'N'].includes(dtype)) throw new RangeError(`Unsupported format dtype: ${dtype}`);
|
|
89
|
+
if (temporal) {
|
|
90
|
+
if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new TypeError(`${dtype} requires a valid Date object`);
|
|
91
|
+
} else if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
92
|
+
throw new TypeError(`${dtype} formatting requires finite JavaScript numbers`);
|
|
93
|
+
}
|
|
94
|
+
if (dtype === 'L' && !Number.isInteger(value)) throw new TypeError('L formatting requires an integer');
|
|
95
|
+
const {pattern, locale, mask} = options;
|
|
96
|
+
if (!temporal && typeof pattern !== 'string') throw new TypeError('Numeric formatting currently requires an explicit pattern');
|
|
97
|
+
if (typeof locale !== 'string' || !locale) throw new TypeError('Formatting currently requires an explicit locale');
|
|
98
|
+
// Do not silently select the browser locale when the requested locale is unavailable.
|
|
99
|
+
const intl = temporal ? Intl.DateTimeFormat : Intl.NumberFormat;
|
|
100
|
+
if (!intl.supportedLocalesOf([locale]).length) throw new RangeError(`Unsupported format locale: ${locale}`);
|
|
101
|
+
validateMask(mask);
|
|
102
|
+
if (temporal) {
|
|
103
|
+
const text = temporalText(value, dtype, options);
|
|
104
|
+
return applyMask(text, mask);
|
|
105
|
+
}
|
|
106
|
+
const {positive, zero, negative} = numericPattern(pattern);
|
|
107
|
+
let text;
|
|
108
|
+
if (value === 0 && zero !== null) {
|
|
109
|
+
if (zero === '') return '';
|
|
110
|
+
if (zero === '-') text = '-';
|
|
111
|
+
else {
|
|
112
|
+
const section = numericSection(zero);
|
|
113
|
+
text = section.prefix + new Intl.NumberFormat(locale, section.intl).format(0) + section.suffix;
|
|
114
|
+
}
|
|
115
|
+
} else {
|
|
116
|
+
const affix = value < 0 && negative ? negative : positive;
|
|
117
|
+
const number = value < 0 && negative ? -value : (value === 0 ? 0 : value);
|
|
118
|
+
text = affix.prefix + new Intl.NumberFormat(locale, positive.intl).format(number) + affix.suffix;
|
|
119
|
+
}
|
|
120
|
+
return applyMask(text, mask);
|
|
121
|
+
}
|
package/src/gramlot.d.ts
CHANGED
|
@@ -14,6 +14,10 @@ import type {UtilitiesHandler} from './handlers/utilities-handler.js';
|
|
|
14
14
|
|
|
15
15
|
/** The options of a `Gramlot` instance. */
|
|
16
16
|
export interface GramlotOptions {
|
|
17
|
+
/** Formatting locale of this page; null/omitted uses the browser locale. */
|
|
18
|
+
locale?: string | null;
|
|
19
|
+
/** Timezone for instants; null/omitted uses the browser timezone. */
|
|
20
|
+
timeZone?: string | null;
|
|
17
21
|
/** The id of the server page, as registered by the server. */
|
|
18
22
|
pageId?: string;
|
|
19
23
|
/** The URL of the rpc endpoint that receives the envelopes. */
|
|
@@ -40,12 +44,27 @@ export type GramlotState = 'ready' | 'loading' | 'started' | 'failed' | 'dispose
|
|
|
40
44
|
/** Opaque registration returned by subscribe; meaningful only to its owning page. */
|
|
41
45
|
export interface SubscriptionHandle { readonly __subscriptionHandle: unique symbol; }
|
|
42
46
|
|
|
47
|
+
/** Bounded formatting subset. Call options override the page context. */
|
|
48
|
+
export interface FormatOptions {
|
|
49
|
+
/** Numeric pattern or temporal short (default), medium, long, full. */
|
|
50
|
+
pattern?: string;
|
|
51
|
+
locale?: string;
|
|
52
|
+
/** Overrides value inference; does not coerce strings or other incompatible values. */
|
|
53
|
+
dtype?: 'L' | 'R' | 'N' | 'D' | 'H' | 'DHZ';
|
|
54
|
+
/** Overrides the page timezone for DHZ; D/H do not shift. */
|
|
55
|
+
timeZone?: string;
|
|
56
|
+
/** Wrap formatted text using {}. Null and an empty zero section bypass the mask. */
|
|
57
|
+
mask?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
43
60
|
/** Legacy-shaped publication. Frame forwarding follows synchronous local delivery. */
|
|
44
61
|
export type Publication = string | {topic: string; nodeId: string} |
|
|
45
62
|
{topic: string; parent?: boolean; iframe?: string | SourceBagNode};
|
|
46
63
|
|
|
47
64
|
/** One Gramlot page: lifecycle, Data and the four proxies `src`, `rpc`, `dom`, `utl`. */
|
|
48
65
|
export class Gramlot {
|
|
66
|
+
locale: string;
|
|
67
|
+
timeZone: string;
|
|
49
68
|
/** The id of the server page. */
|
|
50
69
|
pageId: string | undefined;
|
|
51
70
|
/** The capabilities announced by the server in the bootstrap, frozen. */
|
|
@@ -80,6 +99,8 @@ export class Gramlot {
|
|
|
80
99
|
subscribe(topic: string, callback: (payload: Record<string, unknown>) => unknown): SubscriptionHandle;
|
|
81
100
|
/** Remove a registration; repeating removal of an owned handle is harmless. */
|
|
82
101
|
unsubscribe(registration: SubscriptionHandle): void;
|
|
102
|
+
/** Format a number, Date or null. Explicit dtype overrides TYTX-style Date inference. */
|
|
103
|
+
format(value: number | Date | null, options?: string | FormatOptions): string;
|
|
83
104
|
/** Load `main` from the server and mount it; resolves with the instance. */
|
|
84
105
|
start(): Promise<Gramlot>;
|
|
85
106
|
/** Request `main` from the transport and mount it. */
|
package/src/gramlot.js
CHANGED
|
@@ -10,6 +10,7 @@ import {RpcHandler} from './handlers/rpc-handler.js';
|
|
|
10
10
|
import {DomHandler} from './handlers/dom-handler.js';
|
|
11
11
|
import {SubscriptionsHandler} from './handlers/subscriptions-handler.js';
|
|
12
12
|
import {UtilitiesHandler} from './handlers/utilities-handler.js';
|
|
13
|
+
import {formatValue} from './format.js';
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
16
|
* One Gramlot page: lifecycle, Data and the four proxies `src`, `rpc`, `dom`, `utl`.
|
|
@@ -17,8 +18,13 @@ import {UtilitiesHandler} from './handlers/utilities-handler.js';
|
|
|
17
18
|
*/
|
|
18
19
|
export class Gramlot {
|
|
19
20
|
constructor({pageId, rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close', rootId = 'gramlot-root', capabilities = [],
|
|
20
|
-
element = null, document = element?.ownerDocument ?? globalThis.document, transport = null, collections = []
|
|
21
|
+
element = null, document = element?.ownerDocument ?? globalThis.document, transport = null, collections = [],
|
|
22
|
+
locale = null, timeZone = null} = {}) {
|
|
21
23
|
this.pageId = pageId;
|
|
24
|
+
const browserContext = locale == null || timeZone == null
|
|
25
|
+
? document.defaultView.Intl.DateTimeFormat().resolvedOptions() : null;
|
|
26
|
+
this.locale = locale ?? browserContext.locale;
|
|
27
|
+
this.timeZone = timeZone ?? browserContext.timeZone;
|
|
22
28
|
Object.defineProperty(this, '_subscriptions', {value: new SubscriptionsHandler(this)});
|
|
23
29
|
this.capabilities = Object.freeze([...capabilities]);
|
|
24
30
|
this.src = new SourceHandler(this, {collections, destination: element ?? document.getElementById(rootId)});
|
|
@@ -38,6 +44,7 @@ export class Gramlot {
|
|
|
38
44
|
publish(topic, payload = {}) { return this._subscriptions.publish(topic, payload); }
|
|
39
45
|
subscribe(topic, callback) { return this._subscriptions.subscribe(topic, callback); }
|
|
40
46
|
unsubscribe(registration) { this._subscriptions.unsubscribe(registration); }
|
|
47
|
+
format(value, options) { return formatValue(value, options, {locale: this.locale, timeZone: this.timeZone}); }
|
|
41
48
|
|
|
42
49
|
start() {
|
|
43
50
|
if (this.state === 'disposed') return Promise.reject(new Error('Gramlot is disposed'));
|
package/src/index.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ export {SourceHandler} from './handlers/source-handler.js';
|
|
|
11
11
|
export {RpcHandler} from './handlers/rpc-handler.js';
|
|
12
12
|
export {DomHandler} from './handlers/dom-handler.js';
|
|
13
13
|
export {UtilitiesHandler} from './handlers/utilities-handler.js';
|
|
14
|
-
export type {GramlotOptions, GramlotState, Publication, SubscriptionHandle} from './gramlot.js';
|
|
14
|
+
export type {GramlotOptions, GramlotState, Publication, SubscriptionHandle, FormatOptions} from './gramlot.js';
|
|
15
15
|
export {PageBootstrap} from './bootstrap.js';
|
|
16
16
|
export type {PageBootstrapOptions, PageResources} from './bootstrap.js';
|
|
17
17
|
export {Page} from './server/page.js';
|
|
@@ -31,3 +31,6 @@ export type {BeaconNavigator, DomDocument, DomElement, DomEvent, DomFragment, Do
|
|
|
31
31
|
|
|
32
32
|
export {IndexPage} from "./server/index-page.js";
|
|
33
33
|
export {IndexLogic, mountIndexPage} from "./index-page-runtime.js";
|
|
34
|
+
|
|
35
|
+
export {parseDateExpression} from './date-parser/index.js';
|
|
36
|
+
export type {DateExpressionOptions, DateExpressionResult, DateExpressionErrorCode} from './date-parser/index.js';
|