@veroxm/react-sdk 1.11.1 → 1.12.1
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/CHANGELOG.md +33 -0
- package/dist/editor/handler.js +5 -1
- package/dist/editor/i18n.d.ts +3 -0
- package/dist/editor/i18n.js +6 -0
- package/dist/editor/overlay.d.ts +1 -1
- package/dist/editor/overlay.js +25 -0
- package/dist/form-native/checks.d.ts +53 -0
- package/dist/form-native/checks.js +168 -0
- package/dist/form-native/model.d.ts +184 -0
- package/dist/form-native/model.js +261 -0
- package/dist/form-native/relay.d.ts +11 -0
- package/dist/form-native/relay.js +156 -0
- package/dist/form-native/view.d.ts +28 -0
- package/dist/form-native/view.js +286 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/next/form.d.ts +34 -0
- package/dist/next/form.js +47 -0
- package/dist/next/index.d.ts +2 -0
- package/dist/next/index.js +1 -0
- package/dist/slots-core.d.ts +16 -1
- package/dist/slots-core.js +6 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,38 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.12.1
|
|
4
|
+
|
|
5
|
+
- The quick-quote look for native forms. A date of birth set to **Compact** in the builder (Birth date > Style) is one
|
|
6
|
+
field box: the question title as a small label, then Day / Month / Year as borderless menus sized to their text with
|
|
7
|
+
an arrow in `--vx-color-action`, and, when both calendars are offered, a Hijri switch at the end (`role="switch"`).
|
|
8
|
+
Switching calendar clears the date. The title shows in every field style, "Placeholder only" too. Arabic mirrors it.
|
|
9
|
+
- The mobile number is one field box too: the country code, a divider, then the number with its placeholder.
|
|
10
|
+
- Saudi ID and mobile placeholders, and the button text, are set per form in the builder and translated per language;
|
|
11
|
+
the renderer uses them. `submitLabel` still overrides the button text.
|
|
12
|
+
- An empty error line no longer takes space, so a single-row form is exactly one field high.
|
|
13
|
+
|
|
14
|
+
## 1.12.0
|
|
15
|
+
|
|
16
|
+
- `<VeroxmForm>` from `@veroxm/react-sdk/next` draws a form built in VeroXM's Forms natively in the page (no iframe):
|
|
17
|
+
server-rendered, styled only from design-system tokens (`--vx-field-height`, `--vx-field-radius`,
|
|
18
|
+
`--vx-field-border`, `--vx-color-focus`, `--vx-color-danger`, `--vx-button-height`, `--vx-button-primary-*`...),
|
|
19
|
+
mirrored in Arabic with logical properties while IDs, country codes and numbers stay left to right. Rows lay out as
|
|
20
|
+
the form's layout says (fixed px or flexible columns, a gap per row, column counts below 1100px and 640px).
|
|
21
|
+
Widgets: Saudi ID, date of birth (Gregorian / Hijri Umm al-Qura, month names from `Intl`), mobile with a country
|
|
22
|
+
code, text, email, phone, website, number, menus, single and multiple choice, yes / no, consent. About 9 kB gzipped.
|
|
23
|
+
- Answers are checked as the visitor leaves each field and all together on send, with the same checks VeroXM runs
|
|
24
|
+
(copied from it and kept the same by a test); errors sit under their field (`aria-invalid`, `aria-describedby`)
|
|
25
|
+
and focus moves to the first. VeroXM checks again and its answer decides.
|
|
26
|
+
- `context={{ product, line }}` is sent with the answers (with any `utm_*` in the address); a hand-off form then
|
|
27
|
+
takes the visitor to that product's journey. The same form keeps what was typed when the product changes.
|
|
28
|
+
- Sends go through the site's own route: `POST /api/veroxm/forms/:id/submit` (already mounted by
|
|
29
|
+
`export { POST } from '@veroxm/react-sdk/next/route'`) relays them with the server key and the visitor's address.
|
|
30
|
+
Without script the form still works as a plain post, redirecting to the journey. Same-site only (`X-VeroXM-Form`
|
|
31
|
+
header for JSON, `Origin` / `Sec-Fetch-Site` checked).
|
|
32
|
+
- `field.form()`: a slot field (and a list item field, so each tab or product can carry its own) holding one of the
|
|
33
|
+
project's published forms, chosen from a menu in the on-page editor.
|
|
34
|
+
- `VeroxmFormView` (any React app: pass the form you loaded) and `loadForm`, `localizeForm`, `nativeProblem`.
|
|
35
|
+
|
|
3
36
|
## 1.11.1
|
|
4
37
|
|
|
5
38
|
- The editing bar no longer covers the slot panel's buttons. When the bar wraps to more rows (a narrow window,
|
package/dist/editor/handler.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { resolveSlotsConfig } from '../slots-core.js';
|
|
2
2
|
import { EDITING_FLAG_COOKIE, EDITOR_COOKIE, EDITOR_HEADER, ROUTE_BASE, VISITOR_COOKIE } from './constants.js';
|
|
3
3
|
import { editorApi, readCookie, safePath, secondsLeft } from './server.js';
|
|
4
|
+
import { relayFormSubmit } from '../form-native/relay.js';
|
|
4
5
|
const NOT_FOUND = () => json({ error: 'Not found' }, 404);
|
|
5
6
|
/** Changes the overlay can make to a slot: publish (or send for approval), discard, and approval decisions. */
|
|
6
7
|
const POST_VERBS = new Set(['publish', 'discard', 'approve', 'reject', 'withdraw']);
|
|
@@ -180,6 +181,9 @@ export function createEditorHandler(hooks = {}) {
|
|
|
180
181
|
const method = request.method.toUpperCase();
|
|
181
182
|
if (method === 'POST' && action === 'revalidate' && !name)
|
|
182
183
|
return revalidate(request);
|
|
184
|
+
// A native form's send (<VeroxmForm>): anyone may send one, so it is not an editing request.
|
|
185
|
+
if (method === 'POST' && action === 'forms' && name && verb === 'submit' && !rest.length)
|
|
186
|
+
return relayFormSubmit(request, name);
|
|
183
187
|
if (method === 'GET') {
|
|
184
188
|
if (action === 'draft') {
|
|
185
189
|
const token = url.searchParams.get('token') ?? '';
|
|
@@ -206,7 +210,7 @@ export function createEditorHandler(hooks = {}) {
|
|
|
206
210
|
}
|
|
207
211
|
if (action === 'published' && hooks.servePublished && !name)
|
|
208
212
|
return published(request);
|
|
209
|
-
if ((action === 'session' || action === 'slots' || action === 'media' || action === 'geocode') && !name)
|
|
213
|
+
if ((action === 'session' || action === 'slots' || action === 'media' || action === 'geocode' || action === 'forms') && !name)
|
|
210
214
|
return relay(request, action, 'GET');
|
|
211
215
|
return NOT_FOUND();
|
|
212
216
|
}
|
package/dist/editor/i18n.d.ts
CHANGED
|
@@ -109,6 +109,9 @@ declare const en: {
|
|
|
109
109
|
'component.label': string;
|
|
110
110
|
'component.choose': string;
|
|
111
111
|
'component.none': string;
|
|
112
|
+
'form.none': string;
|
|
113
|
+
'form.unpublished': string;
|
|
114
|
+
'form.loadFailed': string;
|
|
112
115
|
'video.url': string;
|
|
113
116
|
'video.empty': string;
|
|
114
117
|
'video.recognised': string;
|
package/dist/editor/i18n.js
CHANGED
|
@@ -118,6 +118,9 @@ const en = {
|
|
|
118
118
|
'component.label': 'Component',
|
|
119
119
|
'component.choose': 'Choose a component',
|
|
120
120
|
'component.none': 'None (the site’s default)',
|
|
121
|
+
'form.none': 'No form',
|
|
122
|
+
'form.unpublished': 'A form that is no longer published',
|
|
123
|
+
'form.loadFailed': 'Your forms could not be loaded. Close the panel and try again.',
|
|
121
124
|
'video.url': 'YouTube or Vimeo link, or a video file',
|
|
122
125
|
'video.empty': 'The page shows it as a player.',
|
|
123
126
|
'video.recognised': '{provider}: recognised.',
|
|
@@ -317,6 +320,9 @@ const ar = {
|
|
|
317
320
|
'component.label': 'المكوّن',
|
|
318
321
|
'component.choose': 'اختر مكوّنًا',
|
|
319
322
|
'component.none': 'لا شيء (الافتراضي في الموقع)',
|
|
323
|
+
'form.none': 'بلا نموذج',
|
|
324
|
+
'form.unpublished': 'نموذج لم يعد منشورًا',
|
|
325
|
+
'form.loadFailed': 'تعذّر تحميل نماذجك. أغلق اللوحة وحاول مرة أخرى.',
|
|
320
326
|
'video.url': 'رابط YouTube أو Vimeo، أو ملف فيديو',
|
|
321
327
|
'video.empty': 'تعرضه الصفحة في مشغّل فيديو.',
|
|
322
328
|
'video.recognised': '{provider}: تم التعرّف عليه.',
|
package/dist/editor/overlay.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type ReactNode } from 'react';
|
|
2
2
|
import { type EditorTranslator, type LabelMap } from './i18n.js';
|
|
3
3
|
interface FieldDef {
|
|
4
|
-
type: 'text' | 'richText' | 'media' | 'link' | 'number' | 'boolean' | 'select' | 'menu' | 'video' | 'slides' | 'map' | 'chart' | 'component' | 'list';
|
|
4
|
+
type: 'text' | 'richText' | 'media' | 'link' | 'number' | 'boolean' | 'select' | 'menu' | 'video' | 'slides' | 'map' | 'chart' | 'form' | 'component' | 'list';
|
|
5
5
|
label?: string;
|
|
6
6
|
/** The site's label in each language, when it gave more than one. */
|
|
7
7
|
labels?: LabelMap;
|
package/dist/editor/overlay.js
CHANGED
|
@@ -866,6 +866,8 @@ function FieldInput({ name, def, value, shown, fallback, onChange, onFocus, }) {
|
|
|
866
866
|
return _jsx(VideoInput, { name: name, def: def, value: value, onChange: onChange, onFocus: onFocus });
|
|
867
867
|
case 'chart':
|
|
868
868
|
return _jsx(ChartInput, { name: name, def: def, value: value, onChange: onChange, onFocus: onFocus });
|
|
869
|
+
case 'form':
|
|
870
|
+
return _jsx(FormInput, { name: name, def: def, value: value, onChange: onChange, onFocus: onFocus });
|
|
869
871
|
case 'map':
|
|
870
872
|
return _jsx(MapInput, { name: name, def: def, value: value, onChange: onChange, onFocus: onFocus });
|
|
871
873
|
case 'slides':
|
|
@@ -906,6 +908,29 @@ function ComponentInput({ name, def, value, fallback, onChange, onFocus }) {
|
|
|
906
908
|
? Object.entries(schema.fields).map(([f, d]) => (_jsx(FieldInput, { name: `${name}.${f}`, def: d, value: chosen.values?.[f], fallback: asComponentValue(fallback)?.component === chosen.component ? asComponentValue(fallback)?.values?.[f] : undefined, onChange: (v) => onChange({ ...chosen, version: schema.version, values: { ...(chosen.values ?? {}), [f]: v } }), onFocus: onFocus }, `${chosen.component}.${f}`)))
|
|
907
909
|
: null] }));
|
|
908
910
|
}
|
|
911
|
+
let formsList = null;
|
|
912
|
+
/** A form field (field.form): one of the project's published forms, or none. The list is read once per page. */
|
|
913
|
+
function FormInput({ name, def, value, onChange, onFocus }) {
|
|
914
|
+
const ui = useUi();
|
|
915
|
+
const id = useId();
|
|
916
|
+
const [forms, setForms] = useState(null);
|
|
917
|
+
const [failed, setFailed] = useState(false);
|
|
918
|
+
useEffect(() => {
|
|
919
|
+
let live = true;
|
|
920
|
+
formsList ?? (formsList = call('forms').then((r) => r.data ?? []));
|
|
921
|
+
formsList.then((list) => live && setForms(list), () => {
|
|
922
|
+
formsList = null;
|
|
923
|
+
if (live)
|
|
924
|
+
setFailed(true);
|
|
925
|
+
});
|
|
926
|
+
return () => {
|
|
927
|
+
live = false;
|
|
928
|
+
};
|
|
929
|
+
}, []);
|
|
930
|
+
const current = typeof value === 'string' ? value : '';
|
|
931
|
+
const known = !forms || !current || forms.some((f) => f.id === current);
|
|
932
|
+
return (_jsxs("div", { className: "vx-field", children: [_jsxs("label", { htmlFor: id, className: "vx-label", children: [fieldLabel(ui, def, name), def.required ? _jsx("span", { "aria-hidden": "true", children: " *" }) : null] }), _jsxs("select", { id: id, "data-field": name, onFocus: onFocus, value: current, disabled: !forms && !failed, onChange: (e) => onChange(e.target.value || null), children: [_jsx("option", { value: "", children: ui.t('form.none') }), !known ? _jsx("option", { value: current, children: ui.t('form.unpublished') }) : null, (forms ?? []).map((f) => (_jsx("option", { value: f.id, children: f.name }, f.id)))] }), failed ? _jsx("span", { className: "vx-count", role: "alert", children: ui.t('form.loadFailed') }) : null] }));
|
|
933
|
+
}
|
|
909
934
|
function VideoInput({ name, def, value, onChange, onFocus }) {
|
|
910
935
|
const ui = useUi();
|
|
911
936
|
const id = useId();
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export type FormCalendar = 'gregorian' | 'hijri';
|
|
2
|
+
/** A birth_date answer: the date as it was entered, in its own calendar. */
|
|
3
|
+
export interface FormCalendarDate {
|
|
4
|
+
calendar: FormCalendar;
|
|
5
|
+
year: number;
|
|
6
|
+
month: number;
|
|
7
|
+
day: number;
|
|
8
|
+
}
|
|
9
|
+
export declare const FORM_MOBILE_COUNTRIES: Record<string, {
|
|
10
|
+
dial: string;
|
|
11
|
+
en: string;
|
|
12
|
+
ar: string;
|
|
13
|
+
pattern?: RegExp;
|
|
14
|
+
min: number;
|
|
15
|
+
max: number;
|
|
16
|
+
}>;
|
|
17
|
+
/** Western digits for Arabic-Indic and Persian ones ("١٢٣" -> "123"), so an ID typed on an Arabic keyboard counts. */
|
|
18
|
+
export declare function latinDigits(value: string): string;
|
|
19
|
+
/**
|
|
20
|
+
* Whether a Saudi ID's check digit is right (National ID and Iqama): from the left, digits in odd places are doubled
|
|
21
|
+
* and their digits added, the others added as they are; the total is a multiple of 10.
|
|
22
|
+
*/
|
|
23
|
+
export declare function saudiIdCheckDigitOk(id: string): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* A mobile number in E.164, or null when it isn't valid for its country: digits only, a leading 0 (or the country's
|
|
26
|
+
* own code) removed; Saudi numbers are 5 and 8 more digits.
|
|
27
|
+
*/
|
|
28
|
+
export declare function normalizeMobile(country: string, number: string): string | null;
|
|
29
|
+
/**
|
|
30
|
+
* The Gregorian date (UTC midnight) of a Hijri (Umm al-Qura) date, or null when that day doesn't exist (a 30th of a
|
|
31
|
+
* 29-day month) or the runtime has no Umm al-Qura calendar. Searches around the estimate: a Hijri year is about
|
|
32
|
+
* 354.37 days, and 1 Muharram 1 AH was 16 July 622.
|
|
33
|
+
*/
|
|
34
|
+
export declare function hijriToGregorian(year: number, month: number, day: number): Date | null;
|
|
35
|
+
/** Whole years from a date of birth to `now`. */
|
|
36
|
+
export declare function ageOn(birth: Date, now: Date): number;
|
|
37
|
+
/** A birth_date answer's Gregorian date, or null when it isn't a real date. */
|
|
38
|
+
export declare function calendarDateToGregorian(v: FormCalendarDate): Date | null;
|
|
39
|
+
/** The email check the renderer and the server share: one @, a dot in the domain, no spaces. */
|
|
40
|
+
export declare function isValidEmail(value: string): boolean;
|
|
41
|
+
/** A Saudi ID as stored (10 digits), or null when it isn't one this element accepts. */
|
|
42
|
+
export declare function normalizeSaudiId(raw: string, el: {
|
|
43
|
+
prefixes: string[];
|
|
44
|
+
checkDigit: boolean;
|
|
45
|
+
}): string | null;
|
|
46
|
+
/** 7 to 15 digits, optionally after a +, written with spaces, dashes, dots or brackets. */
|
|
47
|
+
export declare function isValidPhone(value: string): boolean;
|
|
48
|
+
/** The days a month has: Gregorian by the calendar, Hijri 30 (the 30th of a 29-day month fails the check). */
|
|
49
|
+
export declare function daysInMonth(calendar: FormCalendar, year: number, month: number): number;
|
|
50
|
+
/** Today's year in a calendar (for the year menu). */
|
|
51
|
+
export declare function currentYear(calendar: FormCalendar, now?: Date): number;
|
|
52
|
+
/** Month names in a language and calendar ("Muharram"... / "محرم"...), from the runtime; numbers when it has none. */
|
|
53
|
+
export declare function monthNames(locale: string, calendar: FormCalendar): string[];
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// The answer checks a form runs in the browser (FB-15), copied from @mycms/shared-types: this package can't depend on
|
|
2
|
+
// it, and the server runs the same checks again (its result decides). checks.spec.ts keeps the copies the same.
|
|
3
|
+
export const FORM_MOBILE_COUNTRIES = {
|
|
4
|
+
SA: { dial: "966", en: "Saudi Arabia", ar: "السعودية", pattern: /^5\d{8}$/, min: 9, max: 9 },
|
|
5
|
+
AE: { dial: "971", en: "United Arab Emirates", ar: "الإمارات", min: 7, max: 10 },
|
|
6
|
+
KW: { dial: "965", en: "Kuwait", ar: "الكويت", min: 7, max: 10 },
|
|
7
|
+
BH: { dial: "973", en: "Bahrain", ar: "البحرين", min: 7, max: 10 },
|
|
8
|
+
QA: { dial: "974", en: "Qatar", ar: "قطر", min: 7, max: 10 },
|
|
9
|
+
OM: { dial: "968", en: "Oman", ar: "عُمان", min: 7, max: 10 },
|
|
10
|
+
EG: { dial: "20", en: "Egypt", ar: "مصر", min: 7, max: 10 },
|
|
11
|
+
JO: { dial: "962", en: "Jordan", ar: "الأردن", min: 7, max: 10 },
|
|
12
|
+
PK: { dial: "92", en: "Pakistan", ar: "باكستان", min: 7, max: 10 },
|
|
13
|
+
IN: { dial: "91", en: "India", ar: "الهند", min: 7, max: 10 },
|
|
14
|
+
};
|
|
15
|
+
// ---- copied from shared-types (keep the same) ----
|
|
16
|
+
/** Western digits for Arabic-Indic and Persian ones ("١٢٣" -> "123"), so an ID typed on an Arabic keyboard counts. */
|
|
17
|
+
export function latinDigits(value) {
|
|
18
|
+
return value.replace(/[\u0660-\u0669]/g, (d) => String(d.charCodeAt(0) - 0x0660)).replace(/[\u06f0-\u06f9]/g, (d) => String(d.charCodeAt(0) - 0x06f0));
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Whether a Saudi ID's check digit is right (National ID and Iqama): from the left, digits in odd places are doubled
|
|
22
|
+
* and their digits added, the others added as they are; the total is a multiple of 10.
|
|
23
|
+
*/
|
|
24
|
+
export function saudiIdCheckDigitOk(id) {
|
|
25
|
+
if (!/^\d{10}$/.test(id))
|
|
26
|
+
return false;
|
|
27
|
+
let sum = 0;
|
|
28
|
+
for (let i = 0; i < 10; i++) {
|
|
29
|
+
const d = Number(id[i]);
|
|
30
|
+
if (i % 2 === 0) {
|
|
31
|
+
const x = d * 2;
|
|
32
|
+
sum += Math.floor(x / 10) + (x % 10);
|
|
33
|
+
}
|
|
34
|
+
else
|
|
35
|
+
sum += d;
|
|
36
|
+
}
|
|
37
|
+
return sum % 10 === 0;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A mobile number in E.164, or null when it isn't valid for its country: digits only, a leading 0 (or the country's
|
|
41
|
+
* own code) removed; Saudi numbers are 5 and 8 more digits.
|
|
42
|
+
*/
|
|
43
|
+
export function normalizeMobile(country, number) {
|
|
44
|
+
const c = FORM_MOBILE_COUNTRIES[country];
|
|
45
|
+
if (!c)
|
|
46
|
+
return null;
|
|
47
|
+
let n = latinDigits(number).replace(/[\s().-]/g, "");
|
|
48
|
+
if (n.startsWith("+"))
|
|
49
|
+
n = n.slice(1);
|
|
50
|
+
if (n.startsWith("00"))
|
|
51
|
+
n = n.slice(2);
|
|
52
|
+
if (n.startsWith(c.dial) && n.length > c.max)
|
|
53
|
+
n = n.slice(c.dial.length);
|
|
54
|
+
n = n.replace(/^0+/, "");
|
|
55
|
+
if (!/^\d+$/.test(n) || n.length < c.min || n.length > c.max)
|
|
56
|
+
return null;
|
|
57
|
+
if (c.pattern && !c.pattern.test(n))
|
|
58
|
+
return null;
|
|
59
|
+
return `+${c.dial}${n}`;
|
|
60
|
+
}
|
|
61
|
+
const umalquraParts = (() => {
|
|
62
|
+
let fmt;
|
|
63
|
+
return (date) => {
|
|
64
|
+
if (fmt === undefined) {
|
|
65
|
+
try {
|
|
66
|
+
fmt = new Intl.DateTimeFormat("en-u-ca-islamic-umalqura-nu-latn", { year: "numeric", month: "numeric", day: "numeric", timeZone: "UTC" });
|
|
67
|
+
if (fmt.resolvedOptions().calendar !== "islamic-umalqura")
|
|
68
|
+
fmt = null;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
fmt = null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (!fmt)
|
|
75
|
+
return null;
|
|
76
|
+
const parts = fmt.formatToParts(date);
|
|
77
|
+
const get = (t) => Number(parts.find((p) => p.type === t)?.value.replace(/\D/g, ""));
|
|
78
|
+
return { year: get("year"), month: get("month"), day: get("day") };
|
|
79
|
+
};
|
|
80
|
+
})();
|
|
81
|
+
/**
|
|
82
|
+
* The Gregorian date (UTC midnight) of a Hijri (Umm al-Qura) date, or null when that day doesn't exist (a 30th of a
|
|
83
|
+
* 29-day month) or the runtime has no Umm al-Qura calendar. Searches around the estimate: a Hijri year is about
|
|
84
|
+
* 354.37 days, and 1 Muharram 1 AH was 16 July 622.
|
|
85
|
+
*/
|
|
86
|
+
export function hijriToGregorian(year, month, day) {
|
|
87
|
+
if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(day) || month < 1 || month > 12 || day < 1 || day > 30)
|
|
88
|
+
return null;
|
|
89
|
+
const epoch = Date.UTC(622, 6, 16);
|
|
90
|
+
const estimate = epoch + ((year - 1) * 354.367 + (month - 1) * 29.53 + (day - 1)) * 86400000;
|
|
91
|
+
for (let off = -3; off <= 3; off++) {
|
|
92
|
+
const d = new Date(estimate + off * 86400000);
|
|
93
|
+
const p = umalquraParts(d);
|
|
94
|
+
if (!p)
|
|
95
|
+
return null;
|
|
96
|
+
if (p.year === year && p.month === month && p.day === day)
|
|
97
|
+
return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
/** Whole years from a date of birth to `now`. */
|
|
102
|
+
export function ageOn(birth, now) {
|
|
103
|
+
let age = now.getUTCFullYear() - birth.getUTCFullYear();
|
|
104
|
+
const m = now.getUTCMonth() - birth.getUTCMonth();
|
|
105
|
+
if (m < 0 || (m === 0 && now.getUTCDate() < birth.getUTCDate()))
|
|
106
|
+
age--;
|
|
107
|
+
return age;
|
|
108
|
+
}
|
|
109
|
+
/** A birth_date answer's Gregorian date, or null when it isn't a real date. */
|
|
110
|
+
export function calendarDateToGregorian(v) {
|
|
111
|
+
if (v.calendar === "hijri")
|
|
112
|
+
return hijriToGregorian(v.year, v.month, v.day);
|
|
113
|
+
const d = new Date(Date.UTC(v.year, v.month - 1, v.day));
|
|
114
|
+
if (v.year < 1800 || d.getUTCFullYear() !== v.year || d.getUTCMonth() !== v.month - 1 || d.getUTCDate() !== v.day)
|
|
115
|
+
return null;
|
|
116
|
+
return d;
|
|
117
|
+
}
|
|
118
|
+
/** The email check the renderer and the server share: one @, a dot in the domain, no spaces. */
|
|
119
|
+
export function isValidEmail(value) {
|
|
120
|
+
return value.length <= 254 && /^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/.test(value);
|
|
121
|
+
}
|
|
122
|
+
// ---- end of copies ----
|
|
123
|
+
/** A Saudi ID as stored (10 digits), or null when it isn't one this element accepts. */
|
|
124
|
+
export function normalizeSaudiId(raw, el) {
|
|
125
|
+
const v = latinDigits(raw).replace(/[\s-]/g, '');
|
|
126
|
+
if (!/^\d{10}$/.test(v) || !el.prefixes.includes(v[0]))
|
|
127
|
+
return null;
|
|
128
|
+
if (el.checkDigit && (v[0] === '1' || v[0] === '2') && !saudiIdCheckDigitOk(v))
|
|
129
|
+
return null;
|
|
130
|
+
return v;
|
|
131
|
+
}
|
|
132
|
+
/** 7 to 15 digits, optionally after a +, written with spaces, dashes, dots or brackets. */
|
|
133
|
+
export function isValidPhone(value) {
|
|
134
|
+
if (!/^\+?[0-9\s().-]+$/.test(value.trim()))
|
|
135
|
+
return false;
|
|
136
|
+
return /^\+?[0-9]{7,15}$/.test(value.trim().replace(/[\s().-]/g, ''));
|
|
137
|
+
}
|
|
138
|
+
/** The days a month has: Gregorian by the calendar, Hijri 30 (the 30th of a 29-day month fails the check). */
|
|
139
|
+
export function daysInMonth(calendar, year, month) {
|
|
140
|
+
if (calendar === 'hijri')
|
|
141
|
+
return hijriToGregorian(year, month, 30) ? 30 : year && month ? 29 : 30;
|
|
142
|
+
if (!year || !month)
|
|
143
|
+
return 31;
|
|
144
|
+
return new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
145
|
+
}
|
|
146
|
+
/** Today's year in a calendar (for the year menu). */
|
|
147
|
+
export function currentYear(calendar, now = new Date()) {
|
|
148
|
+
if (calendar === 'gregorian')
|
|
149
|
+
return now.getUTCFullYear();
|
|
150
|
+
return umalquraParts(now)?.year ?? Math.floor((now.getUTCFullYear() - 622) * 1.0307) + 1;
|
|
151
|
+
}
|
|
152
|
+
/** Month names in a language and calendar ("Muharram"... / "محرم"...), from the runtime; numbers when it has none. */
|
|
153
|
+
export function monthNames(locale, calendar) {
|
|
154
|
+
try {
|
|
155
|
+
const ca = calendar === 'hijri' ? 'islamic-umalqura' : 'gregory';
|
|
156
|
+
const fmt = new Intl.DateTimeFormat(`${locale}-u-ca-${ca}`, { month: 'long', timeZone: 'UTC' });
|
|
157
|
+
if (calendar === 'gregorian')
|
|
158
|
+
return Array.from({ length: 12 }, (_, i) => fmt.format(new Date(Date.UTC(2001, i, 15))));
|
|
159
|
+
// The 15th of each Hijri month of 1446.
|
|
160
|
+
return Array.from({ length: 12 }, (_, i) => {
|
|
161
|
+
const d = hijriToGregorian(1446, i + 1, 15);
|
|
162
|
+
return d ? fmt.format(d) : String(i + 1);
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return Array.from({ length: 12 }, (_, i) => String(i + 1));
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { type FormCalendar } from './checks.js';
|
|
2
|
+
export interface NativeFormChoice {
|
|
3
|
+
id: string;
|
|
4
|
+
label: string;
|
|
5
|
+
}
|
|
6
|
+
interface ElementBase<T extends string> {
|
|
7
|
+
id: string;
|
|
8
|
+
ref: string;
|
|
9
|
+
type: T;
|
|
10
|
+
title: string;
|
|
11
|
+
description: string;
|
|
12
|
+
required: boolean;
|
|
13
|
+
}
|
|
14
|
+
export type NativeFormElement = (ElementBase<'short_text' | 'long_text'> & {
|
|
15
|
+
placeholder: string;
|
|
16
|
+
minLength: number | null;
|
|
17
|
+
maxLength: number;
|
|
18
|
+
}) | (ElementBase<'email' | 'phone' | 'url'> & {
|
|
19
|
+
placeholder: string;
|
|
20
|
+
}) | (ElementBase<'number'> & {
|
|
21
|
+
placeholder: string;
|
|
22
|
+
min: number | null;
|
|
23
|
+
max: number | null;
|
|
24
|
+
integer: boolean;
|
|
25
|
+
}) | (ElementBase<'single_choice'> & {
|
|
26
|
+
choices: NativeFormChoice[];
|
|
27
|
+
}) | (ElementBase<'multiple_choice'> & {
|
|
28
|
+
choices: NativeFormChoice[];
|
|
29
|
+
minSelections: number | null;
|
|
30
|
+
maxSelections: number | null;
|
|
31
|
+
}) | (ElementBase<'dropdown'> & {
|
|
32
|
+
choices: NativeFormChoice[];
|
|
33
|
+
placeholder: string;
|
|
34
|
+
}) | ElementBase<'yes_no'> | ElementBase<'legal'> | (ElementBase<'saudi_id'> & {
|
|
35
|
+
placeholder: string;
|
|
36
|
+
prefixes: string[];
|
|
37
|
+
checkDigit: boolean;
|
|
38
|
+
}) | (ElementBase<'birth_date'> & {
|
|
39
|
+
calendars: FormCalendar[];
|
|
40
|
+
defaultCalendar: FormCalendar;
|
|
41
|
+
minAge: number | null;
|
|
42
|
+
maxAge: number | null;
|
|
43
|
+
/** compact: one field box, the title a small label, the menus in a row, the calendar a switch (1.12.1). */
|
|
44
|
+
display?: 'standard' | 'compact';
|
|
45
|
+
}) | (ElementBase<'mobile'> & {
|
|
46
|
+
placeholder: string;
|
|
47
|
+
countries: string[];
|
|
48
|
+
defaultCountry: string;
|
|
49
|
+
}) | ElementBase<'statement' | 'heading'>;
|
|
50
|
+
export type NativeFormElementType = NativeFormElement['type'];
|
|
51
|
+
/** The element types the native renderer draws; a form with any other is shown in its embed instead. */
|
|
52
|
+
export declare const NATIVE_ELEMENT_TYPES: readonly NativeFormElementType[];
|
|
53
|
+
export declare const FORM_LAYOUT_SUBMIT = "$submit";
|
|
54
|
+
export interface NativeLayoutRow {
|
|
55
|
+
id: string;
|
|
56
|
+
gap: number;
|
|
57
|
+
cells: Array<{
|
|
58
|
+
element: string;
|
|
59
|
+
width: number | null;
|
|
60
|
+
}>;
|
|
61
|
+
medium: number | null;
|
|
62
|
+
small: number | null;
|
|
63
|
+
submitFullWidth: boolean;
|
|
64
|
+
}
|
|
65
|
+
export type NativeFieldStyle = 'label' | 'placeholder' | 'floating';
|
|
66
|
+
export interface NativeFormDefinition {
|
|
67
|
+
mode: 'classic' | 'conversational';
|
|
68
|
+
locale: string;
|
|
69
|
+
elements: Array<NativeFormElement | (ElementBase<string> & Record<string, unknown>)>;
|
|
70
|
+
hiddenFields: Array<{
|
|
71
|
+
ref: string;
|
|
72
|
+
}>;
|
|
73
|
+
logic?: unknown[];
|
|
74
|
+
translations?: Record<string, Record<string, string>>;
|
|
75
|
+
layout?: {
|
|
76
|
+
rows: NativeLayoutRow[];
|
|
77
|
+
fieldStyle: NativeFieldStyle;
|
|
78
|
+
};
|
|
79
|
+
/** The send button's text, set on the form in the builder (translated as form.submit). */
|
|
80
|
+
submitLabel?: string;
|
|
81
|
+
/** What the visitor sees after sending a form that doesn't hand off. */
|
|
82
|
+
endings?: Array<{
|
|
83
|
+
id: string;
|
|
84
|
+
title: string;
|
|
85
|
+
description: string;
|
|
86
|
+
}>;
|
|
87
|
+
}
|
|
88
|
+
/** GET /public/v2/forms/:publicId, as the renderer needs it. */
|
|
89
|
+
export interface PublicForm {
|
|
90
|
+
publicId: string;
|
|
91
|
+
open: boolean;
|
|
92
|
+
closedMessage?: string;
|
|
93
|
+
closedReason?: string;
|
|
94
|
+
signInRequired?: boolean;
|
|
95
|
+
version?: number;
|
|
96
|
+
definition?: NativeFormDefinition;
|
|
97
|
+
settings?: {
|
|
98
|
+
redirectUrl?: string | null;
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** Why a form can't be drawn natively (and is shown in its embed instead), or null when it can. */
|
|
102
|
+
export declare function nativeProblem(def: NativeFormDefinition): string | null;
|
|
103
|
+
/** The form in `locale`: its text replaced by the translation wherever there is one (as localizeFormDefinition). */
|
|
104
|
+
export declare function localizeForm(def: NativeFormDefinition, locale: string): NativeFormDefinition;
|
|
105
|
+
/**
|
|
106
|
+
* The rows to draw, as formLayoutRows in shared-types: the layout's rows, then every element not placed in one, each on
|
|
107
|
+
* its own row, in form order; the submit button last unless a row has it.
|
|
108
|
+
*/
|
|
109
|
+
export declare function layoutRows(def: Pick<NativeFormDefinition, 'elements' | 'layout'>): NativeLayoutRow[];
|
|
110
|
+
/** CSS grid columns for a row: fixed cells in px, flexible ones share what's left (FB-10). */
|
|
111
|
+
export declare function gridColumns(row: NativeLayoutRow): string;
|
|
112
|
+
type N = (n: number) => string;
|
|
113
|
+
export interface NativeFormWords {
|
|
114
|
+
submit: string;
|
|
115
|
+
sending: string;
|
|
116
|
+
sendError: string;
|
|
117
|
+
chooseOption: string;
|
|
118
|
+
yes: string;
|
|
119
|
+
no: string;
|
|
120
|
+
day: string;
|
|
121
|
+
month: string;
|
|
122
|
+
year: string;
|
|
123
|
+
calendar: string;
|
|
124
|
+
gregorian: string;
|
|
125
|
+
hijri: string;
|
|
126
|
+
countryCode: string;
|
|
127
|
+
required: string;
|
|
128
|
+
errorsTitle: string;
|
|
129
|
+
messages: {
|
|
130
|
+
required: string;
|
|
131
|
+
requiredChoice: string;
|
|
132
|
+
mustAccept: string;
|
|
133
|
+
email: string;
|
|
134
|
+
phone: string;
|
|
135
|
+
url: string;
|
|
136
|
+
number: string;
|
|
137
|
+
integer: string;
|
|
138
|
+
min: N;
|
|
139
|
+
max: N;
|
|
140
|
+
minLength: N;
|
|
141
|
+
maxLength: N;
|
|
142
|
+
minSelections: N;
|
|
143
|
+
maxSelections: N;
|
|
144
|
+
choice: string;
|
|
145
|
+
saudiId: string;
|
|
146
|
+
mobile: string;
|
|
147
|
+
birthDate: string;
|
|
148
|
+
minAge: N;
|
|
149
|
+
maxAge: N;
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** The renderer's words in English or Arabic; other languages use English in the browser (the server's messages still come in the form's language). */
|
|
153
|
+
export declare function formWords(locale: string): NativeFormWords;
|
|
154
|
+
/** Right-to-left languages (FB-12). */
|
|
155
|
+
export declare function isRtl(locale: string): boolean;
|
|
156
|
+
/** What the visitor has entered, by element id, before it's checked. */
|
|
157
|
+
export type RawAnswer = string | boolean | string[] | {
|
|
158
|
+
country: string;
|
|
159
|
+
number: string;
|
|
160
|
+
} | {
|
|
161
|
+
calendar: FormCalendar;
|
|
162
|
+
year: string;
|
|
163
|
+
month: string;
|
|
164
|
+
day: string;
|
|
165
|
+
} | undefined;
|
|
166
|
+
/** One answer, checked as the server will (FB-15): the value to send, or the message to show under the field. */
|
|
167
|
+
export declare function checkAnswer(el: NativeFormElement, raw: RawAnswer, m: NativeFormWords['messages'], now?: Date): {
|
|
168
|
+
value?: unknown;
|
|
169
|
+
error: string | null;
|
|
170
|
+
};
|
|
171
|
+
/** Every answer, checked: the answers to send (by question ref, as the API takes them) and the errors to show (by element id, as it returns them). */
|
|
172
|
+
export declare function checkAnswers(def: NativeFormDefinition, raw: Record<string, RawAnswer>, words: NativeFormWords, now?: Date): {
|
|
173
|
+
answers: Record<string, unknown>;
|
|
174
|
+
errors: Record<string, string>;
|
|
175
|
+
};
|
|
176
|
+
/** The country menu's entries: the element's countries, in its order, with their dial codes. */
|
|
177
|
+
export declare function mobileCountries(el: Extract<NativeFormElement, {
|
|
178
|
+
type: 'mobile';
|
|
179
|
+
}>, locale: string): {
|
|
180
|
+
code: string;
|
|
181
|
+
dial: string;
|
|
182
|
+
name: string;
|
|
183
|
+
}[];
|
|
184
|
+
export {};
|