domma-cms 0.79.1 → 0.81.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +6 -1
- package/admin/index.html +2 -2
- package/admin/js/app.js +2 -2
- package/admin/js/lib/action-editor-arrange.js +1 -1
- package/admin/js/lib/desktop-notify.js +1 -0
- package/admin/js/lib/notifications-arrange.js +1 -1
- package/admin/js/lib/sidebar-renderer.js +1 -1
- package/admin/js/templates/action-editor.html +1 -0
- package/admin/js/templates/docs/usage-actions.html +5 -0
- package/admin/js/templates/form-editor.html +72 -0
- package/admin/js/templates/notifications.html +21 -1
- package/admin/js/views/form-editor.js +7 -7
- package/admin/js/views/notifications.js +67 -4
- package/package.json +1 -1
- package/public/css/forms.css +1 -1
- package/public/js/form-logic-engine.js +1 -1
- package/public/js/forms.js +2 -2
- package/public/js/site.js +1 -1
- package/server/routes/api/api-tokens.js +5 -2
- package/server/routes/api/auth.js +15 -1
- package/server/routes/api/effects.js +36 -0
- package/server/routes/api/forms.js +40 -9
- package/server/routes/api/layouts.js +6 -2
- package/server/routes/api/notifications.js +97 -20
- package/server/routes/api/users.js +11 -0
- package/server/server.js +29 -5
- package/server/services/actions.js +28 -0
- package/server/services/adapterRegistry.js +1 -0
- package/server/services/collections.js +10 -4
- package/server/services/connectionManager.js +1 -0
- package/server/services/email.js +3 -0
- package/server/services/notification-sources.js +361 -0
- package/server/services/notify.js +420 -0
- package/server/services/plugins.js +6 -2
- package/server/services/sidebarBadges.js +33 -0
- package/server/templates/page.html +4 -4
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{apiRequest as
|
|
2
|
-
`).filter(x=>x.trim()).map(x=>{const[
|
|
3
|
-
`).filter(f=>f.trim()).map(f=>{const[w,...u]=f.split(":");return{value:w.trim(),label:u.join(":").trim()||w.trim()}});t.cascade={sourceField:h,mapping:y,defaultOptions:v},l=!0}}return l?t:void 0}function B(){C=C.map((e,n)=>Dt(n))}let ae=null;function Rt(e,n,o){const t=e.firstElementChild;if(!t)return;const l=document.createElement("span");l.setAttribute("data-icon","menu"),l.setAttribute("data-icon-size","13"),l.title="Drag to reorder",l.style.cssText="cursor:grab;opacity:.35;flex-shrink:0;display:inline-flex;align-items:center;",t.insertBefore(l,t.firstChild),window.I?.scan?.(t),t.draggable=!0,t.addEventListener("dragstart",a=>{ae=n,a.dataTransfer.effectAllowed="move",e.style.opacity="0.4"}),t.addEventListener("dragend",()=>{e.style.opacity="",document.querySelectorAll("#fields-list .fb-field-card").forEach(a=>a.classList.remove("fb-drag-over"))}),e.addEventListener("dragover",a=>{ae!=null&&(a.preventDefault(),a.dataTransfer.dropEffect="move",document.querySelectorAll("#fields-list .fb-field-card").forEach(i=>i.classList.remove("fb-drag-over")),e.classList.add("fb-drag-over"))}),e.addEventListener("dragleave",()=>e.classList.remove("fb-drag-over")),e.addEventListener("drop",a=>{if(a.preventDefault(),e.classList.remove("fb-drag-over"),ae==null||ae===n){ae=null;return}B();const[i]=C.splice(ae,1);C.splice(n,0,i),ae=null,J(o)})}function J(e){const n=e.find("#fields-list").get(0),o=e.find("#fields-empty-msg").get(0);if(n){if(Array.from(n.querySelectorAll(".fb-field-card")).forEach(t=>t.remove()),C.length===0){o&&(o.style.display=""),se?.(n),Ie();return}o&&(o.style.display="none"),C.forEach((t,l)=>{const a=t.type==="page-break"?Mt(t,l,e):t.type==="spacer"?Pt(t,l,e):_t(t,l,e);Rt(a,l,e),n.appendChild(a)}),se?.(n),Ie()}}function Mt(e,n,o){const t=document.createElement("div");t.className="fb-field-card",t.dataset.index=n,t.style.cssText="border:2px dashed var(--dm-border);border-radius:8px;overflow:hidden;margin-bottom:.75rem;background:var(--dm-card-bg);";const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.6rem;padding:.6rem .8rem;cursor:pointer;user-select:none;";const a=document.createElement("span");a.textContent="- Page Break -",a.style.cssText="font-size:.7rem;padding:.15rem .5rem;border-radius:999px;background:color-mix(in srgb, var(--dm-text-muted) 20%, transparent);color:var(--dm-text-muted);white-space:nowrap;flex-shrink:0;font-style:italic;";const i=document.createElement("span");i.textContent=e.label||"Untitled Step",i.style.cssText="flex:1;font-weight:600;font-size:.9rem;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dm-text-muted);";const s=document.createElement("div");s.style.cssText="display:flex;gap:.25rem;flex-shrink:0;margin-left:.5rem;";const c=document.createElement("button");c.className="btn btn-xs btn-ghost",c.title="Edit step",L(c,"more-horizontal"),c.addEventListener("click",y=>{y.stopPropagation(),p.style.display=p.style.display==="none"?"":"none"}),s.appendChild(c);const r=document.createElement("button");r.className="btn btn-xs btn-ghost",r.style.cssText="line-height:1;opacity:.6;",r.title="Remove page break",L(r,"x"),r.addEventListener("click",async y=>{y.stopPropagation(),await E.confirm("Remove this page break?")&&(B(),C.splice(n,1),J(o))}),s.appendChild(r),l.appendChild(a),l.appendChild(i),l.appendChild(s),l.addEventListener("click",()=>{p.style.display=p.style.display==="none"?"":"none"});const p=document.createElement("div");p.className="fb-field-body",p.style.cssText="padding:.8rem;border-top:1px dashed var(--dm-border);display:none;";const m=O([P("Step Title",`fb-pb-label-${n}`,"text",e.label||"","Shown as the wizard step heading"),P("Step Description",`fb-pb-desc-${n}`,"text",e.description||"","Optional sub-heading")]),h=m.querySelector(`#fb-pb-label-${n}`);return h&&h.addEventListener("input",()=>{i.textContent=h.value||"Untitled Step"}),p.appendChild(m),t.appendChild(l),t.appendChild(p),t}function Pt(e,n,o){const t=document.createElement("div");t.className="fb-field-card",t.dataset.index=n,t.style.cssText="border:1px dashed var(--dm-border);border-radius:6px;margin-bottom:.5rem;background:transparent;";const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.6rem;padding:.4rem .8rem;";const a=document.createElement("div");a.style.cssText="flex:1;height:1px;background:var(--dm-border);";const i=document.createElement("span");i.textContent="Spacer",i.style.cssText="font-size:.7rem;color:var(--dm-text-muted);white-space:nowrap;padding:0 .4rem;font-style:italic;";const s=document.createElement("div");s.style.cssText="flex:1;height:1px;background:var(--dm-border);";const c=document.createElement("div");c.style.cssText="display:flex;gap:.25rem;flex-shrink:0;";const r=document.createElement("button");return r.className="btn btn-xs btn-ghost",r.style.cssText="line-height:1;opacity:.6;",r.title="Remove spacer",L(r,"x"),r.addEventListener("click",async p=>{p.stopPropagation(),B(),C.splice(n,1),J(o)}),c.appendChild(r),l.appendChild(a),l.appendChild(i),l.appendChild(s),l.appendChild(c),t.appendChild(l),t}function _t(e,n,o){const t=document.createElement("div");t.className="fb-field-card",t.dataset.index=n,t.style.cssText="border:1px solid var(--dm-border);border-radius:8px;overflow:hidden;margin-bottom:.75rem;background:var(--dm-card-bg);box-shadow:var(--dm-shadow-sm);";const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.6rem;padding:.65rem .85rem;background:var(--dm-card-header-bg);cursor:pointer;user-select:none;";const a=document.createElement("span");a.textContent=at(e.type),a.style.cssText="font-size:.7rem;padding:.15rem .45rem;border-radius:999px;background:color-mix(in srgb, var(--dm-primary) 14%, transparent);color:var(--dm-primary);white-space:nowrap;flex-shrink:0;";const i=document.createElement("span");i.textContent=e.label||"(unlabelled)",i.style.cssText="flex:1;font-weight:600;font-size:.9rem;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;";const s=document.createElement("div");s.style.cssText="display:flex;gap:.25rem;flex-shrink:0;margin-left:.5rem;";const c=document.createElement("button");c.className="btn btn-xs btn-ghost",c.title="Edit field",L(c,"more-horizontal"),c.addEventListener("click",m=>{m.stopPropagation(),p.style.display=p.style.display==="none"?"":"none"}),s.appendChild(c);const r=document.createElement("button");if(r.className="btn btn-xs btn-ghost",r.style.cssText="line-height:1;opacity:.6;",r.title="Remove field",L(r,"x"),r.addEventListener("click",async m=>{m.stopPropagation(),await E.confirm("Remove this field?")&&(B(),C.splice(n,1),J(o))}),s.appendChild(r),l.appendChild(a),l.appendChild(i),e.required){const m=document.createElement("span");m.textContent="required",m.style.cssText="font-size:.7rem;color:var(--dm-danger);flex-shrink:0;",l.appendChild(m)}if(it(e.logic)){const m=document.createElement("span");L(m,"zap"),m.title="Has conditional logic",m.style.cssText="font-size:.75rem;color:var(--dm-primary);flex-shrink:0;",l.appendChild(m)}l.appendChild(s),l.addEventListener("click",()=>{p.style.display=p.style.display==="none"?"":"none"});const p=jt(e,n,i);return p.style.display="none",t.appendChild(l),t.appendChild(p),t}function jt(e,n,o){const t=document.createElement("div");t.className="fb-field-body",t.style.cssText="padding:1rem .9rem;border-top:1px solid var(--dm-border);";const l=O([P("Label",`fb-label-${n}`,"text",e.label||"","Shown above the field"),P("Field Name",`fb-name-${n}`,"text",e.name||"","Used as data key")]),a=O([rn("Type",`fb-type-${n}`,tt,e.type||"string"),vt("Required",`fb-required-${n}`,e.required||!1)]),i=O([P("Placeholder",`fb-placeholder-${n}`,"text",e.placeholder||"","Hint text inside the field")]),s=O([P("Helper Text",`fb-helper-${n}`,"text",e.helper||"","Shown below the field"),P("Tooltip",`fb-tooltip-${n}`,"text",e.tooltip||"","Shown on hover via a help icon next to the label")]),c=e.formConfig?.span,r=O([P("Column Span",`fb-span-${n}`,"number",c&&c!=="full"?String(c):"1","Columns to span (grid only)"),vt("Full Width",`fb-fullwidth-${n}`,c==="full")]);r.classList.add("fb-grid-row"),r.style.display=document.getElementById("setting-layout")?.value==="grid"?"flex":"none",t.appendChild(l),t.appendChild(a),t.appendChild(i),t.appendChild(s),t.appendChild(r);const p=t.querySelector(`#fb-label-${n}`),m=t.querySelector(`#fb-name-${n}`);p&&p.addEventListener("input",()=>{o&&(o.textContent=p.value||"(unlabelled)"),m&&!m.dataset.manuallyEdited&&(m.value=lt(p.value))}),m&&m.addEventListener("input",()=>{m.dataset.manuallyEdited="1"});const h=t.querySelector(`#fb-type-${n}`);h&&h.addEventListener("change",()=>{const v=t.closest(".fb-field-card");if(v){const u=v.querySelector("span");u&&(u.textContent=at(h.value))}const f=t.querySelector(".fb-field-extras");f&&f.remove();const w=ht(h.value,e,n);w&&t.appendChild(w)});const y=ht(e.type,e,n);return y&&t.appendChild(y),t.appendChild(Ut(e,n)),t.appendChild(Xt(e,n)),t}const fe=[{value:"equals",label:"equals"},{value:"not_equals",label:"does not equal"},{value:"contains",label:"contains"},{value:"not_contains",label:"does not contain"},{value:"starts_with",label:"starts with"},{value:"ends_with",label:"ends with"},{value:"greater_than",label:"is greater than"},{value:"less_than",label:"is less than"},{value:"is_empty",label:"is empty"},{value:"is_not_empty",label:"is not empty"},{value:"in",label:"is one of (comma sep)"},{value:"not_in",label:"is not one of (comma sep)"},{value:"matches_regex",label:"matches regex"}],ze=new Set(["is_empty","is_not_empty"]),st={equals:"includes",not_equals:"does not include",contains:"any value contains",not_contains:"no value contains",starts_with:"any value starts with",ends_with:"any value ends with",greater_than:"any value is greater than",less_than:"any value is less than",is_empty:"nothing selected",is_not_empty:"something selected",in:"includes one of (comma sep)",not_in:"includes none of (comma sep)",matches_regex:"any value matches regex"};function Be(e){return!!e&&(e.type==="checkbox-group"||!!e.multiple)}function he(e){const n=document.createElement("p");return n.textContent=e,n.style.cssText="font-size:.75rem;font-weight:700;color:var(--dm-text-muted);margin:0 0 .7rem;text-transform:uppercase;letter-spacing:.06em;",n}function be(e,n,o,t,l){const a=document.createElement("div");a.className="fb-logic-cond-row",a.style.cssText="display:flex;gap:.55rem;align-items:center;margin-bottom:.6rem;flex-wrap:wrap;";const i=document.createElement("span");i.textContent="When",i.style.cssText="font-size:.73rem;color:var(--dm-text-muted);flex-shrink:0;";const s=document.createElement("select");s.className="form-select fb-logic-cond-field",s.style.cssText="flex:1 1 140px;min-width:140px;",n.forEach(v=>{const f=document.createElement("option");f.value=v.value,f.textContent=v.label,e&&v.value===e.field&&(f.selected=!0),s.appendChild(f)});const c=document.createElement("select");c.className="form-select fb-logic-cond-op",c.style.cssText="flex:1 1 160px;min-width:140px;",fe.forEach(v=>{const f=document.createElement("option");f.value=v.value,f.textContent=v.label,e&&v.value===e.operator&&(f.selected=!0),c.appendChild(f)});const r=()=>{const v=n.find(f=>f.value===s.value);Array.from(c.options).forEach(f=>{const w=fe.find(u=>u.value===f.value);f.textContent=v?.multi&&st[f.value]||w?.label||f.value})};r(),s.addEventListener("change",r);const p=document.createElement("input");p.type="text",p.className="form-input fb-logic-cond-val",p.placeholder="value",p.style.cssText="flex:1 1 120px;min-width:100px;",p.value=e?.value||"",e&&ze.has(e.operator)&&(p.style.display="none"),c.addEventListener("change",()=>{p.style.display=ze.has(c.value)?"none":""});const m=document.createElement("span");L(m,"arrow-right"),m.style.cssText="font-size:.73rem;color:var(--dm-text-muted);flex-shrink:0;";const h=document.createElement("select");h.className=`form-select ${t}`,h.style.cssText="flex:1 1 140px;min-width:120px;",o.forEach(v=>{const f=document.createElement("option");f.value=v.value,f.textContent=v.label,v.value===l&&(f.selected=!0),h.appendChild(f)});const y=document.createElement("button");return y.type="button",y.className="btn btn-xs btn-ghost",y.style.cssText="line-height:1;opacity:.6;",L(y,"x"),y.style.flexShrink="0",y.addEventListener("click",()=>a.remove()),a.appendChild(i),a.appendChild(s),a.appendChild(c),a.appendChild(p),a.appendChild(m),a.appendChild(h),a.appendChild(y),a}function Vt(e,n,o){const t=document.createElement("div");t.dataset.logicSection="visibility",t.appendChild(he("Visibility"));const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.6rem;margin-bottom:.65rem;flex-wrap:wrap;";const a=document.createElement("span");a.textContent="Default:",a.style.cssText="font-size:.8rem;flex-shrink:0;";const i=document.createElement("select");i.className="form-select fb-logic-vis-default",i.style.cssText="max-width:240px;",[{value:"visible",label:"Visible"},{value:"hidden",label:"Hidden"}].forEach(u=>{const x=document.createElement("option");x.value=u.value,x.textContent=u.label,u.value===(e.default||"visible")&&(x.selected=!0),i.appendChild(x)}),l.appendChild(a),l.appendChild(i),t.appendChild(l);const s=document.createElement("div");s.style.cssText="display:flex;align-items:center;gap:.6rem;margin-bottom:.65rem;flex-wrap:wrap;";const c=document.createElement("span");c.textContent="Transition:",c.style.cssText="font-size:.8rem;flex-shrink:0;";const r=document.createElement("select");r.className="form-select fb-logic-vis-transition",r.style.cssText="max-width:240px;",[{value:"none",label:"None (instant)"},{value:"fade",label:"Fade"},{value:"slide",label:"Slide"},{value:"scale",label:"Scale"}].forEach(u=>{const x=document.createElement("option");x.value=u.value,x.textContent=u.label,u.value===(e.transition||"none")&&(x.selected=!0),r.appendChild(x)}),s.appendChild(c),s.appendChild(r),t.appendChild(s);const p=document.createElement("div");p.style.cssText="display:flex;align-items:center;gap:.6rem;margin-bottom:.65rem;flex-wrap:wrap;";const m=document.createElement("span");m.textContent="Speed:",m.style.cssText="font-size:.8rem;flex-shrink:0;";const h=document.createElement("select");h.className="form-select fb-logic-vis-duration",h.style.cssText="max-width:240px;",[{value:"",label:"Default"},{value:"120",label:"Very fast (120ms)"},{value:"200",label:"Fast (200ms)"},{value:"350",label:"Medium (350ms)"},{value:"600",label:"Slow (600ms)"},{value:"1000",label:"Very slow (1s)"}].forEach(u=>{const x=document.createElement("option");x.value=u.value,x.textContent=u.label,u.value===String(e.duration??"")&&(x.selected=!0),h.appendChild(x)}),p.appendChild(m),p.appendChild(h),t.appendChild(p);const y=()=>{p.style.display=r.value==="none"?"none":""};y(),r.addEventListener("change",y);const v=document.createElement("div");v.className="fb-logic-vis-rules";const f=o.map(u=>({value:u.name,label:u.label||u.name,multi:Be(u)})),w=[{value:"visible",label:"Show"},{value:"hidden",label:"Hide"}];if((e.conditions||[]).forEach(u=>{const x=(u.when?.all||u.when?.any||[])[0],N=u.then==="hidden"?"hidden":"visible";f.length>0&&v.appendChild(be(x,f,w,"fb-logic-vis-then",N))}),t.appendChild(v),f.length>0){const u=document.createElement("button");u.type="button",u.className="btn btn-xs btn-ghost",u.style.cssText="font-size:.73rem;margin-top:.35rem;",le(u,"plus","Add visibility rule"),u.addEventListener("click",()=>v.appendChild(be(null,f,w,"fb-logic-vis-then","visible"))),t.appendChild(u)}return t}function Ht(e,n,o){const t=document.createElement("div");t.dataset.logicSection="requirement",t.appendChild(he("Conditional Requirement"));const l=document.createElement("label");l.style.cssText="display:flex;align-items:center;gap:.5rem;font-size:.8rem;cursor:pointer;margin-bottom:.65rem;";const a=document.createElement("input");a.type="checkbox",a.className="fb-logic-req-default",a.checked=e.default===!0,l.appendChild(a),l.appendChild(document.createTextNode("Required by default")),t.appendChild(l);const i=document.createElement("div");i.className="fb-logic-req-rules";const s=o.map(r=>({value:r.name,label:r.label||r.name,multi:Be(r)})),c=[{value:"true",label:"Make required"},{value:"false",label:"Make optional"}];if((e.conditions||[]).forEach(r=>{const p=(r.when?.all||r.when?.any||[])[0],m=r.then===!0?"true":"false";s.length>0&&i.appendChild(be(p,s,c,"fb-logic-req-then",m))}),t.appendChild(i),s.length>0){const r=document.createElement("button");r.type="button",r.className="btn btn-xs btn-ghost",r.style.cssText="font-size:.73rem;margin-top:.35rem;",le(r,"plus","Add requirement rule"),r.addEventListener("click",()=>i.appendChild(be(null,s,c,"fb-logic-req-then","true"))),t.appendChild(r)}return t}function rt(e){const n=document.createElement("div");n.className="fb-logic-val-rule",n.style.cssText="display:flex;gap:.55rem;align-items:center;margin-bottom:.6rem;flex-wrap:wrap;";const o=document.createElement("select");o.className="form-select fb-logic-val-type",o.style.cssText="flex:0 0 140px;",[{value:"regex",label:"Regex"},{value:"match",label:"Match field"}].forEach(s=>{const c=document.createElement("option");c.value=s.value,c.textContent=s.label,s.value===(e?.type||"regex")&&(c.selected=!0),o.appendChild(c)});const t=document.createElement("input");t.type="text",t.className="form-input fb-logic-val-pattern",t.placeholder=e?.type==="match"?"field name":"pattern",t.value=e?.pattern||e?.field||"",t.style.cssText="flex:3;";const l=document.createElement("input");l.type="text",l.className="form-input fb-logic-val-flags",l.placeholder="flags",l.value=e?.flags||"",l.style.cssText="flex:0 0 55px;",e?.type==="match"&&(l.style.display="none"),o.addEventListener("change",()=>{l.style.display=o.value==="match"?"none":"",t.placeholder=o.value==="match"?"field name":"pattern"});const a=document.createElement("input");a.type="text",a.className="form-input fb-logic-val-message",a.placeholder="Error message",a.value=e?.message||"",a.style.cssText="flex:4;";const i=document.createElement("button");return i.type="button",i.className="btn btn-xs btn-ghost",i.style.cssText="line-height:1;opacity:.6;",L(i,"x"),i.style.flexShrink="0",i.addEventListener("click",()=>n.remove()),n.appendChild(o),n.appendChild(t),n.appendChild(l),n.appendChild(a),n.appendChild(i),n}function Gt(e,n,o){const t=document.createElement("div");t.dataset.logicSection="validation",t.appendChild(he("Custom Validation"));const l=document.createElement("div");l.className="fb-logic-val-rules",(e||[]).forEach(i=>l.appendChild(rt(i))),t.appendChild(l);const a=document.createElement("button");return a.type="button",a.className="btn btn-xs btn-ghost",a.style.cssText="font-size:.73rem;margin-top:.35rem;",le(a,"plus","Add validation rule"),a.addEventListener("click",()=>l.appendChild(rt(null))),t.appendChild(a),t}function Wt(e,n,o){const t=document.createElement("div");t.dataset.logicSection="cascade",t.appendChild(he("Cascade Options")),t.lastChild.appendChild(Ae("Make this field's options depend on another field. When the source field changes, the options here are replaced by the mapping entry for its value; if nothing matches, the default options below are shown."));const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.5rem;margin-bottom:.5rem;";const a=document.createElement("span");a.textContent="Source field:",a.style.cssText="font-size:.8rem;flex-shrink:0;";const i=document.createElement("select");i.className="form-select fb-logic-cascade-source",i.style.cssText="flex:1;";const s=document.createElement("option");s.value="",s.textContent="- none -",i.appendChild(s),o.forEach(h=>{const y=document.createElement("option");y.value=h.name,y.textContent=h.label||h.name,h.name===e.sourceField&&(y.selected=!0),i.appendChild(y)}),l.appendChild(a),l.appendChild(i),t.appendChild(l);const c=document.createElement("p");c.textContent='Mapping JSON - {"value":[{"value":"...","label":"..."}]}',c.appendChild(Ae(`Each key is a value of the source field; its list becomes this field's options when that value is picked. Example: {"uk":[{"value":"london","label":"London"}]} shows London when the source is "uk".`)),c.style.cssText="font-size:.73rem;color:var(--dm-text-muted);margin:.3rem 0 .2rem;";const r=document.createElement("textarea");r.className="form-input fb-logic-cascade-mapping",r.rows=4,r.style.cssText="font-family:monospace;",r.placeholder='{"uk": [{"value": "london", "label": "London"}]}',r.value=e.mapping?JSON.stringify(e.mapping,null,2):"",t.appendChild(c),t.appendChild(r);const p=document.createElement("p");p.textContent="Default options (one per line: value:Label)",p.appendChild(Ae("Shown before the source field has a value, or when its value has no mapping entry.")),p.style.cssText="font-size:.73rem;color:var(--dm-text-muted);margin:.3rem 0 .2rem;";const m=document.createElement("textarea");return m.className="form-input fb-logic-cascade-defaults",m.rows=3,m.style.cssText="font-family:monospace;",m.placeholder=`option1:Option 1
|
|
4
|
-
option2:Option 2`,
|
|
5
|
-
`),t.appendChild(p),t.appendChild(m),t}function Ut(e,n){const o=e.logic||{},t=C.filter((m,h)=>h!==n&&m.type!=="page-break"&&m.type!=="spacer"),l=document.createElement("div");l.className="fb-field-logic",l.style.cssText="margin-top:.75rem;border-top:1px solid var(--dm-border);padding-top:.5rem;";const a=document.createElement("div");a.style.cssText="display:flex;align-items:center;justify-content:space-between;cursor:pointer;padding:.15rem 0;";const i=document.createElement("span");i.style.cssText="font-size:.8rem;font-weight:600;color:var(--dm-text-muted);",i.textContent="\u26A1 Conditional Logic";const s=it(o),c=document.createElement("button");c.type="button",c.className="btn btn-xs btn-ghost",L(c,s?"chevron-down":"chevron-right",12);const r=document.createElement("div");r.className="fb-logic-body",r.style.cssText="padding:.25rem 0 .25rem;"+(s?"":"display:none;"),a.addEventListener("click",()=>{const m=r.style.display==="none";r.style.display=m?"":"none",L(c,m?"chevron-down":"chevron-right",12)}),a.appendChild(i),a.appendChild(c),l.appendChild(a),r.appendChild(Vt(o.visibility||{},n,t)),r.appendChild(Ht(o.requirement||{},n,t)),r.appendChild(Gt(o.validation||[],n,t));const p=document.getElementById(`fb-type-${n}`)?.value||e.type;return qe.has(p)&&r.appendChild(Wt(o.cascade||{},n,t)),l.appendChild(r),l}const ge=[{value:"banner",label:"Show a banner",kind:"state",params:["message","level","position","dismissible"]},{value:"toast",label:"Show a toast",kind:"event",params:["message","level"]},{value:"hide-fields",label:"Hide fields",kind:"state",params:["target"]},{value:"disable-fields",label:"Disable fields",kind:"state",params:["target"]},{value:"require-fields",label:"Make fields required",kind:"state",params:["target"]},{value:"block-submit",label:"Block submission",kind:"state",params:["message"]},{value:"goto-step",label:"Jump to a wizard step",kind:"event",params:["step"]},{value:"redirect",label:"Redirect after submit",kind:"event",params:["url"]},{value:"celebrate",label:"Celebrate",kind:"event",params:["theme","intensity"]},{value:"run-action",label:"Run a CMS action",kind:"event",params:["slug"]}],Jt=[{value:"info",label:"Info"},{value:"success",label:"Success"},{value:"warning",label:"Warning"},{value:"error",label:"Error"}],Kt=[{value:"field-below",label:"Below this field"},{value:"field-above",label:"Above this field"},{value:"form-top",label:"Top of the form"}],Yt=[{value:"rest",label:"The rest of the form"},{value:"all",label:"Every other field"},{value:"listed",label:"Chosen fields"}],Qt=[{value:"auto",label:"Whatever is in season"},{value:"christmas",label:"Christmas"},{value:"halloween",label:"Halloween"},{value:"valentines",label:"Valentine's Day"},{value:"guy-fawkes",label:"Guy Fawkes Night"},{value:"st-patricks",label:"St Patrick's Day"},{value:"st-andrews",label:"St Andrew's Day"},{value:"st-davids",label:"St David's Day"},{value:"st-georges",label:"St George's Day"}];function ct(e){return C.map((n,o)=>({field:n,i:o})).filter(({field:n,i:o})=>o!==e&&n.type!=="page-break"&&n.type!=="spacer"&&n.name).map(({field:n})=>({value:n.name,label:n.label||n.name,multi:Be(n)}))}function K(e,n,o,t){const l=document.createElement("select");return l.className=`form-select ${e}`,t&&(l.style.cssText=t),n.forEach(a=>{const i=document.createElement("option");i.value=a.value,i.textContent=a.label,a.value===o&&(i.selected=!0),l.appendChild(i)}),l}function ye(e,n,o,t){const l=document.createElement("input");return l.type="text",l.className=`form-input ${e}`,l.value=n==null?"":String(n),o&&(l.placeholder=o),t&&(l.style.cssText=t),l}function De(e,n){const o=document.createElement("button");return o.type="button",o.className="btn btn-xs btn-ghost",o.style.cssText="line-height:1;opacity:.6;flex-shrink:0;",n&&(o.title=n),L(o,"x"),o.addEventListener("click",e),o}function dt(e,n){const o=document.createElement("div");o.className="fb-trig-cond-row",o.style.cssText="display:flex;gap:.55rem;align-items:center;margin-bottom:.5rem;flex-wrap:wrap;";const t=K("fb-trig-cond-field",n,e?.field,"flex:1 1 140px;min-width:130px;"),l=K("fb-trig-cond-op",fe,e?.operator,"flex:1 1 150px;min-width:130px;"),a=ye("fb-trig-cond-val",e?.value,"value","flex:1 1 110px;min-width:90px;"),i=()=>{const c=n.find(r=>r.value===t.value);Array.from(l.options).forEach(r=>{const p=fe.find(m=>m.value===r.value);r.textContent=c?.multi&&st[r.value]||p?.label||r.value})},s=()=>{a.style.display=ze.has(l.value)?"none":""};return i(),s(),t.addEventListener("change",i),l.addEventListener("change",s),o.appendChild(t),o.appendChild(l),o.appendChild(a),o.appendChild(De(()=>o.remove(),"Remove condition")),o}function pt(e,n){const o=document.createElement("div");o.className="fb-trig-params",o.style.cssText="display:flex;gap:.5rem;align-items:center;flex-wrap:wrap;flex:1 1 100%;margin:.35rem 0 0 .25rem;";const t=ge.find(l=>l.value===(e.type||"banner"));if(!t)return o;for(const l of t.params)switch(l){case"message":o.appendChild(ye("fb-trig-p-message",e.message,"Message shown to the visitor","flex:2 1 260px;"));break;case"level":o.appendChild(K("fb-trig-p-level",Jt,e.level||"info","flex:1 1 120px;"));break;case"position":o.appendChild(K("fb-trig-p-position",Kt,e.position||"field-below","flex:1 1 150px;"));break;case"dismissible":{const a=document.createElement("label");a.style.cssText="display:flex;align-items:center;gap:.3rem;font-size:.78rem;flex-shrink:0;";const i=document.createElement("input");i.type="checkbox",i.className="form-check fb-trig-p-dismissible",i.checked=e.dismissible!==!1,a.appendChild(i),a.appendChild(document.createTextNode("Dismissible")),o.appendChild(a);break}case"target":{const a=K("fb-trig-p-target",Yt,e.target||(e.fields?.length?"listed":"rest"),"flex:1 1 170px;"),i=document.createElement("select");i.className="form-select fb-trig-p-fields",i.multiple=!0,i.size=4,i.style.cssText="flex:2 1 200px;";const s=new Set(e.fields||[]);ct(n).forEach(r=>{const p=document.createElement("option");p.value=r.value,p.textContent=r.label,s.has(r.value)&&(p.selected=!0),i.appendChild(p)});const c=()=>{i.style.display=a.value==="listed"?"":"none"};c(),a.addEventListener("change",c),o.appendChild(a),o.appendChild(i);break}case"step":{const a=ye("fb-trig-p-step",e.step,"0","flex:0 0 90px;");a.type="number",a.min="0",o.appendChild(a);const i=document.createElement("span");i.textContent="Step number, counting from 0",i.style.cssText="font-size:.73rem;color:var(--dm-text-muted);",o.appendChild(i);break}case"url":o.appendChild(ye("fb-trig-p-url",e.url,"/thank-you","flex:2 1 220px;"));break;case"theme":o.appendChild(K("fb-trig-p-theme",Qt,e.theme||"auto","flex:1 1 180px;"));break;case"intensity":o.appendChild(K("fb-trig-p-intensity",[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}],e.intensity||"medium","flex:0 1 120px;"));break;case"slug":{const a=[{value:"",label:$e.length?"Choose an action":"No actions available"}].concat($e.map(i=>({value:i.slug,label:i.title||i.slug})));o.appendChild(K("fb-trig-p-slug",a,e.slug||"","flex:2 1 200px;"));break}default:break}if(t.kind==="event"){const l=document.createElement("label");l.style.cssText="display:flex;align-items:center;gap:.3rem;font-size:.78rem;flex-shrink:0;";const a=document.createElement("input");a.type="checkbox",a.className="form-check fb-trig-p-once",a.checked=!!e.once,l.appendChild(a),l.appendChild(document.createTextNode("Only once")),l.title="Fire the first time only, rather than every time the answer swings back.",o.appendChild(l)}return o}function mt(e,n){const o=document.createElement("div");o.className="fb-trig-action-row",o.style.cssText="display:flex;gap:.5rem;align-items:center;flex-wrap:wrap;padding:.45rem .5rem;margin-bottom:.4rem;border:1px solid var(--dm-border);border-radius:var(--dm-radius-md);";const t=K("fb-trig-action-type",ge,e.type||"banner","flex:1 1 190px;"),l=document.createElement("span");l.className="fb-trig-kind",l.style.cssText="font-size:.7rem;color:var(--dm-text-muted);flex-shrink:0;";const a=pt(e,n),i=()=>{const s=ge.find(c=>c.value===t.value);l.textContent=s?.kind==="event"?"fires once when it becomes true":"applies while it is true"};return i(),t.addEventListener("change",()=>{i();const s=pt({type:t.value},n);o.replaceChild(s,o.querySelector(".fb-trig-params")),window.I?.scan?.()}),o.appendChild(t),o.appendChild(l),o.appendChild(De(()=>o.remove(),"Remove action")),o.appendChild(a),o}function ut(e,n,o,t){const l=document.createElement("div");l.className="fb-trig-branch",l.dataset.branch=e,l.style.cssText="margin-top:.6rem;";const a=document.createElement("p");a.textContent=n,a.style.cssText="font-size:.73rem;font-weight:700;color:var(--dm-text-muted);margin:0 0 .4rem;text-transform:uppercase;letter-spacing:.05em;",l.appendChild(a);const i=document.createElement("div");i.className="fb-trig-action-list",(o||[]).forEach(c=>i.appendChild(mt(c,t))),l.appendChild(i);const s=document.createElement("button");return s.type="button",s.className="btn btn-xs btn-ghost",le(s,"plus","Add action",12),s.addEventListener("click",()=>{i.appendChild(mt({type:"banner"},t)),window.I?.scan?.()}),l.appendChild(s),l}function ft(e,n,o){const t=ct(n),l=document.createElement("div");l.className="fb-trig-card",l.dataset.triggerId=e.id||`trg-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,l.style.cssText="border:1px solid var(--dm-border);border-radius:var(--dm-radius-md);padding:.65rem .7rem;margin-bottom:.7rem;";const a=document.createElement("div");a.style.cssText="display:flex;align-items:center;justify-content:space-between;gap:.5rem;margin-bottom:.5rem;";const i=document.createElement("span");i.textContent=`Trigger ${o+1}`,i.style.cssText="font-size:.78rem;font-weight:600;",a.appendChild(i);const s=document.createElement("div");s.style.cssText="display:flex;align-items:center;gap:.5rem;";const c=document.createElement("label");c.style.cssText="display:flex;align-items:center;gap:.3rem;font-size:.75rem;cursor:pointer;";const r=document.createElement("input");if(r.type="checkbox",r.className="form-check fb-trig-enabled",r.checked=e.enabled!==!1,c.appendChild(r),c.appendChild(document.createTextNode("Enabled")),s.appendChild(c),s.appendChild(De(()=>l.remove(),"Remove trigger")),a.appendChild(s),l.appendChild(a),!t.length){const f=document.createElement("p");return f.textContent="Add another field first - a trigger tests an answer, and this is the only field so far.",f.style.cssText="font-size:.78rem;color:var(--dm-text-muted);margin:0;",l.appendChild(f),l}const p=document.createElement("div");p.style.cssText="display:flex;align-items:center;gap:.45rem;margin-bottom:.45rem;flex-wrap:wrap;";const m=document.createElement("span");m.textContent="When",m.style.cssText="font-size:.75rem;font-weight:700;color:var(--dm-text-muted);",p.appendChild(m),p.appendChild(K("fb-trig-match",[{value:"all",label:"all of these are true"},{value:"any",label:"any of these is true"}],Array.isArray(e.when?.any)?"any":"all","flex:0 1 200px;")),l.appendChild(p);const h=document.createElement("div");h.className="fb-trig-cond-list";const y=e.when?.all||e.when?.any||[];(y.length?y:[{}]).forEach(f=>h.appendChild(dt(f,t))),l.appendChild(h);const v=document.createElement("button");return v.type="button",v.className="btn btn-xs btn-ghost",le(v,"plus","Add condition",12),v.addEventListener("click",()=>{h.appendChild(dt({},t)),window.I?.scan?.()}),l.appendChild(v),l.appendChild(ut("then","Then",e.then,n)),l.appendChild(ut("otherwise","Otherwise (optional)",e.otherwise,n)),l}function Xt(e,n){const o=Array.isArray(e.triggers)?e.triggers:[],t=document.createElement("div");t.className="fb-field-triggers",t.style.cssText="margin-top:.5rem;border-top:1px solid var(--dm-border);padding-top:.5rem;";const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;justify-content:space-between;cursor:pointer;padding:.15rem 0;";const a=document.createElement("span");a.style.cssText="font-size:.8rem;font-weight:600;color:var(--dm-text-muted);",a.textContent=`\u{1F3AF} Triggers${o.length?` (${o.length})`:""}`;const i=document.createElement("button");i.type="button",i.className="btn btn-xs btn-ghost",L(i,o.length?"chevron-down":"chevron-right",12);const s=document.createElement("div");s.className="fb-triggers-body",s.style.cssText="padding:.35rem 0;"+(o.length?"":"display:none;"),l.addEventListener("click",()=>{const m=s.style.display==="none";s.style.display=m?"":"none",L(i,m?"chevron-down":"chevron-right",12)});const c=document.createElement("p");c.textContent="Do something to the form when the answers meet a condition - show a banner or toast, hide, disable or require other fields, refuse the submit, jump to a step, or celebrate.",c.style.cssText="font-size:.75rem;color:var(--dm-text-muted);margin:0 0 .6rem;",s.appendChild(c);const r=document.createElement("div");r.className="fb-trig-list",o.forEach((m,h)=>r.appendChild(ft(m,n,h))),s.appendChild(r);const p=document.createElement("button");return p.type="button",p.className="btn btn-xs btn-ghost",le(p,"plus","Add trigger",12),p.addEventListener("click",()=>{r.appendChild(ft({enabled:!0,then:[{type:"banner"}]},n,r.children.length)),window.I?.scan?.()}),s.appendChild(p),l.appendChild(a),l.appendChild(i),t.appendChild(l),t.appendChild(s),t}function Zt(e){const n=e.querySelector(".fb-trig-action-type")?.value,o=ge.find(a=>a.value===n);if(!o)return null;const t={type:n},l=a=>e.querySelector(a)?.value?.trim()||"";for(const a of o.params)switch(a){case"message":t.message=l(".fb-trig-p-message");break;case"level":t.level=l(".fb-trig-p-level")||"info";break;case"position":t.position=l(".fb-trig-p-position")||"field-below";break;case"dismissible":t.dismissible=!!e.querySelector(".fb-trig-p-dismissible")?.checked;break;case"target":{const i=l(".fb-trig-p-target")||"rest";t.target=i,i==="listed"&&(t.fields=Array.from(e.querySelectorAll(".fb-trig-p-fields option")).filter(s=>s.selected).map(s=>s.value));break}case"step":{const i=parseInt(l(".fb-trig-p-step"),10);Number.isFinite(i)&&(t.step=i);break}case"url":t.url=l(".fb-trig-p-url");break;case"theme":t.theme=l(".fb-trig-p-theme")||"auto";break;case"intensity":t.intensity=l(".fb-trig-p-intensity")||"medium";break;case"slug":t.slug=l(".fb-trig-p-slug");break;default:break}return o.kind==="event"&&e.querySelector(".fb-trig-p-once")?.checked&&(t.once=!0),o.params.includes("message")&&!t.message&&o.value!=="block-submit"||n==="redirect"&&!t.url||n==="run-action"&&!t.slug?null:t}function en(e){const o=document.querySelector(`.fb-field-card[data-index="${e}"]`)?.querySelector(".fb-field-triggers");if(!o)return;const t=[];return o.querySelectorAll(".fb-trig-card").forEach(l=>{const a=Array.from(l.querySelectorAll(".fb-trig-cond-row")).map(m=>{const h=m.querySelector(".fb-trig-cond-field")?.value,y=m.querySelector(".fb-trig-cond-op")?.value;if(!h||!y)return null;const v=m.querySelector(".fb-trig-cond-val")?.value??"";return{field:h,operator:y,value:v}}).filter(Boolean);if(!a.length)return;const i=m=>Array.from(l.querySelectorAll(`.fb-trig-branch[data-branch="${m}"] .fb-trig-action-row`)).map(Zt).filter(Boolean),s=i("then"),c=i("otherwise");if(!s.length&&!c.length)return;const r=l.querySelector(".fb-trig-match")?.value==="any"?"any":"all",p={id:l.dataset.triggerId,enabled:!!l.querySelector(".fb-trig-enabled")?.checked,when:{[r]:a}};s.length&&(p.then=s),c.length&&(p.otherwise=c),t.push(p)}),t.length?t:void 0}function ht(e,n,o){const t=document.createElement("div");return t.className="fb-field-extras",e==="chooser"?(t.appendChild(tn(n,o)),t.appendChild(ln(n.options||[],o))):(qe.has(e)&&t.appendChild(cn(n.options||[],o)),e==="textarea"&&t.appendChild(O([P("Rows",`fb-rows-${o}`,"number",n.formConfig?.rows||4,"Height of textarea")])),(e==="string"||e==="textarea")&&t.appendChild(O([P("Min Length",`fb-minlength-${o}`,"number",n.minLength||"",""),P("Max Length",`fb-maxlength-${o}`,"number",n.maxLength||"","")])),e==="number"&&t.appendChild(O([P("Min",`fb-min-${o}`,"number",n.min??"",""),P("Max",`fb-max-${o}`,"number",n.max??"","")]))),t.children.length?t:null}function bt(e){const n=document.createElement("div");n.className="fb-chooser-section",n.style.cssText="border:1px solid var(--dm-border); border-radius:6px; margin-top:.5rem; overflow:hidden;";const o=document.createElement("div");o.style.cssText="padding:.4rem .6rem; background:color-mix(in srgb, var(--dm-background) 60%, transparent); font-weight:600; font-size:.82rem; border-bottom:1px solid var(--dm-border);",o.textContent=e,n.appendChild(o);const t=document.createElement("div");return t.className="fb-chooser-section-body",t.style.cssText="padding:.55rem .6rem; display:flex; flex-direction:column; gap:.45rem;",n.appendChild(t),{wrap:n,body:t}}function ve(e,n,o,t,l){const a=document.createElement("div");a.style.flex="1";const i=document.createElement("label");i.htmlFor=e,i.className="form-label",i.textContent=n,i.style.fontSize=".8rem";const s=document.createElement("select");if(s.id=e,s.className="form-input",t.forEach(([c,r])=>{const p=document.createElement("option");p.value=c,p.textContent=r,String(c)===String(o)&&(p.selected=!0),s.appendChild(p)}),a.appendChild(i),a.appendChild(s),l){const c=document.createElement("p");c.className="form-hint text-muted",c.textContent=l,c.style.cssText="font-size:.72rem;margin-top:.2rem;",a.appendChild(c)}return a}function gt(e,n,o,t){const l=document.createElement("div");l.style.flex="1";const a=document.createElement("label");a.style.cssText="display:inline-flex;align-items:center;gap:.4rem;font-size:.82rem;";const i=document.createElement("input");if(i.id=e,i.type="checkbox",i.checked=!!o,a.appendChild(i),a.appendChild(document.createTextNode(" "+n)),l.appendChild(a),t){const s=document.createElement("p");s.className="form-hint text-muted",s.textContent=t,s.style.cssText="font-size:.72rem;margin-top:.2rem;",l.appendChild(s)}return l}function Oe(e,n,o,t,l){const a=document.createElement("div");a.style.flex="1";const i=document.createElement("label");i.htmlFor=e,i.className="form-label",i.textContent=n,i.style.fontSize=".8rem",a.appendChild(i);const s=document.createElement("div");s.style.cssText="display:flex;gap:.4rem;align-items:stretch;";const c=document.createElement("input");c.id=e,c.type="text",c.className="form-input",c.value=o||"",t&&(c.placeholder=t),c.style.flex="1";const r=document.createElement("input");r.type="color",r.title="Pick a colour",r.style.cssText="width:36px;height:auto;padding:0;border:1px solid var(--dm-border);border-radius:4px;cursor:pointer;";const p=String(c.value).match(/^#[0-9a-fA-F]{3,8}$/);if(r.value=p?c.value:"#000000",r.addEventListener("input",()=>{c.value=r.value,c.dispatchEvent(new Event("input",{bubbles:!0}))}),s.appendChild(c),s.appendChild(r),a.appendChild(s),l){const m=document.createElement("p");m.className="form-hint text-muted",m.textContent=l,m.style.cssText="font-size:.72rem;margin-top:.2rem;",a.appendChild(m)}return a}function tn(e,n){const o=document.createElement("div");o.style.cssText="margin-top:.5rem; display:flex; flex-direction:column; gap:.4rem;";const t=bt("Layout");t.body.appendChild(O([ve(`fb-chooser-variant-${n}`,"Variant",e.variant||"card",[["card","Card - rich tiles"],["chip","Chip - compact pills"]],"Card supports description and grid columns; chips wrap."),gt(`fb-chooser-multiple-${n}`,"Multi-select",!!e.multiple,"Off = single (radio); on = multi (checkbox).")])),t.body.appendChild(O([ve(`fb-chooser-density-${n}`,"Density",e.density||"comfortable",[["comfortable","Comfortable"],["compact","Compact"]],"Compact strips description (card variant only)."),P("Columns",`fb-chooser-columns-${n}`,"number",e.columns||3,"Card grid (1-6). Ignored for chips.")])),o.appendChild(t.wrap);const l=bt("Visual");return l.body.appendChild(O([Oe(`fb-chooser-accent-${n}`,"Accent",e.accent||"","primary / success / #ec4899","Selected highlight colour - semantic name or any CSS colour."),ve(`fb-chooser-accent-style-${n}`,"Accent style",e.accentStyle||"border",[["border","Border (default)"],["solid","Solid"],["glow","Glow"],["overlay","Overlay"],["underline","Underline"]],"Visual treatment of the selected state.")])),l.body.appendChild(O([gt(`fb-chooser-glow-${n}`,"Glow on selected",!!e.glow,"Soft outer glow."),Oe(`fb-chooser-glow-colour-${n}`,"Glow colour",e.glowColour||"","defaults to accent","Optional; semantic name or CSS colour.")])),l.body.appendChild(O([ve(`fb-chooser-shadow-${n}`,"Shadow",e.shadow||"none",[["none","None"],["sm","Small"],["md","Medium"],["lg","Large"],["xl","Extra Large"]],"Drop shadow on every option."),Oe(`fb-chooser-shadow-colour-${n}`,"Shadow colour",e.shadowColour||"","rgba(0,0,0,0.1)","Optional shadow tint.")])),o.appendChild(l.wrap),o}function nn(e,n,o,t){const l=document.createElement("div");l.className="fb-chooser-option-row",l.dataset.optIdx=String(o),l.style.cssText="border:1px solid var(--dm-border); border-radius:4px; padding:.5rem; background:var(--dm-background-alt); display:flex; flex-direction:column; gap:.35rem;";const a=document.createElement("div");a.style.cssText="display:flex; gap:.4rem; align-items:center;";const i=document.createElement("div");i.style.cssText="display:flex; flex-direction:column; gap:1px;";const s=document.createElement("button");s.type="button",s.className="btn btn-xs btn-ghost",s.title="Move up",L(s,"arrow-up"),s.addEventListener("click",$=>{$.preventDefault(),yt(n,o,-1,t)});const c=document.createElement("button");c.type="button",c.className="btn btn-xs btn-ghost",c.title="Move down",L(c,"arrow-down"),c.addEventListener("click",$=>{$.preventDefault(),yt(n,o,1,t)}),i.appendChild(s),i.appendChild(c),a.appendChild(i);const r=document.createElement("input");r.type="text",r.className="form-input fb-chooser-opt-value",r.placeholder="value",r.value=e.value||"",r.style.flex="1",a.appendChild(r);const p=document.createElement("input");p.type="text",p.className="form-input fb-chooser-opt-label",p.placeholder="label (visible to users)",p.value=e.label||"",p.style.flex="2",a.appendChild(p);const m=document.createElement("button");m.type="button",m.className="btn btn-xs btn-ghost",m.style.cssText="line-height:1;opacity:.6;",m.title="Remove option",L(m,"x"),m.addEventListener("click",$=>{$.preventDefault(),sn(n,o,t)}),a.appendChild(m),l.appendChild(a);const h=document.createElement("div");h.style.cssText="display:flex; gap:.4rem;";const y=qt("icon name (optional)",e.icon||"");y.input.classList.add("fb-chooser-opt-icon"),y.el.style.flex="1",h.appendChild(y.el);const v=document.createElement("input");v.type="text",v.className="form-input fb-chooser-opt-description",v.placeholder="description (card + comfortable only)",v.value=e.description||"",v.style.flex="2",h.appendChild(v),l.appendChild(h);const f=document.createElement("div");f.style.cssText="display:flex; gap:.4rem;";const w=document.createElement("input");w.type="text",w.className="form-input fb-chooser-opt-tooltip",w.placeholder="tooltip (hover hint)",w.value=e.tooltip||"",w.style.flex="2",f.appendChild(w);const u=document.createElement("input");u.type="text",u.className="form-input fb-chooser-opt-badge-text",u.placeholder="badge text",u.value=e.badge?.text||"",u.style.flex="1",f.appendChild(u);const x=document.createElement("select");x.className="form-input fb-chooser-opt-badge-type",x.style.flex="1",[["","no badge"],["primary","primary"],["success","success"],["info","info"],["warning","warning"],["danger","danger"]].forEach(([$,Y])=>{const W=document.createElement("option");W.value=$,W.textContent=Y,(e.badge?.type||"")===$&&(W.selected=!0),x.appendChild(W)}),f.appendChild(x),l.appendChild(f);const N=document.createElement("div");N.style.cssText="display:flex; gap:1rem; font-size:.8rem;";const q=document.createElement("label");q.style.cssText="display:inline-flex;align-items:center;gap:.3rem;";const V=document.createElement("input");V.type="checkbox",V.className="fb-chooser-opt-recommended",V.checked=!!e.recommended,q.appendChild(V),q.appendChild(document.createTextNode(" Recommended")),N.appendChild(q);const _=document.createElement("label");_.style.cssText="display:inline-flex;align-items:center;gap:.3rem;";const j=document.createElement("input");return j.type="checkbox",j.className="fb-chooser-opt-disabled",j.checked=!!e.disabled,_.appendChild(j),_.appendChild(document.createTextNode(" Disabled")),N.appendChild(_),l.appendChild(N),l}function ln(e,n){const o=document.createElement("div");o.style.cssText="margin-top:.5rem;";const t=document.createElement("div");t.style.cssText="display:flex; align-items:center; justify-content:space-between; margin-bottom:.4rem;";const l=document.createElement("p");l.textContent="Options",l.style.cssText="font-size:.85rem;font-weight:600;margin:0;",t.appendChild(l);const a=document.createElement("button");a.type="button",a.className="btn btn-xs btn-ghost",le(a,"plus","Add option"),t.appendChild(a),o.appendChild(t);const i=document.createElement("div");i.className="fb-chooser-options-list",i.id=`fb-chooser-options-${n}`,i.style.cssText="display:flex; flex-direction:column; gap:.4rem;",o.appendChild(i);const s=()=>{i.replaceChildren();const c=an(n);(c.length?c:e||[]).forEach((p,m)=>{i.appendChild(nn(p,n,m,s))})};return a.addEventListener("click",c=>{c.preventDefault(),on(n,s)}),s(),o}function an(e){const n=C[e];return!n||!Array.isArray(n.options)?[]:n.options}function Re(e){return C[e]?(Array.isArray(C[e].options)||(C[e].options=[]),C[e].options):[]}function on(e,n){xe(e),Re(e).push({value:"new",label:"New option"}),n()}function sn(e,n,o){xe(e),Re(e).splice(n,1),o()}function yt(e,n,o,t){xe(e);const l=Re(e),a=n+o;if(a<0||a>=l.length)return;const[i]=l.splice(n,1);l.splice(a,0,i),t()}function xe(e){const n=document.getElementById(`fb-chooser-options-${e}`);if(!n)return;const o=n.querySelectorAll(".fb-chooser-option-row"),t=[];o.forEach(l=>{const a={value:l.querySelector(".fb-chooser-opt-value")?.value.trim()||"",label:l.querySelector(".fb-chooser-opt-label")?.value.trim()||""},i=l.querySelector(".fb-chooser-opt-icon")?.value.trim();i&&(a.icon=i);const s=l.querySelector(".fb-chooser-opt-description")?.value.trim();s&&(a.description=s);const c=l.querySelector(".fb-chooser-opt-tooltip")?.value.trim();c&&(a.tooltip=c);const r=l.querySelector(".fb-chooser-opt-badge-text")?.value.trim(),p=l.querySelector(".fb-chooser-opt-badge-type")?.value;(r||p)&&(a.badge={},r&&(a.badge.text=r),p&&(a.badge.type=p)),l.querySelector(".fb-chooser-opt-recommended")?.checked&&(a.recommended=!0),l.querySelector(".fb-chooser-opt-disabled")?.checked&&(a.disabled=!0),t.push(a)}),C[e]&&(C[e].options=t)}function O(e){const n=document.createElement("div");return n.style.cssText="display:flex;gap:.85rem;margin-bottom:.75rem;",e.forEach(o=>{o&&n.appendChild(o)}),n}function P(e,n,o,t,l){const a=document.createElement("div");a.style.flex="1";const i=document.createElement("label");i.htmlFor=n,i.className="form-label",i.textContent=e,i.style.fontSize=".8rem";const s=document.createElement("input");if(s.id=n,s.type=o||"text",s.className="form-input",s.value=t??"",a.appendChild(i),a.appendChild(s),l){const c=document.createElement("p");c.className="form-hint text-muted",c.textContent=l,c.style.cssText="font-size:.73rem;margin-top:.35rem;",a.appendChild(c)}return a}function rn(e,n,o,t){const l=document.createElement("div");l.style.flex="1";const a=document.createElement("label");a.htmlFor=n,a.className="form-label",a.textContent=e,a.style.fontSize=".8rem";const i=document.createElement("select");return i.id=n,i.className="form-select",o.forEach(s=>{const c=document.createElement("option");c.value=s.value,c.textContent=s.label,s.value===t&&(c.selected=!0),i.appendChild(c)}),l.appendChild(a),l.appendChild(i),l}function vt(e,n,o){const t=document.createElement("div");t.style.cssText="flex:0;min-width:80px;display:flex;flex-direction:column;justify-content:flex-end;";const l=document.createElement("label");l.style.cssText="display:flex;align-items:center;gap:.4rem;cursor:pointer;font-size:.8rem;white-space:nowrap;";const a=document.createElement("input");return a.id=n,a.type="checkbox",a.checked=o,l.appendChild(a),l.appendChild(document.createTextNode(e)),t.appendChild(l),t}function cn(e,n){const o=document.createElement("div");o.style.cssText="margin-top:.4rem;";const t=document.createElement("p");t.textContent="Options (one per line: value or value:Label)",t.style.cssText="font-size:.8rem;font-weight:600;margin-bottom:.3rem;";const l=document.createElement("textarea");return l.id=`fb-options-${n}`,l.className="form-input",l.rows=4,l.placeholder=`yes:Yes
|
|
1
|
+
import{apiRequest as se}from"/admin/js/api.js";import{makeIconInput as zt}from"/admin/js/lib/shortcode-modal.js";import{enhancePickerFields as nt}from"/public/js/forms.js";import{buildWizardSteps as Pt}from"/public/js/form-steps.mjs";import{addBannerAction as Ae}from"../lib/plugin-chrome.js";import{helpPopovers as _t}from"../lib/help-popover.js";import{openMenuAt as lt,sidebarCount as jt}from"../lib/tool-kit.js";import{draftKey as re,draftOf as Vt,duplicateField as Gt,fieldTitle as Fe,fingerprint as at,leavingEditor as ot,moveField as it,restoreDraft as Ht,snapshotOf as Ie}from"../lib/form-editor-arrange.js";const st=[{value:"string",label:"Text (single line)"},{value:"email",label:"Email"},{value:"tel",label:"Phone"},{value:"number",label:"Number"},{value:"textarea",label:"Textarea (multi-line)"},{value:"select",label:"Dropdown (select)"},{value:"radio",label:"Radio buttons"},{value:"checkbox",label:"Single checkbox"},{value:"checkbox-group",label:"Checkbox group"},{value:"chooser",label:"Chooser (visual options)"},{value:"icon",label:"Icon (icon picker)"},{value:"image",label:"Image (media library)"},{value:"date",label:"Date"},{value:"time",label:"Time"},{value:"url",label:"URL"},{value:"password",label:"Password"},{value:"file",label:"File upload"},{value:"hidden",label:"Hidden field"}],Be=new Set(["select","radio","checkbox-group","chooser"]);let C=[],be=[],N=null,ge=null,le=null,ye={};function q(e,t,o=14){e.textContent="";const n=document.createElement("span");return n.setAttribute("data-icon",t),n.setAttribute("data-icon-size",String(o)),n.style.cssText="display:inline-flex;align-items:center;vertical-align:middle;",e.appendChild(n),window.I?.scan?.(e),e}function ce(e,t,o,n=14){return q(e,t,n),e.appendChild(document.createTextNode(" "+o)),e}function Oe(e){const t=document.createElement("span");return t.setAttribute("data-icon","help-circle"),t.setAttribute("data-icon-size","12"),t.style.cssText="display:inline-flex;align-items:center;vertical-align:middle;margin-left:.3rem;opacity:.55;cursor:help;",t.title=e,window.I?.scan?.(t),requestAnimationFrame(()=>{try{t.parentNode&&typeof E<"u"&&E.tooltip&&(t.removeAttribute("title"),E.tooltip(t,{content:e,position:"top"}))}catch{}}),t}let ve=null,rt=null,Me=null,de=null;function Re(){Me?.(),clearTimeout(rt),rt=setTimeout(()=>{ve&&ve()},350)}function ct(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}function dt(e){return st.find(t=>t.value===e)?.label||e}function pt(e){return(e||[]).some(t=>t.logic||Array.isArray(t.triggers)&&t.triggers.length)}function ut(e){return e?!!(e.visibility?.conditions?.length||e.requirement?.conditions?.length||e.validation?.length||e.cascade?.sourceField):!1}function Wt(e){const t={...C[e]};if(t.type==="spacer")return t;if(t.type==="page-break"){const f=document.getElementById(`fb-pb-label-${e}`),x=document.getElementById(`fb-pb-desc-${e}`);return f&&(t.label=f.value.trim()||t.label),x&&(t.description=x.value.trim()),t}const o=document.getElementById(`fb-label-${e}`),n=document.getElementById(`fb-name-${e}`),l=document.getElementById(`fb-type-${e}`),a=document.getElementById(`fb-required-${e}`),i=document.getElementById(`fb-placeholder-${e}`),r=document.getElementById(`fb-helper-${e}`),c=document.getElementById(`fb-tooltip-${e}`);if(o&&(t.label=o.value.trim()||t.label),n&&(t.name=n.value.trim()||t.name),l&&(t.type=l.value||t.type),a&&(t.required=a.checked),i&&(t.placeholder=i.value.trim()),r&&(t.helper=r.value.trim()),c&&(t.tooltip=c.value.trim()),t.type==="chooser"){const f=document.getElementById(`fb-chooser-variant-${e}`)?.value;f&&(t.variant=f);const x=document.getElementById(`fb-chooser-multiple-${e}`);x&&(t.multiple=x.checked);const $=document.getElementById(`fb-chooser-density-${e}`)?.value;$&&(t.density=$);const A=document.getElementById(`fb-chooser-columns-${e}`)?.value;A!==""&&A!==void 0&&(t.columns=parseInt(A,10)||3);const H=document.getElementById(`fb-chooser-accent-${e}`)?.value.trim();H?t.accent=H:delete t.accent;const _=document.getElementById(`fb-chooser-accent-style-${e}`)?.value;_?t.accentStyle=_:delete t.accentStyle;const j=document.getElementById(`fb-chooser-glow-${e}`);j&&(t.glow=j.checked);const I=document.getElementById(`fb-chooser-glow-colour-${e}`)?.value.trim();I?t.glowColour=I:delete t.glowColour;const X=document.getElementById(`fb-chooser-shadow-${e}`)?.value;X&&X!=="none"?t.shadow=X:delete t.shadow;const U=document.getElementById(`fb-chooser-shadow-colour-${e}`)?.value.trim();U?t.shadowColour=U:delete t.shadowColour,Se(e),C[e]&&Array.isArray(C[e].options)&&(t.options=C[e].options)}else if(Be.has(t.type)){["variant","density","columns","accent","accentStyle","glow","glowColour","shadow","shadowColour"].forEach(x=>delete t[x]),t.type!=="checkbox-group"&&t.type!=="multiselect"&&delete t.multiple;const f=document.getElementById(`fb-options-${e}`);f&&(t.options=f.value.split(`
|
|
2
|
+
`).filter(x=>x.trim()).map(x=>{const[$,...A]=x.split(":");return{value:$.trim(),label:A.join(":").trim()||$.trim()}}))}if(t.type==="textarea"){const f=parseInt(document.getElementById(`fb-rows-${e}`)?.value,10);f>0&&(t.formConfig={...t.formConfig||{},rows:f})}const s=document.getElementById(`fb-span-${e}`),d=document.getElementById(`fb-fullwidth-${e}`);if(s||d){const f={...t.formConfig||{}};if(d?.checked)f.span="full";else{const x=parseInt(s?.value,10);x>1?f.span=x:delete f.span}t.formConfig=Object.keys(f).length?f:void 0}const u=document.getElementById(`fb-minlength-${e}`)?.value;u&&(t.minLength=parseInt(u,10));const b=document.getElementById(`fb-maxlength-${e}`)?.value;b&&(t.maxLength=parseInt(b,10));const g=document.getElementById(`fb-min-${e}`)?.value;g!==""&&g!==void 0&&(t.min=parseFloat(g));const m=document.getElementById(`fb-max-${e}`)?.value;m!==""&&m!==void 0&&(t.max=parseFloat(m));const h=Ut(e);h?t.logic=h:delete t.logic;const w=dn(e);return w?t.triggers=w:delete t.triggers,t}function Ut(e){const t=document.querySelector(`.fb-field-card[data-index="${e}"]`);if(!t)return;const o=t.querySelector(".fb-field-logic");if(!o)return;const n={};let l=!1;const a=o.querySelector('[data-logic-section="visibility"]');if(a){const s=a.querySelector(".fb-logic-vis-default"),d=a.querySelector(".fb-logic-vis-transition"),u=Array.from(a.querySelectorAll(".fb-logic-cond-row")).map(h=>{const w=h.querySelector(".fb-logic-cond-field"),f=h.querySelector(".fb-logic-cond-op"),x=h.querySelector(".fb-logic-cond-val"),$=h.querySelector(".fb-logic-vis-then");return w?.value?{when:{all:[{field:w.value,operator:f.value,value:x.value}]},then:$.value}:null}).filter(Boolean),b=s?.value||"visible",g=d?.value||"none",m=parseInt(a.querySelector(".fb-logic-vis-duration")?.value||"",10);(b!=="visible"||u.length>0||g!=="none")&&(n.visibility={default:b,conditions:u},g!=="none"&&(n.visibility.transition=g),g!=="none"&&Number.isFinite(m)&&(n.visibility.duration=m),l=!0)}const i=o.querySelector('[data-logic-section="requirement"]');if(i){const s=i.querySelector(".fb-logic-req-default"),d=Array.from(i.querySelectorAll(".fb-logic-cond-row")).map(u=>{const b=u.querySelector(".fb-logic-cond-field"),g=u.querySelector(".fb-logic-cond-op"),m=u.querySelector(".fb-logic-cond-val"),h=u.querySelector(".fb-logic-req-then");return b?.value?{when:{all:[{field:b.value,operator:g.value,value:m.value}]},then:h.value==="true"}:null}).filter(Boolean);d.length>0&&(n.requirement={default:s?.checked===!0,conditions:d},l=!0)}const r=o.querySelector('[data-logic-section="validation"]');if(r){const s=Array.from(r.querySelectorAll(".fb-logic-val-rule")).map(d=>{const u=d.querySelector(".fb-logic-val-type"),b=d.querySelector(".fb-logic-val-pattern"),g=d.querySelector(".fb-logic-val-flags"),m=d.querySelector(".fb-logic-val-message");if(!b?.value.trim())return null;const h=u?.value||"regex",w={type:h,message:m?.value.trim()||"Invalid value."};return h==="regex"?(w.pattern=b.value.trim(),g?.value.trim()&&(w.flags=g.value.trim())):w.field=b.value.trim(),w}).filter(Boolean);s.length>0&&(n.validation=s,l=!0)}const c=o.querySelector('[data-logic-section="cascade"]');if(c){const s=c.querySelector(".fb-logic-cascade-source"),d=c.querySelector(".fb-logic-cascade-mapping"),u=c.querySelector(".fb-logic-cascade-defaults"),b=s?.value?.trim();if(b){let g={};try{g=JSON.parse(d?.value||"{}")}catch{}const m=(u?.value||"").split(`
|
|
3
|
+
`).filter(h=>h.trim()).map(h=>{const[w,...f]=h.split(":");return{value:w.trim(),label:f.join(":").trim()||w.trim()}});n.cascade={sourceField:b,mapping:g,defaultOptions:m},l=!0}}return l?n:void 0}function O(){C=C.map((e,t)=>Wt(t))}let ae=null;function Jt(e,t,o){const n=e.firstElementChild;if(!n)return;const l=document.createElement("span");l.setAttribute("data-icon","menu"),l.setAttribute("data-icon-size","13"),l.title="Drag to reorder",l.style.cssText="cursor:grab;opacity:.35;flex-shrink:0;display:inline-flex;align-items:center;",n.insertBefore(l,n.firstChild),window.I?.scan?.(n),n.draggable=!0,n.addEventListener("dragstart",a=>{ae=t,a.dataTransfer.effectAllowed="move",e.style.opacity="0.4"}),n.addEventListener("dragend",()=>{e.style.opacity="",document.querySelectorAll("#fields-list .fb-field-card").forEach(a=>a.classList.remove("fb-drag-over"))}),e.addEventListener("dragover",a=>{ae!=null&&(a.preventDefault(),a.dataTransfer.dropEffect="move",document.querySelectorAll("#fields-list .fb-field-card").forEach(i=>i.classList.remove("fb-drag-over")),e.classList.add("fb-drag-over"))}),e.addEventListener("dragleave",()=>e.classList.remove("fb-drag-over")),e.addEventListener("drop",a=>{if(a.preventDefault(),e.classList.remove("fb-drag-over"),ae==null||ae===t){ae=null;return}O();const[i]=C.splice(ae,1);C.splice(t,0,i),ae=null,Y(o)})}function Y(e){const t=e.find("#fields-list").get(0),o=e.find("#fields-empty-msg").get(0);if(t){if(Array.from(t.querySelectorAll(".fb-field-card")).forEach(n=>n.remove()),C.length===0){o&&(o.style.display=""),de?.(t),Re();return}o&&(o.style.display="none"),C.forEach((n,l)=>{const a=n.type==="page-break"?Yt(n,l,e):n.type==="spacer"?Kt(n,l,e):Qt(n,l,e);Jt(a,l,e),t.appendChild(a)}),de?.(t),Re()}}function Yt(e,t,o){const n=document.createElement("div");n.className="fb-field-card",n.dataset.index=t,n.style.cssText="border:2px dashed var(--dm-border);border-radius:8px;overflow:hidden;margin-bottom:.75rem;background:var(--dm-card-bg);";const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.6rem;padding:.6rem .8rem;cursor:pointer;user-select:none;";const a=document.createElement("span");a.textContent="- Page Break -",a.style.cssText="font-size:.7rem;padding:.15rem .5rem;border-radius:999px;background:color-mix(in srgb, var(--dm-text-muted) 20%, transparent);color:var(--dm-text-muted);white-space:nowrap;flex-shrink:0;font-style:italic;";const i=document.createElement("span");i.textContent=e.label||"Untitled Step",i.style.cssText="flex:1;font-weight:600;font-size:.9rem;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dm-text-muted);";const r=document.createElement("div");r.style.cssText="display:flex;gap:.25rem;flex-shrink:0;margin-left:.5rem;";const c=document.createElement("button");c.className="btn btn-xs btn-ghost",c.title="Edit step",q(c,"more-horizontal"),c.addEventListener("click",g=>{g.stopPropagation(),d.style.display=d.style.display==="none"?"":"none"}),r.appendChild(c);const s=document.createElement("button");s.className="btn btn-xs btn-ghost",s.style.cssText="line-height:1;opacity:.6;",s.title="Remove page break",q(s,"x"),s.addEventListener("click",async g=>{g.stopPropagation(),await E.confirm("Remove this page break?")&&(O(),C.splice(t,1),Y(o))}),r.appendChild(s),l.appendChild(a),l.appendChild(i),l.appendChild(r),l.addEventListener("click",()=>{d.style.display=d.style.display==="none"?"":"none"});const d=document.createElement("div");d.className="fb-field-body",d.style.cssText="padding:.8rem;border-top:1px dashed var(--dm-border);display:none;";const u=z([P("Step Title",`fb-pb-label-${t}`,"text",e.label||"","Shown as the wizard step heading"),P("Step Description",`fb-pb-desc-${t}`,"text",e.description||"","Optional sub-heading")]),b=u.querySelector(`#fb-pb-label-${t}`);return b&&b.addEventListener("input",()=>{i.textContent=b.value||"Untitled Step"}),d.appendChild(u),n.appendChild(l),n.appendChild(d),n}function Kt(e,t,o){const n=document.createElement("div");n.className="fb-field-card",n.dataset.index=t,n.style.cssText="border:1px dashed var(--dm-border);border-radius:6px;margin-bottom:.5rem;background:transparent;";const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.6rem;padding:.4rem .8rem;";const a=document.createElement("div");a.style.cssText="flex:1;height:1px;background:var(--dm-border);";const i=document.createElement("span");i.textContent="Spacer",i.style.cssText="font-size:.7rem;color:var(--dm-text-muted);white-space:nowrap;padding:0 .4rem;font-style:italic;";const r=document.createElement("div");r.style.cssText="flex:1;height:1px;background:var(--dm-border);";const c=document.createElement("div");c.style.cssText="display:flex;gap:.25rem;flex-shrink:0;";const s=document.createElement("button");return s.className="btn btn-xs btn-ghost",s.style.cssText="line-height:1;opacity:.6;",s.title="Remove spacer",q(s,"x"),s.addEventListener("click",async d=>{d.stopPropagation(),O(),C.splice(t,1),Y(o)}),c.appendChild(s),l.appendChild(a),l.appendChild(i),l.appendChild(r),l.appendChild(c),n.appendChild(l),n}function Qt(e,t,o){const n=document.createElement("div");n.className="fb-field-card",n.dataset.index=t,n.style.cssText="border:1px solid var(--dm-border);border-radius:8px;overflow:hidden;margin-bottom:.75rem;background:var(--dm-card-bg);box-shadow:var(--dm-shadow-sm);";const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.6rem;padding:.65rem .85rem;background:var(--dm-card-header-bg);cursor:pointer;user-select:none;";const a=document.createElement("span");a.textContent=dt(e.type),a.style.cssText="font-size:.7rem;padding:.15rem .45rem;border-radius:999px;background:color-mix(in srgb, var(--dm-primary) 14%, transparent);color:var(--dm-primary);white-space:nowrap;flex-shrink:0;";const i=document.createElement("span");i.textContent=e.label||"(unlabelled)",i.style.cssText="flex:1;font-weight:600;font-size:.9rem;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;";const r=document.createElement("div");r.style.cssText="display:flex;gap:.25rem;flex-shrink:0;margin-left:.5rem;";const c=document.createElement("button");c.className="btn btn-xs btn-ghost",c.title="Edit field",q(c,"more-horizontal"),c.addEventListener("click",u=>{u.stopPropagation(),d.style.display=d.style.display==="none"?"":"none"}),r.appendChild(c);const s=document.createElement("button");if(s.className="btn btn-xs btn-ghost",s.style.cssText="line-height:1;opacity:.6;",s.title="Remove field",q(s,"x"),s.addEventListener("click",async u=>{u.stopPropagation(),await E.confirm("Remove this field?")&&(O(),C.splice(t,1),Y(o))}),r.appendChild(s),l.appendChild(a),l.appendChild(i),e.required){const u=document.createElement("span");u.textContent="required",u.style.cssText="font-size:.7rem;color:var(--dm-danger);flex-shrink:0;",l.appendChild(u)}if(ut(e.logic)){const u=document.createElement("span");q(u,"zap"),u.title="Has conditional logic",u.style.cssText="font-size:.75rem;color:var(--dm-primary);flex-shrink:0;",l.appendChild(u)}l.appendChild(r),l.addEventListener("click",()=>{d.style.display=d.style.display==="none"?"":"none"});const d=Xt(e,t,i);return d.style.display="none",n.appendChild(l),n.appendChild(d),n}function Xt(e,t,o){const n=document.createElement("div");n.className="fb-field-body",n.style.cssText="padding:1rem .9rem;border-top:1px solid var(--dm-border);";const l=z([P("Label",`fb-label-${t}`,"text",e.label||"","Shown above the field"),P("Field Name",`fb-name-${t}`,"text",e.name||"","Used as data key")]),a=z([gn("Type",`fb-type-${t}`,st,e.type||"string"),qt("Required",`fb-required-${t}`,e.required||!1)]),i=z([P("Placeholder",`fb-placeholder-${t}`,"text",e.placeholder||"","Hint text inside the field")]),r=z([P("Helper Text",`fb-helper-${t}`,"text",e.helper||"","Shown below the field"),P("Tooltip",`fb-tooltip-${t}`,"text",e.tooltip||"","Shown on hover via a help icon next to the label")]),c=e.formConfig?.span,s=z([P("Column Span",`fb-span-${t}`,"number",c&&c!=="full"?String(c):"1","Columns to span (grid only)"),qt("Full Width",`fb-fullwidth-${t}`,c==="full")]);s.classList.add("fb-grid-row"),s.style.display=document.getElementById("setting-layout")?.value==="grid"?"flex":"none",n.appendChild(l),n.appendChild(a),n.appendChild(i),n.appendChild(r),n.appendChild(s);const d=n.querySelector(`#fb-label-${t}`),u=n.querySelector(`#fb-name-${t}`);d&&d.addEventListener("input",()=>{o&&(o.textContent=d.value||"(unlabelled)"),u&&!u.dataset.manuallyEdited&&(u.value=ct(d.value))}),u&&u.addEventListener("input",()=>{u.dataset.manuallyEdited="1"});const b=n.querySelector(`#fb-type-${t}`);b&&b.addEventListener("change",()=>{const m=n.closest(".fb-field-card");if(m){const f=m.querySelector("span");f&&(f.textContent=dt(b.value))}const h=n.querySelector(".fb-field-extras");h&&h.remove();const w=St(b.value,e,t);w&&n.appendChild(w)});const g=St(e.type,e,t);return g&&n.appendChild(g),n.appendChild(ln(e,t)),n.appendChild(rn(e,t)),n}const xe=[{value:"equals",label:"equals"},{value:"not_equals",label:"does not equal"},{value:"contains",label:"contains"},{value:"not_contains",label:"does not contain"},{value:"starts_with",label:"starts with"},{value:"ends_with",label:"ends with"},{value:"greater_than",label:"is greater than"},{value:"less_than",label:"is less than"},{value:"is_empty",label:"is empty"},{value:"is_not_empty",label:"is not empty"},{value:"in",label:"is one of (comma sep)"},{value:"not_in",label:"is not one of (comma sep)"},{value:"matches_regex",label:"matches regex"}],De=new Set(["is_empty","is_not_empty"]),mt={equals:"includes",not_equals:"does not include",contains:"any value contains",not_contains:"no value contains",starts_with:"any value starts with",ends_with:"any value ends with",greater_than:"any value is greater than",less_than:"any value is less than",is_empty:"nothing selected",is_not_empty:"something selected",in:"includes one of (comma sep)",not_in:"includes none of (comma sep)",matches_regex:"any value matches regex"};function ze(e){return!!e&&(e.type==="checkbox-group"||!!e.multiple)}function Ce(e){const t=document.createElement("p");return t.textContent=e,t.style.cssText="font-size:.75rem;font-weight:700;color:var(--dm-text-muted);margin:0 0 .7rem;text-transform:uppercase;letter-spacing:.06em;",t}function Ee(e,t,o,n,l){const a=document.createElement("div");a.className="fb-logic-cond-row",a.style.cssText="display:flex;gap:.55rem;align-items:center;margin-bottom:.6rem;flex-wrap:wrap;";const i=document.createElement("span");i.textContent="When",i.style.cssText="font-size:.73rem;color:var(--dm-text-muted);flex-shrink:0;";const r=document.createElement("select");r.className="form-select fb-logic-cond-field",r.style.cssText="flex:1 1 140px;min-width:140px;",t.forEach(m=>{const h=document.createElement("option");h.value=m.value,h.textContent=m.label,e&&m.value===e.field&&(h.selected=!0),r.appendChild(h)});const c=document.createElement("select");c.className="form-select fb-logic-cond-op",c.style.cssText="flex:1 1 160px;min-width:140px;",xe.forEach(m=>{const h=document.createElement("option");h.value=m.value,h.textContent=m.label,e&&m.value===e.operator&&(h.selected=!0),c.appendChild(h)});const s=()=>{const m=t.find(h=>h.value===r.value);Array.from(c.options).forEach(h=>{const w=xe.find(f=>f.value===h.value);h.textContent=m?.multi&&mt[h.value]||w?.label||h.value})};s(),r.addEventListener("change",s);const d=document.createElement("input");d.type="text",d.className="form-input fb-logic-cond-val",d.placeholder="value",d.style.cssText="flex:1 1 120px;min-width:100px;",d.value=e?.value||"",e&&De.has(e.operator)&&(d.style.display="none"),c.addEventListener("change",()=>{d.style.display=De.has(c.value)?"none":""});const u=document.createElement("span");q(u,"arrow-right"),u.style.cssText="font-size:.73rem;color:var(--dm-text-muted);flex-shrink:0;";const b=document.createElement("select");b.className=`form-select ${n}`,b.style.cssText="flex:1 1 140px;min-width:120px;",o.forEach(m=>{const h=document.createElement("option");h.value=m.value,h.textContent=m.label,m.value===l&&(h.selected=!0),b.appendChild(h)});const g=document.createElement("button");return g.type="button",g.className="btn btn-xs btn-ghost",g.style.cssText="line-height:1;opacity:.6;",q(g,"x"),g.style.flexShrink="0",g.addEventListener("click",()=>a.remove()),a.appendChild(i),a.appendChild(r),a.appendChild(c),a.appendChild(d),a.appendChild(u),a.appendChild(b),a.appendChild(g),a}function Zt(e,t,o){const n=document.createElement("div");n.dataset.logicSection="visibility",n.appendChild(Ce("Visibility"));const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.6rem;margin-bottom:.65rem;flex-wrap:wrap;";const a=document.createElement("span");a.textContent="Default:",a.style.cssText="font-size:.8rem;flex-shrink:0;";const i=document.createElement("select");i.className="form-select fb-logic-vis-default",i.style.cssText="max-width:240px;",[{value:"visible",label:"Visible"},{value:"hidden",label:"Hidden"}].forEach(f=>{const x=document.createElement("option");x.value=f.value,x.textContent=f.label,f.value===(e.default||"visible")&&(x.selected=!0),i.appendChild(x)}),l.appendChild(a),l.appendChild(i),n.appendChild(l);const r=document.createElement("div");r.style.cssText="display:flex;align-items:center;gap:.6rem;margin-bottom:.65rem;flex-wrap:wrap;";const c=document.createElement("span");c.textContent="Transition:",c.style.cssText="font-size:.8rem;flex-shrink:0;";const s=document.createElement("select");s.className="form-select fb-logic-vis-transition",s.style.cssText="max-width:240px;",[{value:"none",label:"None (instant)"},{value:"fade",label:"Fade"},{value:"slide",label:"Slide"},{value:"scale",label:"Scale"}].forEach(f=>{const x=document.createElement("option");x.value=f.value,x.textContent=f.label,f.value===(e.transition||"none")&&(x.selected=!0),s.appendChild(x)}),r.appendChild(c),r.appendChild(s),n.appendChild(r);const d=document.createElement("div");d.style.cssText="display:flex;align-items:center;gap:.6rem;margin-bottom:.65rem;flex-wrap:wrap;";const u=document.createElement("span");u.textContent="Speed:",u.style.cssText="font-size:.8rem;flex-shrink:0;";const b=document.createElement("select");b.className="form-select fb-logic-vis-duration",b.style.cssText="max-width:240px;",[{value:"",label:"Default"},{value:"120",label:"Very fast (120ms)"},{value:"200",label:"Fast (200ms)"},{value:"350",label:"Medium (350ms)"},{value:"600",label:"Slow (600ms)"},{value:"1000",label:"Very slow (1s)"}].forEach(f=>{const x=document.createElement("option");x.value=f.value,x.textContent=f.label,f.value===String(e.duration??"")&&(x.selected=!0),b.appendChild(x)}),d.appendChild(u),d.appendChild(b),n.appendChild(d);const g=()=>{d.style.display=s.value==="none"?"none":""};g(),s.addEventListener("change",g);const m=document.createElement("div");m.className="fb-logic-vis-rules";const h=o.map(f=>({value:f.name,label:f.label||f.name,multi:ze(f)})),w=[{value:"visible",label:"Show"},{value:"hidden",label:"Hide"}];if((e.conditions||[]).forEach(f=>{const x=(f.when?.all||f.when?.any||[])[0],$=f.then==="hidden"?"hidden":"visible";h.length>0&&m.appendChild(Ee(x,h,w,"fb-logic-vis-then",$))}),n.appendChild(m),h.length>0){const f=document.createElement("button");f.type="button",f.className="btn btn-xs btn-ghost",f.style.cssText="font-size:.73rem;margin-top:.35rem;",ce(f,"plus","Add visibility rule"),f.addEventListener("click",()=>m.appendChild(Ee(null,h,w,"fb-logic-vis-then","visible"))),n.appendChild(f)}return n}function en(e,t,o){const n=document.createElement("div");n.dataset.logicSection="requirement",n.appendChild(Ce("Conditional Requirement"));const l=document.createElement("label");l.style.cssText="display:flex;align-items:center;gap:.5rem;font-size:.8rem;cursor:pointer;margin-bottom:.65rem;";const a=document.createElement("input");a.type="checkbox",a.className="fb-logic-req-default",a.checked=e.default===!0,l.appendChild(a),l.appendChild(document.createTextNode("Required by default")),n.appendChild(l);const i=document.createElement("div");i.className="fb-logic-req-rules";const r=o.map(s=>({value:s.name,label:s.label||s.name,multi:ze(s)})),c=[{value:"true",label:"Make required"},{value:"false",label:"Make optional"}];if((e.conditions||[]).forEach(s=>{const d=(s.when?.all||s.when?.any||[])[0],u=s.then===!0?"true":"false";r.length>0&&i.appendChild(Ee(d,r,c,"fb-logic-req-then",u))}),n.appendChild(i),r.length>0){const s=document.createElement("button");s.type="button",s.className="btn btn-xs btn-ghost",s.style.cssText="font-size:.73rem;margin-top:.35rem;",ce(s,"plus","Add requirement rule"),s.addEventListener("click",()=>i.appendChild(Ee(null,r,c,"fb-logic-req-then","true"))),n.appendChild(s)}return n}function ft(e){const t=document.createElement("div");t.className="fb-logic-val-rule",t.style.cssText="display:flex;gap:.55rem;align-items:center;margin-bottom:.6rem;flex-wrap:wrap;";const o=document.createElement("select");o.className="form-select fb-logic-val-type",o.style.cssText="flex:0 0 140px;",[{value:"regex",label:"Regex"},{value:"match",label:"Match field"}].forEach(r=>{const c=document.createElement("option");c.value=r.value,c.textContent=r.label,r.value===(e?.type||"regex")&&(c.selected=!0),o.appendChild(c)});const n=document.createElement("input");n.type="text",n.className="form-input fb-logic-val-pattern",n.placeholder=e?.type==="match"?"field name":"pattern",n.value=e?.pattern||e?.field||"",n.style.cssText="flex:3;";const l=document.createElement("input");l.type="text",l.className="form-input fb-logic-val-flags",l.placeholder="flags",l.value=e?.flags||"",l.style.cssText="flex:0 0 55px;",e?.type==="match"&&(l.style.display="none"),o.addEventListener("change",()=>{l.style.display=o.value==="match"?"none":"",n.placeholder=o.value==="match"?"field name":"pattern"});const a=document.createElement("input");a.type="text",a.className="form-input fb-logic-val-message",a.placeholder="Error message",a.value=e?.message||"",a.style.cssText="flex:4;";const i=document.createElement("button");return i.type="button",i.className="btn btn-xs btn-ghost",i.style.cssText="line-height:1;opacity:.6;",q(i,"x"),i.style.flexShrink="0",i.addEventListener("click",()=>t.remove()),t.appendChild(o),t.appendChild(n),t.appendChild(l),t.appendChild(a),t.appendChild(i),t}function tn(e,t,o){const n=document.createElement("div");n.dataset.logicSection="validation",n.appendChild(Ce("Custom Validation"));const l=document.createElement("div");l.className="fb-logic-val-rules",(e||[]).forEach(i=>l.appendChild(ft(i))),n.appendChild(l);const a=document.createElement("button");return a.type="button",a.className="btn btn-xs btn-ghost",a.style.cssText="font-size:.73rem;margin-top:.35rem;",ce(a,"plus","Add validation rule"),a.addEventListener("click",()=>l.appendChild(ft(null))),n.appendChild(a),n}function nn(e,t,o){const n=document.createElement("div");n.dataset.logicSection="cascade",n.appendChild(Ce("Cascade Options")),n.lastChild.appendChild(Oe("Make this field's options depend on another field. When the source field changes, the options here are replaced by the mapping entry for its value; if nothing matches, the default options below are shown."));const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.5rem;margin-bottom:.5rem;";const a=document.createElement("span");a.textContent="Source field:",a.style.cssText="font-size:.8rem;flex-shrink:0;";const i=document.createElement("select");i.className="form-select fb-logic-cascade-source",i.style.cssText="flex:1;";const r=document.createElement("option");r.value="",r.textContent="- none -",i.appendChild(r),o.forEach(b=>{const g=document.createElement("option");g.value=b.name,g.textContent=b.label||b.name,b.name===e.sourceField&&(g.selected=!0),i.appendChild(g)}),l.appendChild(a),l.appendChild(i),n.appendChild(l);const c=document.createElement("p");c.textContent='Mapping JSON - {"value":[{"value":"...","label":"..."}]}',c.appendChild(Oe(`Each key is a value of the source field; its list becomes this field's options when that value is picked. Example: {"uk":[{"value":"london","label":"London"}]} shows London when the source is "uk".`)),c.style.cssText="font-size:.73rem;color:var(--dm-text-muted);margin:.3rem 0 .2rem;";const s=document.createElement("textarea");s.className="form-input fb-logic-cascade-mapping",s.rows=4,s.style.cssText="font-family:monospace;",s.placeholder='{"uk": [{"value": "london", "label": "London"}]}',s.value=e.mapping?JSON.stringify(e.mapping,null,2):"",n.appendChild(c),n.appendChild(s);const d=document.createElement("p");d.textContent="Default options (one per line: value:Label)",d.appendChild(Oe("Shown before the source field has a value, or when its value has no mapping entry.")),d.style.cssText="font-size:.73rem;color:var(--dm-text-muted);margin:.3rem 0 .2rem;";const u=document.createElement("textarea");return u.className="form-input fb-logic-cascade-defaults",u.rows=3,u.style.cssText="font-family:monospace;",u.placeholder=`option1:Option 1
|
|
4
|
+
option2:Option 2`,u.value=(e.defaultOptions||[]).map(b=>{const g=typeof b=="string"?b:b.value??"",m=typeof b=="string"?b:b.label??g;return g===m?g:`${g}:${m}`}).join(`
|
|
5
|
+
`),n.appendChild(d),n.appendChild(u),n}function ln(e,t){const o=e.logic||{},n=C.filter((u,b)=>b!==t&&u.type!=="page-break"&&u.type!=="spacer"),l=document.createElement("div");l.className="fb-field-logic",l.style.cssText="margin-top:.75rem;border-top:1px solid var(--dm-border);padding-top:.5rem;";const a=document.createElement("div");a.style.cssText="display:flex;align-items:center;justify-content:space-between;cursor:pointer;padding:.15rem 0;";const i=document.createElement("span");i.style.cssText="font-size:.8rem;font-weight:600;color:var(--dm-text-muted);",i.textContent="\u26A1 Conditional Logic";const r=ut(o),c=document.createElement("button");c.type="button",c.className="btn btn-xs btn-ghost",q(c,r?"chevron-down":"chevron-right",12);const s=document.createElement("div");s.className="fb-logic-body",s.style.cssText="padding:.25rem 0 .25rem;"+(r?"":"display:none;"),a.addEventListener("click",()=>{const u=s.style.display==="none";s.style.display=u?"":"none",q(c,u?"chevron-down":"chevron-right",12)}),a.appendChild(i),a.appendChild(c),l.appendChild(a),s.appendChild(Zt(o.visibility||{},t,n)),s.appendChild(en(o.requirement||{},t,n)),s.appendChild(tn(o.validation||[],t,n));const d=document.getElementById(`fb-type-${t}`)?.value||e.type;return Be.has(d)&&s.appendChild(nn(o.cascade||{},t,n)),l.appendChild(s),l}const pe=[{value:"banner",label:"Show a banner",kind:"state",params:["message","level","position","dismissible"],placeholder:"e.g. You must be 18 or over to continue."},{value:"toast",label:"Show a toast",kind:"event",params:["message","level"],placeholder:"e.g. Thanks - carry on."},{value:"hide-fields",label:"Hide fields",kind:"state",params:["target"]},{value:"disable-fields",label:"Disable fields",kind:"state",params:["target"]},{value:"require-fields",label:"Make fields required",kind:"state",params:["target"]},{value:"block-submit",label:"Block submission",kind:"state",params:["message"],messageLabel:"Reason, shown under the button",placeholder:'Blank: "This form cannot be submitted yet."'},{value:"end-form",label:"End the form here",kind:"state",params:["message","finish","finishLabel","doneMessage","record"],messageLabel:"Message shown in place of the rest",placeholder:"e.g. Sorry - you must be 18 or over to apply."},{value:"goto-step",label:"Jump to a wizard step",kind:"event",params:["step"]},{value:"redirect",label:"Redirect after submit",kind:"event",params:["url"]},{value:"celebrate",label:"Celebrate",kind:"event",params:["theme","intensity"]},{value:"run-action",label:"Run a CMS action",kind:"event",params:["slug"]},{value:"notify",label:"Notify the admins",kind:"event",params:["message","level"],messageLabel:"Notification title",placeholder:"Blank: titled after the form",noOnce:!0,kindText:"when the form is submitted"}],we=[{value:"info",label:"Info"},{value:"success",label:"Success"},{value:"warning",label:"Warning"},{value:"error",label:"Error"}],ht=[{value:"field-below",label:"Below this field"},{value:"field-above",label:"Above this field"},{value:"form-top",label:"Top of the form"}],bt=[{value:"rest",label:"The rest of the form"},{value:"all",label:"Every other field"},{value:"listed",label:"Chosen fields"}],gt=[{value:"auto",label:"Whatever is in season"},{value:"christmas",label:"Christmas"},{value:"halloween",label:"Halloween"},{value:"valentines",label:"Valentine's Day"},{value:"guy-fawkes",label:"Guy Fawkes Night"},{value:"st-patricks",label:"St Patrick's Day"},{value:"st-andrews",label:"St Andrew's Day"},{value:"st-davids",label:"St David's Day"},{value:"st-georges",label:"St George's Day"}];function yt(e,t=!1){const o=(i,r)=>({value:i.name,label:`${i.label||i.name}${r?" (this field)":""}`,multi:ze(i)}),n=i=>i&&i.type!=="page-break"&&i.type!=="spacer"&&i.name,l=C.filter((i,r)=>r!==e&&n(i)).map(i=>o(i,!1)),a=C[e];return t&&n(a)?[o(a,!0),...l]:l}function K(e,t,o){const n=document.createElement("select");return n.className=`form-select ${e}`,t.forEach(l=>{const a=document.createElement("option");a.value=l.value,a.textContent=l.label,l.value===o&&(a.selected=!0),n.appendChild(a)}),n}function oe(e,t,o){const n=document.createElement("input");return n.type="text",n.className=`form-input ${e}`,n.value=t==null?"":String(t),o&&(n.placeholder=o),n}function Pe(e,t){const o=document.createElement("button");return o.type="button",o.className="btn btn-xs btn-ghost fb-trig-remove",t&&(o.title=t,o.setAttribute("aria-label",t)),q(o,"x"),o.addEventListener("click",n=>{n.stopPropagation(),e()}),o}function G(e,t,{full:o=!1,hint:n=""}={}){const l=document.createElement("label");l.className=`fb-trig-f${o?" fb-trig-f--full":""}`;const a=document.createElement("span");if(a.className="fb-trig-f-label",a.textContent=e,l.appendChild(a),l.appendChild(t),n){const i=document.createElement("span");i.className="fb-trig-f-hint",i.textContent=n,l.appendChild(i)}return l}function ue(e,t,o,n){const l=document.createElement("label");l.className="fb-trig-check",n&&(l.title=n);const a=document.createElement("input");return a.type="checkbox",a.className=`form-check ${e}`,a.checked=!!t,l.appendChild(a),l.appendChild(document.createTextNode(o)),l}function vt(e,t){const o=document.createElement("div");o.className="fb-trig-cond-row";const n=K("fb-trig-cond-field",t,e?.field),l=K("fb-trig-cond-op",xe,e?.operator),a=oe("fb-trig-cond-val",e?.value,"value"),i=()=>{const c=t.find(s=>s.value===n.value);Array.from(l.options).forEach(s=>{const d=xe.find(u=>u.value===s.value);s.textContent=c?.multi&&mt[s.value]||d?.label||s.value})},r=()=>{a.hidden=De.has(l.value)};return i(),r(),n.addEventListener("change",i),l.addEventListener("change",r),o.appendChild(n),o.appendChild(l),o.appendChild(a),o.appendChild(Pe(()=>o.remove(),"Remove condition")),o}function xt(e,t){const o=document.createElement("div");o.className="fb-trig-params";const n=pe.find(c=>c.value===(e.type||"banner"));if(!n)return o;const l=document.createElement("div");l.className="fb-trig-grid";const a=document.createElement("div");a.className="fb-trig-opts";const i=[];for(const c of n.params)switch(c){case"message":l.appendChild(G(n.messageLabel||"Message",oe("fb-trig-p-message",e.message,n.placeholder||""),{full:!0}));break;case"finish":a.appendChild(ue("fb-trig-p-finish-on",e.finish!==!1,"Let the visitor finish (send the answers given so far)",'Untick to stop the form dead: the submit button is disabled and nothing is sent, so nothing is saved and "Notify the admins" cannot fire.'));break;case"finishLabel":{const s=G("Button text",oe("fb-trig-p-finish",e.finishLabel,"Finish"));i.push(s),l.appendChild(s);break}case"doneMessage":{const s=G("Closing message",oe("fb-trig-p-done",e.doneMessage,"Blank: the form's own success message"));i.push(s),l.appendChild(s);break}case"record":{const s=ue("fb-trig-p-record",e.record!==!1,"Save the answers given so far",`Untick to keep nothing: no submission is stored and the form's email, webhook and actions do not run. A "Notify the admins" action still fires.`);i.push(s),a.appendChild(s);break}case"level":l.appendChild(G(n.value==="notify"?"Severity":"Level",K("fb-trig-p-level",we,e.level||"info")));break;case"position":l.appendChild(G("Where",K("fb-trig-p-position",ht,e.position||"field-below")));break;case"dismissible":a.appendChild(ue("fb-trig-p-dismissible",e.dismissible!==!1,"The visitor can dismiss it"));break;case"target":{const s=K("fb-trig-p-target",bt,e.target||(e.fields?.length?"listed":"rest")),d=document.createElement("select");d.className="form-select fb-trig-p-fields",d.multiple=!0,d.size=4;const u=new Set(e.fields||[]);yt(t).forEach(m=>{const h=document.createElement("option");h.value=m.value,h.textContent=m.label,u.has(m.value)&&(h.selected=!0),d.appendChild(h)});const b=G("Fields",d,{hint:"Ctrl/Cmd-click to pick several"}),g=()=>{b.hidden=s.value!=="listed"};g(),s.addEventListener("change",g),l.appendChild(G("Which fields",s)),l.appendChild(b);break}case"step":{const s=oe("fb-trig-p-step",e.step,"0");s.type="number",s.min="0",l.appendChild(G("Step",s,{hint:"Counting from 0"}));break}case"url":l.appendChild(G("Send them to",oe("fb-trig-p-url",e.url,"/thank-you"),{full:!0}));break;case"theme":l.appendChild(G("Theme",K("fb-trig-p-theme",gt,e.theme||"auto")));break;case"intensity":l.appendChild(G("Intensity",K("fb-trig-p-intensity",[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}],e.intensity||"medium")));break;case"slug":{const s=[{value:"",label:be.length?"Choose an action":"No actions available"}].concat(be.map(d=>({value:d.slug,label:d.title||d.slug})));l.appendChild(G("Action",K("fb-trig-p-slug",s,e.slug||""),{full:!0}));break}default:break}n.kind==="event"&&!n.noOnce&&a.appendChild(ue("fb-trig-p-once",!!e.once,"Only once","Fire the first time only, rather than every time the answer swings back."));const r=a.querySelector(".fb-trig-p-finish-on");if(r){const c=()=>i.forEach(s=>{s.hidden=!r.checked});c(),r.addEventListener("change",c)}return l.children.length&&o.appendChild(l),a.children.length&&o.appendChild(a),o}function an(e){return e?.kindText?e.kindText:e?.kind==="event"?"once, when it becomes true":"while it is true"}const on=(e,t=48)=>e.length>t?`${e.slice(0,t-1)}\u2026`:e,ie=(e,t)=>e.find(o=>o.value===t)?.label||t;function sn(e){if(!e)return"";const t=[],o=l=>l?`"${on(l)}"`:"",n=()=>e.target==="listed"?e.fields?.length?e.fields.join(", "):"no fields chosen":ie(bt,e.target||"rest").toLowerCase();switch(e.type){case"banner":t.push(o(e.message)||"No message yet",ie(we,e.level||"info"),ie(ht,e.position||"field-below").toLowerCase());break;case"toast":t.push(o(e.message)||"No message yet",ie(we,e.level||"info"));break;case"hide-fields":case"disable-fields":case"require-fields":t.push(n());break;case"block-submit":t.push(o(e.message)||"the standard reason");break;case"end-form":t.push(o(e.message)||"no message"),e.finish===!1?t.push("submit disabled"):t.push(`button "${e.finishLabel||"Finish"}"`,e.record===!1?"saves nothing":"saves the answers");break;case"goto-step":t.push(Number.isFinite(e.step)?`step ${e.step}`:"no step yet");break;case"redirect":t.push(e.url||"no address yet");break;case"celebrate":t.push(ie(gt,e.theme||"auto"),`${e.intensity||"medium"} intensity`);break;case"run-action":t.push(e.slug?be.find(l=>l.slug===e.slug)?.title||e.slug:"no action chosen");break;case"notify":t.push(o(e.message)||"titled after the form",ie(we,e.level||"info"));break;default:break}return e.once&&t.push("only once"),t.filter(Boolean).join(" \xB7 ")}function _e(e,t,{open:o=!1}={}){const n=document.createElement("div");n.className="fb-trig-action-row";const l=document.createElement("div");l.className="fb-trig-action-head",l.tabIndex=0,l.setAttribute("role","button");const a=document.createElement("span");a.className="fb-trig-chevron";const i=document.createElement("span");i.className="fb-trig-action-main";const r=document.createElement("strong"),c=document.createElement("small");c.className="fb-trig-action-summary",i.append(r,c);const s=document.createElement("span");s.className="fb-trig-kind",l.append(a,i,s,Pe(()=>n.remove(),"Remove action"));const d=document.createElement("div");d.className="fb-trig-action-body";const u=K("fb-trig-action-type",pe,e.type||"banner");d.appendChild(G("Action",u,{full:!0})),d.appendChild(xt(e,t));const b=()=>{const m=pe.find(h=>h.value===u.value);r.textContent=m?.label||u.value,s.textContent=an(m),s.classList.toggle("fb-trig-kind--event",m?.kind==="event"),c.textContent=sn(kt(n))},g=m=>{d.hidden=!m,n.classList.toggle("is-open",m),l.setAttribute("aria-expanded",String(m)),q(a,m?"chevron-down":"chevron-right",12)};return l.addEventListener("click",()=>g(d.hidden)),l.addEventListener("keydown",m=>{m.target!==l||m.key!=="Enter"&&m.key!==" "||(m.preventDefault(),g(d.hidden))}),u.addEventListener("change",()=>{const m=xt({type:u.value},t);d.replaceChild(m,d.querySelector(".fb-trig-params")),b(),window.I?.scan?.()}),d.addEventListener("input",b),d.addEventListener("change",b),n.append(l,d),g(o),b(),n}function Ct(e,t,o){const n=document.createElement("section");n.className=`fb-trig-sec fb-trig-sec--${e}`;const l=document.createElement("div");l.className="fb-trig-sec-head";const a=document.createElement("span");if(a.className="fb-trig-sec-title",a.textContent=t,l.appendChild(a),o){const i=document.createElement("span");i.className="fb-trig-sec-hint",i.textContent=o,l.appendChild(i)}return n.appendChild(l),n}function je(e,t){const o=document.createElement("button");return o.type="button",o.className="btn btn-xs btn-ghost fb-trig-add",ce(o,"plus",e,12),o.addEventListener("click",t),o}function Et(e,t,o,n){const a=Ct(e,t,e==="then"?"What happens while the answers match.":"What happens while they do not. Leave empty for nothing.");a.classList.add("fb-trig-branch"),a.dataset.branch=e;const i=document.createElement("div");return i.className="fb-trig-action-list",(o||[]).forEach(r=>i.appendChild(_e(r,n))),a.appendChild(i),a.appendChild(je("Add action",()=>{i.appendChild(_e({type:"banner"},n,{open:!0})),window.I?.scan?.()})),a}function wt(e,t,o){const n=yt(t,!0),l=document.createElement("div");l.className="fb-trig-card",l.dataset.triggerId=e.id||`trg-${Date.now()}-${Math.random().toString(36).slice(2,7)}`;const a=document.createElement("div");a.className="fb-trig-card-head";const i=document.createElement("span");i.className="fb-trig-card-title",i.textContent=`Trigger ${o+1}`,a.appendChild(i);const r=ue("fb-trig-enabled",e.enabled!==!1,"Enabled","Untick to keep the trigger but switch it off.");if(a.appendChild(r),a.appendChild(Pe(()=>l.remove(),"Remove trigger")),l.appendChild(a),!n.length){const u=document.createElement("p");return u.className="fb-trig-empty",u.textContent="Give this field a name first - a trigger tests an answer, and it needs something to test.",l.appendChild(u),l}const c=Ct("when","When");c.querySelector(".fb-trig-sec-head").appendChild(K("fb-trig-match",[{value:"all",label:"all of these are true"},{value:"any",label:"any of these is true"}],Array.isArray(e.when?.any)?"any":"all"));const s=document.createElement("div");s.className="fb-trig-cond-list";const d=e.when?.all||e.when?.any||[];return(d.length?d:[{}]).forEach(u=>s.appendChild(vt(u,n))),c.appendChild(s),c.appendChild(je("Add condition",()=>{s.appendChild(vt({},n)),window.I?.scan?.()})),l.appendChild(c),l.appendChild(Et("then","Then",e.then,t)),l.appendChild(Et("otherwise","Otherwise",e.otherwise,t)),l}function rn(e,t){const o=Array.isArray(e.triggers)?e.triggers:[],n=document.createElement("div");n.className="fb-field-triggers";const l=document.createElement("div");l.className="fb-trig-panel-head";const a=document.createElement("span");a.className="fb-trig-panel-title",a.textContent=`\u{1F3AF} Triggers${o.length?` (${o.length})`:""}`;const i=document.createElement("button");i.type="button",i.className="btn btn-xs btn-ghost",q(i,o.length?"chevron-down":"chevron-right",12);const r=document.createElement("div");r.className="fb-triggers-body",r.hidden=!o.length,l.addEventListener("click",()=>{r.hidden=!r.hidden,q(i,r.hidden?"chevron-right":"chevron-down",12)});const c=document.createElement("p");c.className="fb-trig-blurb",c.textContent="Do something to the form when the answers meet a condition - show a banner or toast, hide, disable or require other fields, refuse the submit, end the form early, notify the admins, jump to a step, or celebrate.",r.appendChild(c);const s=document.createElement("div");return s.className="fb-trig-list",o.forEach((d,u)=>s.appendChild(wt(d,t,u))),r.appendChild(s),r.appendChild(je("Add trigger",()=>{const d=wt({enabled:!0,then:[]},t,s.children.length);s.appendChild(d),d.querySelector('.fb-trig-branch[data-branch="then"] .fb-trig-action-list')?.appendChild(_e({type:"banner"},t,{open:!0})),window.I?.scan?.()})),l.appendChild(a),l.appendChild(i),n.appendChild(l),n.appendChild(r),n}function kt(e){const t=e.querySelector(".fb-trig-action-type")?.value,o=pe.find(a=>a.value===t);if(!o)return null;const n={type:t},l=a=>e.querySelector(a)?.value?.trim()||"";for(const a of o.params)switch(a){case"message":n.message=l(".fb-trig-p-message");break;case"finishLabel":{const i=l(".fb-trig-p-finish");i&&(n.finishLabel=i);break}case"doneMessage":{const i=l(".fb-trig-p-done");i&&(n.doneMessage=i);break}case"finish":e.querySelector(".fb-trig-p-finish-on")?.checked||(n.finish=!1);break;case"record":e.querySelector(".fb-trig-p-record")?.checked||(n.record=!1);break;case"level":n.level=l(".fb-trig-p-level")||"info";break;case"position":n.position=l(".fb-trig-p-position")||"field-below";break;case"dismissible":n.dismissible=!!e.querySelector(".fb-trig-p-dismissible")?.checked;break;case"target":{const i=l(".fb-trig-p-target")||"rest";n.target=i,i==="listed"&&(n.fields=Array.from(e.querySelectorAll(".fb-trig-p-fields option")).filter(r=>r.selected).map(r=>r.value));break}case"step":{const i=parseInt(l(".fb-trig-p-step"),10);Number.isFinite(i)&&(n.step=i);break}case"url":n.url=l(".fb-trig-p-url");break;case"theme":n.theme=l(".fb-trig-p-theme")||"auto";break;case"intensity":n.intensity=l(".fb-trig-p-intensity")||"medium";break;case"slug":n.slug=l(".fb-trig-p-slug");break;default:break}return o.kind==="event"&&!o.noOnce&&e.querySelector(".fb-trig-p-once")?.checked&&(n.once=!0),n}function cn(e){const t=kt(e);if(!t)return null;const o=pe.find(a=>a.value===t.type),n=t.type,l=["block-submit","end-form","notify"].includes(o.value);return o.params.includes("message")&&!t.message&&!l?(delete t.message,null):(l&&!t.message&&delete t.message,n==="redirect"&&!t.url||n==="run-action"&&!t.slug?null:t)}function dn(e){const o=document.querySelector(`.fb-field-card[data-index="${e}"]`)?.querySelector(".fb-field-triggers");if(!o)return;const n=[];return o.querySelectorAll(".fb-trig-card").forEach(l=>{const a=Array.from(l.querySelectorAll(".fb-trig-cond-row")).map(u=>{const b=u.querySelector(".fb-trig-cond-field")?.value,g=u.querySelector(".fb-trig-cond-op")?.value;if(!b||!g)return null;const m=u.querySelector(".fb-trig-cond-val")?.value??"";return{field:b,operator:g,value:m}}).filter(Boolean);if(!a.length)return;const i=u=>Array.from(l.querySelectorAll(`.fb-trig-branch[data-branch="${u}"] .fb-trig-action-row`)).map(cn).filter(Boolean),r=i("then"),c=i("otherwise");if(!r.length&&!c.length)return;const s=l.querySelector(".fb-trig-match")?.value==="any"?"any":"all",d={id:l.dataset.triggerId,enabled:!!l.querySelector(".fb-trig-enabled")?.checked,when:{[s]:a}};r.length&&(d.then=r),c.length&&(d.otherwise=c),n.push(d)}),n.length?n:void 0}function St(e,t,o){const n=document.createElement("div");return n.className="fb-field-extras",e==="chooser"?(n.appendChild(pn(t,o)),n.appendChild(mn(t.options||[],o))):(Be.has(e)&&n.appendChild(yn(t.options||[],o)),e==="textarea"&&n.appendChild(z([P("Rows",`fb-rows-${o}`,"number",t.formConfig?.rows||4,"Height of textarea")])),(e==="string"||e==="textarea")&&n.appendChild(z([P("Min Length",`fb-minlength-${o}`,"number",t.minLength||"",""),P("Max Length",`fb-maxlength-${o}`,"number",t.maxLength||"","")])),e==="number"&&n.appendChild(z([P("Min",`fb-min-${o}`,"number",t.min??"",""),P("Max",`fb-max-${o}`,"number",t.max??"","")]))),n.children.length?n:null}function Tt(e){const t=document.createElement("div");t.className="fb-chooser-section",t.style.cssText="border:1px solid var(--dm-border); border-radius:6px; margin-top:.5rem; overflow:hidden;";const o=document.createElement("div");o.style.cssText="padding:.4rem .6rem; background:color-mix(in srgb, var(--dm-background) 60%, transparent); font-weight:600; font-size:.82rem; border-bottom:1px solid var(--dm-border);",o.textContent=e,t.appendChild(o);const n=document.createElement("div");return n.className="fb-chooser-section-body",n.style.cssText="padding:.55rem .6rem; display:flex; flex-direction:column; gap:.45rem;",t.appendChild(n),{wrap:t,body:n}}function ke(e,t,o,n,l){const a=document.createElement("div");a.style.flex="1";const i=document.createElement("label");i.htmlFor=e,i.className="form-label",i.textContent=t,i.style.fontSize=".8rem";const r=document.createElement("select");if(r.id=e,r.className="form-input",n.forEach(([c,s])=>{const d=document.createElement("option");d.value=c,d.textContent=s,String(c)===String(o)&&(d.selected=!0),r.appendChild(d)}),a.appendChild(i),a.appendChild(r),l){const c=document.createElement("p");c.className="form-hint text-muted",c.textContent=l,c.style.cssText="font-size:.72rem;margin-top:.2rem;",a.appendChild(c)}return a}function Nt(e,t,o,n){const l=document.createElement("div");l.style.flex="1";const a=document.createElement("label");a.style.cssText="display:inline-flex;align-items:center;gap:.4rem;font-size:.82rem;";const i=document.createElement("input");if(i.id=e,i.type="checkbox",i.checked=!!o,a.appendChild(i),a.appendChild(document.createTextNode(" "+t)),l.appendChild(a),n){const r=document.createElement("p");r.className="form-hint text-muted",r.textContent=n,r.style.cssText="font-size:.72rem;margin-top:.2rem;",l.appendChild(r)}return l}function Ve(e,t,o,n,l){const a=document.createElement("div");a.style.flex="1";const i=document.createElement("label");i.htmlFor=e,i.className="form-label",i.textContent=t,i.style.fontSize=".8rem",a.appendChild(i);const r=document.createElement("div");r.style.cssText="display:flex;gap:.4rem;align-items:stretch;";const c=document.createElement("input");c.id=e,c.type="text",c.className="form-input",c.value=o||"",n&&(c.placeholder=n),c.style.flex="1";const s=document.createElement("input");s.type="color",s.title="Pick a colour",s.style.cssText="width:36px;height:auto;padding:0;border:1px solid var(--dm-border);border-radius:4px;cursor:pointer;";const d=String(c.value).match(/^#[0-9a-fA-F]{3,8}$/);if(s.value=d?c.value:"#000000",s.addEventListener("input",()=>{c.value=s.value,c.dispatchEvent(new Event("input",{bubbles:!0}))}),r.appendChild(c),r.appendChild(s),a.appendChild(r),l){const u=document.createElement("p");u.className="form-hint text-muted",u.textContent=l,u.style.cssText="font-size:.72rem;margin-top:.2rem;",a.appendChild(u)}return a}function pn(e,t){const o=document.createElement("div");o.style.cssText="margin-top:.5rem; display:flex; flex-direction:column; gap:.4rem;";const n=Tt("Layout");n.body.appendChild(z([ke(`fb-chooser-variant-${t}`,"Variant",e.variant||"card",[["card","Card - rich tiles"],["chip","Chip - compact pills"]],"Card supports description and grid columns; chips wrap."),Nt(`fb-chooser-multiple-${t}`,"Multi-select",!!e.multiple,"Off = single (radio); on = multi (checkbox).")])),n.body.appendChild(z([ke(`fb-chooser-density-${t}`,"Density",e.density||"comfortable",[["comfortable","Comfortable"],["compact","Compact"]],"Compact strips description (card variant only)."),P("Columns",`fb-chooser-columns-${t}`,"number",e.columns||3,"Card grid (1-6). Ignored for chips.")])),o.appendChild(n.wrap);const l=Tt("Visual");return l.body.appendChild(z([Ve(`fb-chooser-accent-${t}`,"Accent",e.accent||"","primary / success / #ec4899","Selected highlight colour - semantic name or any CSS colour."),ke(`fb-chooser-accent-style-${t}`,"Accent style",e.accentStyle||"border",[["border","Border (default)"],["solid","Solid"],["glow","Glow"],["overlay","Overlay"],["underline","Underline"]],"Visual treatment of the selected state.")])),l.body.appendChild(z([Nt(`fb-chooser-glow-${t}`,"Glow on selected",!!e.glow,"Soft outer glow."),Ve(`fb-chooser-glow-colour-${t}`,"Glow colour",e.glowColour||"","defaults to accent","Optional; semantic name or CSS colour.")])),l.body.appendChild(z([ke(`fb-chooser-shadow-${t}`,"Shadow",e.shadow||"none",[["none","None"],["sm","Small"],["md","Medium"],["lg","Large"],["xl","Extra Large"]],"Drop shadow on every option."),Ve(`fb-chooser-shadow-colour-${t}`,"Shadow colour",e.shadowColour||"","rgba(0,0,0,0.1)","Optional shadow tint.")])),o.appendChild(l.wrap),o}function un(e,t,o,n){const l=document.createElement("div");l.className="fb-chooser-option-row",l.dataset.optIdx=String(o),l.style.cssText="border:1px solid var(--dm-border); border-radius:4px; padding:.5rem; background:var(--dm-background-alt); display:flex; flex-direction:column; gap:.35rem;";const a=document.createElement("div");a.style.cssText="display:flex; gap:.4rem; align-items:center;";const i=document.createElement("div");i.style.cssText="display:flex; flex-direction:column; gap:1px;";const r=document.createElement("button");r.type="button",r.className="btn btn-xs btn-ghost",r.title="Move up",q(r,"arrow-up"),r.addEventListener("click",I=>{I.preventDefault(),Lt(t,o,-1,n)});const c=document.createElement("button");c.type="button",c.className="btn btn-xs btn-ghost",c.title="Move down",q(c,"arrow-down"),c.addEventListener("click",I=>{I.preventDefault(),Lt(t,o,1,n)}),i.appendChild(r),i.appendChild(c),a.appendChild(i);const s=document.createElement("input");s.type="text",s.className="form-input fb-chooser-opt-value",s.placeholder="value",s.value=e.value||"",s.style.flex="1",a.appendChild(s);const d=document.createElement("input");d.type="text",d.className="form-input fb-chooser-opt-label",d.placeholder="label (visible to users)",d.value=e.label||"",d.style.flex="2",a.appendChild(d);const u=document.createElement("button");u.type="button",u.className="btn btn-xs btn-ghost",u.style.cssText="line-height:1;opacity:.6;",u.title="Remove option",q(u,"x"),u.addEventListener("click",I=>{I.preventDefault(),bn(t,o,n)}),a.appendChild(u),l.appendChild(a);const b=document.createElement("div");b.style.cssText="display:flex; gap:.4rem;";const g=zt("icon name (optional)",e.icon||"");g.input.classList.add("fb-chooser-opt-icon"),g.el.style.flex="1",b.appendChild(g.el);const m=document.createElement("input");m.type="text",m.className="form-input fb-chooser-opt-description",m.placeholder="description (card + comfortable only)",m.value=e.description||"",m.style.flex="2",b.appendChild(m),l.appendChild(b);const h=document.createElement("div");h.style.cssText="display:flex; gap:.4rem;";const w=document.createElement("input");w.type="text",w.className="form-input fb-chooser-opt-tooltip",w.placeholder="tooltip (hover hint)",w.value=e.tooltip||"",w.style.flex="2",h.appendChild(w);const f=document.createElement("input");f.type="text",f.className="form-input fb-chooser-opt-badge-text",f.placeholder="badge text",f.value=e.badge?.text||"",f.style.flex="1",h.appendChild(f);const x=document.createElement("select");x.className="form-input fb-chooser-opt-badge-type",x.style.flex="1",[["","no badge"],["primary","primary"],["success","success"],["info","info"],["warning","warning"],["danger","danger"]].forEach(([I,X])=>{const U=document.createElement("option");U.value=I,U.textContent=X,(e.badge?.type||"")===I&&(U.selected=!0),x.appendChild(U)}),h.appendChild(x),l.appendChild(h);const $=document.createElement("div");$.style.cssText="display:flex; gap:1rem; font-size:.8rem;";const A=document.createElement("label");A.style.cssText="display:inline-flex;align-items:center;gap:.3rem;";const H=document.createElement("input");H.type="checkbox",H.className="fb-chooser-opt-recommended",H.checked=!!e.recommended,A.appendChild(H),A.appendChild(document.createTextNode(" Recommended")),$.appendChild(A);const _=document.createElement("label");_.style.cssText="display:inline-flex;align-items:center;gap:.3rem;";const j=document.createElement("input");return j.type="checkbox",j.className="fb-chooser-opt-disabled",j.checked=!!e.disabled,_.appendChild(j),_.appendChild(document.createTextNode(" Disabled")),$.appendChild(_),l.appendChild($),l}function mn(e,t){const o=document.createElement("div");o.style.cssText="margin-top:.5rem;";const n=document.createElement("div");n.style.cssText="display:flex; align-items:center; justify-content:space-between; margin-bottom:.4rem;";const l=document.createElement("p");l.textContent="Options",l.style.cssText="font-size:.85rem;font-weight:600;margin:0;",n.appendChild(l);const a=document.createElement("button");a.type="button",a.className="btn btn-xs btn-ghost",ce(a,"plus","Add option"),n.appendChild(a),o.appendChild(n);const i=document.createElement("div");i.className="fb-chooser-options-list",i.id=`fb-chooser-options-${t}`,i.style.cssText="display:flex; flex-direction:column; gap:.4rem;",o.appendChild(i);const r=()=>{i.replaceChildren();const c=fn(t);(c.length?c:e||[]).forEach((d,u)=>{i.appendChild(un(d,t,u,r))})};return a.addEventListener("click",c=>{c.preventDefault(),hn(t,r)}),r(),o}function fn(e){const t=C[e];return!t||!Array.isArray(t.options)?[]:t.options}function Ge(e){return C[e]?(Array.isArray(C[e].options)||(C[e].options=[]),C[e].options):[]}function hn(e,t){Se(e),Ge(e).push({value:"new",label:"New option"}),t()}function bn(e,t,o){Se(e),Ge(e).splice(t,1),o()}function Lt(e,t,o,n){Se(e);const l=Ge(e),a=t+o;if(a<0||a>=l.length)return;const[i]=l.splice(t,1);l.splice(a,0,i),n()}function Se(e){const t=document.getElementById(`fb-chooser-options-${e}`);if(!t)return;const o=t.querySelectorAll(".fb-chooser-option-row"),n=[];o.forEach(l=>{const a={value:l.querySelector(".fb-chooser-opt-value")?.value.trim()||"",label:l.querySelector(".fb-chooser-opt-label")?.value.trim()||""},i=l.querySelector(".fb-chooser-opt-icon")?.value.trim();i&&(a.icon=i);const r=l.querySelector(".fb-chooser-opt-description")?.value.trim();r&&(a.description=r);const c=l.querySelector(".fb-chooser-opt-tooltip")?.value.trim();c&&(a.tooltip=c);const s=l.querySelector(".fb-chooser-opt-badge-text")?.value.trim(),d=l.querySelector(".fb-chooser-opt-badge-type")?.value;(s||d)&&(a.badge={},s&&(a.badge.text=s),d&&(a.badge.type=d)),l.querySelector(".fb-chooser-opt-recommended")?.checked&&(a.recommended=!0),l.querySelector(".fb-chooser-opt-disabled")?.checked&&(a.disabled=!0),n.push(a)}),C[e]&&(C[e].options=n)}function z(e){const t=document.createElement("div");return t.style.cssText="display:flex;gap:.85rem;margin-bottom:.75rem;",e.forEach(o=>{o&&t.appendChild(o)}),t}function P(e,t,o,n,l){const a=document.createElement("div");a.style.flex="1";const i=document.createElement("label");i.htmlFor=t,i.className="form-label",i.textContent=e,i.style.fontSize=".8rem";const r=document.createElement("input");if(r.id=t,r.type=o||"text",r.className="form-input",r.value=n??"",a.appendChild(i),a.appendChild(r),l){const c=document.createElement("p");c.className="form-hint text-muted",c.textContent=l,c.style.cssText="font-size:.73rem;margin-top:.35rem;",a.appendChild(c)}return a}function gn(e,t,o,n){const l=document.createElement("div");l.style.flex="1";const a=document.createElement("label");a.htmlFor=t,a.className="form-label",a.textContent=e,a.style.fontSize=".8rem";const i=document.createElement("select");return i.id=t,i.className="form-select",o.forEach(r=>{const c=document.createElement("option");c.value=r.value,c.textContent=r.label,r.value===n&&(c.selected=!0),i.appendChild(c)}),l.appendChild(a),l.appendChild(i),l}function qt(e,t,o){const n=document.createElement("div");n.style.cssText="flex:0;min-width:80px;display:flex;flex-direction:column;justify-content:flex-end;";const l=document.createElement("label");l.style.cssText="display:flex;align-items:center;gap:.4rem;cursor:pointer;font-size:.8rem;white-space:nowrap;";const a=document.createElement("input");return a.id=t,a.type="checkbox",a.checked=o,l.appendChild(a),l.appendChild(document.createTextNode(e)),n.appendChild(l),n}function yn(e,t){const o=document.createElement("div");o.style.cssText="margin-top:.4rem;";const n=document.createElement("p");n.textContent="Options (one per line: value or value:Label)",n.style.cssText="font-size:.8rem;font-weight:600;margin-bottom:.3rem;";const l=document.createElement("textarea");return l.id=`fb-options-${t}`,l.className="form-input",l.rows=4,l.placeholder=`yes:Yes
|
|
6
6
|
no:No
|
|
7
|
-
maybe:Maybe`,l.value=(e||[]).map(a=>{const i=typeof a=="string"?a:a.value??"",
|
|
8
|
-
`),l.style.fontFamily="monospace",o.appendChild(t),o.appendChild(l),o}function Ce(e){return parseInt(e,10)===3?3:2}function Ee(e){const n=e.find("#field-project").val()||"";return B(),{title:e.find("#field-title").val().trim(),slug:e.find("#field-slug").val().trim(),description:e.find("#field-description").val().trim(),...e.find("#field-bundled").is(":checked")?{bundled:!0}:{},meta:{...me||{},project:n||null},fields:C,settings:{submitText:e.find("#setting-submit-text").val().trim()||"Submit",successMessage:e.find("#setting-success-message").val().trim()||"Thank you.",layout:e.find("#setting-layout").val()||"grid",columns:Ce(e.find("#setting-columns").val()),submitSpan:e.find("#setting-submit-span").val()||"",honeypot:e.find("#setting-honeypot").prop("checked"),rateLimitPerMinute:parseInt(e.find("#setting-rate-limit").val(),10)||3,successRedirect:e.find("#setting-success-redirect").val().trim()||null,actionSlug:e.find("#action-cms-slug").val()||null},actions:{email:{enabled:e.find("#action-email-enabled").prop("checked"),recipients:e.find("#action-email-recipients").val().trim(),subjectPrefix:e.find("#action-email-subject-prefix").val().trim()},webhook:{enabled:e.find("#action-webhook-enabled").prop("checked"),url:e.find("#action-webhook-url").val().trim(),method:e.find("#action-webhook-method").val()},...pe!==null&&{collection:pe}}}}function xt(e,n){const o={};return e.forEach(t=>{if(t.type==="page-break"||t.type==="spacer")return;const l={...t.formConfig||{}};l.span==="full"&&n&&(l.span=n);const a=t.type==="chooser"||!!(t.variant&&["select","radio","checkbox-group"].includes(t.type)),s={type:t.type==="checkbox"?"boolean":t.type==="date"||t.type==="icon"||t.type==="image"?"string":a?"chooser":t.type,label:t.label,required:t.required,options:t.options,formConfig:{...t.placeholder&&{placeholder:t.placeholder},...t.helper&&{helperText:t.helper},...t.tooltip&&{tooltip:t.tooltip},...l}};a&&(t.variant&&(s.variant=t.variant),(t.multiple||t.type==="checkbox-group")&&(s.multiple=!0),t.density&&(s.density=t.density),t.columns&&(s.columns=t.columns),t.accent&&(s.accent=t.accent),t.accentStyle&&(s.accentStyle=t.accentStyle),t.glow&&(s.glow=!0),t.glowColour&&(s.glowColour=t.glowColour),t.shadow&&(s.shadow=t.shadow),t.shadowColour&&(s.shadowColour=t.shadowColour)),o[t.name]=s}),o}function Ct(e,n){const o=typeof e=="string"?document.querySelector(e):e;o&&(n||[]).forEach(t=>{if(t.type!=="date"||!t.name)return;const l=o.querySelector(`[name="${t.name}"]`);l&&l.type!=="date"&&(l.type="date")})}function Et(e,n){const o=e?.querySelector?.(".dm-plugin-banner-name .dm-plugin-banner-sep");if(o){for(;o.nextSibling;)o.nextSibling.remove();o.after(document.createTextNode(String(n||"")))}}const dn=e=>String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");let G=null,wt=0,kt=!1;const we=e=>String(e||"").split("?")[0].replace(/\/$/,"");function pn(){kt||!window.R?.use||(kt=!0,R.use((e,n,o)=>!G||!Ze(n?.path,e?.path)||G.path!==we(n?.path)||(G.flush(),!G.dirty())?o():E.confirm("You have unsaved changes to this form. Leave anyway? They are kept as a draft for your next visit to it.").then(t=>{t?o():history.replaceState(null,"",`#${n.path}`)})),M.subscribe("router:afterChange",({to:e,from:n}={})=>{if(G&&G.path===we(n?.path)&&Ze(n?.path,e?.path)){const o=G;G=null,o.dispose()}}))}export const formEditorView={templateUrl:"/admin/js/templates/form-editor.html",async onMount(e){if(pn(),G){const d=G;G=null,d.dispose()}const n=we(location.hash.replace(/^#/,"")),o=++wt,t=()=>o!==wt||!e.get(0)?.isConnected||we(location.hash.replace(/^#/,""))!==n;C=[],T=null,pe=null;const l=window.location.hash.match(/\/forms\/edit\/([^/?#]+)/);T=l?l[1]:null;let a=null;const i=E.loader(e.get(0),{type:"dots"});if(T)try{if(a=await oe(`/forms/${T}`),t()){i.destroy();return}C=a.fields||[],pe=a.actions?.collection??null}catch{if(t()){i.destroy();return}E.toast("Could not load form.",{type:"error"})}me={};try{const d=await oe("/projects").catch(()=>[]);if(t()){i.destroy();return}const g=e.find("#field-project").get(0);g&&(Array.isArray(d)?d:[]).forEach(b=>{const k=document.createElement("option");k.value=b.slug,k.textContent=b.name||b.slug,g.appendChild(k)})}catch{}if(i.destroy(),Et(e.get(0),a?a.title||a.slug:"New form"),T||e.find("#field-title").get(0).addEventListener("input",function(){e.find("#field-slug").val(lt(this.value))}),E.tabs(e.find("#editor-tabs").get(0)),a){e.find("#field-title").val(a.title),e.find("#field-slug").val(a.slug),e.find("#field-description").val(a.description||""),e.find("#field-bundled").prop("checked",!!a.bundled),me=a.meta||{},e.find("#field-project").val(a.meta?.project||"");const d=a.settings||{};e.find("#setting-submit-text").val(d.submitText||"Submit"),e.find("#setting-success-message").val(d.successMessage||""),e.find("#setting-layout").val(d.layout||"grid"),e.find("#setting-columns").val(Ce(d.columns)),e.find("#setting-submit-span").val(d.submitSpan||""),e.find("#columns-group").get(0).style.display=(d.layout||"grid")==="grid"?"":"none",e.find("#setting-honeypot").prop("checked",d.honeypot!==!1),e.find("#setting-rate-limit").val(d.rateLimitPerMinute||3),e.find("#setting-success-redirect").val(d.successRedirect||"");const g=a.actions?.email||{};e.find("#action-email-enabled").prop("checked",g.enabled||!1),e.find("#action-email-recipients").val(g.recipients||""),e.find("#action-email-subject-prefix").val(g.subjectPrefix||"");const b=a.actions?.webhook||{};e.find("#action-webhook-enabled").prop("checked",b.enabled||!1),e.find("#action-webhook-url").val(b.url||""),e.find("#action-webhook-method").val(b.method||"POST")}const s=a?.settings?.actionSlug||"";try{const d=await oe("/actions").catch(()=>[]);if(t())return;const g=e.find("#action-cms-slug").get(0);if($e=Array.isArray(d)?d:[],(Array.isArray(d)?d:[]).forEach(b=>{const k=document.createElement("option");k.value=b.slug,k.textContent=b.title||b.slug,b.slug===s&&(k.selected=!0),g.appendChild(k)}),!d.length){const b=document.createElement("option");b.value="",b.textContent="No actions available",b.disabled=!0,g.appendChild(b)}}catch{}const c=d=>{e.find("#columns-group").get(0).style.display=d?"":"none",document.querySelectorAll(".fb-grid-row").forEach(g=>{g.style.display=d?"flex":"none"})};e.find("#setting-layout").get(0)?.addEventListener("change",function(){c(this.value==="grid")}),c(e.find("#setting-layout").val()==="grid"),J(e);const r=e.find("#add-element-menu").get(0);e.find("#add-element-btn").get(0).addEventListener("click",d=>{d.stopPropagation(),r.style.display=r.style.display==="none"?"":"none"}),ne&&document.removeEventListener("click",ne),ne=()=>{r&&(r.style.display="none")},document.addEventListener("click",ne),e.find("#add-field-btn").get(0).addEventListener("click",()=>{r&&(r.style.display="none"),B();const d=C.length;C.push({name:`field_${d+1}`,type:"string",label:"New Field",required:!1,placeholder:""}),J(e);const g=e.find("#fields-list").get(0)?.lastElementChild;if(g){const b=g.querySelector(".fb-field-body");b&&(b.style.display="")}}),e.find("#add-spacer-btn").get(0).addEventListener("click",()=>{r&&(r.style.display="none"),B(),C.push({type:"spacer"}),J(e)}),e.find("#add-page-break-btn").get(0).addEventListener("click",()=>{r&&(r.style.display="none"),B();const d=C.filter(g=>g.type==="page-break").length+2;C.push({type:"page-break",label:`Step ${d}`,description:""}),J(e)}),ue=()=>{const d=Ee(e),g=e.find("#preview-container").get(0);if(!g)return;const b=e.find("#preview-test-result").get(0),k=e.find("#preview-test-badge").get(0);b&&(b.style.display="none",b.textContent=""),k&&(k.style.display=T?"":"none"),e.find("#preview-card").get(0).style.display="",g.textContent="";const H=document.createElement("div");H.id="fb-preview-form",g.appendChild(H);const U=T?async A=>{b&&(b.style.display="none",b.textContent="");try{const I=await fetch(`/api/forms/submit/${T}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)}),ee=await I.json();if(!I.ok)throw new Error(ee.error||"Submission failed.");b&&(b.textContent=ee.message||d.settings?.successMessage||"Submitted successfully.",b.style.cssText="display:block;margin-top:.75rem;padding:.6rem .9rem;border-radius:6px;font-size:.9rem;background:color-mix(in srgb, var(--dm-success) 12%, transparent);color:var(--dm-success);"),E.toast("Test submission stored.",{type:"success"})}catch(I){b&&(b.textContent=I.message,b.style.cssText="display:block;margin-top:.75rem;padding:.6rem .9rem;border-radius:6px;font-size:.9rem;background:color-mix(in srgb, var(--dm-danger) 12%, transparent);color:var(--dm-danger);"),E.toast(I.message,{type:"error"})}return!1}:()=>!1,ce=d.fields.some(A=>A.type==="page-break");if(typeof F<"u"){const A=Ce(d.settings?.columns),I=d.settings?.layout||"grid";if(ce&&F.wizard){const ee=$t(d.fields,d.title),de=ee.map(te=>({title:te.title,description:te.description,fields:xt(te.fields,A)}));let z=0,Q=null,Se=null;const Je=te=>{const Ke=(ee[z]||{}).fields||[];Ct("#fb-preview-form",Ke),Ye(H,Ke),te&&window.FormLogicEngine&&ot(d.fields)&&(Q?.destroy?.(),Q=new window.FormLogicEngine.FormLogicRuntime({fields:d.fields},H,{baseValues:Se?.getStepData?Se.getStepData():{}}),Q.init())};Se=F.wizard("#fb-preview-form",{schema:{steps:de},layout:I,columns:A,finishText:d.settings?.submitText||"Finish",onStepChange:te=>{z=te,queueMicrotask(()=>Je(!0))},onSubmit:U}),Je(!1)}else if(F.render){const ee=xt(d.fields,A),de={};if(d.fields.forEach(z=>{if(!(!z.name||z.type==="page-break"||z.type==="spacer")&&(z.type==="select"||z.type==="multiselect")&&z.required){const Q=(z.options||[])[0];Q&&(de[z.name]=typeof Q=="object"?Q.value:Q)}}),F.render("#fb-preview-form",ee,de,{submitText:d.settings?.submitText||"Submit",layout:I,columns:A,onSubmit:U}),I==="grid"&&d.settings?.submitSpan==="full"){const z=document.querySelector("#fb-preview-form .form-buttons");z&&z.classList.add("col-span-full")}Ct("#fb-preview-form",d.fields),Ye(H,d.fields)}window.FormLogicEngine&&ot(d.fields)&&requestAnimationFrame(()=>{new window.FormLogicEngine.FormLogicRuntime({fields:d.fields},H).init()})}else{const A=document.createElement("p");A.textContent=`${d.fields.filter(I=>I.type!=="page-break").length} field(s): ${d.fields.filter(I=>I.type!=="page-break").map(I=>I.label).join(", ")}`,A.style.cssText="color:var(--dm-text-muted);font-style:italic;",H.appendChild(A)}},ue();const p=e.find("#editor-tabs").get(0),m=e.find("#preview-card").get(0),h=d=>{m&&m.contains(d.target)||Ie()};p&&(p.addEventListener("input",h),p.addEventListener("change",h));const y=e.get(0),v=[],f=d=>(v.push(d),d);let w=!1;const u=M.observable(!1),x=M.observable(!1);let N=T,q=Ee(e),V=Le(q),_=q;const j=()=>{w||!y.isConnected||(_=Ee(e),u.value=Le(_)!==V)};let $=null;Fe=()=>{clearTimeout($),$=setTimeout(j,150)},f(()=>{clearTimeout($),Fe=null,se=null});const Y=d=>{const g=d.settings||{};e.find("#field-title").val(d.title||""),e.find("#field-slug").val(d.slug||""),e.find("#field-description").val(d.description||""),e.find("#field-bundled").prop("checked",!!d.bundled),me={...d.meta||{}},e.find("#field-project").val(d.meta?.project||""),e.find("#setting-submit-text").val(g.submitText||"Submit"),e.find("#setting-success-message").val(g.successMessage||""),e.find("#setting-layout").val(g.layout||"grid"),e.find("#setting-columns").val(Ce(g.columns)),e.find("#setting-submit-span").val(g.submitSpan||""),e.find("#setting-honeypot").prop("checked",g.honeypot!==!1),e.find("#setting-rate-limit").val(g.rateLimitPerMinute||3),e.find("#setting-success-redirect").val(g.successRedirect||""),e.find("#action-cms-slug").val(g.actionSlug||"");const b=d.actions?.email||{};e.find("#action-email-enabled").prop("checked",!!b.enabled),e.find("#action-email-recipients").val(b.recipients||""),e.find("#action-email-subject-prefix").val(b.subjectPrefix||"");const k=d.actions?.webhook||{};e.find("#action-webhook-enabled").prop("checked",!!k.enabled),e.find("#action-webhook-url").val(k.url||""),e.find("#action-webhook-method").val(k.method||"POST"),C=JSON.parse(JSON.stringify(d.fields||[])),c((g.layout||"grid")==="grid"),J(e)};async function W(){if(x.peek()||w)return;const d=Ee(e);if(!d.title){E.toast("Please enter a form title (Form Details).",{type:"error"});return}x.value=!0;const g=T;try{T?(await oe(`/forms/${T}`,{method:"PUT",body:JSON.stringify(d)}),E.toast("Form saved.",{type:"success"})):(T=(await oe("/forms",{method:"POST",body:JSON.stringify(d)})).slug,E.toast("Form created.",{type:"success"})),N=T,q=d,V=Le(d),_=d,u.value=!1;for(const b of new Set([ie(g),ie(T)]))try{S.remove?S.remove(b):S.set(b,null)}catch{}Et(y,d.title),Ft("#/forms"),g||R.navigate(`/forms/edit/${T}`)}catch(b){g||(T=null),E.toast(b.message||"Failed to save form.",{type:"error"})}finally{x.value=!1}}async function St(){u.peek()&&(!await E.confirm("Discard the changes you have not saved?")||w||(Y(q),j(),Ge()))}const Me=y.querySelector(".fex-bar");if(Me){const d=M.applyBindings({dirty:u,saving:x},Me,{methods:{save:W,discard:St}});f(()=>d.dispose())}f(At(y,{position:"bottom"})),Te(e,{id:"form-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>W()}),Te(e,{id:"form-editor-back",icon:"arrow-left",title:"All forms",onClick:()=>{location.hash="#/forms"}}),T&&Te(e,{id:"form-editor-subs",icon:"list",title:"Submissions",onClick:()=>{location.hash=`#/forms/${encodeURIComponent(T)}/submissions`}});const Pe=d=>{t()||!(d.ctrlKey||d.metaKey)||String(d.key).toLowerCase()!=="s"||(d.preventDefault(),d.stopImmediatePropagation(),W())};document.addEventListener("keydown",Pe,!0),f(()=>document.removeEventListener("keydown",Pe,!0));const X=e.find("#fields-list").get(0),Tt=d=>d?.closest?.(".fb-field-card"),_e=d=>Number(d?.dataset.index),je=d=>d?.querySelector(":scope > .fb-field-body"),Ve=d=>{const g=je(d);g&&(g.style.display=g.style.display==="none"?"":"none")},re=(d,g)=>{C=d,J(e),g!=null&&X?.querySelectorAll(".fb-field-card")[g]?.focus()},Nt=async d=>{try{await navigator.clipboard.writeText(d),E.toast(`Copied "${d}".`,{type:"success"})}catch{E.toast(`Copy failed - the name is ${d}.`,{type:"info"})}},Lt=d=>{const g=Tt(d),b=_e(g);B();const k=C[b];if(!k)return[];const H=k.type!=="spacer"&&k.type!=="page-break",U=je(g),ce=U&&U.style.display!=="none";return[{header:Ne(k)},...U?[{label:ce?"Close":"Edit",icon:ce?"chevron-up":"edit",action:()=>Ve(g)}]:[],...H?[{label:"Logic & triggers",icon:"zap",action:()=>{U&&(U.style.display=""),(U?.querySelector(".fb-field-logic")||U)?.scrollIntoView({block:"center",behavior:"smooth"})}}]:[],{label:"Duplicate",icon:"copy",action:()=>{B(),re(zt(C,b),b+1)}},{type:"divider"},{label:"Move up",icon:"arrow-up",disabled:b===0,action:()=>{B(),re(et(C,b,-1),b-1)}},{label:"Move down",icon:"arrow-down",disabled:b>=C.length-1,action:()=>{B(),re(et(C,b,1),b+1)}},...H&&k.name?[{label:"Copy field name",icon:"clipboard",action:()=>Nt(k.name)}]:[],{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:async()=>{if(k.type!=="spacer"&&!await E.confirm(`Remove "${dn(Ne(k))}"?`))return;B();const A=[...C];A.splice(b,1),re(A,Math.min(b,A.length-1))}}]};let He=null;if(X&&E.contextMenu&&(He=E.contextMenu(X,{cursor:"glyph",match:".fb-field-card > :first-child",inherit:!1,density:"compact",items:d=>Lt(d)}),f(()=>He?.destroy?.())),se=d=>{for(const g of d.querySelectorAll(".fb-field-card")){g.tabIndex=0;const b=g.firstElementChild;if(!b||b.querySelector(".fex-kebab"))continue;const k=document.createElement("button");k.type="button",k.className="fex-kebab",k.textContent="\u22EE",k.title="Actions",B(),k.setAttribute("aria-label",`Actions for ${Ne(C[_e(g)])}`),k.addEventListener("click",H=>{H.stopPropagation(),Qe(k)}),b.appendChild(k)}},X){se(X);const d=g=>{const b=g.target?.classList?.contains("fb-field-card")?g.target:null;b&&(g.key==="F10"&&g.shiftKey?(g.preventDefault(),Qe(b.firstElementChild)):g.key==="Enter"&&(g.preventDefault(),Ve(b)))};X.addEventListener("keydown",d),f(()=>X.removeEventListener("keydown",d))}const Ge=()=>{try{const d=ie(N);S.remove?S.remove(d):S.set(d,null)}catch{}},We=d=>{if(!u.peek()||!d){Ge();return}try{S.set(ie(N),{data:It(d),base:Xe(V),at:new Date().toISOString()})}catch{}},Ue=d=>{j(),u.peek()&&(We(_),d.preventDefault(),d.returnValue="")};window.addEventListener("beforeunload",Ue),f(()=>window.removeEventListener("beforeunload",Ue)),f(()=>{ne&&(document.removeEventListener("click",ne),ne=null)}),G={path:n,dirty:()=>u.peek(),flush:()=>{clearTimeout($),j()},dispose(){w||(We(_),w=!0,v.splice(0).reverse().forEach(d=>{try{d?.()}catch{}}))}};const ke=ie(T);let Z=null;try{Z=S.get(ke)}catch{}if(Z?.data){try{S.remove?S.remove(ke):S.set(ke,null)}catch{}const d=Z.base&&Z.base!==Xe(V),g=Z.at?` (${D(Z.at).format("D MMM HH:mm")})`:"";await E.confirm(`You left unsaved changes to this form${g}.${d?" The saved form has changed since then.":""} Pick up where you left off?`)&&!w&&(Y(Bt(Z.data,q)),j())}}};
|
|
7
|
+
maybe:Maybe`,l.value=(e||[]).map(a=>{const i=typeof a=="string"?a:a.value??"",r=typeof a=="string"?a:a.label??i;return i===r?i:`${i}:${r}`}).join(`
|
|
8
|
+
`),l.style.fontFamily="monospace",o.appendChild(n),o.appendChild(l),o}function Te(e){return parseInt(e,10)===3?3:2}function Ne(e){const t=e.find("#field-project").val()||"";return O(),{title:e.find("#field-title").val().trim(),slug:e.find("#field-slug").val().trim(),description:e.find("#field-description").val().trim(),...e.find("#field-bundled").is(":checked")?{bundled:!0}:{},meta:{...ye||{},project:t||null},fields:C,settings:{submitText:e.find("#setting-submit-text").val().trim()||"Submit",successMessage:e.find("#setting-success-message").val().trim()||"Thank you.",layout:e.find("#setting-layout").val()||"grid",columns:Te(e.find("#setting-columns").val()),submitSpan:e.find("#setting-submit-span").val()||"",honeypot:e.find("#setting-honeypot").prop("checked"),rateLimitPerMinute:parseInt(e.find("#setting-rate-limit").val(),10)||3,successRedirect:e.find("#setting-success-redirect").val().trim()||null,actionSlug:e.find("#action-cms-slug").val()||null},actions:{email:{enabled:e.find("#action-email-enabled").prop("checked"),recipients:e.find("#action-email-recipients").val().trim(),subjectPrefix:e.find("#action-email-subject-prefix").val().trim()},webhook:{enabled:e.find("#action-webhook-enabled").prop("checked"),url:e.find("#action-webhook-url").val().trim(),method:e.find("#action-webhook-method").val()},...ge!==null&&{collection:ge}}}}function $t(e,t){const o={};return e.forEach(n=>{if(n.type==="page-break"||n.type==="spacer")return;const l={...n.formConfig||{}};l.span==="full"&&t&&(l.span=t);const a=n.type==="chooser"||!!(n.variant&&["select","radio","checkbox-group"].includes(n.type)),r={type:n.type==="checkbox"?"boolean":n.type==="date"||n.type==="icon"||n.type==="image"?"string":a?"chooser":n.type,label:n.label,required:n.required,options:n.options,formConfig:{...n.placeholder&&{placeholder:n.placeholder},...n.helper&&{helperText:n.helper},...n.tooltip&&{tooltip:n.tooltip},...l}};a&&(n.variant&&(r.variant=n.variant),(n.multiple||n.type==="checkbox-group")&&(r.multiple=!0),n.density&&(r.density=n.density),n.columns&&(r.columns=n.columns),n.accent&&(r.accent=n.accent),n.accentStyle&&(r.accentStyle=n.accentStyle),n.glow&&(r.glow=!0),n.glowColour&&(r.glowColour=n.glowColour),n.shadow&&(r.shadow=n.shadow),n.shadowColour&&(r.shadowColour=n.shadowColour)),o[n.name]=r}),o}function At(e,t){const o=typeof e=="string"?document.querySelector(e):e;o&&(t||[]).forEach(n=>{if(n.type!=="date"||!n.name)return;const l=o.querySelector(`[name="${n.name}"]`);l&&l.type!=="date"&&(l.type="date")})}function Ft(e,t){const o=e?.querySelector?.(".dm-plugin-banner-name .dm-plugin-banner-sep");if(o){for(;o.nextSibling;)o.nextSibling.remove();o.after(document.createTextNode(String(t||"")))}}const vn=e=>String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");let W=null,It=0,Bt=!1;const Le=e=>String(e||"").split("?")[0].replace(/\/$/,"");function xn(){Bt||!window.R?.use||(Bt=!0,R.use((e,t,o)=>!W||!ot(t?.path,e?.path)||W.path!==Le(t?.path)||(W.flush(),!W.dirty())?o():E.confirm("You have unsaved changes to this form. Leave anyway? They are kept as a draft for your next visit to it.").then(n=>{n?o():history.replaceState(null,"",`#${t.path}`)})),M.subscribe("router:afterChange",({to:e,from:t}={})=>{if(W&&W.path===Le(t?.path)&&ot(t?.path,e?.path)){const o=W;W=null,o.dispose()}}))}export const formEditorView={templateUrl:"/admin/js/templates/form-editor.html",async onMount(e){if(xn(),W){const p=W;W=null,p.dispose()}const t=Le(location.hash.replace(/^#/,"")),o=++It,n=()=>o!==It||!e.get(0)?.isConnected||Le(location.hash.replace(/^#/,""))!==t;C=[],N=null,ge=null;const l=window.location.hash.match(/\/forms\/edit\/([^/?#]+)/);N=l?l[1]:null;let a=null;const i=E.loader(e.get(0),{type:"dots"});if(N)try{if(a=await se(`/forms/${N}`),n()){i.destroy();return}C=a.fields||[],ge=a.actions?.collection??null}catch{if(n()){i.destroy();return}E.toast("Could not load form.",{type:"error"})}ye={};try{const p=await se("/projects").catch(()=>[]);if(n()){i.destroy();return}const v=e.find("#field-project").get(0);v&&(Array.isArray(p)?p:[]).forEach(y=>{const k=document.createElement("option");k.value=y.slug,k.textContent=y.name||y.slug,v.appendChild(k)})}catch{}if(i.destroy(),Ft(e.get(0),a?a.title||a.slug:"New form"),N||e.find("#field-title").get(0).addEventListener("input",function(){e.find("#field-slug").val(ct(this.value))}),E.tabs(e.find("#editor-tabs").get(0)),a){e.find("#field-title").val(a.title),e.find("#field-slug").val(a.slug),e.find("#field-description").val(a.description||""),e.find("#field-bundled").prop("checked",!!a.bundled),ye=a.meta||{},e.find("#field-project").val(a.meta?.project||"");const p=a.settings||{};e.find("#setting-submit-text").val(p.submitText||"Submit"),e.find("#setting-success-message").val(p.successMessage||""),e.find("#setting-layout").val(p.layout||"grid"),e.find("#setting-columns").val(Te(p.columns)),e.find("#setting-submit-span").val(p.submitSpan||""),e.find("#columns-group").get(0).style.display=(p.layout||"grid")==="grid"?"":"none",e.find("#setting-honeypot").prop("checked",p.honeypot!==!1),e.find("#setting-rate-limit").val(p.rateLimitPerMinute||3),e.find("#setting-success-redirect").val(p.successRedirect||"");const v=a.actions?.email||{};e.find("#action-email-enabled").prop("checked",v.enabled||!1),e.find("#action-email-recipients").val(v.recipients||""),e.find("#action-email-subject-prefix").val(v.subjectPrefix||"");const y=a.actions?.webhook||{};e.find("#action-webhook-enabled").prop("checked",y.enabled||!1),e.find("#action-webhook-url").val(y.url||""),e.find("#action-webhook-method").val(y.method||"POST")}const r=a?.settings?.actionSlug||"";try{const p=await se("/actions").catch(()=>[]);if(n())return;const v=e.find("#action-cms-slug").get(0);if(be=Array.isArray(p)?p:[],(Array.isArray(p)?p:[]).forEach(y=>{const k=document.createElement("option");k.value=y.slug,k.textContent=y.title||y.slug,y.slug===r&&(k.selected=!0),v.appendChild(k)}),!p.length){const y=document.createElement("option");y.value="",y.textContent="No actions available",y.disabled=!0,v.appendChild(y)}}catch{}const c=p=>{e.find("#columns-group").get(0).style.display=p?"":"none",document.querySelectorAll(".fb-grid-row").forEach(v=>{v.style.display=p?"flex":"none"})};e.find("#setting-layout").get(0)?.addEventListener("change",function(){c(this.value==="grid")}),c(e.find("#setting-layout").val()==="grid"),Y(e);const s=e.find("#add-element-menu").get(0);e.find("#add-element-btn").get(0).addEventListener("click",p=>{p.stopPropagation(),s.style.display=s.style.display==="none"?"":"none"}),le&&document.removeEventListener("click",le),le=()=>{s&&(s.style.display="none")},document.addEventListener("click",le),e.find("#add-field-btn").get(0).addEventListener("click",()=>{s&&(s.style.display="none"),O();const p=C.length;C.push({name:`field_${p+1}`,type:"string",label:"New Field",required:!1,placeholder:""}),Y(e);const v=e.find("#fields-list").get(0)?.lastElementChild;if(v){const y=v.querySelector(".fb-field-body");y&&(y.style.display="")}}),e.find("#add-spacer-btn").get(0).addEventListener("click",()=>{s&&(s.style.display="none"),O(),C.push({type:"spacer"}),Y(e)}),e.find("#add-page-break-btn").get(0).addEventListener("click",()=>{s&&(s.style.display="none"),O();const p=C.filter(v=>v.type==="page-break").length+2;C.push({type:"page-break",label:`Step ${p}`,description:""}),Y(e)}),ve=()=>{const p=Ne(e),v=e.find("#preview-container").get(0);if(!v)return;const y=e.find("#preview-test-result").get(0),k=e.find("#preview-test-badge").get(0);y&&(y.style.display="none",y.textContent=""),k&&(k.style.display=N?"":"none"),e.find("#preview-card").get(0).style.display="",v.textContent="";const V=document.createElement("div");V.id="fb-preview-form",v.appendChild(V);const J=N?async L=>{y&&(y.style.display="none",y.textContent="");try{const T=await fetch(`/api/forms/submit/${N}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)}),Q=await T.json();if(!T.ok)throw new Error(Q.error||"Submission failed.");y&&(y.textContent=Q.message||p.settings?.successMessage||"Submitted successfully.",y.style.cssText="display:block;margin-top:.75rem;padding:.6rem .9rem;border-radius:6px;font-size:.9rem;background:color-mix(in srgb, var(--dm-success) 12%, transparent);color:var(--dm-success);"),E.toast("Test submission stored.",{type:"success"})}catch(T){y&&(y.textContent=T.message,y.style.cssText="display:block;margin-top:.75rem;padding:.6rem .9rem;border-radius:6px;font-size:.9rem;background:color-mix(in srgb, var(--dm-danger) 12%, transparent);color:var(--dm-danger);"),E.toast(T.message,{type:"error"})}return!1}:()=>!1,fe=p.fields.some(L=>L.type==="page-break");if(V.addEventListener("dm-form-end",L=>{const T=L.detail?.validation;if(T&&!T.valid){E.toast(`Still to answer: ${T.missing.map(Q=>Q.label).concat(T.errors).join(", ")}`,{type:"warning"});return}J(L.detail?.values||{})}),typeof F<"u"){const L=Te(p.settings?.columns),T=p.settings?.layout||"grid";if(fe&&F.wizard){const Q=Pt(p.fields,p.title),he=Q.map(ne=>({title:ne.title,description:ne.description,fields:$t(ne.fields,L)}));let B=0,Z=null,$e=null;const et=ne=>{const tt=(Q[B]||{}).fields||[];At("#fb-preview-form",tt),nt(V,tt),ne&&window.FormLogicEngine&&pt(p.fields)&&(Z?.destroy?.(),Z=new window.FormLogicEngine.FormLogicRuntime({fields:p.fields},V,{baseValues:$e?.getStepData?$e.getStepData():{}}),Z.init())};$e=F.wizard("#fb-preview-form",{schema:{steps:he},layout:T,columns:L,finishText:p.settings?.submitText||"Finish",onStepChange:ne=>{B=ne,queueMicrotask(()=>et(!0))},onSubmit:J}),et(!1)}else if(F.render){const Q=$t(p.fields,L),he={};if(p.fields.forEach(B=>{if(!(!B.name||B.type==="page-break"||B.type==="spacer")&&(B.type==="select"||B.type==="multiselect")&&B.required){const Z=(B.options||[])[0];Z&&(he[B.name]=typeof Z=="object"?Z.value:Z)}}),F.render("#fb-preview-form",Q,he,{submitText:p.settings?.submitText||"Submit",layout:T,columns:L,onSubmit:J}),T==="grid"&&p.settings?.submitSpan==="full"){const B=document.querySelector("#fb-preview-form .form-buttons");B&&B.classList.add("col-span-full")}At("#fb-preview-form",p.fields),nt(V,p.fields)}window.FormLogicEngine&&pt(p.fields)&&requestAnimationFrame(()=>{new window.FormLogicEngine.FormLogicRuntime({fields:p.fields},V).init()})}else{const L=document.createElement("p");L.textContent=`${p.fields.filter(T=>T.type!=="page-break").length} field(s): ${p.fields.filter(T=>T.type!=="page-break").map(T=>T.label).join(", ")}`,L.style.cssText="color:var(--dm-text-muted);font-style:italic;",V.appendChild(L)}},ve();const d=e.find("#editor-tabs").get(0),u=e.find("#preview-card").get(0),b=p=>{u&&u.contains(p.target)||Re()};d&&(d.addEventListener("input",b),d.addEventListener("change",b));const g=e.get(0),m=[],h=p=>(m.push(p),p);let w=!1;const f=M.observable(!1),x=M.observable(!1);let $=N,A=Ne(e),H=Ie(A),_=A;const j=()=>{w||!g.isConnected||(_=Ne(e),f.value=Ie(_)!==H)};let I=null;Me=()=>{clearTimeout(I),I=setTimeout(j,150)},h(()=>{clearTimeout(I),Me=null,de=null});const X=p=>{const v=p.settings||{};e.find("#field-title").val(p.title||""),e.find("#field-slug").val(p.slug||""),e.find("#field-description").val(p.description||""),e.find("#field-bundled").prop("checked",!!p.bundled),ye={...p.meta||{}},e.find("#field-project").val(p.meta?.project||""),e.find("#setting-submit-text").val(v.submitText||"Submit"),e.find("#setting-success-message").val(v.successMessage||""),e.find("#setting-layout").val(v.layout||"grid"),e.find("#setting-columns").val(Te(v.columns)),e.find("#setting-submit-span").val(v.submitSpan||""),e.find("#setting-honeypot").prop("checked",v.honeypot!==!1),e.find("#setting-rate-limit").val(v.rateLimitPerMinute||3),e.find("#setting-success-redirect").val(v.successRedirect||""),e.find("#action-cms-slug").val(v.actionSlug||"");const y=p.actions?.email||{};e.find("#action-email-enabled").prop("checked",!!y.enabled),e.find("#action-email-recipients").val(y.recipients||""),e.find("#action-email-subject-prefix").val(y.subjectPrefix||"");const k=p.actions?.webhook||{};e.find("#action-webhook-enabled").prop("checked",!!k.enabled),e.find("#action-webhook-url").val(k.url||""),e.find("#action-webhook-method").val(k.method||"POST"),C=JSON.parse(JSON.stringify(p.fields||[])),c((v.layout||"grid")==="grid"),Y(e)};async function U(){if(x.peek()||w)return;const p=Ne(e);if(!p.title){E.toast("Please enter a form title (Form Details).",{type:"error"});return}x.value=!0;const v=N;try{N?(await se(`/forms/${N}`,{method:"PUT",body:JSON.stringify(p)}),E.toast("Form saved.",{type:"success"})):(N=(await se("/forms",{method:"POST",body:JSON.stringify(p)})).slug,E.toast("Form created.",{type:"success"})),$=N,A=p,H=Ie(p),_=p,f.value=!1;for(const y of new Set([re(v),re(N)]))try{S.remove?S.remove(y):S.set(y,null)}catch{}Ft(g,p.title),jt("#/forms"),v||R.navigate(`/forms/edit/${N}`)}catch(y){v||(N=null),E.toast(y.message||"Failed to save form.",{type:"error"})}finally{x.value=!1}}async function Ot(){f.peek()&&(!await E.confirm("Discard the changes you have not saved?")||w||(X(A),j(),Qe()))}const He=g.querySelector(".fex-bar");if(He){const p=M.applyBindings({dirty:f,saving:x},He,{methods:{save:U,discard:Ot}});h(()=>p.dispose())}h(_t(g,{position:"bottom"})),Ae(e,{id:"form-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>U()}),Ae(e,{id:"form-editor-back",icon:"arrow-left",title:"All forms",onClick:()=>{location.hash="#/forms"}}),N&&Ae(e,{id:"form-editor-subs",icon:"list",title:"Submissions",onClick:()=>{location.hash=`#/forms/${encodeURIComponent(N)}/submissions`}});const We=p=>{n()||!(p.ctrlKey||p.metaKey)||String(p.key).toLowerCase()!=="s"||(p.preventDefault(),p.stopImmediatePropagation(),U())};document.addEventListener("keydown",We,!0),h(()=>document.removeEventListener("keydown",We,!0));const ee=e.find("#fields-list").get(0),Mt=p=>p?.closest?.(".fb-field-card"),Ue=p=>Number(p?.dataset.index),Je=p=>p?.querySelector(":scope > .fb-field-body"),Ye=p=>{const v=Je(p);v&&(v.style.display=v.style.display==="none"?"":"none")},me=(p,v)=>{C=p,Y(e),v!=null&&ee?.querySelectorAll(".fb-field-card")[v]?.focus()},Rt=async p=>{try{await navigator.clipboard.writeText(p),E.toast(`Copied "${p}".`,{type:"success"})}catch{E.toast(`Copy failed - the name is ${p}.`,{type:"info"})}},Dt=p=>{const v=Mt(p),y=Ue(v);O();const k=C[y];if(!k)return[];const V=k.type!=="spacer"&&k.type!=="page-break",J=Je(v),fe=J&&J.style.display!=="none";return[{header:Fe(k)},...J?[{label:fe?"Close":"Edit",icon:fe?"chevron-up":"edit",action:()=>Ye(v)}]:[],...V?[{label:"Logic & triggers",icon:"zap",action:()=>{J&&(J.style.display=""),(J?.querySelector(".fb-field-logic")||J)?.scrollIntoView({block:"center",behavior:"smooth"})}}]:[],{label:"Duplicate",icon:"copy",action:()=>{O(),me(Gt(C,y),y+1)}},{type:"divider"},{label:"Move up",icon:"arrow-up",disabled:y===0,action:()=>{O(),me(it(C,y,-1),y-1)}},{label:"Move down",icon:"arrow-down",disabled:y>=C.length-1,action:()=>{O(),me(it(C,y,1),y+1)}},...V&&k.name?[{label:"Copy field name",icon:"clipboard",action:()=>Rt(k.name)}]:[],{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:async()=>{if(k.type!=="spacer"&&!await E.confirm(`Remove "${vn(Fe(k))}"?`))return;O();const L=[...C];L.splice(y,1),me(L,Math.min(y,L.length-1))}}]};let Ke=null;if(ee&&E.contextMenu&&(Ke=E.contextMenu(ee,{cursor:"glyph",match:".fb-field-card > :first-child",inherit:!1,density:"compact",items:p=>Dt(p)}),h(()=>Ke?.destroy?.())),de=p=>{for(const v of p.querySelectorAll(".fb-field-card")){v.tabIndex=0;const y=v.firstElementChild;if(!y||y.querySelector(".fex-kebab"))continue;const k=document.createElement("button");k.type="button",k.className="fex-kebab",k.textContent="\u22EE",k.title="Actions",O(),k.setAttribute("aria-label",`Actions for ${Fe(C[Ue(v)])}`),k.addEventListener("click",V=>{V.stopPropagation(),lt(k)}),y.appendChild(k)}},ee){de(ee);const p=v=>{const y=v.target?.classList?.contains("fb-field-card")?v.target:null;y&&(v.key==="F10"&&v.shiftKey?(v.preventDefault(),lt(y.firstElementChild)):v.key==="Enter"&&(v.preventDefault(),Ye(y)))};ee.addEventListener("keydown",p),h(()=>ee.removeEventListener("keydown",p))}const Qe=()=>{try{const p=re($);S.remove?S.remove(p):S.set(p,null)}catch{}},Xe=p=>{if(!f.peek()||!p){Qe();return}try{S.set(re($),{data:Vt(p),base:at(H),at:new Date().toISOString()})}catch{}},Ze=p=>{j(),f.peek()&&(Xe(_),p.preventDefault(),p.returnValue="")};window.addEventListener("beforeunload",Ze),h(()=>window.removeEventListener("beforeunload",Ze)),h(()=>{le&&(document.removeEventListener("click",le),le=null)}),W={path:t,dirty:()=>f.peek(),flush:()=>{clearTimeout(I),j()},dispose(){w||(Xe(_),w=!0,m.splice(0).reverse().forEach(p=>{try{p?.()}catch{}}))}};const qe=re(N);let te=null;try{te=S.get(qe)}catch{}if(te?.data){try{S.remove?S.remove(qe):S.set(qe,null)}catch{}const p=te.base&&te.base!==at(H),v=te.at?` (${D(te.at).format("D MMM HH:mm")})`:"";await E.confirm(`You left unsaved changes to this form${v}.${p?" The saved form has changed since then.":""} Pick up where you left off?`)&&!w&&(X(Ht(te.data,A)),j())}}};
|