@veroxm/react-sdk 1.11.0 → 1.12.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/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.12.0
4
+
5
+ - `<VeroxmForm>` from `@veroxm/react-sdk/next` draws a form built in VeroXM's Forms natively in the page (no iframe):
6
+ server-rendered, styled only from design-system tokens (`--vx-field-height`, `--vx-field-radius`,
7
+ `--vx-field-border`, `--vx-color-focus`, `--vx-color-danger`, `--vx-button-height`, `--vx-button-primary-*`...),
8
+ mirrored in Arabic with logical properties while IDs, country codes and numbers stay left to right. Rows lay out as
9
+ the form's layout says (fixed px or flexible columns, a gap per row, column counts below 1100px and 640px).
10
+ Widgets: Saudi ID, date of birth (Gregorian / Hijri Umm al-Qura, month names from `Intl`), mobile with a country
11
+ code, text, email, phone, website, number, menus, single and multiple choice, yes / no, consent. About 9 kB gzipped.
12
+ - Answers are checked as the visitor leaves each field and all together on send, with the same checks VeroXM runs
13
+ (copied from it and kept the same by a test); errors sit under their field (`aria-invalid`, `aria-describedby`)
14
+ and focus moves to the first. VeroXM checks again and its answer decides.
15
+ - `context={{ product, line }}` is sent with the answers (with any `utm_*` in the address); a hand-off form then
16
+ takes the visitor to that product's journey. The same form keeps what was typed when the product changes.
17
+ - Sends go through the site's own route: `POST /api/veroxm/forms/:id/submit` (already mounted by
18
+ `export { POST } from '@veroxm/react-sdk/next/route'`) relays them with the server key and the visitor's address.
19
+ Without script the form still works as a plain post, redirecting to the journey. Same-site only (`X-VeroXM-Form`
20
+ header for JSON, `Origin` / `Sec-Fetch-Site` checked).
21
+ - `field.form()`: a slot field (and a list item field, so each tab or product can carry its own) holding one of the
22
+ project's published forms, chosen from a menu in the on-page editor.
23
+ - `VeroxmFormView` (any React app: pass the form you loaded) and `loadForm`, `localizeForm`, `nativeProblem`.
24
+
25
+ ## 1.11.1
26
+
27
+ - The editing bar no longer covers the slot panel's buttons. When the bar wraps to more rows (a narrow window,
28
+ longer Arabic words), the panel and the slot list end above it: their bottom follows the bar's measured height
29
+ (`ResizeObserver`), and they sit above the bar in stacking order. The interface language and Arabic digits are
30
+ one menu (English / العربية · 0123 / العربية · ٠١٢٣), and the project name hides in windows under 1000px, so the
31
+ bar stays one row where it can (863px wide: one row in English and Arabic).
32
+
3
33
  ## 1.11.0
4
34
 
5
35
  - The on-page editor in Arabic. Every word of the editor (the editing bar, the panel, buttons, messages, errors, empty
@@ -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
  }
@@ -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;
@@ -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}: تم التعرّف عليه.',
@@ -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;
@@ -394,11 +394,29 @@ function Overlay({ onChange, tools }) {
394
394
  document.documentElement.removeEventListener('mouseleave', onLeave);
395
395
  };
396
396
  }, [editMode, ended]);
397
+ // The bar can wrap (a narrow window, longer Arabic words): the panel and the slot list always end above it, so the
398
+ // bar never covers the panel's buttons. barSpace = from the bar's top edge to the bottom of the window.
399
+ const barRef = useRef(null);
400
+ const [barSpace, setBarSpace] = useState(64);
401
+ useEffect(() => {
402
+ const bar = barRef.current;
403
+ if (!bar)
404
+ return;
405
+ const measure = () => setBarSpace(Math.max(0, Math.ceil(window.innerHeight - bar.getBoundingClientRect().top)));
406
+ measure();
407
+ const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(measure) : null;
408
+ observer?.observe(bar);
409
+ window.addEventListener('resize', measure);
410
+ return () => {
411
+ observer?.disconnect();
412
+ window.removeEventListener('resize', measure);
413
+ };
414
+ }, []);
397
415
  const openEl = open ? slotElement(open.name, open.locale) : null;
398
416
  const hoverRect = hover && hover !== openEl ? rectOf(hover) : null;
399
417
  const openRect = rectOf(openEl);
400
418
  const fieldRect = openEl && highlightField ? rectOf(openEl.querySelector(`[data-veroxm-field="${CSS.escape(highlightField)}"]`)) : null;
401
- return (_jsx(Ui.Provider, { value: ui, children: _jsxs("div", { ref: rootRef, className: "vx-root", "data-veroxm-overlay": "", dir: ui.dir, lang: ui.lang, children: [_jsx("style", { children: STYLES + RICH_TEXT_STYLES + MENU_STYLES }), hoverRect && _jsx(Outline, { rect: hoverRect, label: hover ? elementLabel(ui, hover) : '' }), openRect && _jsx(Outline, { rect: openRect, active: true }), fieldRect && !inlineHint && _jsx(Outline, { rect: fieldRect, field: true }), inlineHint ? _jsx(InlineHintBar, { hint: inlineHint }) : null, open && session && !ended && (_jsx(SlotPanel, { slot: open, canPublish: session.canPublish, canManageTests: session.canManageTests ?? false, canUploadMedia: session.canUploadMedia ?? false, dashboardUrl: session.dashboardUrl ?? null, onClose: () => {
419
+ return (_jsx(Ui.Provider, { value: ui, children: _jsxs("div", { ref: rootRef, className: "vx-root", "data-veroxm-overlay": "", dir: ui.dir, lang: ui.lang, style: { '--vx-bar-space': `${barSpace}px` }, children: [_jsx("style", { children: STYLES + RICH_TEXT_STYLES + MENU_STYLES }), hoverRect && _jsx(Outline, { rect: hoverRect, label: hover ? elementLabel(ui, hover) : '' }), openRect && _jsx(Outline, { rect: openRect, active: true }), fieldRect && !inlineHint && _jsx(Outline, { rect: fieldRect, field: true }), inlineHint ? _jsx(InlineHintBar, { hint: inlineHint }) : null, open && session && !ended && (_jsx(SlotPanel, { slot: open, canPublish: session.canPublish, canManageTests: session.canManageTests ?? false, canUploadMedia: session.canUploadMedia ?? false, dashboardUrl: session.dashboardUrl ?? null, onClose: () => {
402
420
  setOpen(null);
403
421
  setHighlightField(null);
404
422
  }, onFieldFocus: setHighlightField, onSessionError: onSessionError, onChange: onChange, onInline: setInlineHint }, `${open.name}|${open.locale}`)), listOpen && (_jsx(SlotList, { onPick: (s) => {
@@ -408,7 +426,17 @@ function Overlay({ onChange, tools }) {
408
426
  }, onClose: () => {
409
427
  setListOpen(false);
410
428
  listToggleRef.current?.focus();
411
- } })), _jsxs("div", { className: "vx-toolbar", role: "toolbar", "aria-label": ui.t('bar.aria'), dir: ui.dir, lang: ui.lang, children: [_jsxs("span", { className: "vx-brand", children: [_jsx("span", { className: "vx-dot", "aria-hidden": "true" }), ended ? ui.t('bar.ended') : ui.t('bar.editing'), session?.projectName ? (_jsxs("span", { className: "vx-muted", children: [' · ', _jsx("bdi", { children: session.projectName })] })) : null] }), ended ? (_jsx("span", { className: "vx-muted vx-ended", role: "alert", children: ended })) : (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "vx-btn", "aria-pressed": editMode, onClick: () => setEditMode((v) => !v), children: editMode ? ui.t('bar.clickOn') : ui.t('bar.clickOff') }), _jsx("button", { type: "button", ref: listToggleRef, className: "vx-btn", "data-vx-list-toggle": "", "aria-expanded": listOpen, onClick: () => setListOpen((v) => !v), children: ui.t('bar.slots') }), tools] })), _jsx("select", { className: "vx-lang", "aria-label": ui.t('bar.language'), value: ui.lang, onChange: (e) => savePrefs({ ...prefs, language: editorLang(e.target.value) ?? 'en' }), children: EDITOR_LANGS.map((l) => (_jsx("option", { value: l, lang: l, children: LANG_NAMES[l] }, l))) }), ui.lang === 'ar' ? (_jsxs("select", { className: "vx-lang", "aria-label": ui.t('bar.digits'), value: ui.digits, onChange: (e) => savePrefs({ ...prefs, digits: e.target.value === 'arab' ? 'arab' : 'latn' }), children: [_jsx("option", { value: "latn", children: ui.t('bar.digitsLatn') }), _jsx("option", { value: "arab", children: ui.t('bar.digitsArab') })] })) : null, _jsx("button", { type: "button", className: "vx-btn", onClick: () => transport.exit(), children: ui.t('bar.exit') })] })] }) }));
429
+ } })), _jsxs("div", { ref: barRef, className: "vx-toolbar", role: "toolbar", "aria-label": ui.t('bar.aria'), dir: ui.dir, lang: ui.lang, children: [_jsxs("span", { className: "vx-brand", children: [_jsx("span", { className: "vx-dot", "aria-hidden": "true" }), ended ? ui.t('bar.ended') : ui.t('bar.editing'), session?.projectName ? (_jsxs("span", { className: "vx-muted vx-project", title: session.projectName, children: [' · ', _jsx("bdi", { children: session.projectName })] })) : null] }), ended ? (_jsx("span", { className: "vx-muted vx-ended", role: "alert", children: ended })) : (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "vx-btn", "aria-pressed": editMode, onClick: () => setEditMode((v) => !v), children: editMode ? ui.t('bar.clickOn') : ui.t('bar.clickOff') }), _jsx("button", { type: "button", ref: listToggleRef, className: "vx-btn", "data-vx-list-toggle": "", "aria-expanded": listOpen, onClick: () => setListOpen((v) => !v), children: ui.t('bar.slots') }), tools] })), _jsx("select", { className: "vx-lang", "aria-label": ui.t('bar.language'), title: ui.t('bar.language'), value: ui.lang === 'ar' ? `ar-${ui.digits}` : ui.lang, onChange: (e) => {
430
+ const [language, digits] = e.target.value.split('-');
431
+ savePrefs({ language: editorLang(language) ?? 'en', digits: digits === 'arab' ? 'arab' : digits === 'latn' ? 'latn' : prefs.digits });
432
+ }, children: EDITOR_LANGS.flatMap((l) => l === 'ar'
433
+ ? [
434
+ _jsxs("option", { value: "ar-latn", lang: "ar", "aria-label": `${LANG_NAMES.ar} – ${ui.t('bar.digitsLatn')}`, children: [LANG_NAMES.ar, " \u00B7 0123"] }, "ar-latn"),
435
+ _jsxs("option", { value: "ar-arab", lang: "ar", "aria-label": `${LANG_NAMES.ar} – ${ui.t('bar.digitsArab')}`, children: [LANG_NAMES.ar, " \u00B7 \u0660\u0661\u0662\u0663"] }, "ar-arab"),
436
+ ]
437
+ : [
438
+ _jsx("option", { value: l, lang: l, children: LANG_NAMES[l] }, l),
439
+ ]) }), _jsx("button", { type: "button", className: "vx-btn", onClick: () => transport.exit(), children: ui.t('bar.exit') })] })] }) }));
412
440
  }
413
441
  /** A slot's name on the page, in the interface language (data-veroxm-labels), else its one label, else its name. */
414
442
  function elementLabel(ui, el) {
@@ -838,6 +866,8 @@ function FieldInput({ name, def, value, shown, fallback, onChange, onFocus, }) {
838
866
  return _jsx(VideoInput, { name: name, def: def, value: value, onChange: onChange, onFocus: onFocus });
839
867
  case 'chart':
840
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 });
841
871
  case 'map':
842
872
  return _jsx(MapInput, { name: name, def: def, value: value, onChange: onChange, onFocus: onFocus });
843
873
  case 'slides':
@@ -878,6 +908,29 @@ function ComponentInput({ name, def, value, fallback, onChange, onFocus }) {
878
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}`)))
879
909
  : null] }));
880
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
+ }
881
934
  function VideoInput({ name, def, value, onChange, onFocus }) {
882
935
  const ui = useUi();
883
936
  const id = useId();
@@ -1130,17 +1183,20 @@ const STYLES = `
1130
1183
  .vx-tag{position:absolute;top:-24px;inset-inline-start:-2px;background:#6d28d9;color:#fff;font-size:12px;padding:2px 8px;border-radius:4px;white-space:nowrap}
1131
1184
  .vx-toolbar{position:fixed;z-index:2147483002;left:50%;bottom:16px;transform:translateX(-50%);width:max-content;display:flex;flex-wrap:wrap;align-items:center;gap:8px;max-width:calc(100vw - 32px);background:#18181b;color:#fafafa;padding:8px 10px;border-radius:12px;box-shadow:0 8px 30px rgba(0,0,0,.3)}
1132
1185
  .vx-toolbar .vx-muted{color:#a1a1aa}
1133
- .vx-brand{display:flex;align-items:center;gap:6px;font-weight:600;padding:0 4px}
1186
+ .vx-brand{display:flex;align-items:center;gap:6px;font-weight:600;padding:0 4px;white-space:nowrap;min-width:0}
1187
+ .vx-project{max-width:10rem;overflow:hidden;text-overflow:ellipsis}
1188
+ .vx-toolbar .vx-btn{white-space:nowrap}
1189
+ @media (max-width:1000px){.vx-project{display:none}}
1134
1190
  .vx-dot{width:8px;height:8px;border-radius:50%;background:#a78bfa}
1135
1191
  .vx-ended{max-width:28rem}
1136
1192
  .vx-btn{appearance:none;cursor:pointer;display:inline-flex;align-items:center;min-height:32px;padding:4px 12px;border-radius:8px;border:1px solid #d4d4d8;background:#fff;color:#18181b;text-decoration:none}
1137
1193
  .vx-toolbar .vx-btn{background:#27272a;border-color:#3f3f46;color:#fafafa}
1138
1194
  .vx-toolbar .vx-btn[aria-pressed="true"]{background:#4c1d95;border-color:#6d28d9}
1139
- .vx-lang{appearance:auto;min-height:32px;padding:4px 8px;border-radius:8px;border:1px solid #3f3f46;background:#27272a;color:#fafafa;cursor:pointer}
1195
+ .vx-lang{appearance:auto;min-height:32px;max-width:9.5rem;padding:4px 8px;border-radius:8px;border:1px solid #3f3f46;background:#27272a;color:#fafafa;cursor:pointer}
1140
1196
  .vx-btn:disabled{opacity:.5;cursor:not-allowed}
1141
1197
  .vx-primary{background:#6d28d9;border-color:#6d28d9;color:#fff}
1142
1198
  .vx-root :focus-visible{outline:2px solid #f59e0b;outline-offset:2px}
1143
- .vx-panel{position:fixed;z-index:2147483001;top:12px;inset-inline-end:12px;bottom:76px;width:min(380px,calc(100vw - 24px));display:flex;flex-direction:column;background:#fff;border:1px solid #e4e4e7;border-radius:14px;box-shadow:0 12px 40px rgba(0,0,0,.18)}
1199
+ .vx-panel{position:fixed;z-index:2147483003;top:12px;inset-inline-end:12px;bottom:calc(var(--vx-bar-space,64px) + 12px);max-height:calc(100vh - var(--vx-bar-space,64px) - 24px);width:min(380px,calc(100vw - 24px));display:flex;flex-direction:column;background:#fff;border:1px solid #e4e4e7;border-radius:14px;box-shadow:0 12px 40px rgba(0,0,0,.18)}
1144
1200
  .vx-panel-head{display:flex;justify-content:space-between;gap:8px;padding:14px 16px;border-bottom:1px solid #f4f4f5}
1145
1201
  .vx-panel-head h2{margin:0;font-size:16px;font-weight:650}
1146
1202
  .vx-panel-head p{margin:2px 0 0}
@@ -1179,7 +1235,7 @@ const STYLES = `
1179
1235
  .vx-review-title{margin:0;font-weight:600}
1180
1236
  .vx-review-comment{width:100%;padding:6px 8px;border:1px solid #d4d4d8;border-radius:8px;background:#fff;resize:vertical}
1181
1237
  .vx-review-withdraw{align-self:flex-start;margin-top:4px}
1182
- .vx-list{position:fixed;z-index:2147483002;left:50%;bottom:70px;transform:translateX(-50%);width:min(360px,calc(100vw - 24px));max-height:50vh;overflow:auto;background:#fff;border:1px solid #e4e4e7;border-radius:12px;box-shadow:0 12px 40px rgba(0,0,0,.18);padding:10px}
1238
+ .vx-list{position:fixed;z-index:2147483003;left:50%;bottom:calc(var(--vx-bar-space,64px) + 8px);transform:translateX(-50%);width:min(360px,calc(100vw - 24px));max-height:50vh;overflow:auto;background:#fff;border:1px solid #e4e4e7;border-radius:12px;box-shadow:0 12px 40px rgba(0,0,0,.18);padding:10px}
1183
1239
  .vx-list-title{font-weight:650;margin:0 0 6px}
1184
1240
  .vx-list ul{list-style:none;margin:0;padding:0}
1185
1241
  .vx-list button{appearance:none;cursor:pointer;width:100%;text-align:start;border:0;background:transparent;padding:8px;border-radius:8px;display:flex;gap:6px;align-items:baseline;flex-wrap:wrap}
@@ -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,180 @@
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
+ }) | (ElementBase<'mobile'> & {
44
+ placeholder: string;
45
+ countries: string[];
46
+ defaultCountry: string;
47
+ }) | ElementBase<'statement' | 'heading'>;
48
+ export type NativeFormElementType = NativeFormElement['type'];
49
+ /** The element types the native renderer draws; a form with any other is shown in its embed instead. */
50
+ export declare const NATIVE_ELEMENT_TYPES: readonly NativeFormElementType[];
51
+ export declare const FORM_LAYOUT_SUBMIT = "$submit";
52
+ export interface NativeLayoutRow {
53
+ id: string;
54
+ gap: number;
55
+ cells: Array<{
56
+ element: string;
57
+ width: number | null;
58
+ }>;
59
+ medium: number | null;
60
+ small: number | null;
61
+ submitFullWidth: boolean;
62
+ }
63
+ export type NativeFieldStyle = 'label' | 'placeholder' | 'floating';
64
+ export interface NativeFormDefinition {
65
+ mode: 'classic' | 'conversational';
66
+ locale: string;
67
+ elements: Array<NativeFormElement | (ElementBase<string> & Record<string, unknown>)>;
68
+ hiddenFields: Array<{
69
+ ref: string;
70
+ }>;
71
+ logic?: unknown[];
72
+ translations?: Record<string, Record<string, string>>;
73
+ layout?: {
74
+ rows: NativeLayoutRow[];
75
+ fieldStyle: NativeFieldStyle;
76
+ };
77
+ /** What the visitor sees after sending a form that doesn't hand off. */
78
+ endings?: Array<{
79
+ id: string;
80
+ title: string;
81
+ description: string;
82
+ }>;
83
+ }
84
+ /** GET /public/v2/forms/:publicId, as the renderer needs it. */
85
+ export interface PublicForm {
86
+ publicId: string;
87
+ open: boolean;
88
+ closedMessage?: string;
89
+ closedReason?: string;
90
+ signInRequired?: boolean;
91
+ version?: number;
92
+ definition?: NativeFormDefinition;
93
+ settings?: {
94
+ redirectUrl?: string | null;
95
+ };
96
+ }
97
+ /** Why a form can't be drawn natively (and is shown in its embed instead), or null when it can. */
98
+ export declare function nativeProblem(def: NativeFormDefinition): string | null;
99
+ /** The form in `locale`: its text replaced by the translation wherever there is one (as localizeFormDefinition). */
100
+ export declare function localizeForm(def: NativeFormDefinition, locale: string): NativeFormDefinition;
101
+ /**
102
+ * The rows to draw, as formLayoutRows in shared-types: the layout's rows, then every element not placed in one, each on
103
+ * its own row, in form order; the submit button last unless a row has it.
104
+ */
105
+ export declare function layoutRows(def: Pick<NativeFormDefinition, 'elements' | 'layout'>): NativeLayoutRow[];
106
+ /** CSS grid columns for a row: fixed cells in px, flexible ones share what's left (FB-10). */
107
+ export declare function gridColumns(row: NativeLayoutRow): string;
108
+ type N = (n: number) => string;
109
+ export interface NativeFormWords {
110
+ submit: string;
111
+ sending: string;
112
+ sendError: string;
113
+ chooseOption: string;
114
+ yes: string;
115
+ no: string;
116
+ day: string;
117
+ month: string;
118
+ year: string;
119
+ calendar: string;
120
+ gregorian: string;
121
+ hijri: string;
122
+ countryCode: string;
123
+ required: string;
124
+ errorsTitle: string;
125
+ messages: {
126
+ required: string;
127
+ requiredChoice: string;
128
+ mustAccept: string;
129
+ email: string;
130
+ phone: string;
131
+ url: string;
132
+ number: string;
133
+ integer: string;
134
+ min: N;
135
+ max: N;
136
+ minLength: N;
137
+ maxLength: N;
138
+ minSelections: N;
139
+ maxSelections: N;
140
+ choice: string;
141
+ saudiId: string;
142
+ mobile: string;
143
+ birthDate: string;
144
+ minAge: N;
145
+ maxAge: N;
146
+ };
147
+ }
148
+ /** 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). */
149
+ export declare function formWords(locale: string): NativeFormWords;
150
+ /** Right-to-left languages (FB-12). */
151
+ export declare function isRtl(locale: string): boolean;
152
+ /** What the visitor has entered, by element id, before it's checked. */
153
+ export type RawAnswer = string | boolean | string[] | {
154
+ country: string;
155
+ number: string;
156
+ } | {
157
+ calendar: FormCalendar;
158
+ year: string;
159
+ month: string;
160
+ day: string;
161
+ } | undefined;
162
+ /** One answer, checked as the server will (FB-15): the value to send, or the message to show under the field. */
163
+ export declare function checkAnswer(el: NativeFormElement, raw: RawAnswer, m: NativeFormWords['messages'], now?: Date): {
164
+ value?: unknown;
165
+ error: string | null;
166
+ };
167
+ /** 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). */
168
+ export declare function checkAnswers(def: NativeFormDefinition, raw: Record<string, RawAnswer>, words: NativeFormWords, now?: Date): {
169
+ answers: Record<string, unknown>;
170
+ errors: Record<string, string>;
171
+ };
172
+ /** The country menu's entries: the element's countries, in its order, with their dial codes. */
173
+ export declare function mobileCountries(el: Extract<NativeFormElement, {
174
+ type: 'mobile';
175
+ }>, locale: string): {
176
+ code: string;
177
+ dial: string;
178
+ name: string;
179
+ }[];
180
+ export {};