@gramlot/gramlot 0.2.19 → 0.3.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.
- package/dist/gramlot.js +2145 -224
- package/dist/gramlot.min.js +363 -21
- package/package.json +6 -3
- package/src/binding/ask-dialog.js +2 -2
- package/src/binding/inline.js +11 -12
- package/src/binding/installation.js +4 -1
- package/src/binding/pointer.js +63 -0
- package/src/binding/providers.js +8 -4
- package/src/binding/runtime.js +11 -5
- package/src/bootstrap.d.ts +2 -0
- package/src/bootstrap.js +9 -2
- package/src/builder/gramlot-builder.js +24 -3
- package/src/builder/source.js +33 -9
- package/src/components/bases.js +182 -0
- package/src/components/buttons.js +254 -0
- package/src/components/choice-editor.js +221 -0
- package/src/components/choices.js +13 -0
- package/src/components/date-calendar.js +139 -0
- package/src/components/field-state.js +166 -0
- package/src/components/formlet-labels.js +80 -0
- package/src/components/index.js +5 -0
- package/src/components/inputs.js +196 -0
- package/src/components/labelbox.js +74 -0
- package/src/components/layout.js +190 -0
- package/src/components/parameters.js +6 -0
- package/src/components/popup.js +22 -0
- package/src/components/registry.js +83 -0
- package/src/components/typed-editor.js +260 -0
- package/src/components/validation.js +138 -0
- 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 +128 -0
- package/src/gramlot.d.ts +25 -0
- package/src/gramlot.js +15 -1
- package/src/handlers/dom-handler.d.ts +1 -0
- package/src/handlers/dom-handler.js +7 -0
- package/src/index-page-runtime.js +78 -30
- package/src/index-page-styles.js +2 -2
- package/src/index-theme.js +1 -1
- package/src/index.d.ts +4 -1
- package/src/index.js +2 -0
- package/src/renderer/attributes.js +25 -50
- package/src/renderer/gramlot-html-renderer.js +4 -3
- package/src/renderer/gramlot-renderer.js +63 -3
- package/src/server/gramlot-server.d.ts +5 -0
- package/src/server/gramlot-server.js +14 -5
- package/src/server/index-page.d.ts +1 -0
- package/src/server/index-page.js +8 -3
- package/src/server/page-base.js +3 -0
- package/src/server/page.d.ts +3 -0
- package/src/server/resources.d.ts +2 -0
- package/src/view/button.js +17 -13
- package/src/view/controls.js +152 -4
- package/src/view/html.js +18 -0
- package/themes/gramlot-base/README.md +6 -0
- package/themes/gramlot-base/theme.css +34 -6
- package/themes/gramlot-compact/README.md +6 -0
- package/themes/gramlot-compact/theme.css +8 -4
- package/themes/joanna/README.md +23 -0
- package/themes/joanna/theme.css +89 -0
- package/themes/mimi/README.md +23 -0
- package/themes/mimi/theme.css +89 -0
- package/tools/gramlot-tools-inspector.js +42 -18
- package/tools/inspector-agent.js +8 -4
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import {Bag} from '@genrojs/bag';
|
|
2
|
+
import {pointerTemplate} from '@genrojs/builders';
|
|
3
|
+
|
|
4
|
+
/** Shared ordered rules. Context supplies activated callbacks/RPC; this module never writes Data. */
|
|
5
|
+
export const validationRules = ['select', 'notnull', 'empty', 'case', 'len', 'min', 'max', 'email', 'regex', 'call', 'remote'];
|
|
6
|
+
const deferredRules = ['nodup', 'exist', 'gridnodup'];
|
|
7
|
+
const empty = value => value == null || value === '';
|
|
8
|
+
const then = (value, next) => value instanceof Promise ? value.then(next) : next(value);
|
|
9
|
+
|
|
10
|
+
export function validateInput(value, parameters, context = {}) {
|
|
11
|
+
const result = {value, modified:false, error:null, warnings:[], issues:[], datachanges:[]};
|
|
12
|
+
const validations = Object.fromEntries(Object.entries(parameters).map(([key, val]) => [key.slice(9), val]));
|
|
13
|
+
const configured = name => Object.hasOwn(parameters, `validate_${name}`) && parameters[`validate_${name}`] != null;
|
|
14
|
+
for (const name of deferredRules) if (configured(name)) throw new Error(`validate_${name} requires the DB/grid integration.`);
|
|
15
|
+
const invoke = (name, current, expression = false) => context.invoke(name, parameters[name], {
|
|
16
|
+
...validations, value:current, result, validations, userChange:true, signal:context.signal
|
|
17
|
+
}, expression);
|
|
18
|
+
const consume = (rule, output) => {
|
|
19
|
+
if (output == null || output === true) return;
|
|
20
|
+
if (typeof output !== 'boolean' && typeof output !== 'string' && (typeof output !== 'object' || Array.isArray(output))) throw new TypeError('A validator returns true, false, null, an error code, or a result object/Bag.');
|
|
21
|
+
const prefix = `validate_${rule}`;
|
|
22
|
+
const response = output instanceof Bag ? Object.fromEntries(output.getNodes().map(node => [node.label, node.value])) : typeof output === 'object' ? output : {errorcode:output === false ? 'error' : output};
|
|
23
|
+
if (Object.hasOwn(response, 'value')) {
|
|
24
|
+
result.modified ||= !Object.is(result.value, response.value);
|
|
25
|
+
result.value = response.value;
|
|
26
|
+
}
|
|
27
|
+
if (response.data != null) { context.checkDataPatch(response.data); result.datachanges.push(response.data); }
|
|
28
|
+
if (!response.errorcode) return;
|
|
29
|
+
const warning = parameters[`${prefix}_iswarning`] ?? response.iswarning
|
|
30
|
+
?? Boolean(parameters[`${prefix}_warning`] && !parameters[`${prefix}_error`]);
|
|
31
|
+
const message = parameters[`${prefix}_${response.errorcode}`]
|
|
32
|
+
|| parameters[`${prefix}_${warning ? 'warning' : 'error'}`]
|
|
33
|
+
|| response.message || parameters[`${prefix}_${warning ? 'error' : 'warning'}`] || String(response.errorcode);
|
|
34
|
+
const renderedMessage = pointerTemplate(message, name => name ? ({...validations, ...response, value:result.value})[name] : result.value);
|
|
35
|
+
if (renderedMessage == null) throw new Error('A validation message references a missing value.');
|
|
36
|
+
const issue = {rule, code:response.errorcode, severity:warning ? 'warning' : 'error', message:renderedMessage};
|
|
37
|
+
result.issues.push(issue);
|
|
38
|
+
if (warning) result.warnings.push(renderedMessage);
|
|
39
|
+
else { result.error = renderedMessage; result.required = Boolean(response.required); }
|
|
40
|
+
};
|
|
41
|
+
const step = index => {
|
|
42
|
+
if (context.signal?.aborted) throw context.signal.reason;
|
|
43
|
+
if (result.error || index === validationRules.length) return result;
|
|
44
|
+
const rule = validationRules[index], prefix = `validate_${rule}`, param = parameters[prefix];
|
|
45
|
+
if (!configured(rule) || (param === false && rule !== 'empty')) return step(index + 1);
|
|
46
|
+
const run = allowed => {
|
|
47
|
+
if (!allowed) return step(index + 1);
|
|
48
|
+
let output;
|
|
49
|
+
if (rule === 'remote' && result.value == null) return step(index + 1);
|
|
50
|
+
if (rule === 'call') output = invoke(prefix, result.value);
|
|
51
|
+
else if (rule === 'remote') output = context.remote(param, {...remoteArguments(parameters), value:result.value}, context.signal);
|
|
52
|
+
else output = localRule(rule, param, result.value, context);
|
|
53
|
+
return then(output, answer => {
|
|
54
|
+
if (context.signal?.aborted) throw context.signal.reason;
|
|
55
|
+
const complete = () => { consume(rule, answer); return step(index + 1); };
|
|
56
|
+
if (rule === 'remote' && parameters.validate__onResult) return then(context.invoke('validate__onResult', parameters.validate__onResult,
|
|
57
|
+
{result:answer, value:result.value, validations, signal:context.signal}), complete);
|
|
58
|
+
return complete();
|
|
59
|
+
});
|
|
60
|
+
};
|
|
61
|
+
const condition = parameters[`${prefix}_if`];
|
|
62
|
+
return then(condition == null ? true : typeof condition === 'boolean' ? condition
|
|
63
|
+
: invoke(`${prefix}_if`, result.value, true), run);
|
|
64
|
+
};
|
|
65
|
+
return step(0);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function remoteArguments(parameters) {
|
|
69
|
+
const excluded = new Set(['if', 'error', 'warning', 'iswarning']);
|
|
70
|
+
return Object.fromEntries(Object.entries(parameters).filter(([key]) => key.startsWith('validate_remote_')
|
|
71
|
+
&& !excluded.has(key.slice(16))).map(([key, value]) => [key.slice(16), value]));
|
|
72
|
+
}
|
|
73
|
+
function fail(errorcode, message, extra = {}) { return {errorcode, message, ...extra}; }
|
|
74
|
+
function localRule(rule, param, value, context) {
|
|
75
|
+
if (rule === 'select') return context.selection(value);
|
|
76
|
+
if (rule === 'notnull') return empty(value) && param ? fail('notnull', 'A value is required.', {required:true}) : null;
|
|
77
|
+
if (rule === 'empty') return empty(value) ? {value:param} : null;
|
|
78
|
+
if (rule === 'len') {
|
|
79
|
+
if (typeof param !== 'string' || !/^(?:\d+|\d+:\d*|:\d+)$/.test(param)) throw new Error('Invalid validate_len: use a length or min:max.');
|
|
80
|
+
const [low, high] = param.split(':');
|
|
81
|
+
const min = Number(low || 0), max = high === undefined ? min : high === '' ? Infinity : Number(high);
|
|
82
|
+
if (min > max) throw new Error('Invalid validate_len: minimum exceeds maximum.');
|
|
83
|
+
if (empty(value)) return;
|
|
84
|
+
if (typeof value !== 'string') throw new TypeError('validate_len requires a text value.');
|
|
85
|
+
if (value.length < min || value.length > max) return fail(min === max ? 'wrong length' : value.length < min ? 'too short' : 'too long',
|
|
86
|
+
min === max ? `Enter exactly ${min} characters.` : max === Infinity ? `Enter at least ${min} characters.`
|
|
87
|
+
: min === 0 ? `Enter no more than ${max} characters.` : `Enter between ${min} and ${max} characters.`);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (empty(value)) return;
|
|
91
|
+
if (rule === 'case') {
|
|
92
|
+
if (typeof value !== 'string') throw new TypeError('validate_case requires a text value.');
|
|
93
|
+
switch (param) {
|
|
94
|
+
case 'upper': case 'u': return {value:value.toUpperCase()};
|
|
95
|
+
case 'lower': case 'l': return {value:value.toLowerCase()};
|
|
96
|
+
case 'title': case 't': return {value:value.replace(/\p{L}[\p{L}\p{M}]*/gu, word => word[0].toUpperCase() + word.slice(1).toLowerCase())};
|
|
97
|
+
case 'capitalize': case 'c': return {value:value[0].toUpperCase() + value.slice(1).toLowerCase()};
|
|
98
|
+
default: throw new Error('Invalid validate_case: use upper, lower, title or capitalize.');
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (rule === 'min' || rule === 'max') {
|
|
102
|
+
let comparison;
|
|
103
|
+
if (context.isDecimal?.(value)) comparison = value.comparedTo(param);
|
|
104
|
+
else if (value instanceof Date && param instanceof Date) comparison = value.getTime() - param.getTime();
|
|
105
|
+
else if (typeof value === 'number' && Number.isFinite(value) && typeof param === 'number' && Number.isFinite(param)) comparison = value - param;
|
|
106
|
+
else throw new TypeError(`validate_${rule} requires matching numeric or date/time values.`);
|
|
107
|
+
if (rule === 'min' ? comparison < 0 : comparison > 0) return fail(rule, `Value must be ${rule === 'min' ? 'at least' : 'at most'} ${param}.`);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (rule === 'email') {
|
|
111
|
+
if (typeof value !== 'string') throw new TypeError('validate_email requires a text value.');
|
|
112
|
+
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(value) ? null : fail('email', 'Check email format.', {iswarning:true});
|
|
113
|
+
}
|
|
114
|
+
if (rule === 'regex') {
|
|
115
|
+
if (typeof value !== 'string' || typeof param !== 'string') throw new TypeError('validate_regex requires text.');
|
|
116
|
+
const pattern = param.trim(), negative = pattern.startsWith('!');
|
|
117
|
+
return new RegExp(negative ? pattern.slice(1) : pattern, 'u').test(value) !== negative ? null : fail('regex', 'The value does not match the required pattern.');
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Shared metadata exports the same rule types to both Builders. */
|
|
122
|
+
const text = {dtype:'T', nullable:true, binding:'read'};
|
|
123
|
+
const boolean = {dtype:'B', nullable:true, binding:'read'};
|
|
124
|
+
const scalar = {dtype:['T','L','N','R','B','D','H','DH','DHZ'], nullable:true, binding:'read'};
|
|
125
|
+
export const validationParameters = {
|
|
126
|
+
validate_select:boolean, validate_notnull:{...boolean,default:false}, validate_empty:scalar,
|
|
127
|
+
validate_case:{...text,enum:['upper','lower','title','capitalize','u','l','t','c']},
|
|
128
|
+
validate_len:text, validate_min:scalar, validate_max:scalar, validate_email:boolean,
|
|
129
|
+
validate_regex:text, validate_call:{dtype:'T',nullable:true}, validate_remote:text,
|
|
130
|
+
validate_onAccept:{dtype:'T',nullable:true}, validate_onReject:{dtype:'T',nullable:true},
|
|
131
|
+
validate__onResult:{dtype:'T',nullable:true},
|
|
132
|
+
validate_timeout:{dtype:'L',nullable:true,binding:'read'},
|
|
133
|
+
...Object.fromEntries(validationRules.flatMap(rule => [
|
|
134
|
+
[`validate_${rule}_if`, {dtype:['T','B'],nullable:true}],
|
|
135
|
+
[`validate_${rule}_iswarning`, boolean],
|
|
136
|
+
...['error','warning'].map(suffix => [`validate_${rule}_${suffix}`, {...text,qualification:'intl_str'}])
|
|
137
|
+
]))
|
|
138
|
+
};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Copyright 2026 Softwell S.r.l. - SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Gregorian civil calendar arithmetic. No clock, timezone, or Date object.
|
|
3
|
+
export function daysInMonth(year, month) {
|
|
4
|
+
if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
|
|
5
|
+
return [4, 6, 9, 11].includes(month) ? 30 : 31;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function civil(year, month, day) {
|
|
9
|
+
if (![year, month, day].every(Number.isInteger) || year < 1 || year > 9999 ||
|
|
10
|
+
month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {
|
|
11
|
+
throw new RangeError('Date must exist in Gregorian years 0001–9999.');
|
|
12
|
+
}
|
|
13
|
+
return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function parts(date) {
|
|
17
|
+
if (typeof date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(date)) {
|
|
18
|
+
throw new RangeError('Expected a civil date in YYYY-MM-DD format.');
|
|
19
|
+
}
|
|
20
|
+
const result = date.split('-').map(Number);
|
|
21
|
+
civil(...result);
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function ordinal(year, month, day) {
|
|
26
|
+
const previous = year - 1;
|
|
27
|
+
let result = 365 * previous + Math.floor(previous / 4) - Math.floor(previous / 100) +
|
|
28
|
+
Math.floor(previous / 400) + day - 1;
|
|
29
|
+
for (let m = 1; m < month; m++) result += daysInMonth(year, m);
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function addDays(date, offset) {
|
|
34
|
+
let target = ordinal(...parts(date)) + offset;
|
|
35
|
+
if (!Number.isSafeInteger(target) || target < 0 || target > ordinal(9999, 12, 31)) {
|
|
36
|
+
throw new RangeError('Date offset exceeds Gregorian years 0001–9999.');
|
|
37
|
+
}
|
|
38
|
+
// Binary search keeps arbitrarily large supported offsets bounded.
|
|
39
|
+
let low = 1, high = 10000;
|
|
40
|
+
while (high - low > 1) {
|
|
41
|
+
const middle = Math.floor((low + high) / 2);
|
|
42
|
+
if (ordinal(middle, 1, 1) <= target) low = middle;
|
|
43
|
+
else high = middle;
|
|
44
|
+
}
|
|
45
|
+
target -= ordinal(low, 1, 1);
|
|
46
|
+
let month = 1;
|
|
47
|
+
while (target >= daysInMonth(low, month)) target -= daysInMonth(low, month++);
|
|
48
|
+
return civil(low, month, target + 1);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function monday(date) {
|
|
52
|
+
return addDays(date, -(ordinal(...parts(date)) % 7));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function monthPeriod(year, month, offset = 0, count = 1) {
|
|
56
|
+
const index = year * 12 + month - 1 + offset;
|
|
57
|
+
const y = Math.floor(index / 12), m = ((index % 12) + 12) % 12 + 1;
|
|
58
|
+
const endIndex = index + count - 1;
|
|
59
|
+
const ey = Math.floor(endIndex / 12), em = ((endIndex % 12) + 12) % 12 + 1;
|
|
60
|
+
return {start: civil(y, m, 1), end: civil(ey, em, daysInMonth(ey, em))};
|
|
61
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Natural-language civil dates and periods, independent of DOM, clock and timezone. */
|
|
2
|
+
export interface DateExpressionOptions {
|
|
3
|
+
/** Required Gregorian civil ISO date, YYYY-MM-DD (0001–9999). */
|
|
4
|
+
workdate: string;
|
|
5
|
+
/** Supported Italian/English locale; defaults to it-IT. */
|
|
6
|
+
locale?: string;
|
|
7
|
+
/** Integer 0–99, default 20. Inclusive window [work year + ahead - 100, work year + ahead - 1]. */
|
|
8
|
+
twoDigitYearAhead?: number;
|
|
9
|
+
}
|
|
10
|
+
export type DateExpressionErrorCode = 'INVALID_CONTEXT' | 'INVALID_INPUT' |
|
|
11
|
+
'UNRECOGNIZED_EXPRESSION' | 'INVALID_DATE' |
|
|
12
|
+
'INVALID_RANGE';
|
|
13
|
+
export type DateExpressionResult =
|
|
14
|
+
{ok: true; kind: 'date'; date: string} |
|
|
15
|
+
{ok: true; kind: 'period'; start: string | null; end: string | null} |
|
|
16
|
+
{ok: false; error: {code: DateExpressionErrorCode; message: string}};
|
|
17
|
+
/** Parse a complete expression without reading or modifying page state. */
|
|
18
|
+
export function parseDateExpression(text: string, options: DateExpressionOptions): DateExpressionResult;
|
|
@@ -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
|
+
}
|