@jay-framework/wix-bookings 0.25.5 → 0.26.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.
@@ -1,7 +1,7 @@
1
1
  import { makeJayInit, makeJayStackComponent } from "@jay-framework/fullstack-component";
2
2
  import { createJayContext, useGlobalContext, registerGlobalContext } from "@jay-framework/runtime";
3
- import { wixFetch, WixApiError, WIX_CLIENT_CONTEXT } from "@jay-framework/wix-server-client/client";
4
- import { createSignal } from "@jay-framework/component";
3
+ import { wixFetch, WixApiError, WIX_CLIENT_CONTEXT, ensureSessionFresh } from "@jay-framework/wix-server-client/client";
4
+ import { createSignal, createEffect, useReactive } from "@jay-framework/component";
5
5
  import { createActionCaller } from "@jay-framework/stack-client-runtime";
6
6
  const MAX_SLOTS_PER_QUERY = 200;
7
7
  const SERVICES_PAGE_SIZE = 100;
@@ -45,6 +45,11 @@ async function getBookingServiceById(client, serviceId) {
45
45
  });
46
46
  return result.services?.[0];
47
47
  }
48
+ const DEFAULT_FORM_ID = "00000000-0000-0000-0000-000000000000";
49
+ function participantFormId(form) {
50
+ const id = form?.id ?? form?._id ?? "";
51
+ return id === DEFAULT_FORM_ID ? "" : id;
52
+ }
48
53
  function formatPrice(service) {
49
54
  const price = service.payment?.fixed?.price;
50
55
  if (!price?.value) {
@@ -69,7 +74,7 @@ function mapService(raw) {
69
74
  description: raw.description ?? "",
70
75
  priceLabel: formatPrice(raw),
71
76
  durationLabel: duration,
72
- formId: raw.form?._id ?? ""
77
+ formId: participantFormId(raw.form)
73
78
  };
74
79
  }
75
80
  function createSlotId(resourceId, localStartDate) {
@@ -472,6 +477,34 @@ function provideWixBookingsContext(config) {
472
477
  const init = makeJayInit().withClient(async ({ config }) => {
473
478
  provideWixBookingsContext(config);
474
479
  });
480
+ var ServicesFailure = /* @__PURE__ */ ((ServicesFailure2) => {
481
+ ServicesFailure2[ServicesFailure2["NONE"] = 0] = "NONE";
482
+ ServicesFailure2[ServicesFailure2["PERMISSION"] = 1] = "PERMISSION";
483
+ ServicesFailure2[ServicesFailure2["UNKNOWN"] = 2] = "UNKNOWN";
484
+ return ServicesFailure2;
485
+ })(ServicesFailure || {});
486
+ var SlotsFailure = /* @__PURE__ */ ((SlotsFailure2) => {
487
+ SlotsFailure2[SlotsFailure2["NONE"] = 0] = "NONE";
488
+ SlotsFailure2[SlotsFailure2["UNKNOWN"] = 1] = "UNKNOWN";
489
+ return SlotsFailure2;
490
+ })(SlotsFailure || {});
491
+ var BookingState = /* @__PURE__ */ ((BookingState2) => {
492
+ BookingState2[BookingState2["IDLE"] = 0] = "IDLE";
493
+ BookingState2[BookingState2["BOOKING"] = 1] = "BOOKING";
494
+ BookingState2[BookingState2["CONFIRMED"] = 2] = "CONFIRMED";
495
+ BookingState2[BookingState2["FAILED"] = 3] = "FAILED";
496
+ return BookingState2;
497
+ })(BookingState || {});
498
+ var BookingFailure = /* @__PURE__ */ ((BookingFailure2) => {
499
+ BookingFailure2[BookingFailure2["NONE"] = 0] = "NONE";
500
+ BookingFailure2[BookingFailure2["VALIDATION"] = 1] = "VALIDATION";
501
+ BookingFailure2[BookingFailure2["FORM_UNAVAILABLE"] = 2] = "FORM_UNAVAILABLE";
502
+ BookingFailure2[BookingFailure2["CHECKOUT_PERMISSION"] = 3] = "CHECKOUT_PERMISSION";
503
+ BookingFailure2[BookingFailure2["CHECKOUT_REDIRECT_REJECTED"] = 4] = "CHECKOUT_REDIRECT_REJECTED";
504
+ BookingFailure2[BookingFailure2["SITE_NOT_PUBLISHED"] = 5] = "SITE_NOT_PUBLISHED";
505
+ BookingFailure2[BookingFailure2["UNKNOWN"] = 6] = "UNKNOWN";
506
+ return BookingFailure2;
507
+ })(BookingFailure || {});
475
508
  const listServices = createActionCaller("wixBookings.listServices", "GET");
476
509
  const listSlots = createActionCaller("wixBookings.listSlots", "GET");
477
510
  const createBooking = createActionCaller("wixBookings.createBooking", "POST");
@@ -503,7 +536,14 @@ function validateFormSummaryField(field, value) {
503
536
  return "";
504
537
  }
505
538
  function validateFormField(field, value) {
506
- const trimmed = (value ?? "").trim();
539
+ if (field.inputType === "checkbox") {
540
+ return field.required && value !== true ? `${field.label} is required.` : "";
541
+ }
542
+ if (field.inputType === "multiselect") {
543
+ const empty = !Array.isArray(value) || value.length === 0;
544
+ return field.required && empty ? `${field.label} is required.` : "";
545
+ }
546
+ const trimmed = (typeof value === "string" ? value : "").trim();
507
547
  if (field.required && !trimmed) {
508
548
  return `${field.label} is required.`;
509
549
  }
@@ -536,127 +576,618 @@ function validateFormField(field, value) {
536
576
  }
537
577
  return "";
538
578
  }
539
- function parseSubmissionFieldErrors(responseBody) {
540
- try {
541
- const parsed = JSON.parse(responseBody);
542
- const fieldErrors = {};
543
- const violations = parsed.details?.validationError?.fieldViolations ?? [];
544
- for (const violation of violations) {
545
- for (const fieldError of violation.data?.errors ?? []) {
546
- if (fieldError.errorPath && !fieldErrors[fieldError.errorPath]) {
547
- fieldErrors[fieldError.errorPath] = fieldError.errorMessage ?? "Invalid value";
548
- }
549
- }
579
+ const SUBMIT_FAILED_MESSAGE = "We could not complete your request. Please try again.";
580
+ var SubmitState = /* @__PURE__ */ ((SubmitState2) => {
581
+ SubmitState2[SubmitState2["IDLE"] = 0] = "IDLE";
582
+ SubmitState2[SubmitState2["SUBMITTING"] = 1] = "SUBMITTING";
583
+ SubmitState2[SubmitState2["SUCCEEDED"] = 2] = "SUCCEEDED";
584
+ SubmitState2[SubmitState2["FAILED"] = 3] = "FAILED";
585
+ return SubmitState2;
586
+ })(SubmitState || {});
587
+ var SubmitFailure = /* @__PURE__ */ ((SubmitFailure2) => {
588
+ SubmitFailure2[SubmitFailure2["NONE"] = 0] = "NONE";
589
+ SubmitFailure2[SubmitFailure2["VALIDATION"] = 1] = "VALIDATION";
590
+ SubmitFailure2[SubmitFailure2["REJECTED"] = 2] = "REJECTED";
591
+ SubmitFailure2[SubmitFailure2["PERMISSION"] = 3] = "PERMISSION";
592
+ SubmitFailure2[SubmitFailure2["NETWORK"] = 4] = "NETWORK";
593
+ SubmitFailure2[SubmitFailure2["UNKNOWN"] = 5] = "UNKNOWN";
594
+ return SubmitFailure2;
595
+ })(SubmitFailure || {});
596
+ function presentSubmitRejection(result, fields) {
597
+ const view = { errorByTarget: {}, invalidByTarget: {}, statusMessage: "" };
598
+ const statusLines = result.message ? [result.message] : [];
599
+ for (const [target, message] of Object.entries(result.fieldErrors ?? {})) {
600
+ const field = fields.find((candidate) => candidate.target === target);
601
+ if (field && !field.hidden) {
602
+ view.errorByTarget[target] = message;
603
+ view.invalidByTarget[target] = true;
604
+ } else {
605
+ statusLines.push(`${field?.label || target}: ${message}`);
550
606
  }
551
- return fieldErrors;
607
+ }
608
+ view.statusMessage = statusLines.join(" ");
609
+ if (!view.statusMessage && !Object.keys(view.errorByTarget).length) {
610
+ view.statusMessage = SUBMIT_FAILED_MESSAGE;
611
+ }
612
+ return view;
613
+ }
614
+ const PROBE_ORIGIN = "https://site.invalid";
615
+ function toSitePath(candidate) {
616
+ if (typeof candidate !== "string" || !candidate.startsWith("/") || /[\u0000-\u001F\u007F\\]/.test(candidate)) {
617
+ return void 0;
618
+ }
619
+ try {
620
+ const url = new URL(candidate, PROBE_ORIGIN);
621
+ if (url.origin !== PROBE_ORIGIN) return void 0;
622
+ const path = url.pathname + url.search + url.hash;
623
+ return path.startsWith("//") ? void 0 : path;
552
624
  } catch {
553
- return {};
625
+ return void 0;
626
+ }
627
+ }
628
+ function emptyValueFor(field) {
629
+ if (field.inputType === "checkbox") return false;
630
+ if (field.inputType === "multiselect") return [];
631
+ return "";
632
+ }
633
+ function projectSubmissionValues(fields, store) {
634
+ const values = {};
635
+ for (const field of fields) {
636
+ values[field.target] = field.target in store ? store[field.target] : emptyValueFor(field);
637
+ }
638
+ return values;
639
+ }
640
+ function emptyStoreFor(fields) {
641
+ const store = {};
642
+ for (const field of fields) {
643
+ store[field.target] = emptyValueFor(field);
644
+ }
645
+ return store;
646
+ }
647
+ function toggleSelection(field, { current, optionValue, checked }) {
648
+ const selected = new Set(Array.isArray(current) ? current : []);
649
+ if (checked) selected.add(optionValue);
650
+ else selected.delete(optionValue);
651
+ return field.options.map((option) => option.value).filter((value) => selected.has(value));
652
+ }
653
+ function seedControlValues(store, seeds) {
654
+ const seeded = { ...store };
655
+ for (const { target, value, dirty } of seeds) {
656
+ if (dirty || target in seeded || !hasValue(value)) {
657
+ continue;
658
+ }
659
+ seeded[target] = value;
660
+ }
661
+ return seeded;
662
+ }
663
+ function hasValue(value) {
664
+ if (typeof value === "string") return value.length > 0;
665
+ if (Array.isArray(value)) return value.length > 0;
666
+ return value === true;
667
+ }
668
+ function validateVisibleFields(fields, values) {
669
+ const errors = {};
670
+ for (const field of fields) {
671
+ if (field.hidden) continue;
672
+ const message = validateFormField(field, values[field.target] ?? emptyValueFor(field));
673
+ if (message) errors[field.target] = message;
554
674
  }
675
+ return errors;
676
+ }
677
+ var __assign = function() {
678
+ __assign = Object.assign || function __assign2(t) {
679
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
680
+ s = arguments[i];
681
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
682
+ }
683
+ return t;
684
+ };
685
+ return __assign.apply(this, arguments);
686
+ };
687
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
688
+ var e = new Error(message);
689
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
690
+ };
691
+ function lowerCase(str) {
692
+ return str.toLowerCase();
693
+ }
694
+ var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
695
+ var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
696
+ function noCase(input, options) {
697
+ if (options === void 0) {
698
+ options = {};
699
+ }
700
+ var _a = options.splitRegexp, splitRegexp = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a, _b = options.stripRegexp, stripRegexp = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b, _c = options.transform, transform = _c === void 0 ? lowerCase : _c, _d = options.delimiter, delimiter = _d === void 0 ? " " : _d;
701
+ var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
702
+ var start = 0;
703
+ var end = result.length;
704
+ while (result.charAt(start) === "\0")
705
+ start++;
706
+ while (result.charAt(end - 1) === "\0")
707
+ end--;
708
+ return result.slice(start, end).split("\0").map(transform).join(delimiter);
709
+ }
710
+ function replace(input, re, value) {
711
+ if (re instanceof RegExp)
712
+ return input.replace(re, value);
713
+ return re.reduce(function(input2, re2) {
714
+ return input2.replace(re2, value);
715
+ }, input);
716
+ }
717
+ function pascalCaseTransform(input, index) {
718
+ var firstChar = input.charAt(0);
719
+ var lowerChars = input.substr(1).toLowerCase();
720
+ if (index > 0 && firstChar >= "0" && firstChar <= "9") {
721
+ return "_" + firstChar + lowerChars;
722
+ }
723
+ return "" + firstChar.toUpperCase() + lowerChars;
724
+ }
725
+ function pascalCase(input, options) {
726
+ if (options === void 0) {
727
+ options = {};
728
+ }
729
+ return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options));
730
+ }
731
+ function camelCaseTransform(input, index) {
732
+ if (index === 0)
733
+ return input.toLowerCase();
734
+ return pascalCaseTransform(input, index);
555
735
  }
556
- function toContractFields(fields) {
557
- return fields.map((field) => ({
558
- target: field.target,
736
+ function camelCase$1(input, options) {
737
+ if (options === void 0) {
738
+ options = {};
739
+ }
740
+ return pascalCase(input, __assign({ transform: camelCaseTransform }, options));
741
+ }
742
+ function camelCase(value) {
743
+ let leadingUnderscores = 0;
744
+ for (const char of value) {
745
+ if (char === "_") leadingUnderscores++;
746
+ else break;
747
+ }
748
+ if (leadingUnderscores === 0) return camelCase$1(value);
749
+ const withoutLeadingUnderscores = value.slice(leadingUnderscores);
750
+ return "_".repeat(leadingUnderscores) + camelCase$1(withoutLeadingUnderscores);
751
+ }
752
+ const RESERVED_TAG_NAMES = /* @__PURE__ */ new Set([
753
+ "isLoading",
754
+ "loadError",
755
+ "isSubmitting",
756
+ "isSubmitted",
757
+ "statusMessage",
758
+ "submitState",
759
+ "submitFailure",
760
+ "submitButton",
761
+ "resetButton",
762
+ "honeypot",
763
+ "confirmation"
764
+ ]);
765
+ function contractTagName(target) {
766
+ const name = camelCase(target);
767
+ return RESERVED_TAG_NAMES.has(name) ? `${name}Field` : name;
768
+ }
769
+ function fieldToViewState(field, state) {
770
+ const viewState = {
559
771
  label: field.label,
560
- inputType: field.inputType,
561
- isTextarea: field.inputType === "textarea",
562
772
  required: field.required,
563
- placeholder: field.placeholder,
564
- hasOptions: field.options.length > 0
565
- }));
773
+ error: state.error,
774
+ invalid: state.invalid
775
+ };
776
+ if (field.inputType === "checkbox") {
777
+ viewState.value = state.value === true;
778
+ } else if (field.inputType === "select" || field.inputType === "multiselect") {
779
+ const selectedValues = Array.isArray(state.value) ? state.value : [];
780
+ viewState.options = field.options.map((option) => {
781
+ const optionView = {
782
+ value: option.value,
783
+ label: option.label
784
+ };
785
+ if (field.inputType === "multiselect") {
786
+ optionView.selected = selectedValues.includes(option.value);
787
+ }
788
+ return optionView;
789
+ });
790
+ } else {
791
+ viewState.placeholder = field.placeholder;
792
+ viewState.value = typeof state.value === "string" ? state.value : "";
793
+ }
794
+ return viewState;
566
795
  }
567
- function WixFormInteractive(props, refs, viewStateSignals, carryForward) {
796
+ function buildFieldsViewState(fields, errorByTarget = {}, invalidByTarget = {}, valueByTarget = {}) {
797
+ const viewState = {};
798
+ for (const field of fields) {
799
+ viewState[contractTagName(field.target)] = fieldToViewState(field, {
800
+ error: errorByTarget[field.target] ?? "",
801
+ invalid: invalidByTarget[field.target] ?? false,
802
+ value: valueByTarget[field.target] ?? ""
803
+ });
804
+ }
805
+ return viewState;
806
+ }
807
+ function buildFormViewState(fields, overrides) {
808
+ return {
809
+ ...buildFieldsViewState(
810
+ fields,
811
+ overrides.errorByTarget,
812
+ overrides.invalidByTarget,
813
+ overrides.valueByTarget
814
+ ),
815
+ isLoading: fields.length === 0 && !overrides.loadError,
816
+ loadError: overrides.loadError,
817
+ isSubmitting: overrides.isSubmitting,
818
+ statusMessage: overrides.statusMessage,
819
+ isSubmitted: overrides.isSubmitted ?? false,
820
+ submitState: submitStateOf(overrides),
821
+ submitFailure: overrides.submitFailure ?? SubmitFailure.NONE
822
+ };
823
+ }
824
+ function submitStateOf(overrides) {
825
+ if (overrides.isSubmitted) return SubmitState.SUCCEEDED;
826
+ if (overrides.isSubmitting) return SubmitState.SUBMITTING;
827
+ if (overrides.submitFailure) return SubmitState.FAILED;
828
+ return SubmitState.IDLE;
829
+ }
830
+ function createSubmitFlight() {
831
+ let generation = 0;
832
+ return {
833
+ begin() {
834
+ return ++generation;
835
+ },
836
+ invalidate() {
837
+ generation++;
838
+ },
839
+ isCurrent(generationAtStart) {
840
+ return generationAtStart === generation;
841
+ }
842
+ };
843
+ }
844
+ async function runFormSubmit(params) {
845
+ if (params.isSubmitting()) return;
846
+ const generation = params.flight.begin();
847
+ params.setIsSubmitting(true);
848
+ let result;
849
+ try {
850
+ await params.ensureSessionFresh();
851
+ result = await params.submitForm({
852
+ formId: params.formId,
853
+ values: params.submissionValues
854
+ });
855
+ } catch {
856
+ if (!params.flight.isCurrent(generation)) return;
857
+ params.onNetworkFailure();
858
+ params.setIsSubmitting(false);
859
+ return;
860
+ }
861
+ if (!params.flight.isCurrent(generation)) return;
862
+ const redirectPath = params.presentSubmitResult(result);
863
+ if (redirectPath) {
864
+ params.navigate(redirectPath);
865
+ } else {
866
+ params.setIsSubmitting(false);
867
+ }
868
+ }
869
+ const guardedForms = /* @__PURE__ */ new WeakSet();
870
+ function guardNativeFormSubmit(form, submit) {
871
+ if (!form || guardedForms.has(form)) return;
872
+ guardedForms.add(form);
873
+ form.addEventListener("submit", (event) => {
874
+ event.preventDefault();
875
+ void submit();
876
+ });
877
+ }
878
+ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
568
879
  const [isSubmitting, setIsSubmitting] = createSignal(false);
569
880
  const [statusMessage, setStatusMessage] = createSignal("");
570
- const [fieldErrors, setFieldErrors] = createSignal([]);
571
- async function readFormValues() {
572
- const values = {};
573
- const inputReads = refs.fields?.formInputs?.map((input, field) => input.exec$((element) => ({
574
- target: field.target,
575
- value: element.value
576
- }))) ?? [];
577
- const textareaReads = refs.fields?.formTextareas?.map((textarea, field) => textarea.exec$((element) => ({
578
- target: field.target,
579
- value: element.value
580
- }))) ?? [];
581
- const selectReads = refs.fields?.formSelects?.map((select, field) => select.exec$((element) => ({
582
- target: field.target,
583
- value: element.value
584
- }))) ?? [];
585
- const resolved = await Promise.all([...inputReads, ...textareaReads, ...selectReads]);
586
- for (const entry of resolved) {
587
- values[entry.target] = entry.value;
588
- }
589
- return values;
590
- }
591
- async function clearFormValues() {
592
- const clears = [
593
- ...refs.fields?.formInputs?.map((input) => input.exec$((element) => {
594
- element.value = "";
595
- })) ?? [],
596
- ...refs.fields?.formTextareas?.map((textarea) => textarea.exec$((element) => {
597
- element.value = "";
598
- })) ?? [],
599
- ...refs.fields?.formSelects?.map((select) => select.exec$((element) => {
600
- element.value = "";
601
- })) ?? []
602
- ];
603
- await Promise.all(clears);
604
- }
605
- refs.submitButton?.onclick(async () => {
881
+ const [errorByTarget, setErrorByTarget] = createSignal({});
882
+ const [invalidByTarget, setInvalidByTarget] = createSignal({});
883
+ const [isSubmitted, setIsSubmitted] = createSignal(false);
884
+ const [submitFailure, setSubmitFailure] = createSignal(SubmitFailure.NONE);
885
+ const [values, setValues] = createSignal({});
886
+ const dirtyTargets = /* @__PURE__ */ new Set();
887
+ let honeypotValue = "";
888
+ const submitFlight = createSubmitFlight();
889
+ function setFieldValue(target, value) {
890
+ setValues((current) => ({ ...current, [target]: value }));
891
+ }
892
+ function readFormValues() {
893
+ return projectSubmissionValues(carryForward.fields, values());
894
+ }
895
+ function validateField(field) {
896
+ const message = validateFormField(field, values()[field.target] ?? emptyValueFor(field));
897
+ setErrorByTarget((current) => ({ ...current, [field.target]: message }));
898
+ setInvalidByTarget((current) => ({ ...current, [field.target]: Boolean(message) }));
899
+ }
900
+ function clearFieldError(field) {
901
+ setErrorByTarget((current) => ({ ...current, [field.target]: "" }));
902
+ setInvalidByTarget((current) => ({ ...current, [field.target]: false }));
903
+ }
904
+ function reflectToInput(field, value) {
905
+ const fieldRef = refs[contractTagName(field.target)];
906
+ fieldRef?.input?.exec$((element) => {
907
+ if (field.inputType === "checkbox") {
908
+ element.checked = value === true;
909
+ } else if (field.inputType === "multiselect") {
910
+ const selected = Array.isArray(value) ? value : [];
911
+ for (const option of Array.from(element.options)) {
912
+ option.selected = selected.includes(option.value);
913
+ }
914
+ } else {
915
+ element.value = typeof value === "string" ? value : "";
916
+ }
917
+ });
918
+ if (field.inputType === "multiselect") {
919
+ const selected = Array.isArray(value) ? value : [];
920
+ fieldRef?.options?.toggle?.map((option, item) => void option.exec$((element) => {
921
+ element.checked = selected.includes(item.value);
922
+ }));
923
+ }
924
+ }
925
+ function handleNativeInput(field, event) {
926
+ dirtyTargets.add(field.target);
927
+ setFieldValue(field.target, readNativeValue(field, event.target));
928
+ clearFieldError(field);
929
+ }
930
+ function handleControl(field, event) {
931
+ dirtyTargets.add(field.target);
932
+ const value = readControlValue(event.target);
933
+ setFieldValue(field.target, value);
934
+ reflectToInput(field, value);
935
+ validateField(field);
936
+ }
937
+ function handleOptionToggle(field, change) {
938
+ dirtyTargets.add(field.target);
939
+ setFieldValue(field.target, toggleSelection(field, { current: values()[field.target], ...change }));
940
+ validateField(field);
941
+ }
942
+ wireFieldEvents(refs, carryForward.fields, {
943
+ onNativeInput: handleNativeInput,
944
+ onNativeBlur: validateField,
945
+ onControl: handleControl,
946
+ onOptionToggle: handleOptionToggle
947
+ });
948
+ wireHoneypot(refs, (value) => {
949
+ honeypotValue = value;
950
+ });
951
+ createEffect(() => {
952
+ void seedControlsIntoStore(refs, carryForward.fields, dirtyTargets, setValues);
953
+ });
954
+ const reactive = useReactive();
955
+ function afterRemount(work) {
956
+ void reactive.toBeClean().then(work);
957
+ }
958
+ afterRemount(() => wireNativeFormSubmit(refs, submit));
959
+ function resetForm() {
960
+ submitFlight.invalidate();
961
+ setValues(emptyStoreFor(carryForward.fields));
962
+ setErrorByTarget({});
963
+ setInvalidByTarget({});
606
964
  setStatusMessage("");
607
- setFieldErrors([]);
608
- const values = await readFormValues();
609
- const clientErrors = [];
610
- for (const field of carryForward.fields) {
611
- const errorMessage = validateFormField(field, values[field.target] ?? "");
612
- if (errorMessage) {
613
- clientErrors.push({ target: field.target, errorMessage });
965
+ setSubmitFailure(SubmitFailure.NONE);
966
+ setIsSubmitted(false);
967
+ setIsSubmitting(false);
968
+ dirtyTargets.clear();
969
+ honeypotValue = "";
970
+ clearNativeInputsAfterRemount();
971
+ afterRemount(() => focusFirstFieldInput(refs, carryForward.fields, () => true));
972
+ }
973
+ function showSubmitted() {
974
+ setIsSubmitted(true);
975
+ afterRemount(() => void refs.confirmation?.exec$((element) => element.focus()));
976
+ }
977
+ function showFieldErrors(errors) {
978
+ focusFirstFieldInput(refs, carryForward.fields, (field) => Boolean(errors[field.target]));
979
+ }
980
+ function clearNativeInputsAfterRemount() {
981
+ afterRemount(() => {
982
+ for (const field of carryForward.fields) {
983
+ reflectToInput(field, emptyValueFor(field));
614
984
  }
985
+ wireNativeFormSubmit(refs, submit);
986
+ });
987
+ }
988
+ refs.resetButton?.onclick(({ event }) => {
989
+ event.preventDefault();
990
+ resetForm();
991
+ });
992
+ refs.submitButton?.onclick(({ event }) => {
993
+ const form = owningSubmitForm(event.target);
994
+ if (form) {
995
+ guardNativeFormSubmit(form, submit);
996
+ return;
997
+ }
998
+ event.preventDefault();
999
+ void submit();
1000
+ });
1001
+ if (typeof window !== "undefined") {
1002
+ window.addEventListener("pageshow", (event) => {
1003
+ if (event.persisted)
1004
+ setIsSubmitting(false);
1005
+ });
1006
+ }
1007
+ async function submit() {
1008
+ if (isSubmitting())
1009
+ return;
1010
+ setStatusMessage("");
1011
+ setSubmitFailure(SubmitFailure.NONE);
1012
+ setErrorByTarget({});
1013
+ if (honeypotValue.trim()) {
1014
+ showSubmitted();
1015
+ return;
615
1016
  }
616
- if (clientErrors.length) {
617
- setFieldErrors(clientErrors);
1017
+ await seedControlsIntoStore(refs, carryForward.fields, dirtyTargets, setValues);
1018
+ const submissionValues = readFormValues();
1019
+ const clientErrors = validateVisibleFields(carryForward.fields, submissionValues);
1020
+ if (Object.keys(clientErrors).length) {
1021
+ setErrorByTarget(clientErrors);
1022
+ setInvalidByTarget(Object.fromEntries(Object.keys(clientErrors).map((target) => [target, true])));
1023
+ showFieldErrors(clientErrors);
1024
+ setSubmitFailure(SubmitFailure.VALIDATION);
618
1025
  return;
619
1026
  }
620
- setIsSubmitting(true);
621
- try {
622
- await submitForm({
623
- formId: carryForward.formId || (typeof props.formId === "string" ? props.formId : ""),
624
- values
625
- });
626
- setStatusMessage("Form submitted successfully.");
627
- await clearFormValues();
628
- } catch (error) {
629
- if (error instanceof WixApiError) {
630
- const mapped = parseSubmissionFieldErrors(error.responseBody);
631
- const mappedErrors = Object.entries(mapped).map(([target, errorMessage]) => ({
632
- target,
633
- errorMessage
634
- }));
635
- if (mappedErrors.length) {
636
- setFieldErrors(mappedErrors);
637
- return;
638
- }
1027
+ await runFormSubmit({
1028
+ flight: submitFlight,
1029
+ isSubmitting,
1030
+ setIsSubmitting,
1031
+ ensureSessionFresh,
1032
+ submitForm,
1033
+ formId: carryForward.formId,
1034
+ submissionValues,
1035
+ presentSubmitResult,
1036
+ navigate: (path) => window.location.assign(path),
1037
+ onNetworkFailure: () => {
1038
+ setStatusMessage(SUBMIT_FAILED_MESSAGE);
1039
+ setSubmitFailure(SubmitFailure.NETWORK);
639
1040
  }
640
- const rawMessage = error instanceof Error ? error.message : "Something went wrong. Please try again.";
641
- const message = rawMessage.includes("403") ? "Form submission denied. Add Wix Forms permission to your API key in the Wix dashboard." : rawMessage;
642
- setStatusMessage(message);
643
- } finally {
644
- setIsSubmitting(false);
1041
+ });
1042
+ }
1043
+ function presentSubmitResult(result) {
1044
+ if (!result.success) {
1045
+ const rejection = presentSubmitRejection(result, carryForward.fields);
1046
+ setErrorByTarget(rejection.errorByTarget);
1047
+ setInvalidByTarget(rejection.invalidByTarget);
1048
+ setStatusMessage(rejection.statusMessage);
1049
+ setSubmitFailure(result.reason ?? SubmitFailure.UNKNOWN);
1050
+ showFieldErrors(rejection.errorByTarget);
1051
+ return void 0;
645
1052
  }
646
- });
1053
+ showSubmitted();
1054
+ const redirectTo = result.redirectTo;
1055
+ const redirectPath = toSitePath(redirectTo);
1056
+ if (redirectTo !== void 0 && !redirectPath) {
1057
+ console.error("[wix-forms] dropped an unsafe redirectTo", {
1058
+ formId: carryForward.formId
1059
+ });
1060
+ }
1061
+ return redirectPath;
1062
+ }
647
1063
  return {
648
- render: () => ({
649
- fields: toContractFields(carryForward.fields),
650
- options: carryForward.options,
651
- isLoading: carryForward.fields.length === 0 && !carryForward.loadError,
652
- loadError: carryForward.loadError ?? (carryForward.fields.length ? "" : "Could not load the form. Please try again later."),
1064
+ render: () => buildFormViewState(carryForward.fields, {
653
1065
  isSubmitting: isSubmitting(),
654
1066
  statusMessage: statusMessage(),
655
- fieldErrors: fieldErrors()
1067
+ loadError: carryForward.loadError ?? "",
1068
+ errorByTarget: errorByTarget(),
1069
+ invalidByTarget: invalidByTarget(),
1070
+ valueByTarget: values(),
1071
+ isSubmitted: isSubmitted(),
1072
+ submitFailure: submitFailure()
656
1073
  })
657
1074
  };
658
1075
  }
1076
+ function wireFieldEvents(refs, fields, handlers) {
1077
+ for (const field of fields) {
1078
+ const fieldRef = refs[contractTagName(field.target)];
1079
+ if (!fieldRef)
1080
+ continue;
1081
+ fieldRef.input?.oninput(({ event }) => handlers.onNativeInput(field, event));
1082
+ fieldRef.input?.onblur(() => handlers.onNativeBlur(field));
1083
+ fieldRef.control?.onclick(({ event }) => handlers.onControl(field, event));
1084
+ fieldRef.control?.oninput(({ event }) => handlers.onControl(field, event));
1085
+ if (field.inputType === "multiselect") {
1086
+ fieldRef.options?.toggle?.onchange(({ event, viewState }) => handlers.onOptionToggle(field, {
1087
+ optionValue: viewState.value,
1088
+ checked: event.target.checked
1089
+ }));
1090
+ }
1091
+ }
1092
+ }
1093
+ function focusFirstFieldInput(refs, fields, matches) {
1094
+ const field = fields.find((candidate) => !candidate.hidden && matches(candidate) && focusableRef(refs, candidate));
1095
+ if (!field)
1096
+ return;
1097
+ void focusableRef(refs, field).exec$((element) => element.focus());
1098
+ }
1099
+ function focusableRef(refs, field) {
1100
+ const fieldRef = refs[contractTagName(field.target)];
1101
+ if (field.inputType === "multiselect") {
1102
+ const firstChip = fieldRef?.options?.toggle?.find(() => true);
1103
+ if (firstChip)
1104
+ return firstChip;
1105
+ }
1106
+ return fieldRef?.input;
1107
+ }
1108
+ function owningSubmitForm(target) {
1109
+ const button = target?.closest?.("button");
1110
+ return button?.type === "submit" ? button.form ?? void 0 : void 0;
1111
+ }
1112
+ function wireNativeFormSubmit(refs, submit) {
1113
+ void refs.submitButton?.exec$((button) => guardNativeFormSubmit(button.form, submit));
1114
+ }
1115
+ function seedControlsIntoStore(refs, fields, dirtyTargets, setValues) {
1116
+ const seeds = [];
1117
+ const reads = fields.map((field) => {
1118
+ const control = refs[contractTagName(field.target)]?.control;
1119
+ if (!control?.exec$)
1120
+ return Promise.resolve();
1121
+ return control.exec$((element) => readControlValue(element)).then((value) => {
1122
+ seeds.push({
1123
+ target: field.target,
1124
+ value: value ?? "",
1125
+ dirty: dirtyTargets.has(field.target)
1126
+ });
1127
+ });
1128
+ });
1129
+ return Promise.all(reads).then(() => {
1130
+ setValues((current) => seedControlValues(current, seeds));
1131
+ });
1132
+ }
1133
+ function wireHoneypot(refs, record) {
1134
+ refs.honeypot?.oninput(({ event }) => {
1135
+ record(event.target.value ?? "");
1136
+ });
1137
+ }
1138
+ function readNativeValue(field, target) {
1139
+ if (field.inputType === "checkbox") {
1140
+ return target?.checked ?? false;
1141
+ }
1142
+ if (field.inputType === "multiselect") {
1143
+ const select = target;
1144
+ return select ? Array.from(select.selectedOptions).map((option) => option.value) : [];
1145
+ }
1146
+ const element = target;
1147
+ return element?.value ?? "";
1148
+ }
1149
+ function readControlValue(target) {
1150
+ const element = target;
1151
+ if (!element)
1152
+ return "";
1153
+ const dataValue = element.getAttribute?.("data-value");
1154
+ if (dataValue !== null && dataValue !== void 0) {
1155
+ return dataValue;
1156
+ }
1157
+ return element.value ?? "";
1158
+ }
659
1159
  makeJayStackComponent().withProps().withInteractive(WixFormInteractive);
1160
+ function describeBookingError(error) {
1161
+ const rawMessage = error instanceof Error ? error.message : "";
1162
+ if (rawMessage.includes("/ecom/v2/carts") && rawMessage.includes("403")) {
1163
+ return {
1164
+ failure: BookingFailure.CHECKOUT_PERMISSION,
1165
+ message: "Checkout API access denied. Add Wix eCommerce (carts/checkout) permission to your API key in the Wix dashboard."
1166
+ };
1167
+ }
1168
+ if (rawMessage.includes("redirect-session") && rawMessage.includes("400")) {
1169
+ return {
1170
+ failure: BookingFailure.CHECKOUT_REDIRECT_REJECTED,
1171
+ message: "Checkout redirect rejected. In Wix Dashboard → Headless Settings → your client → Allowed redirect domains, add localhost:3000 for local dev (or your deployed domain)."
1172
+ };
1173
+ }
1174
+ if (rawMessage.includes("get-checkout-url")) {
1175
+ return {
1176
+ failure: BookingFailure.SITE_NOT_PUBLISHED,
1177
+ message: "Could not open Wix checkout. Publish your Wix site (hosted checkout requires a published site)."
1178
+ };
1179
+ }
1180
+ return {
1181
+ failure: BookingFailure.UNKNOWN,
1182
+ message: rawMessage || "Booking failed. Please try again."
1183
+ };
1184
+ }
1185
+ function bookingStateOf(state) {
1186
+ if (state.failure !== BookingFailure.NONE) return BookingState.FAILED;
1187
+ if (state.isBooking) return BookingState.BOOKING;
1188
+ if (state.isConfirmed) return BookingState.CONFIRMED;
1189
+ return BookingState.IDLE;
1190
+ }
660
1191
  const DEFAULT_PARTICIPANT_FIELDS = [
661
1192
  { target: "first_name", label: "First Name", type: "STRING", required: true },
662
1193
  { target: "last_name", label: "Last Name", type: "STRING", required: true },
@@ -683,6 +1214,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
683
1214
  const [showServices, setShowServices] = createSignal(true);
684
1215
  const showNoServices = _carryForward.services.length === 0 && !_carryForward.servicesError;
685
1216
  const servicesError = _carryForward.servicesError ?? "";
1217
+ const servicesFailure = _carryForward.servicesFailure ?? ServicesFailure.NONE;
686
1218
  const [hasSlots, setHasSlots] = createSignal(false);
687
1219
  const [showSlots, setShowSlots] = createSignal(false);
688
1220
  const [showForm, setShowForm] = createSignal(false);
@@ -692,14 +1224,23 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
692
1224
  const [slots, setSlots] = createSignal([]);
693
1225
  const [slotsLoading, setSlotsLoading] = createSignal(false);
694
1226
  const [slotsMessage, setSlotsMessage] = createSignal("");
1227
+ const [slotsFailure, setSlotsFailure] = createSignal(SlotsFailure.NONE);
695
1228
  const [formFields, setFormFields] = createSignal([]);
696
1229
  const [formLoading, setFormLoading] = createSignal(false);
697
1230
  const [isBooking, setIsBooking] = createSignal(false);
698
1231
  const [bookingStatus, setBookingStatus] = createSignal("");
699
1232
  const [bookingError, setBookingError] = createSignal("");
1233
+ const [bookingFailure, setBookingFailure] = createSignal(BookingFailure.NONE);
1234
+ const [isConfirmed, setIsConfirmed] = createSignal(false);
700
1235
  function resetBookingMessages() {
701
1236
  setBookingStatus("");
702
1237
  setBookingError("");
1238
+ setBookingFailure(BookingFailure.NONE);
1239
+ setIsConfirmed(false);
1240
+ }
1241
+ function failBooking(failure, message) {
1242
+ setBookingFailure(failure);
1243
+ setBookingError(message);
703
1244
  }
704
1245
  async function onSelectService(service) {
705
1246
  resetBookingMessages();
@@ -711,6 +1252,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
711
1252
  setShowForm(false);
712
1253
  setSlotsLoading(true);
713
1254
  setSlotsMessage("");
1255
+ setSlotsFailure(SlotsFailure.NONE);
714
1256
  setSlots([]);
715
1257
  setHasSlots(false);
716
1258
  try {
@@ -725,6 +1267,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
725
1267
  setSlots(result.slots);
726
1268
  setHasSlots(result.slots.length > 0);
727
1269
  } catch (error) {
1270
+ setSlotsFailure(SlotsFailure.UNKNOWN);
728
1271
  setSlotsMessage(error instanceof Error ? error.message : "Could not load availability.");
729
1272
  } finally {
730
1273
  setSlotsLoading(false);
@@ -754,7 +1297,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
754
1297
  })));
755
1298
  } catch (error) {
756
1299
  const message = error instanceof Error ? error.message : "Could not load participant form fields.";
757
- setBookingError(message);
1300
+ failBooking(BookingFailure.FORM_UNAVAILABLE, message);
758
1301
  setShowForm(false);
759
1302
  } finally {
760
1303
  setFormLoading(false);
@@ -778,14 +1321,13 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
778
1321
  if (!service || !slot) {
779
1322
  return;
780
1323
  }
781
- setBookingError("");
782
- setBookingStatus("");
1324
+ resetBookingMessages();
783
1325
  const formValues = await readFormValues();
784
1326
  const fields = formFields();
785
1327
  for (const field of fields) {
786
1328
  const validationError = validateFormSummaryField(field, formValues[field.target] ?? "");
787
1329
  if (validationError) {
788
- setBookingError(validationError);
1330
+ failBooking(BookingFailure.VALIDATION, validationError);
789
1331
  return;
790
1332
  }
791
1333
  }
@@ -809,19 +1351,12 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
809
1351
  return;
810
1352
  }
811
1353
  setBookingStatus("Booking confirmed!");
1354
+ setIsConfirmed(true);
812
1355
  setShowForm(false);
813
1356
  setSelectedSlot(null);
814
1357
  } catch (error) {
815
- const rawMessage = error instanceof Error ? error.message : "Booking failed. Please try again.";
816
- let message = rawMessage;
817
- if (rawMessage.includes("/ecom/v2/carts") && rawMessage.includes("403")) {
818
- message = "Checkout API access denied. Add Wix eCommerce (carts/checkout) permission to your API key in the Wix dashboard.";
819
- } else if (rawMessage.includes("redirect-session") && rawMessage.includes("400")) {
820
- message = "Checkout redirect rejected. In Wix Dashboard → Headless Settings → your client → Allowed redirect domains, add localhost:3000 for local dev (or your deployed domain).";
821
- } else if (rawMessage.includes("get-checkout-url")) {
822
- message = "Could not open Wix checkout. Publish your Wix site (hosted checkout requires a published site).";
823
- }
824
- setBookingError(message);
1358
+ const { failure, message } = describeBookingError(error);
1359
+ failBooking(failure, message);
825
1360
  } finally {
826
1361
  setIsBooking(false);
827
1362
  }
@@ -836,6 +1371,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
836
1371
  setSelectedServiceName("");
837
1372
  setSlots([]);
838
1373
  setSlotsMessage("");
1374
+ setSlotsFailure(SlotsFailure.NONE);
839
1375
  setHasSlots(false);
840
1376
  setFormFields([]);
841
1377
  }
@@ -864,6 +1400,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
864
1400
  services: services(),
865
1401
  servicesLoading: false,
866
1402
  servicesError,
1403
+ servicesFailure,
867
1404
  showServices: showServices(),
868
1405
  showNoServices,
869
1406
  showSlots: showSlots(),
@@ -872,12 +1409,19 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
872
1409
  slots: slots().map(toContractSlot),
873
1410
  slotsLoading: slotsLoading(),
874
1411
  slotsMessage: slotsMessage(),
1412
+ slotsFailure: slotsFailure(),
875
1413
  hasSlots: hasSlots(),
876
1414
  formFields: formFields(),
877
1415
  formLoading: formLoading(),
878
1416
  isBooking: isBooking(),
879
1417
  bookingStatus: bookingStatus(),
880
- bookingError: bookingError()
1418
+ bookingError: bookingError(),
1419
+ bookingState: bookingStateOf({
1420
+ isBooking: isBooking(),
1421
+ isConfirmed: isConfirmed(),
1422
+ failure: bookingFailure()
1423
+ }),
1424
+ bookingFailure: bookingFailure()
881
1425
  })
882
1426
  };
883
1427
  }