@overmap-ai/forms 1.0.3-form-improvements.2 → 1.0.3-form-improvements.3

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.
@@ -3,6 +3,7 @@ import { FC, ReactNode } from "react";
3
3
  import { FieldTypeIdentifier, ISerializedField } from "@overmap-ai/core";
4
4
  import { Form } from '../typings';
5
5
  interface FieldOptionsFormProps {
6
+ editing?: boolean;
6
7
  defaultField?: ISerializedField;
7
8
  fieldType: FieldTypeIdentifier;
8
9
  /** fields that can be used as a condition */
package/dist/forms.js CHANGED
@@ -1435,31 +1435,33 @@ const Pe = (s, i) => x(() => !i || !s ? null : s.getInput(i), [s, i]), Et = (s,
1435
1435
  new ce({ label: "Required", description: null, required: !1, identifier: "required" })
1436
1436
  ];
1437
1437
  }, sn = S(function(i) {
1438
- const { fieldType: e, handleCancel: t, handleCreateField: n, defaultField: o, conditionalSourceFields: l } = i, c = Lt[e], a = ue(), f = x(() => {
1439
- const d = a.values.fields.flatMap(
1440
- (p) => p.type === "section" ? [...p.fields.map((h) => h.label), p.label] : p.label
1441
- ).filter((p) => p !== (o == null ? void 0 : o.label) && p !== null);
1442
- let u = on(d, e);
1443
- if (console.log(d, u), c === K) {
1438
+ const { fieldType: e, handleCancel: t, handleCreateField: n, defaultField: o, conditionalSourceFields: l, editing: c } = i, a = Lt[e];
1439
+ console.log("default field", o);
1440
+ const f = ue(), d = x(() => {
1441
+ const u = f.values.fields.flatMap(
1442
+ (h) => h.type === "section" ? [...h.fields.map((g) => g.label), h.label] : h.label
1443
+ ).filter((h) => !c || h !== (o == null ? void 0 : o.label) && h !== null);
1444
+ let p = on(u, e);
1445
+ if (console.log(u, p), a === K) {
1444
1446
  if (l === void 0)
1445
1447
  throw new Error("Conditional source fields must be provided when changing sections.");
1446
- u = u.concat(c.getFieldCreationSchema(l));
1448
+ p = p.concat(a.getFieldCreationSchema(l));
1447
1449
  } else {
1448
- if (!(c.prototype instanceof $))
1449
- throw new Error(`Field must be an instance of BaseField. Got ${c}.`);
1450
- u = [...u, ...c.getFieldCreationSchema()];
1450
+ if (!(a.prototype instanceof $))
1451
+ throw new Error(`Field must be an instance of BaseField. Got ${a}.`);
1452
+ p = [...p, ...a.getFieldCreationSchema()];
1451
1453
  }
1452
1454
  return {
1453
- fields: u,
1455
+ fields: p,
1454
1456
  meta: { readonly: !1 },
1455
1457
  // using the dialog title as the form title
1456
1458
  title: null
1457
1459
  };
1458
- }, [a.values.fields, e, c, o == null ? void 0 : o.label, l]);
1460
+ }, [f.values.fields, e, a, c, o == null ? void 0 : o.label, l]);
1459
1461
  return /* @__PURE__ */ r(
1460
1462
  it,
1461
1463
  {
1462
- schema: f,
1464
+ schema: d,
1463
1465
  values: o,
1464
1466
  onSubmit: n,
1465
1467
  cancelText: o ? void 0 : "Back",
@@ -1500,10 +1502,11 @@ const Pe = (s, i) => x(() => !i || !s ? null : s.getInput(i), [s, i]), Et = (s,
1500
1502
  handleCancel: F,
1501
1503
  handleCreateField: (L) => A(L, I),
1502
1504
  fieldType: d,
1503
- defaultField: o
1505
+ defaultField: o,
1506
+ editing: l
1504
1507
  }
1505
1508
  ),
1506
- [c, F, A, o, g, d]
1509
+ [c, l, F, A, o, g, d]
1507
1510
  );
1508
1511
  return /* @__PURE__ */ r(ii, { onCloseInterrupt: w, title: C, description: z, content: P, children: n });
1509
1512
  }), lt = ({ children: s }) => /* @__PURE__ */ r(ut, { children: s }), at = (s, i) => ({
@@ -1626,7 +1629,9 @@ const Pe = (s, i) => x(() => !i || !s ? null : s.getInput(i), [s, i]), Et = (s,
1626
1629
  ) });
1627
1630
  }), an = S(function(i) {
1628
1631
  var P, I, L, M, U, R, j;
1629
- const { field: e, index: t, dropState: n } = i, o = (P = n[e.identifier]) == null ? void 0 : P.disabled, { setFieldValue: l, values: c } = ue(), a = ci(), f = E(
1632
+ const { field: e, index: t, dropState: n } = i, o = (P = n[e.identifier]) == null ? void 0 : P.disabled, { setFieldValue: l, values: c } = ue(), a = ci();
1633
+ console.log("field section", e, t, c);
1634
+ const f = E(
1630
1635
  (v, T) => {
1631
1636
  for (const D of v) {
1632
1637
  const k = T.indexOf(D);
@@ -1719,7 +1724,7 @@ const Pe = (s, i) => x(() => !i || !s ? null : s.getInput(i), [s, i]), Et = (s,
1719
1724
  () => ({
1720
1725
  index: t + 1,
1721
1726
  parentPath: "fields",
1722
- initial: e,
1727
+ initial: { ...e, identifier: "" },
1723
1728
  conditionalSourceFields: Ie(c.fields, t + 1)
1724
1729
  }),
1725
1730
  [e, t, c.fields]
@@ -1 +1 @@
1
- (function(x,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("react/jsx-runtime"),require("@overmap-ai/blocks"),require("formik"),require("react"),require("@hello-pangea/dnd"),require("@overmap-ai/core"),require("lodash.get"),require("lodash.set")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","@overmap-ai/blocks","formik","react","@hello-pangea/dnd","@overmap-ai/core","lodash.get","lodash.set"],i):(x=typeof globalThis<"u"?globalThis:x||self,i(x.forms={},x.jsxRuntime,x.blocks,x.formik,x.React,x.dnd,x.core,x.get,x.set))})(this,function(x,i,s,D,c,j,I,Q,Se){"use strict";var Qt=Object.defineProperty;var Xt=(x,i,s)=>i in x?Qt(x,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):x[i]=s;var m=(x,i,s)=>(Xt(x,typeof i!="symbol"?i+"":i,s),s);class qe{constructor(n){m(this,"type");m(this,"identifier");m(this,"description");const{description:e=null,identifier:t,type:r}=n;this.identifier=t,this.description=e,this.type=r}getId(){return this.identifier}static deserialize(n){throw new Error(`${this.name} must implement deserialize.`)}_serialize(){if(!this.identifier)throw new Error("Field identifier must be set before serializing.");return{type:this.type,identifier:this.identifier,description:this.description}}}class V extends qe{constructor(e){const{label:t,required:r,fieldValidators:o=[],formValidators:a=[],...u}=e;super(u);m(this,"required");m(this,"formValidators");m(this,"fieldValidators");m(this,"label");m(this,"onlyValidateAfterTouched",!0);this.label=t,this.required=r,this.fieldValidators=o,this.formValidators=a}static getFieldCreationSchema(){return[]}isBlank(e){return e==null||e===""}getValueFromChangeEvent(e){return e.target.value}getError(e,t){if(this.required&&this.isBlank(e))return"This field is required.";for(const r of this.getFieldValidators()){const o=r(e);if(o)return o}if(t)for(const r of this.getFormValidators()){const o=r(e,t);if(o)return o}}_serialize(){return{...super._serialize(),label:this.label,required:this.required}}getFieldValidators(){return[...this.fieldValidators]}getFormValidators(){return[...this.formValidators]}}m(V,"fieldTypeName"),m(V,"fieldTypeDescription");const pe={description:"_description_17zed_1"},$=l=>{const{label:n,children:e,severity:t,inputId:r,labelId:o,flexProps:a}=l;return i.jsx(s.Flex,{direction:"column",gap:"1",asChild:!0,...a,children:i.jsxs("label",{htmlFor:r,children:[i.jsx(s.Text,{severity:t,id:o,children:n}),e]})})},O=l=>{const{helpText:n,children:e,severity:t}=l;return i.jsxs(s.Flex,{direction:"column",gap:"1",children:[e,i.jsx(s.Flex,{direction:"column",children:i.jsx(s.Text,{size:"1",severity:t,className:pe.description,children:n})})]})},q=l=>{const{id:n,field:e,formId:t,...r}=l,[o,a,u]=D.useField(e.getId()),{touched:d}=a,h=a.error??e.description,f=a.error?"danger":void 0,p=n??`${t}-${e.getId()}-input`,g=`${p}-label`,y=e.required?`${e.label} *`:e.label,v=c.useMemo(()=>({...o,onChange:T=>{const F=e.getValueFromChangeEvent(T);u.setValue(F,!1).then(),(d||!e.onlyValidateAfterTouched)&&u.setError(e.getError(F))},onBlur:T=>{u.setTouched(!0,!1).then(),u.setError(e.getError(e.getValueFromChangeEvent(T)))}}),[e,o,u,d]);return[{helpText:h,severity:f,inputId:p,labelId:g,label:y,fieldProps:v,helpers:u,field:e},{...r,"aria-labelledby":g}]},dt=[!0,"true"],Ne=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u},d]=q(n),h=s.useSeverityColor(r),f=dt.includes(u.value);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,flexProps:{direction:"row-reverse",justify:"end",align:"center",gap:"2"},children:i.jsx(s.Checkbox,{...d,...u,id:e,color:h,value:f.toString(),checked:f,onCheckedChange:u.onChange,onChange:void 0,onBlur:void 0})})})}),Z=class Z extends V{constructor(e){super({...e,type:"boolean"});m(this,"onlyValidateAfterTouched",!1)}isBlank(e){return this.required&&!e}getValueFromChangeEvent(e){return typeof e=="boolean"?e:e.target.checked}serialize(){return super._serialize()}static deserialize(e){if(e.type!=="boolean")throw new Error("Type mismatch.");return new Z(e)}getInput(e){return i.jsx(Ne,{...e,field:this})}};m(Z,"fieldTypeName","Checkbox"),m(Z,"fieldTypeDescription","Perfect for both optional and required yes/no questions."),m(Z,"Icon",s.CheckCircledIcon);let K=Z;const We=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u,field:d},h]=q(n),f=s.useSeverityColor(r);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.TextField.Input,{...h,...u,type:"number",id:e,min:d.minimum,max:d.maximum,step:d.integers?1:.1,color:f})})})}),_=class _ extends V{constructor(e){const{minimum:t=Number.MIN_SAFE_INTEGER,maximum:r=Number.MAX_SAFE_INTEGER,integers:o=!1,...a}=e;super({...a,type:"number"});m(this,"minimum");m(this,"maximum");m(this,"integers");this.minimum=t,this.maximum=r,this.integers=o}getValueFromChangeEvent(e){const t=Number.parseFloat(e.target.value);return Number.isNaN(t)?"":t}static getFieldCreationSchema(){return[new _({label:"Minimum",description:"Minimum value",integers:!0,required:!1,identifier:"minimum",formValidators:[this._validateMin]}),new _({label:"Maximum",description:"Maximum value",integers:!0,required:!1,identifier:"maximum",formValidators:[this._validateMax]}),new K({label:"Integers",description:"Whole numbers only",required:!1,identifier:"integers"})]}getFieldValidators(){const e=super.getFieldValidators(),t=this.minimum,r=this.maximum;return typeof t=="number"&&e.push(o=>{if(typeof o=="number"&&o<t)return`Must be at least ${this.minimum}.`}),typeof r=="number"&&e.push(o=>{if(typeof o=="number"&&o>r)return`Must be at most ${this.maximum}.`}),this.integers&&e.push(o=>{if(typeof o=="number"&&!Number.isInteger(o))return"Must be a whole number."}),e}serialize(){return{...super._serialize(),minimum:this.minimum,maximum:this.maximum,integers:this.integers}}static deserialize(e){if(e.type!=="number")throw new Error("Type mismatch.");return new _(e)}getInput(e){return i.jsx(We,{field:this,...e})}};m(_,"fieldTypeName","Number"),m(_,"fieldTypeDescription","Allows specifying a number within a given range."),m(_,"Icon",s.FontFamilyIcon),m(_,"_validateMin",(e,t)=>typeof t.maximum=="number"&&typeof e=="number"&&t.maximum<e?"Minimum cannot be greater than minimum.":null),m(_,"_validateMax",(e,t)=>typeof t.minimum=="number"&&typeof e=="number"&&t.minimum>e?"Maximum cannot be less than minimum.":null);let H=_;const je=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u},d]=q(n),h=s.useSeverityColor(r),f=u.value?u.value.split("T")[0]:"";return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.TextField.Input,{...d,...u,type:"date",id:e,color:h,value:f})})})}),k=class k extends V{constructor(e){super({...e,type:"date"});m(this,"onlyValidateAfterTouched",!1)}serialize(){return super._serialize()}getValueFromChangeEvent(e){return new Date(e.target.value).toISOString()}static deserialize(e){if(e.type!=="date")throw new Error("Type mismatch.");return new k(e)}getInput(e){return i.jsx(je,{field:this,...e})}};m(k,"fieldTypeName","Date"),m(k,"fieldTypeDescription","Allows specifying a date."),m(k,"Icon",s.CalendarIcon);let he=k;class me extends V{constructor(e){const{minLength:t,maxLength:r=5e3,...o}=e;super(o);m(this,"minLength");m(this,"maxLength");this.minLength=t?Math.max(t,0):void 0,this.maxLength=r?Math.max(r,0):5e3}static getFieldCreationSchema(){return[new H({label:"Minimum length",description:"Minimum number of characters",required:!1,identifier:"minimum_length",minimum:0,maximum:100,formValidators:[this._validateMin],integers:!0}),new H({label:"Maximum length",description:"Maximum number of characters",required:!1,identifier:"maximum_length",minimum:1,maximum:5e3,formValidators:[this._validateMax],integers:!0})]}getFieldValidators(){const e=super.getFieldValidators();return this.minLength&&e.push(t=>{if(this.minLength&&(!t||t.length<this.minLength))return!this.required&&!t?null:`Minimum ${this.minLength} character(s).`}),this.maxLength&&e.push(t=>{if(typeof t=="string"&&this.maxLength&&t.length>this.maxLength)return`Maximum ${this.maxLength} character(s).`}),e}_serialize(){if(!this.identifier)throw new Error("Field identifier must be set before serializing.");return{...super._serialize(),minimum_length:this.minLength,maximum_length:this.maxLength}}}m(me,"_validateMin",(e,t)=>typeof t.maximum_length=="number"&&typeof e=="number"&&t.maximum_length<e?"Minimum cannot be greater than maximum.":null),m(me,"_validateMax",(e,t)=>{if(typeof e!="number")return null;const{minimum_length:r}=t;return typeof r!="number"?null:r>e?"Maximum cannot be less than minimum.":null});const He=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u,field:d},h]=q(n),f=s.useSeverityColor(r);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.TextField.Input,{...h,...u,type:d.inputType,id:e,color:f})})})}),R=class R extends me{constructor(e){const{inputType:t="text",...r}=e,o=e.maxLength?Math.min(500,e.maxLength):500,a=e.minLength?Math.min(e.minLength,o):void 0;super({...r,maxLength:o,minLength:a,type:"string"});m(this,"inputType");this.inputType=t}serialize(){return{...super._serialize(),input_type:this.inputType}}static deserialize(e){if(e.type!=="string")throw new Error("Type mismatch.");const{maximum_length:t,minimum_length:r,input_type:o,...a}=e;return new R({...a,maxLength:t,minLength:r,inputType:o})}getInput(e){return i.jsx(He,{field:this,...e})}};m(R,"fieldTypeName","Short Text"),m(R,"fieldTypeDescription","Short text fields can hold up to 500 characters on a single line."),m(R,"Icon",s.InputIcon);let X=R;const Ue=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u},d]=q(n);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.TextArea,{...d,...u,resize:"vertical",id:e,severity:r})})})}),ee=class ee extends me{constructor(n){const e=n.maxLength?Math.min(5e3,n.maxLength):5e3,t=n.minLength?Math.min(n.minLength,e):void 0;super({...n,maxLength:e,minLength:t,type:"text"})}serialize(){return super._serialize()}static deserialize(n){if(n.type!=="text")throw new Error("Type mismatch.");const{maximum_length:e,minimum_length:t,...r}=n;return new ee({...r,maxLength:e,minLength:t})}getInput(n){return i.jsx(Ue,{field:this,...n})}};m(ee,"fieldTypeName","Paragraph"),m(ee,"fieldTypeDescription","Paragraph fields can hold up to 5000 characters and can have multiple lines."),m(ee,"Icon",s.RowsIcon);let J=ee;const Ge=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u,field:d},h]=q(n),{onChange:f,onBlur:p}=u,g=c.useMemo(()=>d.options.map(v=>({value:v.value,itemContent:v.label})),[d.options]),y=c.useCallback(v=>{f(v),p(v)},[f,p]);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.Select,{items:g,...u,onValueChange:y,placeholder:"Select one...",id:e,severity:r,...h})})})}),ge=(l="",n=[])=>({type:"section",fields:n,identifier:l,label:null,condition:null,conditional:!1}),ct=l=>{if(!l)return;const n=l.fields;let e=[];const t=[];for(const r of n)r.type==="section"?(e.length>0&&(t.push(ge(`AUTO_section-${n.indexOf(r)}`,e)),e=[]),t.push(r)):e.push(r);return e.length>0&&t.push(ge("AUTO_section-last",e)),{...l,fields:t,description:l.description??""}};function ze(l,n,e){const t=Array.from(l),[r]=t.splice(n,1);if(!r)throw new Error("Could not find field to reorder.");return t.splice(e,0,r),t}function ut(l,n,e){const t=Array.from(l);return t[n]=e,t}function Ke(l,n,e){const t=Array.from(l??[]);return t.splice(n,0,e),t}function ye(l,n){const e=Array.from(l);return e.splice(n,1),e}const ft=(l,n)=>{if(typeof l=="string"&&l.length>0)return l;const e=new Date;return`${I.slugify(n)}-${e.getTime()}`},Ye=(l,n)=>{if(!n)return null;for(const e of l)if(e.type==="section"){const t=Ye(e.fields,n);if(t)return t}else if(e.identifier===n)return e;return null},xe=(l,n)=>l.filter((e,t)=>t<n).flatMap(e=>e.fields),Qe=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u},d]=q(n),h=s.useSeverityColor(r),f=c.useMemo(()=>Array.isArray(u.value)?u.value:[],[u.value]),{onChange:p,onBlur:g}=u,y=`${e}-droppable`,{disabled:v}=d,[b,z]=c.useState(""),[T,F]=c.useState(""),E=T||o,M=T?"red":h,C=c.useCallback(w=>{p(w),g(w)},[p,g]),A=c.useCallback(w=>{f.findIndex(S=>S.value===w.target.value.trim())>=0?F("All options must be unique"):w.target.value?F(""):F("Option cannot be empty"),z(w.target.value)},[z,f]),B=c.useCallback(()=>{if(T)return;if(!b.trim())return F("Option cannot be empty");const w=b.trim();C([...f,{value:w,label:w}]),z("")},[b,T,C,f]),Y=c.useCallback(w=>{w.key==="Enter"&&(w.preventDefault(),B())},[B]),N=c.useCallback(w=>{C(ye(f,w))},[f,C]),G=c.useCallback(w=>{if(!w.destination)return;const S=w.source.index,P=w.destination.index;C(ze(f,S,P))},[C,f]);return i.jsx(j.DragDropContext,{onDragEnd:G,children:i.jsxs(s.Flex,{direction:"column",gap:"2",children:[i.jsx(O,{helpText:E,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:(!v||f.length===0)&&i.jsxs(s.Flex,{gap:"2",children:[i.jsx(s.Box,{grow:"1",children:i.jsx(s.TextField.Input,{placeholder:"Press enter to add a new option",...d,...u,value:b,onChange:A,onKeyDown:Y,id:e,color:M,onBlur:void 0})}),i.jsx(s.IconButton,{type:"button","aria-label":"Add option",disabled:!!T||v,onClick:B,children:i.jsx(s.PlusIcon,{})})]})})}),i.jsx(j.Droppable,{droppableId:y,children:w=>i.jsxs(s.Flex,{...w.droppableProps,ref:w.innerRef,direction:"column",children:[f.map((S,P)=>i.jsx(j.Draggable,{draggableId:`${S.value}-draggable`,index:P,isDragDisabled:v,children:({draggableProps:L,dragHandleProps:W,innerRef:fe})=>i.jsx(s.Flex,{...W,...L,ref:fe,gap:"2",align:"center",justify:"between",mb:"1",asChild:!0,children:i.jsxs(s.Badge,{color:"gray",size:"2",children:[i.jsx("span",{children:S.label}),i.jsx(s.IconButton,{size:"small",variant:"ghost",type:"button","aria-label":"Delete option",severity:"info",disabled:v,onClick:()=>N(P),children:i.jsx(s.Cross1Icon,{})})]})})},S.value)),w.placeholder]})})]})})}),te=class te extends V{constructor(e){const{minimum_length:t,maximum_length:r,...o}=e;super({...o,type:"multi-string"});m(this,"minLength");m(this,"maxLength");m(this,"onlyValidateAfterTouched",!1);this.minLength=t??0,this.maxLength=r??1/0}getValueFromChangeEvent(e){if(Array.isArray(e))return e;throw new Error("Expected an array.")}getInput(e){return i.jsx(Qe,{field:this,...e})}serialize(){return{...super._serialize(),minimum_length:this.minLength,maximum_length:this.maxLength}}isBlank(e){return super.isBlank(e)||e.length===0}getFieldValidators(){const e=super.getFieldValidators();return e.push(t=>{if(Array.isArray(t)&&t.length<this.minLength)return`Must have at least ${this.minLength} options.`}),e.push(t=>{if(Array.isArray(t)&&t.length>this.maxLength)return`Must have at most ${this.maxLength} options.`}),e}static deserialize(e){if(e.type!=="multi-string")throw new Error("Type mismatch.");return new te(e)}};m(te,"fieldTypeName","Multi-string"),m(te,"fieldTypeDescription","Allows the user to provide multiple unique strings."),m(te,"Icon",s.ListBulletIcon);let oe=te;class Xe extends V{constructor(e){super(e);m(this,"options");m(this,"onlyValidateAfterTouched",!1);const t=new Set;this.options=e.options.map(r=>(typeof r=="string"&&(r={label:r,value:r}),t.add(r.label),r)),t.size!==e.options.length&&console.error(`${e.options.length-t.size} duplicate identifiers found in options. This may cause unexpected behavior. Options:`,e.options)}_serialize(){return{...super._serialize(),options:this.options}}static getFieldCreationSchema(){return[new oe({label:"Options",description:"List possible options for the user to select from.",required:!0,identifier:"options",minimum_length:2,maximum_length:20})]}}const ie=class ie extends Xe{constructor(n){super({...n,type:"select"})}getValueFromChangeEvent(n){return typeof n=="string"?n:n.target.value}serialize(){return super._serialize()}static deserialize(n){if(n.type!=="select")throw new Error("Type mismatch.");return new ie(n)}getInput(n){return i.jsx(Ge,{field:this,...n})}};m(ie,"fieldTypeName","Dropdown"),m(ie,"fieldTypeDescription","Allows the user to select a single option from a list of options."),m(ie,"Icon",s.DropdownMenuIcon);let le=ie;const pt=l=>l?Array.isArray(l)?l:[l]:[],Je=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u,field:d},h]=q(n),{onChange:f,onBlur:p}=u,g=c.useMemo(()=>pt(u.value),[u.value]),y=c.useCallback(v=>{f(v),p(v)},[f,p]);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.MultiSelect,{value:g,onValueChange:y,options:d.options,name:u.name,placeholder:"Select one or more...",id:e,severity:r,...h})})})}),ne=class ne extends Xe{constructor(n){super({...n,type:"multi-select"})}getValueFromChangeEvent(n){if(Array.isArray(n))return n;throw new Error("Expected an array.")}isBlank(n){return super.isBlank(n)||n.length===0}serialize(){return super._serialize()}static deserialize(n){if(n.type!=="multi-select")throw new Error("Type mismatch.");return new ne(n)}getInput(n){return i.jsx(Je,{field:this,...n})}};m(ne,"fieldTypeName","Multi-select"),m(ne,"fieldTypeDescription","Allows the user to select a multiple options from a list of options."),m(ne,"Icon",s.CheckboxIcon);let ae=ne;const ht=c.memo(function({field:n,...e}){const[{value:t}]=D.useField(n.options.clonedFieldIdentifier),r=c.useMemo(()=>{const o=n.options.getFieldToClone(t);return o?de(o):null},[n.options,t]);return ce(r,e)});class ve extends V{constructor(e,t){super({...e,type:"custom"});m(this,"Component");m(this,"options");this.options=e,this.Component=t}serialize(){throw new Error("Serializing only supported for public input types.")}getInput(e){const t=this.Component;return i.jsx(t,{field:this,...e})}}m(ve,"fieldTypeName","Custom"),m(ve,"fieldTypeDescription","Allows re-rendering of field already in the form");class mt extends ve{constructor(n){super(n,ht)}}const gt=c.memo(function(n){const{field:e,...t}=n,{label:r,description:o,fields:a,condition:u}=e,{values:d,setFieldValue:h}=D.useFormikContext(),f=u!=null&&u.identifier?Q(d,u.identifier):void 0,p=c.useMemo(()=>Le(u,f),[u,f]);c.useEffect(()=>{if(!p)for(const y of a)h(y.getId(),"").then()},[p,a,h]);const g=Ve(a,t);return p?r?i.jsx(s.Card,{children:i.jsxs(s.Flex,{direction:"column",gap:"3",children:[i.jsxs(s.Flex,{direction:"column",children:[i.jsx(s.Heading,{as:"h3",size:"3",children:r}),i.jsx(s.Text,{className:pe.description,children:o})]}),g]})}):g:null}),re=class re extends qe{constructor(e){const{label:t=null,fields:r,condition:o=null,conditional:a,...u}=e;super({...u,type:"section"});m(this,"label");m(this,"fields");m(this,"condition");this.fields=r,this.condition=o,this.label=t,a===!1&&(this.condition=null)}static getFieldCreationSchema(e){return e.length===0?[]:[new K({label:"Conditional",description:"Conditionally show or hide this section.",identifier:"conditional",required:!1}),new re({label:"Conditional settings",identifier:"conditional-settings",condition:{identifier:"conditional",value:!0},fields:[new le({label:"Field",description:"The field to use for the condition.",options:e.map(t=>!t.label||t.type==="upload"?null:{label:t.label,value:t.identifier}).filter(t=>!!t),identifier:"condition.identifier",required:!0}),new mt({label:"Value",identifier:"condition.value",required:!0,clonedFieldIdentifier:"condition.identifier",getFieldToClone(t){if(!t)return null;const r=e.find(o=>o.identifier===t);return r?{...r,label:"Value",identifier:"condition.value",description:"The value to compare against.",required:r.type!=="boolean"}:(console.error("Could not find field with identifier",t),null)}})]})]}static deserialize(e){var r;if(e.type!=="section")throw new Error("Invalid type");const t=((r=e.fields)==null?void 0:r.map(Pe))??[];return new re({...e,fields:t})}conditional(){return this.condition!==null}serialize(){return{...super._serialize(),label:this.label,condition:this.condition,conditional:this.conditional(),fields:this.fields.map(e=>e.serialize())}}getErrors(e){const t={};for(const r of this.fields){const o=r.getId(),a=r.getError(Q(e,o),e);a&&Se(t,r.getId(),a)}return t}getInput(e){return i.jsx(gt,{field:this,...e})}};m(re,"fieldTypeName","Section"),m(re,"fieldTypeDescription","Sections can be useful for grouping fields together. They can also be conditionally shown or hidden.");let U=re;const yt={previewImage:"_previewImage_1ig84_1"},Ee=l=>{const n=["byte","kilobyte","megabyte"];let e=l,t=0;for(;e>1024&&t<n.length-1;)e/=1024,t++;return new Intl.NumberFormat([],{maximumFractionDigits:2,style:"unit",unit:n[t]}).format(e)},xt=c.memo(function(n){var M;const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u,field:d},h]=q(n),{onChange:f}=u,p=s.useSeverityColor(r),g=c.useRef(null),{value:y}=u,v=c.useMemo(()=>o||(d.maxFileSize?`Maximum file size: ${Ee(d.maxFileSize)}`:null),[d.maxFileSize,o]),b=c.useCallback(()=>{var C;(C=g.current)==null||C.click()},[]),z=c.useCallback(C=>{const A=[...y];A.splice(C,1),f({target:{files:A}})},[y,f]),T=y?"Select new files":"Select files",F=y?"Select new file":"Select a file",E=d.maxFiles>1?T:F;return i.jsxs(s.Flex,{direction:"column",gap:"2",children:[i.jsx(O,{helpText:v,severity:r,children:i.jsxs($,{severity:r,inputId:e,labelId:t,label:a,children:[i.jsx(s.Flex,{direction:"row",gap:"2",children:i.jsx(s.Box,{width:"max-content",asChild:!0,children:i.jsxs(s.Button,{...h,onClick:b,children:[i.jsx(s.UploadIcon,{})," ",E]})})}),i.jsx("input",{...h,type:"file",ref:g,id:e,accept:(M=d.extensions)==null?void 0:M.join(","),multiple:d.maxFiles>1,color:p,style:{display:"none"},...u,value:""})]})}),Array.isArray(y)&&y.length>0&&i.jsx(s.Flex,{direction:"column",gap:"2",children:y.map((C,A)=>i.jsx(vt,{field:d,file:C,onRemove:()=>z(A),disabled:h.disabled},A))})]})}),vt=c.memo(function({file:n,field:e,onRemove:t,disabled:r}){const[o,a]=c.useState(null),u=c.useMemo(()=>o&&e.getError([o]),[e,o]),{url:d,name:h,size:f}=c.useMemo(()=>{let p=null,g,y;return o!=null&&o.type.startsWith("image/")&&(p=URL.createObjectURL(o)),o?(g=o.name,y=Ee(o.size)):(g="Downloading...",y="..."),{url:p,name:g,size:y}},[o]);return c.useEffect(()=>{n instanceof Promise?n.then(a):a(n)},[n]),i.jsx(s.Card,{children:i.jsxs(s.Flex,{direction:{initial:"column",sm:"row"},gap:"3",justify:"between",children:[i.jsxs(s.Flex,{direction:"row",gap:"3",align:"center",grow:"1",shrink:"0",children:[i.jsx(s.IconButton,{severity:"info",variant:"outline","aria-label":`Remove ${h}`,disabled:r,onClick:t,children:i.jsx(s.Cross1Icon,{})}),i.jsxs(s.Flex,{direction:"column",gap:"1",children:[i.jsx(s.Text,{children:h}),i.jsx(s.Text,{size:"1",children:f}),u&&i.jsx(s.Text,{size:"1",severity:"danger",children:u})]})]}),d&&i.jsx("img",{className:yt.previewImage,src:d,alt:h})]})})}),Ze=50*1024*1024,se=class se extends V{constructor(e){const{extensions:t,maximum_files:r,maximum_size:o,...a}=e;super({...a,type:"upload"});m(this,"extensions");m(this,"maxFileSize");m(this,"maxFiles");m(this,"onlyValidateAfterTouched",!1);this.maxFileSize=typeof o=="number"?o:void 0,this.maxFiles=Math.max(typeof r=="number"?r:1,1),this.extensions=t}getValueFromChangeEvent(e){return Array.from(e.target.files||[])}isBlank(e){return super.isBlank(e)||e.length===0}static getFieldCreationSchema(){return[new H({label:"How many files can be uploaded?",description:"By default, only one file can be uploaded.",required:!1,minimum:1,maximum:10,identifier:"maximum_files"}),new H({label:"What is the maximum size of each file?",description:"Maximum file size in bytes.",required:!1,identifier:"maximum_size",minimum:1,maximum:Ze,integers:!0}),new ae({label:"Accepted file types",description:"Types of allowed files to upload. If left blank, all files will be accepted.",required:!1,identifier:"extensions",options:[{value:"image/*",label:"Images"},{value:"audio/*",label:"Audio files"},{value:"video/*",label:"Videos"},{value:"text/*",label:"Text files"},{value:"application/*",label:"Application files (includes PDFs and Word documents)"}]})]}getFieldValidators(){const e=super.getFieldValidators(),t=this.maxFileSize??Ze,r=this.maxFiles??1;return e.push(o=>{if(o&&o.some(a=>a.size>t))return`Files must be at most ${Ee(t)}.`}),e.push(o=>{if(o&&o.length>r)return`You can only upload ${r} files.`}),e}serialize(){return{...super._serialize(),extensions:this.extensions,maximum_size:this.maxFileSize,maximum_files:this.maxFiles}}static deserialize(e){if(e.type!=="upload")throw new Error("Type mismatch.");return new se(e)}getInput(e){return i.jsx(xt,{field:this,...e})}};m(se,"fieldTypeName","Upload"),m(se,"fieldTypeDescription","Allows a file to be uploaded."),m(se,"Icon",s.UploadIcon);let Me=se;const Ae={date:he,number:H,boolean:K,select:le,string:X,text:J,custom:ve,upload:Me,"multi-string":oe,"multi-select":ae},Pe=l=>{const n=l.type;return Ae[n].deserialize(l)},de=l=>l.type==="section"?U.deserialize(l):Pe(l);function De(l,n={}){const{readonly:e=!1}=n;return{title:l.title,description:l.description,fields:l.fields.map(t=>de(t)),meta:{readonly:e}}}function we(l){return!!(Array.isArray(l)&&l.some(n=>n instanceof File||n instanceof Promise))}function Le(l,n){if(!l)return!0;if(we(n)||we(l.value))throw new Error("Conditions do not support file uploads");const e=Array.isArray(n)?n.map(r=>typeof r=="string"?r:r.value):n,t=Array.isArray(l.value)?l.value.map(r=>typeof r=="string"?r:r.value):l.value;if(Array.isArray(t)&&Array.isArray(e)){for(const r of t)if(!e.includes(r))return!1;return!0}return t===n}const ce=(l,n)=>c.useMemo(()=>!n||!l?null:l.getInput(n),[l,n]),Ve=(l,n)=>{const e=c.useMemo(()=>l.map(t=>i.jsx("div",{children:t.getInput(n)},t.getId())),[l,n]);return i.jsx(s.Flex,{direction:"column",gap:"2",children:e})},Fe=l=>Object.keys(l).length>0,ke=async(l,n)=>{const e={};for(const t of l.fields)if(t instanceof U){if(t.condition){const{identifier:r}=t.condition;if(!Le(t.condition,Q(n,r)))continue}Object.assign(e,t.getErrors(n))}else{if(!(t instanceof V))throw new Error("Invalid field type");const r=t.getId(),o=t.getError(Q(n,r),n);o&&Se(e,r,o)}if(Fe(e))return e},wt=[null,void 0],Be=(l,n)=>l.reduce((e,t)=>t instanceof U?{...e,...Be(t.fields,n)}:(wt.includes(Q(e,t.getId()))&&Se(e,t.getId(),""),e),n),Ft=()=>{throw new Error("onSubmit must be provided if form is not readonly.")},Ie=c.memo(c.forwardRef((l,n)=>{const{schema:e,values:t={},onSubmit:r=Ft,submitText:o="Submit",cancelText:a,onCancel:u,onDirty:d,hideTitle:h=!e.title,hideDescription:f,className:p}=l,{readonly:g}=e.meta,y=c.useMemo(()=>crypto.randomUUID(),[]),v=D.useFormik({initialValues:Be(e.fields,t),onSubmit:r,validate:E=>ke(e,E),validateOnBlur:!1,validateOnChange:!1}),{dirty:b}=v,z=c.useMemo(()=>typeof e.title=="string"?i.jsx(s.Heading,{children:e.title}):e.title,[e.title]),T=c.useMemo(()=>typeof e.description=="string"?i.jsx(s.Text,{className:pe.description,children:e.description}):e.description,[e.description]),F=Ve(e.fields,{formId:y,disabled:g});return c.useEffect(()=>{b&&d&&d()},[b,d]),i.jsx(D.FormikProvider,{value:v,children:i.jsx(s.Flex,{ref:n,direction:"column",gap:"2",className:p,asChild:!0,children:i.jsxs("form",{id:y,onSubmit:v.handleSubmit,children:[!h&&i.jsx(s.Card,{children:i.jsxs(s.Flex,{direction:"column",gap:"1",children:[z,!f&&T]})}),F,!g&&i.jsxs(s.Flex,{justify:"end",gap:"2",children:[a&&i.jsx(s.Button,{type:"button",variant:"soft",onClick:u,children:a}),i.jsx(s.Button,{type:"submit",disabled:!v.isValid,children:o})]})]})})})})),It=c.memo(c.forwardRef((l,n)=>{const{submission:e,showFormDescription:t=!1,showFormTitle:r=!0}=l,o=I.useAppSelector(I.selectFormRevision(e.form_revision)),{sdk:a}=I.useSDK();if(!o)throw new Error(`Could not find revision ${e.form_revision} for submission ${e.offline_id}.`);const u=c.useMemo(()=>De(o,{readonly:!0}),[o]),d=c.useMemo(()=>{const h=I.selectSubmissionAttachments(e.offline_id)(a.store.getState())??[],f={};for(const p of h){const g=a.files.fetchFileFromUrl(p.file,p.file_sha1,p.file_name).then(v=>{if(!v.success)throw new Error(`Failed to download attachment ${p.file_name}.`);return v.body}),y=f[p.field_identifier];y?y.push(g):f[p.field_identifier]=[g]}return{...e.values,...f}},[a.files,a.store,e.offline_id,e.values]);return i.jsx(Ie,{ref:n,schema:u,values:d,hideDescription:!t,hideTitle:!r})})),Re={favoriteIcon:"_favoriteIcon_1bixi_1",regularIcon:"_regularIcon_1bixi_9"},_e="organization:",$e="user:",Ct=c.memo(c.forwardRef((l,n)=>{const{maxResults:e=20,...t}=l,[r,o]=c.useState(""),[a,u]=c.useState(""),{sdk:d}=I.useSDK(),h=c.useMemo(()=>{const F={maxResults:e,searchTerm:r};return a&&(a.startsWith(_e)?F.owner_organization=parseInt(a.slice(_e.length)):a.startsWith($e)&&(F.owner_user=parseInt(a.slice($e.length)))),F},[r,e,a]),f=I.useAppSelector(I.selectFilteredUserForms(h))??[],p=I.useAppSelector(I.selectUserFormMapping),g=c.useCallback(F=>{F.favorite?d.userForms.unfavorite(F.offline_id).then():d.userForms.favorite(F.offline_id).then()},[d]),y=c.useMemo(()=>{const F=d.store.getState(),E={};for(const M of Object.values(p)){const C=I.selectOrganization(M.owner_organization||-1)(F);C&&(E[`${_e}${C.id}`]=C.name);const A=I.selectUser(M.owner_user||-1)(F);A&&(E[`${$e}${A.id}`]=A.username)}return Object.entries(E).map(([M,C])=>({itemContent:C,value:M}))},[p,d.store]),v=c.useCallback(F=>{o(F.currentTarget.value)},[]),z=(I.useAppSelector(I.selectNumberOfUserForms)||0)-f.length,T=f.length==e&&z>0?`Only the first ${e} results are shown (${z} hidden)`:z>0&&`${z} hidden forms`;return i.jsxs(s.Flex,{ref:n,direction:"column",gap:"2",children:[i.jsxs(s.Flex,{gap:"2",grow:"1",children:[i.jsx(s.Box,{grow:"1",asChild:!0,children:i.jsx(s.TextField.Root,{size:"3",children:i.jsx(s.TextField.Input,{placeholder:"Filter",value:r,onChange:v})})}),i.jsx(s.Select,{items:y,value:a,onValueChange:u,placeholder:"Owner",size:"large"})]}),f.length>0&&i.jsx(s.ButtonList.Root,{children:f.map(F=>i.jsx(bt,{...t,form:F,handleToggleFavorite:()=>g(F)},F.offline_id))}),i.jsx(s.Box,{px:"3",children:i.jsx(s.Text,{size:"2",severity:"info",children:T})})]})})),bt=l=>{var g;const{form:n,onSelectForm:e,isFavoriteEditable:t,handleToggleFavorite:r}=l,o=(g=I.useAppSelector(I.selectOrganization(n.owner_organization||-1)))==null?void 0:g.name,a=I.useAppSelector(I.selectUser(n.owner_user||-1)),u=I.useAppSelector(I.selectCurrentUser).id,d=!!a&&a.id===u,h=o??(d?"You":a==null?void 0:a.username)??"Unknown",f=c.useCallback(y=>{y.stopPropagation(),r()},[r]),p=i.jsx(s.ButtonList.Item,{onClick:()=>e(n),asChild:!0,children:i.jsxs(s.Flex,{justify:"between",gap:"2",py:"2",px:"3",...s.divButtonProps,children:[i.jsxs(s.Flex,{grow:"1",align:"center",gap:"2",children:[i.jsx(s.IconButton,{className:I.classNames(n.favorite?Re.favoriteIcon:Re.regularIcon),variant:"ghost",onClick:f,"aria-label":n.favorite?"Favorite form":"Standard form",disabled:!t,children:n.favorite?i.jsx(s.StarFilledIcon,{}):i.jsx(s.StarIcon,{})}),i.jsx(s.Text,{noWrap:!0,children:n.latestRevision.title}),n.latestRevision.description&&i.jsx(s.QuestionMarkCircledIcon,{})]}),h&&i.jsxs(s.Flex,{align:"center",gap:"2",children:[i.jsx(s.PersonIcon,{})," ",h]})]})});return n.latestRevision.description?i.jsx(s.Tooltip,{content:n.latestRevision.description,children:p},n.offline_id):p},et={submissionsContainer:"_submissionsContainer_9iirt_1",stopHorizontalOverflow:"_stopHorizontalOverflow_9iirt_6"},Tt=c.memo(function(n){var F;const{submission:e,onSubmissionClick:t,compact:r,labelType:o,rowDecorator:a}=n,u=I.useAppSelector(I.selectCurrentUser),d=I.useAppSelector(I.selectUser("created_by"in e?e.created_by:u.id)),h=Oe(e),f=I.isToday(h)?h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):I.getLocalDateString(h),p=I.useAppSelector(I.selectFormRevision(e.form_revision));if(!p)throw new Error(`Could not find revision ${e.form_revision} for submission ${e.offline_id}.`);const g=(F=I.useAppSelector(I.selectLatestFormRevision(p.form)))==null?void 0:F.revision,y=I.useFileSrc({file:(d==null?void 0:d.profile.file)??null,fileSha1:(d==null?void 0:d.profile.file_sha1)??null}),v=(d==null?void 0:d.username.charAt(0).toUpperCase())??"?",b=p.revision===g,z=c.useCallback(()=>{t&&t({submission:e})},[e,t]),T=i.jsx(s.ButtonList.Item,{onClick:z,asChild:!0,children:i.jsxs(s.Flex,{grow:"1",width:"100%",p:"2",gap:"2",justify:"between",children:[i.jsxs(s.Flex,{gap:"2",align:"center",className:et.stopHorizontalOverflow,children:[i.jsx(s.Avatar,{src:y,size:"1",fallback:v}),i.jsx(s.Text,{size:"2",noWrap:!0,children:o==="creator"?(d||u).username:p.title})]}),i.jsxs(s.Flex,{gap:"2",align:"center",children:[!r&&(p.revision?i.jsx(s.Badge,{variant:"soft",severity:b?"primary":"info",children:r?p.revision.toString():`Revision #${p.revision}`}):!!g&&i.jsx(s.Badge,{children:"Original"})),i.jsx(s.Text,{size:"2",noWrap:!0,children:f})]})]})});return a?a(e,T):T}),Oe=l=>{const n="created_at"in l?l.created_at:l.submitted_at;return new Date(n)},St=c.memo(function(n){const{formId:e,submissions:t,compact:r=!1,className:o,after:a,variant:u="outline",...d}=n;if(!!e==!!t)throw new Error("Either formId or submissions must be provided, but not both.");const h=I.useAppSelector(t?()=>t:I.selectSubmissionsForForm(e)),f=c.useMemo(()=>h==null?void 0:h.sort((p,g)=>Oe(g).getTime()-Oe(p).getTime()),[h]);return i.jsx(s.ButtonList.Root,{className:I.classNames(et.submissionsContainer,o),size:"small",variant:u,before:!r&&i.jsxs(s.Text,{severity:"info",children:["There are ",((h==null?void 0:h.length)||0).toString()," submissions of this form."]}),after:a,children:f==null?void 0:f.map((p,g)=>i.jsx(Tt,{submission:p,compact:r,...d},g))})}),zt=c.memo(function(n){const{name:e,render:t}=n,{submitForm:r}=D.useFormikContext(),[o,a,u]=D.useField(e);return c.useMemo(()=>{const d=h=>u.setValue(h,!1);return t({value:o.value,setValue:d,patchValue:r})},[r,u,o.value,t])}),Et=c.memo(c.forwardRef((l,n)=>{const{children:e,schema:t,values:r,onPatch:o,onError:a,...u}=l,d=c.useMemo(()=>Be(t.fields,r),[t.fields,r]),h=c.useCallback(v=>{const b={};for(const z in v){const T=v[z];T!==d[z]&&T!==void 0&&(b[z]=T)}Fe(b)&&o(b)},[d,o]),f=c.useCallback(async v=>{const b=await ke(t,v);return b&&a(b),b},[t,a]),p=D.useFormik({initialValues:d,onSubmit:h,validate:f,validateOnBlur:!1,validateOnChange:!1}),{errors:g,resetForm:y}=p;return c.useEffect(()=>{Fe(g)&&y({values:d,errors:{}})},[g,d,y]),i.jsx(D.FormikProvider,{value:p,children:i.jsx("form",{...u,ref:n,onSubmit:p.handleSubmit,children:e})})})),tt={...Ae,section:U},Mt=c.memo(function(n){const{field:e,setFieldType:t}=n,r=e.fieldTypeName,o=e.fieldTypeDescription,a=e.Icon;return i.jsxs(s.Flex,{gap:"4",align:"center",children:[i.jsx(s.Button,{type:"button",variant:"surface",onClick:t,style:{width:"135px"},children:i.jsxs(s.Flex,{gap:"3",align:"center",grow:"1",children:[i.jsx(a,{}),r]})}),i.jsx(s.Text,{children:o})]})}),it=[["string","text"],["select","multi-select","upload"],["boolean","date","number","multi-string"]],At=it.length-1,Pt=c.memo(function(n){const{setFieldType:e}=n;return i.jsx(s.Flex,{direction:"column",gap:"3",children:it.map((t,r)=>i.jsxs(s.Flex,{direction:"column",gap:"3",children:[i.jsx(s.Flex,{direction:"column",gap:"2",children:t.map(o=>i.jsx(Mt,{field:Ae[o],setFieldType:()=>e(o)},o))}),r<At&&i.jsx(s.Separator,{size:"4"})]},r))})}),Dt=l=>n=>{if(console.log("in validate",l,n),!(!n||typeof n!="string")&&l.includes(n.trim()))return"This name is already taken."},Lt=(l,n)=>{const e=[new X({label:"Label",required:!0,maxLength:200,identifier:"label",fieldValidators:[Dt(l)]}),new J({label:"Description",required:!1,maxLength:1e3,identifier:"description"})];return n==="section"?e:[...e,new K({label:"Required",description:null,required:!1,identifier:"required"})]},Vt=c.memo(function(n){const{fieldType:e,handleCancel:t,handleCreateField:r,defaultField:o,conditionalSourceFields:a}=n,u=tt[e],d=D.useFormikContext(),h=c.useMemo(()=>{const f=d.values.fields.flatMap(g=>g.type==="section"?[...g.fields.map(y=>y.label),g.label]:g.label).filter(g=>g!==(o==null?void 0:o.label)&&g!==null);let p=Lt(f,e);if(console.log(f,p),u===U){if(a===void 0)throw new Error("Conditional source fields must be provided when changing sections.");p=p.concat(u.getFieldCreationSchema(a))}else{if(!(u.prototype instanceof V))throw new Error(`Field must be an instance of BaseField. Got ${u}.`);p=[...p,...u.getFieldCreationSchema()]}return{fields:p,meta:{readonly:!1},title:null}},[d.values.fields,e,u,o==null?void 0:o.label,a]);return i.jsx(Ie,{schema:h,values:o,onSubmit:r,cancelText:o?void 0:"Back",onCancel:t})}),ue=c.memo(function(n){const{parentPath:e,index:t,children:r,initial:o,editing:a,conditionalSourceFields:u}=n,[d,h]=c.useState(),f=(o==null?void 0:o.type)??d,p=f?tt[f].fieldTypeName:void 0,{setFieldValue:g,values:y}=D.useFormikContext();if(a&&!o)throw new Error("Initial field must be provided if editing is true.");const v=!f&&!a&&!o,b=v?"Choose a field type":`${p} settings`,z=v?"Select a field type to add to this section.":(p==null?void 0:p.toLowerCase())==="section"?"Customize your section":`Customize your ${p==null?void 0:p.toLowerCase()} field.`,T=c.useCallback(()=>h(void 0),[]),F=c.useCallback(C=>{h(void 0),C()},[]),E=c.useCallback((C,A)=>{const{label:B}=C;if(!f)throw new Error("Field type must be selected before creating a field.");if(!B||typeof B!="string")throw new Error("Label must be provided before creating a field.");const Y=de({type:f,...C,identifier:ft(C.identifier,B)}).serialize(),N=Q(y,e);if(N===void 0)throw new Error("Parent path must point to an existing field.");let G;if(!Array.isArray(N))throw new Error("Parent path must point to an array.");a?G=ut(N,t,Y):G=Ke(N,t,Y),g(e,G).then(),A()},[a,f,y,e,g,t]),M=c.useCallback(C=>v?i.jsx(Pt,{setFieldType:h}):i.jsx(Vt,{conditionalSourceFields:u,handleCancel:T,handleCreateField:A=>E(A,C),fieldType:f,defaultField:o}),[u,T,E,o,v,f]);return i.jsx(s.Dialog,{onCloseInterrupt:F,title:b,description:z,content:M,children:r})}),nt=({children:l})=>i.jsx(i.Fragment,{children:l}),rt=(l,n)=>({initial:l?n:"none",sm:l?"none":n}),st=c.memo(function(n){const{remove:e,dragHandleProps:t,editProps:r,insertAfterProps:o,duplicateProps:a}=n,u=c.useMemo(()=>[{Wrapper:ue,wrapperProps:r,Icon:s.Pencil1Icon,text:"Edit"},{Icon:s.TrashIcon,buttonProps:{onClick:e},text:"Delete"},{Wrapper:ue,wrapperProps:a,Icon:s.CopyIcon,text:"Duplicate"},{Wrapper:ue,wrapperProps:o,Icon:s.PlusIcon,text:"Add after"},{Icon:d=>i.jsx("div",{...d,children:i.jsx(s.DragHandleDots2Icon,{})}),text:"Reorder",disableOnMobile:!0,buttonProps:{...t,asChild:!0}}],[t,a,r,o,e]);return i.jsxs(i.Fragment,{children:[i.jsx(s.Flex,{gap:"4",display:rt(!1,"flex"),children:u.map(d=>{const h=d.Wrapper??nt;return i.jsx(h,{...d.wrapperProps,children:i.jsx(s.IconButton,{type:"button",variant:"ghost","aria-label":d.text,...d.buttonProps,children:i.jsx(d.Icon,{})})},d.text)})}),i.jsx(s.Box,{display:rt(!0,"block"),children:i.jsx(s.DropdownMenu,{trigger:i.jsx(s.IconButton,{variant:"ghost","aria-label":"Actions menu",children:i.jsx(s.DotsVerticalIcon,{})}),closeOnSelect:!1,items:u.map(d=>{var f;if(d.disableOnMobile)return null;const h=d.Wrapper??nt;return{...d.buttonProps,onSelect:(f=d.buttonProps)==null?void 0:f.onClick,content:i.jsx(h,{...d.wrapperProps,children:i.jsxs(s.Flex,{gap:"2",align:"center",children:[i.jsx(d.Icon,{}),d.text]})})}}).filter(d=>d!==null)})})]})}),Ce="form-builder",Bt=c.memo(function(n){const{field:e,index:t,sectionIndex:r,remove:o}=n,a=c.useMemo(()=>de(e),[e]),u=ce(a,{formId:Ce,disabled:!0});console.log(e,t,r,a);const d=c.useMemo(()=>({index:t,parentPath:`fields.${r}.fields`,initial:e,editing:!0}),[e,t,r]),h=c.useMemo(()=>({parentPath:`fields.${r}.fields`,index:t+1,initial:{...e,identifier:""}}),[e,t,r]),f=c.useMemo(()=>({parentPath:`fields.${r}.fields`,index:t+1,initial:void 0}),[t,r]);return i.jsx(j.Draggable,{draggableId:e.identifier,index:t,children:p=>i.jsx(s.Card,{ref:p.innerRef,...p.draggableProps,...p.dragHandleProps,mb:"4",children:i.jsxs(s.Flex,{gap:"4",justify:"between",align:"center",children:[u,i.jsx(st,{remove:o,editProps:d,duplicateProps:h,insertAfterProps:f,dragHandleProps:p.dragHandleProps})]})})})}),_t=c.memo(function(n){var M,C,A,B,Y,N,G;const{field:e,index:t,dropState:r}=n,o=(M=r[e.identifier])==null?void 0:M.disabled,{setFieldValue:a,values:u}=D.useFormikContext(),d=s.useAlertDialog(),h=c.useCallback((w,S)=>{for(const P of w){const L=S.indexOf(P);a(`fields.${L}.condition`,null).then(),a(`fields.${L}.conditional`,!1).then()}},[a]),f=c.useCallback(w=>{var L;const S=e.fields[w];if(!S)throw new Error("Could not find field to remove.");const P=[];for(const W of u.fields)((L=W.condition)==null?void 0:L.identifier)===S.identifier&&P.push(W);return{removing:S,affectedSections:P,action:()=>a(`fields.${t}.fields`,ye(e.fields,w))}},[e.fields,u.fields,a,t]),p=c.useCallback(w=>{const{affectedSections:S,action:P,removing:L}=f(w),W=()=>{P().then(),h(S,u.fields)};if(S.length>0){const fe=S.map(be=>be.label).join(", ");return d({title:"Remove condition?",description:`${L.label} is being used as a condition, deleting it will remove the condition from the ${fe} section(s).`,severity:"danger",actionText:"Remove",onAction:W})}W()},[f,h,u.fields,d]),g=c.useCallback(()=>{const S=e.fields.map((Te,Yt)=>f(Yt)).flatMap(Te=>Te.affectedSections),P=S.length?"Remove fields and conditions?":"Remove fields?",L=e.fields.length,W=S.map(Te=>Te.label).join(", "),fe=S.length?`Deleting this section will remove the ${L} field(s) it contains and will remove the conditions from following sections: ${W}`:`Deleting this section will remove the ${L} field(s) it contains.`,be=ye(u.fields,t),at=()=>a("fields",be);if(S.length>0)return d({title:P,description:fe,severity:"danger",actionText:"Remove",onAction:()=>{at().then(()=>{h(S,be)})}});at().then()},[e.fields,u.fields,t,f,a,d,h]),y=c.useMemo(()=>({index:t,parentPath:"fields",initial:e,editing:!0,conditionalSourceFields:xe(u.fields,t)}),[e,t,u.fields]),v=c.useMemo(()=>({index:t+1,parentPath:"fields",initial:ge(),conditionalSourceFields:xe(u.fields,t+1)}),[t,u.fields]),b=c.useMemo(()=>({parentPath:`fields.${t}.fields`,index:e.fields.length,initial:void 0}),[e.fields.length,t]),z=c.useMemo(()=>({index:t+1,parentPath:"fields",initial:e,conditionalSourceFields:xe(u.fields,t+1)}),[e,t,u.fields]),T=c.useMemo(()=>{var w,S;return(S=Ye(u.fields,(w=e.condition)==null?void 0:w.identifier))==null?void 0:S.label},[(C=e.condition)==null?void 0:C.identifier,u.fields]),F=Array.isArray((A=e.condition)==null?void 0:A.value)?"contains all of":"equals";if(we((B=e.condition)==null?void 0:B.value))throw new Error("File values are not supported for conditions.");const E=Array.isArray((Y=e.condition)==null?void 0:Y.value)?(N=e.condition)==null?void 0:N.value.map(w=>typeof w=="string"?w:w.label).join(", "):(G=e.condition)==null?void 0:G.value.toString();return i.jsx(j.Draggable,{draggableId:e.identifier,index:t,children:w=>i.jsx(s.Card,{ref:w.innerRef,...w.draggableProps,...w.dragHandleProps,mb:"4",children:i.jsxs(s.Flex,{gap:"3",justify:"between",align:"center",children:[i.jsxs(s.Flex,{direction:"column",gap:"2",grow:"1",children:[i.jsxs(s.Flex,{direction:"column",children:[i.jsx(s.Heading,{as:"h3",size:"3",children:e.label}),i.jsx(s.Text,{className:pe.description,children:e.description})]}),e.condition&&i.jsx(s.Text,{size:"1",children:i.jsxs(s.Em,{children:["Display only if ",i.jsx(s.Strong,{children:T})," ",F," ",i.jsx(s.Strong,{children:E})]})}),i.jsx(j.Droppable,{droppableId:e.identifier,type:"SECTION",isDropDisabled:o,children:S=>i.jsxs(s.Flex,{ref:S.innerRef,...S.droppableProps,direction:"column",gap:"0",children:[e.fields.map((P,L)=>i.jsx(Bt,{field:P,index:L,sectionIndex:t,remove:()=>p(L)},P.identifier)),S.placeholder,i.jsx(ue,{...b,children:i.jsxs(s.Button,{type:"button",variant:"outline",children:[i.jsx(s.PlusIcon,{})," Add a field"]})})]})})]}),i.jsx(st,{remove:g,insertAfterProps:v,dragHandleProps:w.dragHandleProps,editProps:y,duplicateProps:z})]})})})}),$t=(l,n)=>{var t;const e={...l};switch(n.type){case"release":for(const r in e)e[r].disabled=!1;return e;case"hold":for(const r in e)(t=e[r])!=null&&t.conditionFields.has(n.fieldId)&&(e[r].disabled=!0);return e;case"update":return n.state}},Ot=(l,n)=>{if(n)for(let e=0;e<l.length;e++){const t=l[e];if(t){for(const r of t.fields)if(r.identifier===n)return e}}},ot=l=>{var e,t,r;const n={};for(let o=0;o<l.length;o++){const a=l[o];if(!a)throw new Error("Field is undefined.");const u=o>0?(e=n[l[o-1].identifier])==null?void 0:e.conditionFields:void 0,d=new Set(u);(t=a.condition)!=null&&t.identifier&&d.add(a.condition.identifier),n[a.identifier]={disabled:!1,conditionFields:d,conditionIndex:Ot(l,(r=a.condition)==null?void 0:r.identifier),index:o,label:a.label}}return n},lt=(l,n)=>{for(const[e,t]of Object.entries(l))if(t.identifier===n)return[t,e]},qt=c.memo(function(){const{values:n,setFieldValue:e}=D.useFormikContext(),[t,r]=c.useReducer($t,n.fields,ot),{showInfo:o}=s.useToast();c.useEffect(()=>{r({type:"update",state:ot(n.fields)})},[r,n.fields]);const a=c.useCallback(h=>{h.type==="SECTION"&&r({type:"hold",fieldId:h.draggableId})},[]),u=c.useCallback(h=>{const{source:f,destination:p,type:g,reason:y,draggableId:v}=h;if(r({type:"release"}),!p||y==="CANCEL")return;if(g==="ROOT"){const E=t[v];if(!E)throw new Error("Could not find section context.");let M=typeof E.conditionIndex<"u"?Math.max(E.conditionIndex+1,p.index):p.index;for(const C of Object.values(t))C.conditionIndex===f.index&&(M=Math.min(M,C.index-1));return M!=p.index&&o({title:"Reordered sections",description:"Sections with conditions must be below the fields they reference."}),e("fields",ze(n.fields,f.index,M))}if(g!=="SECTION")throw new Error("Unexpected droppable type.");const[b,z]=lt(n.fields,f.droppableId)??[],[T,F]=lt(n.fields,p.droppableId)??[];if(!(b!=null&&b.fields)||!T)throw new Error("Could not find section with fields.");if(b.identifier===T.identifier)e(`fields.${z}.fields`,ze(b.fields,f.index,p.index)).then();else{const E=b.fields[f.index];if(!E)throw new Error("Could not find field to reorder.");e(`fields.${z}.fields`,ye(b.fields,f.index)).then(),e(`fields.${F}.fields`,Ke(T.fields,p.index,E)).then()}},[n.fields,e,t,o]),d=c.useMemo(()=>({index:n.fields.length,parentPath:"fields",initial:ge(),conditionalSourceFields:xe(n.fields,n.fields.length)}),[n.fields]);return i.jsx(j.DragDropContext,{onDragStart:a,onDragEnd:u,children:i.jsx(j.Droppable,{droppableId:"droppable",type:"ROOT",children:h=>i.jsxs(s.Flex,{ref:h.innerRef,...h.droppableProps,direction:"column",gap:"0",children:[n.fields.map((f,p)=>i.jsx(_t,{field:f,index:p,dropState:t},f.label)),h.placeholder,i.jsx(ue,{...d,children:i.jsxs(s.Button,{type:"button",variant:"outline",children:[i.jsx(s.PlusIcon,{})," Add a section"]})})]})})})}),Nt={title:"",description:"",fields:[]},Wt=new X({label:"Title",minLength:0,maxLength:100,required:!0,identifier:"title"}),jt={formId:Ce,placeholder:"Give your form a title."},Ht=new J({label:"Description",minLength:0,maxLength:1e3,required:!1,identifier:"description"}),Ut={formId:Ce,placeholder:"Explain the purpose of this form."},Gt=()=>{alert("This is a form preview, your data will not be saved.")},Kt=c.memo(c.forwardRef((l,n)=>{const{onCancel:e,onSave:t,revision:r}=l,o=r?"Edit form":"Create a new form",{heading:a=o}=l,u=c.useCallback(y=>{const v={};if(y.title||(v.title="Title is required."),(!y.fields||y.fields.length===0)&&(v.fields="At least one field is required."),Fe(v))return v},[]),d=D.useFormik({initialValues:ct(r)??Nt,validate:u,onSubmit:y=>t(y),validateOnChange:!1,validateOnBlur:!1}),h=c.useMemo(()=>De(d.values),[d.values]),f=ce(Wt,jt),p=ce(Ht,Ut),g=c.useMemo(()=>typeof a=="object"?a:i.jsx(s.Heading,{children:a}),[a]);return i.jsx(s.Tabs.Root,{ref:n,defaultValue:"edit",children:i.jsxs(s.Flex,{direction:"column",gap:"2",children:[i.jsxs(s.Tabs.List,{children:[i.jsx(s.Tabs.Trigger,{value:"edit",children:"Edit"}),i.jsx(s.Tabs.Trigger,{value:"preview",children:"Preview"})]}),i.jsxs(s.Tabs.Content,{value:"edit",children:[g,i.jsxs(s.Text,{children:["Add a new form field by clicking a + button. Specify options for each field, then drag and drop to rearrange them. You can see what a submitted form might look like in the"," ",i.jsx("em",{children:"Preview"})," tab, but"," ",i.jsx("strong",{children:"field values entered on this page will not be saved."})]}),i.jsx(s.Flex,{asChild:!0,direction:"column",gap:"2",mt:"3",children:i.jsxs("form",{id:Ce,onSubmit:d.handleSubmit,children:[i.jsxs(D.FormikProvider,{value:d,children:[f,p,i.jsx(qt,{}),i.jsx(s.Text,{severity:"danger",size:"1",children:typeof d.errors.fields=="string"&&d.errors.fields})]}),i.jsxs(s.Flex,{justify:"end",gap:"2",children:[i.jsx(s.Button,{type:"button",variant:"soft",onClick:e,children:"Cancel"}),i.jsx(s.Button,{type:"submit",disabled:!d.isValid,children:"Save"})]})]})})]}),i.jsx(s.Tabs.Content,{value:"preview",children:i.jsx(Ie,{schema:h,onSubmit:Gt})})]})})}));x.BooleanField=K,x.BooleanInput=Ne,x.DateField=he,x.DateInput=je,x.FieldSection=U,x.FormBrowser=Ct,x.FormBuilder=Kt,x.FormRenderer=Ie,x.FormSubmissionBrowser=St,x.FormSubmissionViewer=It,x.MultiSelectField=ae,x.MultiSelectInput=Je,x.MultiStringField=oe,x.MultiStringInput=Qe,x.NumberField=H,x.NumberInput=We,x.PatchField=zt,x.PatchFormProvider=Et,x.SelectField=le,x.SelectInput=Ge,x.StringField=X,x.StringInput=He,x.TextField=J,x.TextInput=Ue,x.deserialize=de,x.deserializeField=Pe,x.formRevisionToSchema=De,x.isConditionMet=Le,x.useFieldInput=ce,x.useFieldInputs=Ve,x.valueIsFile=we,Object.defineProperty(x,Symbol.toStringTag,{value:"Module"})});
1
+ (function(x,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("react/jsx-runtime"),require("@overmap-ai/blocks"),require("formik"),require("react"),require("@hello-pangea/dnd"),require("@overmap-ai/core"),require("lodash.get"),require("lodash.set")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","@overmap-ai/blocks","formik","react","@hello-pangea/dnd","@overmap-ai/core","lodash.get","lodash.set"],i):(x=typeof globalThis<"u"?globalThis:x||self,i(x.forms={},x.jsxRuntime,x.blocks,x.formik,x.React,x.dnd,x.core,x.get,x.set))})(this,function(x,i,s,D,c,j,I,Q,Se){"use strict";var Qt=Object.defineProperty;var Xt=(x,i,s)=>i in x?Qt(x,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):x[i]=s;var m=(x,i,s)=>(Xt(x,typeof i!="symbol"?i+"":i,s),s);class qe{constructor(n){m(this,"type");m(this,"identifier");m(this,"description");const{description:e=null,identifier:t,type:r}=n;this.identifier=t,this.description=e,this.type=r}getId(){return this.identifier}static deserialize(n){throw new Error(`${this.name} must implement deserialize.`)}_serialize(){if(!this.identifier)throw new Error("Field identifier must be set before serializing.");return{type:this.type,identifier:this.identifier,description:this.description}}}class V extends qe{constructor(e){const{label:t,required:r,fieldValidators:o=[],formValidators:a=[],...u}=e;super(u);m(this,"required");m(this,"formValidators");m(this,"fieldValidators");m(this,"label");m(this,"onlyValidateAfterTouched",!0);this.label=t,this.required=r,this.fieldValidators=o,this.formValidators=a}static getFieldCreationSchema(){return[]}isBlank(e){return e==null||e===""}getValueFromChangeEvent(e){return e.target.value}getError(e,t){if(this.required&&this.isBlank(e))return"This field is required.";for(const r of this.getFieldValidators()){const o=r(e);if(o)return o}if(t)for(const r of this.getFormValidators()){const o=r(e,t);if(o)return o}}_serialize(){return{...super._serialize(),label:this.label,required:this.required}}getFieldValidators(){return[...this.fieldValidators]}getFormValidators(){return[...this.formValidators]}}m(V,"fieldTypeName"),m(V,"fieldTypeDescription");const pe={description:"_description_17zed_1"},$=l=>{const{label:n,children:e,severity:t,inputId:r,labelId:o,flexProps:a}=l;return i.jsx(s.Flex,{direction:"column",gap:"1",asChild:!0,...a,children:i.jsxs("label",{htmlFor:r,children:[i.jsx(s.Text,{severity:t,id:o,children:n}),e]})})},O=l=>{const{helpText:n,children:e,severity:t}=l;return i.jsxs(s.Flex,{direction:"column",gap:"1",children:[e,i.jsx(s.Flex,{direction:"column",children:i.jsx(s.Text,{size:"1",severity:t,className:pe.description,children:n})})]})},q=l=>{const{id:n,field:e,formId:t,...r}=l,[o,a,u]=D.useField(e.getId()),{touched:d}=a,h=a.error??e.description,f=a.error?"danger":void 0,p=n??`${t}-${e.getId()}-input`,g=`${p}-label`,y=e.required?`${e.label} *`:e.label,v=c.useMemo(()=>({...o,onChange:T=>{const F=e.getValueFromChangeEvent(T);u.setValue(F,!1).then(),(d||!e.onlyValidateAfterTouched)&&u.setError(e.getError(F))},onBlur:T=>{u.setTouched(!0,!1).then(),u.setError(e.getError(e.getValueFromChangeEvent(T)))}}),[e,o,u,d]);return[{helpText:h,severity:f,inputId:p,labelId:g,label:y,fieldProps:v,helpers:u,field:e},{...r,"aria-labelledby":g}]},dt=[!0,"true"],Ne=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u},d]=q(n),h=s.useSeverityColor(r),f=dt.includes(u.value);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,flexProps:{direction:"row-reverse",justify:"end",align:"center",gap:"2"},children:i.jsx(s.Checkbox,{...d,...u,id:e,color:h,value:f.toString(),checked:f,onCheckedChange:u.onChange,onChange:void 0,onBlur:void 0})})})}),Z=class Z extends V{constructor(e){super({...e,type:"boolean"});m(this,"onlyValidateAfterTouched",!1)}isBlank(e){return this.required&&!e}getValueFromChangeEvent(e){return typeof e=="boolean"?e:e.target.checked}serialize(){return super._serialize()}static deserialize(e){if(e.type!=="boolean")throw new Error("Type mismatch.");return new Z(e)}getInput(e){return i.jsx(Ne,{...e,field:this})}};m(Z,"fieldTypeName","Checkbox"),m(Z,"fieldTypeDescription","Perfect for both optional and required yes/no questions."),m(Z,"Icon",s.CheckCircledIcon);let K=Z;const We=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u,field:d},h]=q(n),f=s.useSeverityColor(r);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.TextField.Input,{...h,...u,type:"number",id:e,min:d.minimum,max:d.maximum,step:d.integers?1:.1,color:f})})})}),_=class _ extends V{constructor(e){const{minimum:t=Number.MIN_SAFE_INTEGER,maximum:r=Number.MAX_SAFE_INTEGER,integers:o=!1,...a}=e;super({...a,type:"number"});m(this,"minimum");m(this,"maximum");m(this,"integers");this.minimum=t,this.maximum=r,this.integers=o}getValueFromChangeEvent(e){const t=Number.parseFloat(e.target.value);return Number.isNaN(t)?"":t}static getFieldCreationSchema(){return[new _({label:"Minimum",description:"Minimum value",integers:!0,required:!1,identifier:"minimum",formValidators:[this._validateMin]}),new _({label:"Maximum",description:"Maximum value",integers:!0,required:!1,identifier:"maximum",formValidators:[this._validateMax]}),new K({label:"Integers",description:"Whole numbers only",required:!1,identifier:"integers"})]}getFieldValidators(){const e=super.getFieldValidators(),t=this.minimum,r=this.maximum;return typeof t=="number"&&e.push(o=>{if(typeof o=="number"&&o<t)return`Must be at least ${this.minimum}.`}),typeof r=="number"&&e.push(o=>{if(typeof o=="number"&&o>r)return`Must be at most ${this.maximum}.`}),this.integers&&e.push(o=>{if(typeof o=="number"&&!Number.isInteger(o))return"Must be a whole number."}),e}serialize(){return{...super._serialize(),minimum:this.minimum,maximum:this.maximum,integers:this.integers}}static deserialize(e){if(e.type!=="number")throw new Error("Type mismatch.");return new _(e)}getInput(e){return i.jsx(We,{field:this,...e})}};m(_,"fieldTypeName","Number"),m(_,"fieldTypeDescription","Allows specifying a number within a given range."),m(_,"Icon",s.FontFamilyIcon),m(_,"_validateMin",(e,t)=>typeof t.maximum=="number"&&typeof e=="number"&&t.maximum<e?"Minimum cannot be greater than minimum.":null),m(_,"_validateMax",(e,t)=>typeof t.minimum=="number"&&typeof e=="number"&&t.minimum>e?"Maximum cannot be less than minimum.":null);let H=_;const je=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u},d]=q(n),h=s.useSeverityColor(r),f=u.value?u.value.split("T")[0]:"";return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.TextField.Input,{...d,...u,type:"date",id:e,color:h,value:f})})})}),k=class k extends V{constructor(e){super({...e,type:"date"});m(this,"onlyValidateAfterTouched",!1)}serialize(){return super._serialize()}getValueFromChangeEvent(e){return new Date(e.target.value).toISOString()}static deserialize(e){if(e.type!=="date")throw new Error("Type mismatch.");return new k(e)}getInput(e){return i.jsx(je,{field:this,...e})}};m(k,"fieldTypeName","Date"),m(k,"fieldTypeDescription","Allows specifying a date."),m(k,"Icon",s.CalendarIcon);let he=k;class me extends V{constructor(e){const{minLength:t,maxLength:r=5e3,...o}=e;super(o);m(this,"minLength");m(this,"maxLength");this.minLength=t?Math.max(t,0):void 0,this.maxLength=r?Math.max(r,0):5e3}static getFieldCreationSchema(){return[new H({label:"Minimum length",description:"Minimum number of characters",required:!1,identifier:"minimum_length",minimum:0,maximum:100,formValidators:[this._validateMin],integers:!0}),new H({label:"Maximum length",description:"Maximum number of characters",required:!1,identifier:"maximum_length",minimum:1,maximum:5e3,formValidators:[this._validateMax],integers:!0})]}getFieldValidators(){const e=super.getFieldValidators();return this.minLength&&e.push(t=>{if(this.minLength&&(!t||t.length<this.minLength))return!this.required&&!t?null:`Minimum ${this.minLength} character(s).`}),this.maxLength&&e.push(t=>{if(typeof t=="string"&&this.maxLength&&t.length>this.maxLength)return`Maximum ${this.maxLength} character(s).`}),e}_serialize(){if(!this.identifier)throw new Error("Field identifier must be set before serializing.");return{...super._serialize(),minimum_length:this.minLength,maximum_length:this.maxLength}}}m(me,"_validateMin",(e,t)=>typeof t.maximum_length=="number"&&typeof e=="number"&&t.maximum_length<e?"Minimum cannot be greater than maximum.":null),m(me,"_validateMax",(e,t)=>{if(typeof e!="number")return null;const{minimum_length:r}=t;return typeof r!="number"?null:r>e?"Maximum cannot be less than minimum.":null});const He=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u,field:d},h]=q(n),f=s.useSeverityColor(r);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.TextField.Input,{...h,...u,type:d.inputType,id:e,color:f})})})}),R=class R extends me{constructor(e){const{inputType:t="text",...r}=e,o=e.maxLength?Math.min(500,e.maxLength):500,a=e.minLength?Math.min(e.minLength,o):void 0;super({...r,maxLength:o,minLength:a,type:"string"});m(this,"inputType");this.inputType=t}serialize(){return{...super._serialize(),input_type:this.inputType}}static deserialize(e){if(e.type!=="string")throw new Error("Type mismatch.");const{maximum_length:t,minimum_length:r,input_type:o,...a}=e;return new R({...a,maxLength:t,minLength:r,inputType:o})}getInput(e){return i.jsx(He,{field:this,...e})}};m(R,"fieldTypeName","Short Text"),m(R,"fieldTypeDescription","Short text fields can hold up to 500 characters on a single line."),m(R,"Icon",s.InputIcon);let X=R;const Ue=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u},d]=q(n);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.TextArea,{...d,...u,resize:"vertical",id:e,severity:r})})})}),ee=class ee extends me{constructor(n){const e=n.maxLength?Math.min(5e3,n.maxLength):5e3,t=n.minLength?Math.min(n.minLength,e):void 0;super({...n,maxLength:e,minLength:t,type:"text"})}serialize(){return super._serialize()}static deserialize(n){if(n.type!=="text")throw new Error("Type mismatch.");const{maximum_length:e,minimum_length:t,...r}=n;return new ee({...r,maxLength:e,minLength:t})}getInput(n){return i.jsx(Ue,{field:this,...n})}};m(ee,"fieldTypeName","Paragraph"),m(ee,"fieldTypeDescription","Paragraph fields can hold up to 5000 characters and can have multiple lines."),m(ee,"Icon",s.RowsIcon);let J=ee;const Ge=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u,field:d},h]=q(n),{onChange:f,onBlur:p}=u,g=c.useMemo(()=>d.options.map(v=>({value:v.value,itemContent:v.label})),[d.options]),y=c.useCallback(v=>{f(v),p(v)},[f,p]);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.Select,{items:g,...u,onValueChange:y,placeholder:"Select one...",id:e,severity:r,...h})})})}),ge=(l="",n=[])=>({type:"section",fields:n,identifier:l,label:null,condition:null,conditional:!1}),ct=l=>{if(!l)return;const n=l.fields;let e=[];const t=[];for(const r of n)r.type==="section"?(e.length>0&&(t.push(ge(`AUTO_section-${n.indexOf(r)}`,e)),e=[]),t.push(r)):e.push(r);return e.length>0&&t.push(ge("AUTO_section-last",e)),{...l,fields:t,description:l.description??""}};function ze(l,n,e){const t=Array.from(l),[r]=t.splice(n,1);if(!r)throw new Error("Could not find field to reorder.");return t.splice(e,0,r),t}function ut(l,n,e){const t=Array.from(l);return t[n]=e,t}function Ke(l,n,e){const t=Array.from(l??[]);return t.splice(n,0,e),t}function ye(l,n){const e=Array.from(l);return e.splice(n,1),e}const ft=(l,n)=>{if(typeof l=="string"&&l.length>0)return l;const e=new Date;return`${I.slugify(n)}-${e.getTime()}`},Ye=(l,n)=>{if(!n)return null;for(const e of l)if(e.type==="section"){const t=Ye(e.fields,n);if(t)return t}else if(e.identifier===n)return e;return null},xe=(l,n)=>l.filter((e,t)=>t<n).flatMap(e=>e.fields),Qe=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u},d]=q(n),h=s.useSeverityColor(r),f=c.useMemo(()=>Array.isArray(u.value)?u.value:[],[u.value]),{onChange:p,onBlur:g}=u,y=`${e}-droppable`,{disabled:v}=d,[b,z]=c.useState(""),[T,F]=c.useState(""),E=T||o,M=T?"red":h,C=c.useCallback(w=>{p(w),g(w)},[p,g]),A=c.useCallback(w=>{f.findIndex(S=>S.value===w.target.value.trim())>=0?F("All options must be unique"):w.target.value?F(""):F("Option cannot be empty"),z(w.target.value)},[z,f]),B=c.useCallback(()=>{if(T)return;if(!b.trim())return F("Option cannot be empty");const w=b.trim();C([...f,{value:w,label:w}]),z("")},[b,T,C,f]),Y=c.useCallback(w=>{w.key==="Enter"&&(w.preventDefault(),B())},[B]),N=c.useCallback(w=>{C(ye(f,w))},[f,C]),G=c.useCallback(w=>{if(!w.destination)return;const S=w.source.index,P=w.destination.index;C(ze(f,S,P))},[C,f]);return i.jsx(j.DragDropContext,{onDragEnd:G,children:i.jsxs(s.Flex,{direction:"column",gap:"2",children:[i.jsx(O,{helpText:E,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:(!v||f.length===0)&&i.jsxs(s.Flex,{gap:"2",children:[i.jsx(s.Box,{grow:"1",children:i.jsx(s.TextField.Input,{placeholder:"Press enter to add a new option",...d,...u,value:b,onChange:A,onKeyDown:Y,id:e,color:M,onBlur:void 0})}),i.jsx(s.IconButton,{type:"button","aria-label":"Add option",disabled:!!T||v,onClick:B,children:i.jsx(s.PlusIcon,{})})]})})}),i.jsx(j.Droppable,{droppableId:y,children:w=>i.jsxs(s.Flex,{...w.droppableProps,ref:w.innerRef,direction:"column",children:[f.map((S,P)=>i.jsx(j.Draggable,{draggableId:`${S.value}-draggable`,index:P,isDragDisabled:v,children:({draggableProps:L,dragHandleProps:W,innerRef:fe})=>i.jsx(s.Flex,{...W,...L,ref:fe,gap:"2",align:"center",justify:"between",mb:"1",asChild:!0,children:i.jsxs(s.Badge,{color:"gray",size:"2",children:[i.jsx("span",{children:S.label}),i.jsx(s.IconButton,{size:"small",variant:"ghost",type:"button","aria-label":"Delete option",severity:"info",disabled:v,onClick:()=>N(P),children:i.jsx(s.Cross1Icon,{})})]})})},S.value)),w.placeholder]})})]})})}),te=class te extends V{constructor(e){const{minimum_length:t,maximum_length:r,...o}=e;super({...o,type:"multi-string"});m(this,"minLength");m(this,"maxLength");m(this,"onlyValidateAfterTouched",!1);this.minLength=t??0,this.maxLength=r??1/0}getValueFromChangeEvent(e){if(Array.isArray(e))return e;throw new Error("Expected an array.")}getInput(e){return i.jsx(Qe,{field:this,...e})}serialize(){return{...super._serialize(),minimum_length:this.minLength,maximum_length:this.maxLength}}isBlank(e){return super.isBlank(e)||e.length===0}getFieldValidators(){const e=super.getFieldValidators();return e.push(t=>{if(Array.isArray(t)&&t.length<this.minLength)return`Must have at least ${this.minLength} options.`}),e.push(t=>{if(Array.isArray(t)&&t.length>this.maxLength)return`Must have at most ${this.maxLength} options.`}),e}static deserialize(e){if(e.type!=="multi-string")throw new Error("Type mismatch.");return new te(e)}};m(te,"fieldTypeName","Multi-string"),m(te,"fieldTypeDescription","Allows the user to provide multiple unique strings."),m(te,"Icon",s.ListBulletIcon);let oe=te;class Xe extends V{constructor(e){super(e);m(this,"options");m(this,"onlyValidateAfterTouched",!1);const t=new Set;this.options=e.options.map(r=>(typeof r=="string"&&(r={label:r,value:r}),t.add(r.label),r)),t.size!==e.options.length&&console.error(`${e.options.length-t.size} duplicate identifiers found in options. This may cause unexpected behavior. Options:`,e.options)}_serialize(){return{...super._serialize(),options:this.options}}static getFieldCreationSchema(){return[new oe({label:"Options",description:"List possible options for the user to select from.",required:!0,identifier:"options",minimum_length:2,maximum_length:20})]}}const ie=class ie extends Xe{constructor(n){super({...n,type:"select"})}getValueFromChangeEvent(n){return typeof n=="string"?n:n.target.value}serialize(){return super._serialize()}static deserialize(n){if(n.type!=="select")throw new Error("Type mismatch.");return new ie(n)}getInput(n){return i.jsx(Ge,{field:this,...n})}};m(ie,"fieldTypeName","Dropdown"),m(ie,"fieldTypeDescription","Allows the user to select a single option from a list of options."),m(ie,"Icon",s.DropdownMenuIcon);let le=ie;const pt=l=>l?Array.isArray(l)?l:[l]:[],Je=c.memo(function(n){const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u,field:d},h]=q(n),{onChange:f,onBlur:p}=u,g=c.useMemo(()=>pt(u.value),[u.value]),y=c.useCallback(v=>{f(v),p(v)},[f,p]);return i.jsx(O,{helpText:o,severity:r,children:i.jsx($,{severity:r,inputId:e,labelId:t,label:a,children:i.jsx(s.MultiSelect,{value:g,onValueChange:y,options:d.options,name:u.name,placeholder:"Select one or more...",id:e,severity:r,...h})})})}),ne=class ne extends Xe{constructor(n){super({...n,type:"multi-select"})}getValueFromChangeEvent(n){if(Array.isArray(n))return n;throw new Error("Expected an array.")}isBlank(n){return super.isBlank(n)||n.length===0}serialize(){return super._serialize()}static deserialize(n){if(n.type!=="multi-select")throw new Error("Type mismatch.");return new ne(n)}getInput(n){return i.jsx(Je,{field:this,...n})}};m(ne,"fieldTypeName","Multi-select"),m(ne,"fieldTypeDescription","Allows the user to select a multiple options from a list of options."),m(ne,"Icon",s.CheckboxIcon);let ae=ne;const ht=c.memo(function({field:n,...e}){const[{value:t}]=D.useField(n.options.clonedFieldIdentifier),r=c.useMemo(()=>{const o=n.options.getFieldToClone(t);return o?de(o):null},[n.options,t]);return ce(r,e)});class ve extends V{constructor(e,t){super({...e,type:"custom"});m(this,"Component");m(this,"options");this.options=e,this.Component=t}serialize(){throw new Error("Serializing only supported for public input types.")}getInput(e){const t=this.Component;return i.jsx(t,{field:this,...e})}}m(ve,"fieldTypeName","Custom"),m(ve,"fieldTypeDescription","Allows re-rendering of field already in the form");class mt extends ve{constructor(n){super(n,ht)}}const gt=c.memo(function(n){const{field:e,...t}=n,{label:r,description:o,fields:a,condition:u}=e,{values:d,setFieldValue:h}=D.useFormikContext(),f=u!=null&&u.identifier?Q(d,u.identifier):void 0,p=c.useMemo(()=>Le(u,f),[u,f]);c.useEffect(()=>{if(!p)for(const y of a)h(y.getId(),"").then()},[p,a,h]);const g=Ve(a,t);return p?r?i.jsx(s.Card,{children:i.jsxs(s.Flex,{direction:"column",gap:"3",children:[i.jsxs(s.Flex,{direction:"column",children:[i.jsx(s.Heading,{as:"h3",size:"3",children:r}),i.jsx(s.Text,{className:pe.description,children:o})]}),g]})}):g:null}),re=class re extends qe{constructor(e){const{label:t=null,fields:r,condition:o=null,conditional:a,...u}=e;super({...u,type:"section"});m(this,"label");m(this,"fields");m(this,"condition");this.fields=r,this.condition=o,this.label=t,a===!1&&(this.condition=null)}static getFieldCreationSchema(e){return e.length===0?[]:[new K({label:"Conditional",description:"Conditionally show or hide this section.",identifier:"conditional",required:!1}),new re({label:"Conditional settings",identifier:"conditional-settings",condition:{identifier:"conditional",value:!0},fields:[new le({label:"Field",description:"The field to use for the condition.",options:e.map(t=>!t.label||t.type==="upload"?null:{label:t.label,value:t.identifier}).filter(t=>!!t),identifier:"condition.identifier",required:!0}),new mt({label:"Value",identifier:"condition.value",required:!0,clonedFieldIdentifier:"condition.identifier",getFieldToClone(t){if(!t)return null;const r=e.find(o=>o.identifier===t);return r?{...r,label:"Value",identifier:"condition.value",description:"The value to compare against.",required:r.type!=="boolean"}:(console.error("Could not find field with identifier",t),null)}})]})]}static deserialize(e){var r;if(e.type!=="section")throw new Error("Invalid type");const t=((r=e.fields)==null?void 0:r.map(Pe))??[];return new re({...e,fields:t})}conditional(){return this.condition!==null}serialize(){return{...super._serialize(),label:this.label,condition:this.condition,conditional:this.conditional(),fields:this.fields.map(e=>e.serialize())}}getErrors(e){const t={};for(const r of this.fields){const o=r.getId(),a=r.getError(Q(e,o),e);a&&Se(t,r.getId(),a)}return t}getInput(e){return i.jsx(gt,{field:this,...e})}};m(re,"fieldTypeName","Section"),m(re,"fieldTypeDescription","Sections can be useful for grouping fields together. They can also be conditionally shown or hidden.");let U=re;const yt={previewImage:"_previewImage_1ig84_1"},Ee=l=>{const n=["byte","kilobyte","megabyte"];let e=l,t=0;for(;e>1024&&t<n.length-1;)e/=1024,t++;return new Intl.NumberFormat([],{maximumFractionDigits:2,style:"unit",unit:n[t]}).format(e)},xt=c.memo(function(n){var M;const[{inputId:e,labelId:t,severity:r,helpText:o,label:a,fieldProps:u,field:d},h]=q(n),{onChange:f}=u,p=s.useSeverityColor(r),g=c.useRef(null),{value:y}=u,v=c.useMemo(()=>o||(d.maxFileSize?`Maximum file size: ${Ee(d.maxFileSize)}`:null),[d.maxFileSize,o]),b=c.useCallback(()=>{var C;(C=g.current)==null||C.click()},[]),z=c.useCallback(C=>{const A=[...y];A.splice(C,1),f({target:{files:A}})},[y,f]),T=y?"Select new files":"Select files",F=y?"Select new file":"Select a file",E=d.maxFiles>1?T:F;return i.jsxs(s.Flex,{direction:"column",gap:"2",children:[i.jsx(O,{helpText:v,severity:r,children:i.jsxs($,{severity:r,inputId:e,labelId:t,label:a,children:[i.jsx(s.Flex,{direction:"row",gap:"2",children:i.jsx(s.Box,{width:"max-content",asChild:!0,children:i.jsxs(s.Button,{...h,onClick:b,children:[i.jsx(s.UploadIcon,{})," ",E]})})}),i.jsx("input",{...h,type:"file",ref:g,id:e,accept:(M=d.extensions)==null?void 0:M.join(","),multiple:d.maxFiles>1,color:p,style:{display:"none"},...u,value:""})]})}),Array.isArray(y)&&y.length>0&&i.jsx(s.Flex,{direction:"column",gap:"2",children:y.map((C,A)=>i.jsx(vt,{field:d,file:C,onRemove:()=>z(A),disabled:h.disabled},A))})]})}),vt=c.memo(function({file:n,field:e,onRemove:t,disabled:r}){const[o,a]=c.useState(null),u=c.useMemo(()=>o&&e.getError([o]),[e,o]),{url:d,name:h,size:f}=c.useMemo(()=>{let p=null,g,y;return o!=null&&o.type.startsWith("image/")&&(p=URL.createObjectURL(o)),o?(g=o.name,y=Ee(o.size)):(g="Downloading...",y="..."),{url:p,name:g,size:y}},[o]);return c.useEffect(()=>{n instanceof Promise?n.then(a):a(n)},[n]),i.jsx(s.Card,{children:i.jsxs(s.Flex,{direction:{initial:"column",sm:"row"},gap:"3",justify:"between",children:[i.jsxs(s.Flex,{direction:"row",gap:"3",align:"center",grow:"1",shrink:"0",children:[i.jsx(s.IconButton,{severity:"info",variant:"outline","aria-label":`Remove ${h}`,disabled:r,onClick:t,children:i.jsx(s.Cross1Icon,{})}),i.jsxs(s.Flex,{direction:"column",gap:"1",children:[i.jsx(s.Text,{children:h}),i.jsx(s.Text,{size:"1",children:f}),u&&i.jsx(s.Text,{size:"1",severity:"danger",children:u})]})]}),d&&i.jsx("img",{className:yt.previewImage,src:d,alt:h})]})})}),Ze=50*1024*1024,se=class se extends V{constructor(e){const{extensions:t,maximum_files:r,maximum_size:o,...a}=e;super({...a,type:"upload"});m(this,"extensions");m(this,"maxFileSize");m(this,"maxFiles");m(this,"onlyValidateAfterTouched",!1);this.maxFileSize=typeof o=="number"?o:void 0,this.maxFiles=Math.max(typeof r=="number"?r:1,1),this.extensions=t}getValueFromChangeEvent(e){return Array.from(e.target.files||[])}isBlank(e){return super.isBlank(e)||e.length===0}static getFieldCreationSchema(){return[new H({label:"How many files can be uploaded?",description:"By default, only one file can be uploaded.",required:!1,minimum:1,maximum:10,identifier:"maximum_files"}),new H({label:"What is the maximum size of each file?",description:"Maximum file size in bytes.",required:!1,identifier:"maximum_size",minimum:1,maximum:Ze,integers:!0}),new ae({label:"Accepted file types",description:"Types of allowed files to upload. If left blank, all files will be accepted.",required:!1,identifier:"extensions",options:[{value:"image/*",label:"Images"},{value:"audio/*",label:"Audio files"},{value:"video/*",label:"Videos"},{value:"text/*",label:"Text files"},{value:"application/*",label:"Application files (includes PDFs and Word documents)"}]})]}getFieldValidators(){const e=super.getFieldValidators(),t=this.maxFileSize??Ze,r=this.maxFiles??1;return e.push(o=>{if(o&&o.some(a=>a.size>t))return`Files must be at most ${Ee(t)}.`}),e.push(o=>{if(o&&o.length>r)return`You can only upload ${r} files.`}),e}serialize(){return{...super._serialize(),extensions:this.extensions,maximum_size:this.maxFileSize,maximum_files:this.maxFiles}}static deserialize(e){if(e.type!=="upload")throw new Error("Type mismatch.");return new se(e)}getInput(e){return i.jsx(xt,{field:this,...e})}};m(se,"fieldTypeName","Upload"),m(se,"fieldTypeDescription","Allows a file to be uploaded."),m(se,"Icon",s.UploadIcon);let Me=se;const Ae={date:he,number:H,boolean:K,select:le,string:X,text:J,custom:ve,upload:Me,"multi-string":oe,"multi-select":ae},Pe=l=>{const n=l.type;return Ae[n].deserialize(l)},de=l=>l.type==="section"?U.deserialize(l):Pe(l);function De(l,n={}){const{readonly:e=!1}=n;return{title:l.title,description:l.description,fields:l.fields.map(t=>de(t)),meta:{readonly:e}}}function we(l){return!!(Array.isArray(l)&&l.some(n=>n instanceof File||n instanceof Promise))}function Le(l,n){if(!l)return!0;if(we(n)||we(l.value))throw new Error("Conditions do not support file uploads");const e=Array.isArray(n)?n.map(r=>typeof r=="string"?r:r.value):n,t=Array.isArray(l.value)?l.value.map(r=>typeof r=="string"?r:r.value):l.value;if(Array.isArray(t)&&Array.isArray(e)){for(const r of t)if(!e.includes(r))return!1;return!0}return t===n}const ce=(l,n)=>c.useMemo(()=>!n||!l?null:l.getInput(n),[l,n]),Ve=(l,n)=>{const e=c.useMemo(()=>l.map(t=>i.jsx("div",{children:t.getInput(n)},t.getId())),[l,n]);return i.jsx(s.Flex,{direction:"column",gap:"2",children:e})},Fe=l=>Object.keys(l).length>0,ke=async(l,n)=>{const e={};for(const t of l.fields)if(t instanceof U){if(t.condition){const{identifier:r}=t.condition;if(!Le(t.condition,Q(n,r)))continue}Object.assign(e,t.getErrors(n))}else{if(!(t instanceof V))throw new Error("Invalid field type");const r=t.getId(),o=t.getError(Q(n,r),n);o&&Se(e,r,o)}if(Fe(e))return e},wt=[null,void 0],Be=(l,n)=>l.reduce((e,t)=>t instanceof U?{...e,...Be(t.fields,n)}:(wt.includes(Q(e,t.getId()))&&Se(e,t.getId(),""),e),n),Ft=()=>{throw new Error("onSubmit must be provided if form is not readonly.")},Ie=c.memo(c.forwardRef((l,n)=>{const{schema:e,values:t={},onSubmit:r=Ft,submitText:o="Submit",cancelText:a,onCancel:u,onDirty:d,hideTitle:h=!e.title,hideDescription:f,className:p}=l,{readonly:g}=e.meta,y=c.useMemo(()=>crypto.randomUUID(),[]),v=D.useFormik({initialValues:Be(e.fields,t),onSubmit:r,validate:E=>ke(e,E),validateOnBlur:!1,validateOnChange:!1}),{dirty:b}=v,z=c.useMemo(()=>typeof e.title=="string"?i.jsx(s.Heading,{children:e.title}):e.title,[e.title]),T=c.useMemo(()=>typeof e.description=="string"?i.jsx(s.Text,{className:pe.description,children:e.description}):e.description,[e.description]),F=Ve(e.fields,{formId:y,disabled:g});return c.useEffect(()=>{b&&d&&d()},[b,d]),i.jsx(D.FormikProvider,{value:v,children:i.jsx(s.Flex,{ref:n,direction:"column",gap:"2",className:p,asChild:!0,children:i.jsxs("form",{id:y,onSubmit:v.handleSubmit,children:[!h&&i.jsx(s.Card,{children:i.jsxs(s.Flex,{direction:"column",gap:"1",children:[z,!f&&T]})}),F,!g&&i.jsxs(s.Flex,{justify:"end",gap:"2",children:[a&&i.jsx(s.Button,{type:"button",variant:"soft",onClick:u,children:a}),i.jsx(s.Button,{type:"submit",disabled:!v.isValid,children:o})]})]})})})})),It=c.memo(c.forwardRef((l,n)=>{const{submission:e,showFormDescription:t=!1,showFormTitle:r=!0}=l,o=I.useAppSelector(I.selectFormRevision(e.form_revision)),{sdk:a}=I.useSDK();if(!o)throw new Error(`Could not find revision ${e.form_revision} for submission ${e.offline_id}.`);const u=c.useMemo(()=>De(o,{readonly:!0}),[o]),d=c.useMemo(()=>{const h=I.selectSubmissionAttachments(e.offline_id)(a.store.getState())??[],f={};for(const p of h){const g=a.files.fetchFileFromUrl(p.file,p.file_sha1,p.file_name).then(v=>{if(!v.success)throw new Error(`Failed to download attachment ${p.file_name}.`);return v.body}),y=f[p.field_identifier];y?y.push(g):f[p.field_identifier]=[g]}return{...e.values,...f}},[a.files,a.store,e.offline_id,e.values]);return i.jsx(Ie,{ref:n,schema:u,values:d,hideDescription:!t,hideTitle:!r})})),Re={favoriteIcon:"_favoriteIcon_1bixi_1",regularIcon:"_regularIcon_1bixi_9"},_e="organization:",$e="user:",Ct=c.memo(c.forwardRef((l,n)=>{const{maxResults:e=20,...t}=l,[r,o]=c.useState(""),[a,u]=c.useState(""),{sdk:d}=I.useSDK(),h=c.useMemo(()=>{const F={maxResults:e,searchTerm:r};return a&&(a.startsWith(_e)?F.owner_organization=parseInt(a.slice(_e.length)):a.startsWith($e)&&(F.owner_user=parseInt(a.slice($e.length)))),F},[r,e,a]),f=I.useAppSelector(I.selectFilteredUserForms(h))??[],p=I.useAppSelector(I.selectUserFormMapping),g=c.useCallback(F=>{F.favorite?d.userForms.unfavorite(F.offline_id).then():d.userForms.favorite(F.offline_id).then()},[d]),y=c.useMemo(()=>{const F=d.store.getState(),E={};for(const M of Object.values(p)){const C=I.selectOrganization(M.owner_organization||-1)(F);C&&(E[`${_e}${C.id}`]=C.name);const A=I.selectUser(M.owner_user||-1)(F);A&&(E[`${$e}${A.id}`]=A.username)}return Object.entries(E).map(([M,C])=>({itemContent:C,value:M}))},[p,d.store]),v=c.useCallback(F=>{o(F.currentTarget.value)},[]),z=(I.useAppSelector(I.selectNumberOfUserForms)||0)-f.length,T=f.length==e&&z>0?`Only the first ${e} results are shown (${z} hidden)`:z>0&&`${z} hidden forms`;return i.jsxs(s.Flex,{ref:n,direction:"column",gap:"2",children:[i.jsxs(s.Flex,{gap:"2",grow:"1",children:[i.jsx(s.Box,{grow:"1",asChild:!0,children:i.jsx(s.TextField.Root,{size:"3",children:i.jsx(s.TextField.Input,{placeholder:"Filter",value:r,onChange:v})})}),i.jsx(s.Select,{items:y,value:a,onValueChange:u,placeholder:"Owner",size:"large"})]}),f.length>0&&i.jsx(s.ButtonList.Root,{children:f.map(F=>i.jsx(bt,{...t,form:F,handleToggleFavorite:()=>g(F)},F.offline_id))}),i.jsx(s.Box,{px:"3",children:i.jsx(s.Text,{size:"2",severity:"info",children:T})})]})})),bt=l=>{var g;const{form:n,onSelectForm:e,isFavoriteEditable:t,handleToggleFavorite:r}=l,o=(g=I.useAppSelector(I.selectOrganization(n.owner_organization||-1)))==null?void 0:g.name,a=I.useAppSelector(I.selectUser(n.owner_user||-1)),u=I.useAppSelector(I.selectCurrentUser).id,d=!!a&&a.id===u,h=o??(d?"You":a==null?void 0:a.username)??"Unknown",f=c.useCallback(y=>{y.stopPropagation(),r()},[r]),p=i.jsx(s.ButtonList.Item,{onClick:()=>e(n),asChild:!0,children:i.jsxs(s.Flex,{justify:"between",gap:"2",py:"2",px:"3",...s.divButtonProps,children:[i.jsxs(s.Flex,{grow:"1",align:"center",gap:"2",children:[i.jsx(s.IconButton,{className:I.classNames(n.favorite?Re.favoriteIcon:Re.regularIcon),variant:"ghost",onClick:f,"aria-label":n.favorite?"Favorite form":"Standard form",disabled:!t,children:n.favorite?i.jsx(s.StarFilledIcon,{}):i.jsx(s.StarIcon,{})}),i.jsx(s.Text,{noWrap:!0,children:n.latestRevision.title}),n.latestRevision.description&&i.jsx(s.QuestionMarkCircledIcon,{})]}),h&&i.jsxs(s.Flex,{align:"center",gap:"2",children:[i.jsx(s.PersonIcon,{})," ",h]})]})});return n.latestRevision.description?i.jsx(s.Tooltip,{content:n.latestRevision.description,children:p},n.offline_id):p},et={submissionsContainer:"_submissionsContainer_9iirt_1",stopHorizontalOverflow:"_stopHorizontalOverflow_9iirt_6"},Tt=c.memo(function(n){var F;const{submission:e,onSubmissionClick:t,compact:r,labelType:o,rowDecorator:a}=n,u=I.useAppSelector(I.selectCurrentUser),d=I.useAppSelector(I.selectUser("created_by"in e?e.created_by:u.id)),h=Oe(e),f=I.isToday(h)?h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):I.getLocalDateString(h),p=I.useAppSelector(I.selectFormRevision(e.form_revision));if(!p)throw new Error(`Could not find revision ${e.form_revision} for submission ${e.offline_id}.`);const g=(F=I.useAppSelector(I.selectLatestFormRevision(p.form)))==null?void 0:F.revision,y=I.useFileSrc({file:(d==null?void 0:d.profile.file)??null,fileSha1:(d==null?void 0:d.profile.file_sha1)??null}),v=(d==null?void 0:d.username.charAt(0).toUpperCase())??"?",b=p.revision===g,z=c.useCallback(()=>{t&&t({submission:e})},[e,t]),T=i.jsx(s.ButtonList.Item,{onClick:z,asChild:!0,children:i.jsxs(s.Flex,{grow:"1",width:"100%",p:"2",gap:"2",justify:"between",children:[i.jsxs(s.Flex,{gap:"2",align:"center",className:et.stopHorizontalOverflow,children:[i.jsx(s.Avatar,{src:y,size:"1",fallback:v}),i.jsx(s.Text,{size:"2",noWrap:!0,children:o==="creator"?(d||u).username:p.title})]}),i.jsxs(s.Flex,{gap:"2",align:"center",children:[!r&&(p.revision?i.jsx(s.Badge,{variant:"soft",severity:b?"primary":"info",children:r?p.revision.toString():`Revision #${p.revision}`}):!!g&&i.jsx(s.Badge,{children:"Original"})),i.jsx(s.Text,{size:"2",noWrap:!0,children:f})]})]})});return a?a(e,T):T}),Oe=l=>{const n="created_at"in l?l.created_at:l.submitted_at;return new Date(n)},St=c.memo(function(n){const{formId:e,submissions:t,compact:r=!1,className:o,after:a,variant:u="outline",...d}=n;if(!!e==!!t)throw new Error("Either formId or submissions must be provided, but not both.");const h=I.useAppSelector(t?()=>t:I.selectSubmissionsForForm(e)),f=c.useMemo(()=>h==null?void 0:h.sort((p,g)=>Oe(g).getTime()-Oe(p).getTime()),[h]);return i.jsx(s.ButtonList.Root,{className:I.classNames(et.submissionsContainer,o),size:"small",variant:u,before:!r&&i.jsxs(s.Text,{severity:"info",children:["There are ",((h==null?void 0:h.length)||0).toString()," submissions of this form."]}),after:a,children:f==null?void 0:f.map((p,g)=>i.jsx(Tt,{submission:p,compact:r,...d},g))})}),zt=c.memo(function(n){const{name:e,render:t}=n,{submitForm:r}=D.useFormikContext(),[o,a,u]=D.useField(e);return c.useMemo(()=>{const d=h=>u.setValue(h,!1);return t({value:o.value,setValue:d,patchValue:r})},[r,u,o.value,t])}),Et=c.memo(c.forwardRef((l,n)=>{const{children:e,schema:t,values:r,onPatch:o,onError:a,...u}=l,d=c.useMemo(()=>Be(t.fields,r),[t.fields,r]),h=c.useCallback(v=>{const b={};for(const z in v){const T=v[z];T!==d[z]&&T!==void 0&&(b[z]=T)}Fe(b)&&o(b)},[d,o]),f=c.useCallback(async v=>{const b=await ke(t,v);return b&&a(b),b},[t,a]),p=D.useFormik({initialValues:d,onSubmit:h,validate:f,validateOnBlur:!1,validateOnChange:!1}),{errors:g,resetForm:y}=p;return c.useEffect(()=>{Fe(g)&&y({values:d,errors:{}})},[g,d,y]),i.jsx(D.FormikProvider,{value:p,children:i.jsx("form",{...u,ref:n,onSubmit:p.handleSubmit,children:e})})})),tt={...Ae,section:U},Mt=c.memo(function(n){const{field:e,setFieldType:t}=n,r=e.fieldTypeName,o=e.fieldTypeDescription,a=e.Icon;return i.jsxs(s.Flex,{gap:"4",align:"center",children:[i.jsx(s.Button,{type:"button",variant:"surface",onClick:t,style:{width:"135px"},children:i.jsxs(s.Flex,{gap:"3",align:"center",grow:"1",children:[i.jsx(a,{}),r]})}),i.jsx(s.Text,{children:o})]})}),it=[["string","text"],["select","multi-select","upload"],["boolean","date","number","multi-string"]],At=it.length-1,Pt=c.memo(function(n){const{setFieldType:e}=n;return i.jsx(s.Flex,{direction:"column",gap:"3",children:it.map((t,r)=>i.jsxs(s.Flex,{direction:"column",gap:"3",children:[i.jsx(s.Flex,{direction:"column",gap:"2",children:t.map(o=>i.jsx(Mt,{field:Ae[o],setFieldType:()=>e(o)},o))}),r<At&&i.jsx(s.Separator,{size:"4"})]},r))})}),Dt=l=>n=>{if(console.log("in validate",l,n),!(!n||typeof n!="string")&&l.includes(n.trim()))return"This name is already taken."},Lt=(l,n)=>{const e=[new X({label:"Label",required:!0,maxLength:200,identifier:"label",fieldValidators:[Dt(l)]}),new J({label:"Description",required:!1,maxLength:1e3,identifier:"description"})];return n==="section"?e:[...e,new K({label:"Required",description:null,required:!1,identifier:"required"})]},Vt=c.memo(function(n){const{fieldType:e,handleCancel:t,handleCreateField:r,defaultField:o,conditionalSourceFields:a,editing:u}=n,d=tt[e];console.log("default field",o);const h=D.useFormikContext(),f=c.useMemo(()=>{const p=h.values.fields.flatMap(y=>y.type==="section"?[...y.fields.map(v=>v.label),y.label]:y.label).filter(y=>!u||y!==(o==null?void 0:o.label)&&y!==null);let g=Lt(p,e);if(console.log(p,g),d===U){if(a===void 0)throw new Error("Conditional source fields must be provided when changing sections.");g=g.concat(d.getFieldCreationSchema(a))}else{if(!(d.prototype instanceof V))throw new Error(`Field must be an instance of BaseField. Got ${d}.`);g=[...g,...d.getFieldCreationSchema()]}return{fields:g,meta:{readonly:!1},title:null}},[h.values.fields,e,d,u,o==null?void 0:o.label,a]);return i.jsx(Ie,{schema:f,values:o,onSubmit:r,cancelText:o?void 0:"Back",onCancel:t})}),ue=c.memo(function(n){const{parentPath:e,index:t,children:r,initial:o,editing:a,conditionalSourceFields:u}=n,[d,h]=c.useState(),f=(o==null?void 0:o.type)??d,p=f?tt[f].fieldTypeName:void 0,{setFieldValue:g,values:y}=D.useFormikContext();if(a&&!o)throw new Error("Initial field must be provided if editing is true.");const v=!f&&!a&&!o,b=v?"Choose a field type":`${p} settings`,z=v?"Select a field type to add to this section.":(p==null?void 0:p.toLowerCase())==="section"?"Customize your section":`Customize your ${p==null?void 0:p.toLowerCase()} field.`,T=c.useCallback(()=>h(void 0),[]),F=c.useCallback(C=>{h(void 0),C()},[]),E=c.useCallback((C,A)=>{const{label:B}=C;if(!f)throw new Error("Field type must be selected before creating a field.");if(!B||typeof B!="string")throw new Error("Label must be provided before creating a field.");const Y=de({type:f,...C,identifier:ft(C.identifier,B)}).serialize(),N=Q(y,e);if(N===void 0)throw new Error("Parent path must point to an existing field.");let G;if(!Array.isArray(N))throw new Error("Parent path must point to an array.");a?G=ut(N,t,Y):G=Ke(N,t,Y),g(e,G).then(),A()},[a,f,y,e,g,t]),M=c.useCallback(C=>v?i.jsx(Pt,{setFieldType:h}):i.jsx(Vt,{conditionalSourceFields:u,handleCancel:T,handleCreateField:A=>E(A,C),fieldType:f,defaultField:o,editing:a}),[u,a,T,E,o,v,f]);return i.jsx(s.Dialog,{onCloseInterrupt:F,title:b,description:z,content:M,children:r})}),nt=({children:l})=>i.jsx(i.Fragment,{children:l}),rt=(l,n)=>({initial:l?n:"none",sm:l?"none":n}),st=c.memo(function(n){const{remove:e,dragHandleProps:t,editProps:r,insertAfterProps:o,duplicateProps:a}=n,u=c.useMemo(()=>[{Wrapper:ue,wrapperProps:r,Icon:s.Pencil1Icon,text:"Edit"},{Icon:s.TrashIcon,buttonProps:{onClick:e},text:"Delete"},{Wrapper:ue,wrapperProps:a,Icon:s.CopyIcon,text:"Duplicate"},{Wrapper:ue,wrapperProps:o,Icon:s.PlusIcon,text:"Add after"},{Icon:d=>i.jsx("div",{...d,children:i.jsx(s.DragHandleDots2Icon,{})}),text:"Reorder",disableOnMobile:!0,buttonProps:{...t,asChild:!0}}],[t,a,r,o,e]);return i.jsxs(i.Fragment,{children:[i.jsx(s.Flex,{gap:"4",display:rt(!1,"flex"),children:u.map(d=>{const h=d.Wrapper??nt;return i.jsx(h,{...d.wrapperProps,children:i.jsx(s.IconButton,{type:"button",variant:"ghost","aria-label":d.text,...d.buttonProps,children:i.jsx(d.Icon,{})})},d.text)})}),i.jsx(s.Box,{display:rt(!0,"block"),children:i.jsx(s.DropdownMenu,{trigger:i.jsx(s.IconButton,{variant:"ghost","aria-label":"Actions menu",children:i.jsx(s.DotsVerticalIcon,{})}),closeOnSelect:!1,items:u.map(d=>{var f;if(d.disableOnMobile)return null;const h=d.Wrapper??nt;return{...d.buttonProps,onSelect:(f=d.buttonProps)==null?void 0:f.onClick,content:i.jsx(h,{...d.wrapperProps,children:i.jsxs(s.Flex,{gap:"2",align:"center",children:[i.jsx(d.Icon,{}),d.text]})})}}).filter(d=>d!==null)})})]})}),Ce="form-builder",Bt=c.memo(function(n){const{field:e,index:t,sectionIndex:r,remove:o}=n,a=c.useMemo(()=>de(e),[e]),u=ce(a,{formId:Ce,disabled:!0});console.log(e,t,r,a);const d=c.useMemo(()=>({index:t,parentPath:`fields.${r}.fields`,initial:e,editing:!0}),[e,t,r]),h=c.useMemo(()=>({parentPath:`fields.${r}.fields`,index:t+1,initial:{...e,identifier:""}}),[e,t,r]),f=c.useMemo(()=>({parentPath:`fields.${r}.fields`,index:t+1,initial:void 0}),[t,r]);return i.jsx(j.Draggable,{draggableId:e.identifier,index:t,children:p=>i.jsx(s.Card,{ref:p.innerRef,...p.draggableProps,...p.dragHandleProps,mb:"4",children:i.jsxs(s.Flex,{gap:"4",justify:"between",align:"center",children:[u,i.jsx(st,{remove:o,editProps:d,duplicateProps:h,insertAfterProps:f,dragHandleProps:p.dragHandleProps})]})})})}),_t=c.memo(function(n){var M,C,A,B,Y,N,G;const{field:e,index:t,dropState:r}=n,o=(M=r[e.identifier])==null?void 0:M.disabled,{setFieldValue:a,values:u}=D.useFormikContext(),d=s.useAlertDialog();console.log("field section",e,t,u);const h=c.useCallback((w,S)=>{for(const P of w){const L=S.indexOf(P);a(`fields.${L}.condition`,null).then(),a(`fields.${L}.conditional`,!1).then()}},[a]),f=c.useCallback(w=>{var L;const S=e.fields[w];if(!S)throw new Error("Could not find field to remove.");const P=[];for(const W of u.fields)((L=W.condition)==null?void 0:L.identifier)===S.identifier&&P.push(W);return{removing:S,affectedSections:P,action:()=>a(`fields.${t}.fields`,ye(e.fields,w))}},[e.fields,u.fields,a,t]),p=c.useCallback(w=>{const{affectedSections:S,action:P,removing:L}=f(w),W=()=>{P().then(),h(S,u.fields)};if(S.length>0){const fe=S.map(be=>be.label).join(", ");return d({title:"Remove condition?",description:`${L.label} is being used as a condition, deleting it will remove the condition from the ${fe} section(s).`,severity:"danger",actionText:"Remove",onAction:W})}W()},[f,h,u.fields,d]),g=c.useCallback(()=>{const S=e.fields.map((Te,Yt)=>f(Yt)).flatMap(Te=>Te.affectedSections),P=S.length?"Remove fields and conditions?":"Remove fields?",L=e.fields.length,W=S.map(Te=>Te.label).join(", "),fe=S.length?`Deleting this section will remove the ${L} field(s) it contains and will remove the conditions from following sections: ${W}`:`Deleting this section will remove the ${L} field(s) it contains.`,be=ye(u.fields,t),at=()=>a("fields",be);if(S.length>0)return d({title:P,description:fe,severity:"danger",actionText:"Remove",onAction:()=>{at().then(()=>{h(S,be)})}});at().then()},[e.fields,u.fields,t,f,a,d,h]),y=c.useMemo(()=>({index:t,parentPath:"fields",initial:e,editing:!0,conditionalSourceFields:xe(u.fields,t)}),[e,t,u.fields]),v=c.useMemo(()=>({index:t+1,parentPath:"fields",initial:ge(),conditionalSourceFields:xe(u.fields,t+1)}),[t,u.fields]),b=c.useMemo(()=>({parentPath:`fields.${t}.fields`,index:e.fields.length,initial:void 0}),[e.fields.length,t]),z=c.useMemo(()=>({index:t+1,parentPath:"fields",initial:{...e,identifier:""},conditionalSourceFields:xe(u.fields,t+1)}),[e,t,u.fields]),T=c.useMemo(()=>{var w,S;return(S=Ye(u.fields,(w=e.condition)==null?void 0:w.identifier))==null?void 0:S.label},[(C=e.condition)==null?void 0:C.identifier,u.fields]),F=Array.isArray((A=e.condition)==null?void 0:A.value)?"contains all of":"equals";if(we((B=e.condition)==null?void 0:B.value))throw new Error("File values are not supported for conditions.");const E=Array.isArray((Y=e.condition)==null?void 0:Y.value)?(N=e.condition)==null?void 0:N.value.map(w=>typeof w=="string"?w:w.label).join(", "):(G=e.condition)==null?void 0:G.value.toString();return i.jsx(j.Draggable,{draggableId:e.identifier,index:t,children:w=>i.jsx(s.Card,{ref:w.innerRef,...w.draggableProps,...w.dragHandleProps,mb:"4",children:i.jsxs(s.Flex,{gap:"3",justify:"between",align:"center",children:[i.jsxs(s.Flex,{direction:"column",gap:"2",grow:"1",children:[i.jsxs(s.Flex,{direction:"column",children:[i.jsx(s.Heading,{as:"h3",size:"3",children:e.label}),i.jsx(s.Text,{className:pe.description,children:e.description})]}),e.condition&&i.jsx(s.Text,{size:"1",children:i.jsxs(s.Em,{children:["Display only if ",i.jsx(s.Strong,{children:T})," ",F," ",i.jsx(s.Strong,{children:E})]})}),i.jsx(j.Droppable,{droppableId:e.identifier,type:"SECTION",isDropDisabled:o,children:S=>i.jsxs(s.Flex,{ref:S.innerRef,...S.droppableProps,direction:"column",gap:"0",children:[e.fields.map((P,L)=>i.jsx(Bt,{field:P,index:L,sectionIndex:t,remove:()=>p(L)},P.identifier)),S.placeholder,i.jsx(ue,{...b,children:i.jsxs(s.Button,{type:"button",variant:"outline",children:[i.jsx(s.PlusIcon,{})," Add a field"]})})]})})]}),i.jsx(st,{remove:g,insertAfterProps:v,dragHandleProps:w.dragHandleProps,editProps:y,duplicateProps:z})]})})})}),$t=(l,n)=>{var t;const e={...l};switch(n.type){case"release":for(const r in e)e[r].disabled=!1;return e;case"hold":for(const r in e)(t=e[r])!=null&&t.conditionFields.has(n.fieldId)&&(e[r].disabled=!0);return e;case"update":return n.state}},Ot=(l,n)=>{if(n)for(let e=0;e<l.length;e++){const t=l[e];if(t){for(const r of t.fields)if(r.identifier===n)return e}}},ot=l=>{var e,t,r;const n={};for(let o=0;o<l.length;o++){const a=l[o];if(!a)throw new Error("Field is undefined.");const u=o>0?(e=n[l[o-1].identifier])==null?void 0:e.conditionFields:void 0,d=new Set(u);(t=a.condition)!=null&&t.identifier&&d.add(a.condition.identifier),n[a.identifier]={disabled:!1,conditionFields:d,conditionIndex:Ot(l,(r=a.condition)==null?void 0:r.identifier),index:o,label:a.label}}return n},lt=(l,n)=>{for(const[e,t]of Object.entries(l))if(t.identifier===n)return[t,e]},qt=c.memo(function(){const{values:n,setFieldValue:e}=D.useFormikContext(),[t,r]=c.useReducer($t,n.fields,ot),{showInfo:o}=s.useToast();c.useEffect(()=>{r({type:"update",state:ot(n.fields)})},[r,n.fields]);const a=c.useCallback(h=>{h.type==="SECTION"&&r({type:"hold",fieldId:h.draggableId})},[]),u=c.useCallback(h=>{const{source:f,destination:p,type:g,reason:y,draggableId:v}=h;if(r({type:"release"}),!p||y==="CANCEL")return;if(g==="ROOT"){const E=t[v];if(!E)throw new Error("Could not find section context.");let M=typeof E.conditionIndex<"u"?Math.max(E.conditionIndex+1,p.index):p.index;for(const C of Object.values(t))C.conditionIndex===f.index&&(M=Math.min(M,C.index-1));return M!=p.index&&o({title:"Reordered sections",description:"Sections with conditions must be below the fields they reference."}),e("fields",ze(n.fields,f.index,M))}if(g!=="SECTION")throw new Error("Unexpected droppable type.");const[b,z]=lt(n.fields,f.droppableId)??[],[T,F]=lt(n.fields,p.droppableId)??[];if(!(b!=null&&b.fields)||!T)throw new Error("Could not find section with fields.");if(b.identifier===T.identifier)e(`fields.${z}.fields`,ze(b.fields,f.index,p.index)).then();else{const E=b.fields[f.index];if(!E)throw new Error("Could not find field to reorder.");e(`fields.${z}.fields`,ye(b.fields,f.index)).then(),e(`fields.${F}.fields`,Ke(T.fields,p.index,E)).then()}},[n.fields,e,t,o]),d=c.useMemo(()=>({index:n.fields.length,parentPath:"fields",initial:ge(),conditionalSourceFields:xe(n.fields,n.fields.length)}),[n.fields]);return i.jsx(j.DragDropContext,{onDragStart:a,onDragEnd:u,children:i.jsx(j.Droppable,{droppableId:"droppable",type:"ROOT",children:h=>i.jsxs(s.Flex,{ref:h.innerRef,...h.droppableProps,direction:"column",gap:"0",children:[n.fields.map((f,p)=>i.jsx(_t,{field:f,index:p,dropState:t},f.label)),h.placeholder,i.jsx(ue,{...d,children:i.jsxs(s.Button,{type:"button",variant:"outline",children:[i.jsx(s.PlusIcon,{})," Add a section"]})})]})})})}),Nt={title:"",description:"",fields:[]},Wt=new X({label:"Title",minLength:0,maxLength:100,required:!0,identifier:"title"}),jt={formId:Ce,placeholder:"Give your form a title."},Ht=new J({label:"Description",minLength:0,maxLength:1e3,required:!1,identifier:"description"}),Ut={formId:Ce,placeholder:"Explain the purpose of this form."},Gt=()=>{alert("This is a form preview, your data will not be saved.")},Kt=c.memo(c.forwardRef((l,n)=>{const{onCancel:e,onSave:t,revision:r}=l,o=r?"Edit form":"Create a new form",{heading:a=o}=l,u=c.useCallback(y=>{const v={};if(y.title||(v.title="Title is required."),(!y.fields||y.fields.length===0)&&(v.fields="At least one field is required."),Fe(v))return v},[]),d=D.useFormik({initialValues:ct(r)??Nt,validate:u,onSubmit:y=>t(y),validateOnChange:!1,validateOnBlur:!1}),h=c.useMemo(()=>De(d.values),[d.values]),f=ce(Wt,jt),p=ce(Ht,Ut),g=c.useMemo(()=>typeof a=="object"?a:i.jsx(s.Heading,{children:a}),[a]);return i.jsx(s.Tabs.Root,{ref:n,defaultValue:"edit",children:i.jsxs(s.Flex,{direction:"column",gap:"2",children:[i.jsxs(s.Tabs.List,{children:[i.jsx(s.Tabs.Trigger,{value:"edit",children:"Edit"}),i.jsx(s.Tabs.Trigger,{value:"preview",children:"Preview"})]}),i.jsxs(s.Tabs.Content,{value:"edit",children:[g,i.jsxs(s.Text,{children:["Add a new form field by clicking a + button. Specify options for each field, then drag and drop to rearrange them. You can see what a submitted form might look like in the"," ",i.jsx("em",{children:"Preview"})," tab, but"," ",i.jsx("strong",{children:"field values entered on this page will not be saved."})]}),i.jsx(s.Flex,{asChild:!0,direction:"column",gap:"2",mt:"3",children:i.jsxs("form",{id:Ce,onSubmit:d.handleSubmit,children:[i.jsxs(D.FormikProvider,{value:d,children:[f,p,i.jsx(qt,{}),i.jsx(s.Text,{severity:"danger",size:"1",children:typeof d.errors.fields=="string"&&d.errors.fields})]}),i.jsxs(s.Flex,{justify:"end",gap:"2",children:[i.jsx(s.Button,{type:"button",variant:"soft",onClick:e,children:"Cancel"}),i.jsx(s.Button,{type:"submit",disabled:!d.isValid,children:"Save"})]})]})})]}),i.jsx(s.Tabs.Content,{value:"preview",children:i.jsx(Ie,{schema:h,onSubmit:Gt})})]})})}));x.BooleanField=K,x.BooleanInput=Ne,x.DateField=he,x.DateInput=je,x.FieldSection=U,x.FormBrowser=Ct,x.FormBuilder=Kt,x.FormRenderer=Ie,x.FormSubmissionBrowser=St,x.FormSubmissionViewer=It,x.MultiSelectField=ae,x.MultiSelectInput=Je,x.MultiStringField=oe,x.MultiStringInput=Qe,x.NumberField=H,x.NumberInput=We,x.PatchField=zt,x.PatchFormProvider=Et,x.SelectField=le,x.SelectInput=Ge,x.StringField=X,x.StringInput=He,x.TextField=J,x.TextInput=Ue,x.deserialize=de,x.deserializeField=Pe,x.formRevisionToSchema=De,x.isConditionMet=Le,x.useFieldInput=ce,x.useFieldInputs=Ve,x.valueIsFile=we,Object.defineProperty(x,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "Form functionality for Overmap",
4
4
  "author": "Wôrdn Inc.",
5
5
  "license": "UNLICENSED",
6
- "version": "1.0.3-form-improvements.2",
6
+ "version": "1.0.3-form-improvements.3",
7
7
  "type": "module",
8
8
  "main": "dist/forms.umd.cjs",
9
9
  "module": "dist/forms.js",