domma-cms 1.67.2 → 1.69.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/CLAUDE.md +2 -0
- package/admin/js/lib/layouts-arrange.js +1 -1
- package/admin/js/lib/rich-field.js +9 -2
- package/admin/js/lib/seo-defaults.js +1 -1
- package/admin/js/templates/docs/api-content.html +3 -2
- package/admin/js/templates/docs/api-layouts.html +1 -1
- package/admin/js/templates/docs/usage-navigation.html +2 -1
- package/admin/js/templates/docs/usage-pages.html +3 -1
- package/admin/js/templates/docs/usage-search-engines.html +3 -0
- package/admin/js/templates/page-editor.html +3 -3
- package/admin/js/views/form-editor.js +5 -5
- package/admin/js/views/layouts.js +7 -7
- package/admin/js/views/menu-editor.js +20 -20
- package/admin/js/views/page-editor.js +9 -9
- package/admin/js/views/seo.js +31 -30
- package/docs/DommaFeatures.md +6 -2
- package/docs/api-reference.md +7 -3
- package/docs/guides/multi-page-forms.md +1 -1
- package/docs/markdown-shortcodes.md +1 -1
- package/docs/plugin-development.md +20 -0
- package/package.json +1 -1
- package/plugins/blog/CHANGELOG.md +3 -0
- package/plugins/blog/CLAUDE.md +15 -0
- package/plugins/blog/admin/views/categories.js +5 -2
- package/plugins/blog/admin/views/kit.js +19 -0
- package/plugins/blog/docs/guide.md +2 -0
- package/plugins/blog/plugin.js +18 -2
- package/plugins/blog/plugin.json +6 -6
- package/plugins/blog/plugin.public.js +16 -2
- package/plugins/blog/public/blog.css +3 -0
- package/plugins/blog/tests/public.test.js +29 -2
- package/plugins/feedback/CLAUDE.md +22 -0
- package/plugins/feedback/admin/css/index.css +2 -0
- package/plugins/feedback/admin/views/inbox.js +5 -2
- package/plugins/feedback/admin/views/send.js +12 -5
- package/plugins/feedback/docs/guide.md +3 -2
- package/plugins/feedback/lib/sender.js +1 -1
- package/plugins/feedback/lib/shape.js +72 -11
- package/plugins/feedback/plugin.js +3 -3
- package/plugins/feedback/plugin.json +3 -2
- package/plugins/feedback/tests/api.test.js +47 -1
- package/plugins/feedback/tests/shape.test.js +87 -1
- package/plugins/free-tier.lock.json +43 -42
- package/plugins/shopping-cart/CHANGELOG.md +20 -0
- package/plugins/shopping-cart/CLAUDE.md +38 -1
- package/plugins/shopping-cart/admin/css/index.css +4 -0
- package/plugins/shopping-cart/admin/lib/kit.js +1 -0
- package/plugins/shopping-cart/admin/views/products.js +95 -3
- package/plugins/shopping-cart/admin/views/shop.js +2 -1
- package/plugins/shopping-cart/docs/guide.md +6 -1
- package/plugins/shopping-cart/inject/body.html +2 -2
- package/plugins/shopping-cart/lib/description.js +173 -0
- package/plugins/shopping-cart/lib/render.js +3 -2
- package/plugins/shopping-cart/lib/shop.js +4 -1
- package/plugins/shopping-cart/plugin.js +17 -2
- package/plugins/shopping-cart/plugin.json +3 -2
- package/plugins/shopping-cart/plugin.public.js +6 -9
- package/plugins/shopping-cart/public/lib/products.js +40 -3
- package/plugins/shopping-cart/public/shop.css +1 -0
- package/plugins/shopping-cart/tests/pure.test.js +26 -1
- package/plugins/shopping-cart/tests/seo.test.js +174 -0
- package/public/js/collection-browser.js +1 -1
- package/public/js/menu-cards.mjs +4 -4
- package/public/js/menu-look.mjs +1 -1
- package/public/js/rich-text.mjs +4 -4
- package/public/js/site.js +1 -1
- package/server/routes/api/collections.js +26 -12
- package/server/routes/api/forms.js +5 -3
- package/server/routes/api/layouts.js +8 -4
- package/server/routes/api/seo.js +10 -4
- package/server/services/adapters/FileAdapter.js +4 -3
- package/server/services/adapters/MongoAdapter.js +4 -2
- package/server/services/content.js +23 -0
- package/server/services/contentApi.js +27 -4
- package/server/services/filterEngine.js +33 -0
- package/server/services/forms.js +58 -2
- package/server/services/health.js +3 -1
- package/server/services/markdown.js +288 -38
- package/server/services/menus.js +56 -6
- package/server/services/renderer.js +28 -4
- package/server/services/richText.js +56 -3
- package/server/services/search.js +5 -2
- package/server/services/sitemap.js +5 -3
- package/server/templates/page.html +2 -2
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{apiRequest as fe}from"/admin/js/api.js";import{makeIconInput as
|
|
2
|
-
`).filter(b=>b.trim()).map(b=>{const[C,...$]=b.split(":");return{value:C.trim(),label:$.join(":").trim()||C.trim()}}))}for(const x of["prefix","suffix"]){const b=document.getElementById(`fb-${x}-icon-${e}`),C=document.getElementById(`fb-${x}-text-${e}`),$={...t.formConfig||{}};if(b||C){const
|
|
3
|
-
`).filter(v=>v.trim()).map(v=>{const[w,...N]=v.split(":");return{value:w.trim(),label:N.join(":").trim()||w.trim()}});n.cascade={sourceField:m,mapping:g,defaultOptions:f},i=!0}}return i?n:void 0}function H(){T=T.map((e,t)=>In(t))}function Mn(e){const t=e.firstElementChild;if(!t||t.querySelector(".fb-drag-grip"))return;const o=document.createElement("span");o.className="fb-drag-grip",o.setAttribute("data-icon","grip-vertical"),o.setAttribute("data-icon-size","16"),o.title="Drag to reorder",t.insertBefore(o,t.firstChild),window.I?.scan?.(t)}function ne(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()),T.length===0){o&&(o.style.display=""),ve?.(t),Ye();return}o&&(o.style.display="none"),T.forEach((n,i)=>{const a=n.type==="page-break"?Rn(n,i,e):n.type==="spacer"?Dn(n,i,e):_n(n,i,e);Mn(a),t.appendChild(a)}),ve?.(t),Ye()}}function Rn(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 i=document.createElement("div");i.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 s=document.createElement("span");s.textContent=e.label||"Untitled Step",s.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 l=document.createElement("div");l.style.cssText="display:flex;gap:.25rem;flex-shrink:0;margin-left:.5rem;";const u=document.createElement("button");u.className="btn btn-xs btn-ghost",u.title="Edit step",O(u,"more-horizontal"),u.addEventListener("click",g=>{g.stopPropagation(),d.style.display=d.style.display==="none"?"":"none"}),l.appendChild(u);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",O(r,"x"),r.addEventListener("click",async g=>{g.stopPropagation(),await E.confirm("Remove this page break?")&&(H(),T.splice(t,1),ne(o))}),l.appendChild(r),i.appendChild(a),i.appendChild(s),i.appendChild(l),i.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 p=_([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")]),m=p.querySelector(`#fb-pb-label-${t}`);return m&&m.addEventListener("input",()=>{s.textContent=m.value||"Untitled Step"}),d.appendChild(p),n.appendChild(i),n.appendChild(d),n}function Dn(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 i=document.createElement("div");i.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 s=document.createElement("span");s.textContent="Spacer",s.style.cssText="font-size:.7rem;color:var(--dm-text-muted);white-space:nowrap;padding:0 .4rem;font-style:italic;";const l=document.createElement("div");l.style.cssText="flex:1;height:1px;background:var(--dm-border);";const u=document.createElement("div");u.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",O(r,"x"),r.addEventListener("click",async d=>{d.stopPropagation(),H(),T.splice(t,1),ne(o)}),u.appendChild(r),i.appendChild(a),i.appendChild(s),i.appendChild(l),i.appendChild(u),n.appendChild(i),n}function _n(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 i=document.createElement("div");i.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=Ft(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 s=document.createElement("span");s.textContent=e.label||"(unlabelled)",s.style.cssText="flex:1;font-weight:600;font-size:.9rem;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;";const l=document.createElement("div");l.style.cssText="display:flex;gap:.25rem;flex-shrink:0;margin-left:.5rem;";const u=document.createElement("button");u.className="btn btn-xs btn-ghost",u.title="Edit field",O(u,"more-horizontal"),u.addEventListener("click",p=>{p.stopPropagation(),d.style.display=d.style.display==="none"?"":"none"}),l.appendChild(u);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",O(r,"x"),r.addEventListener("click",async p=>{p.stopPropagation(),await E.confirm("Remove this field?")&&(H(),T.splice(t,1),ne(o))}),l.appendChild(r),i.appendChild(a),i.appendChild(s),e.required){const p=document.createElement("span");p.textContent="required",p.style.cssText="font-size:.7rem;color:var(--dm-danger);flex-shrink:0;",i.appendChild(p)}if(Bt(e.logic)){const p=document.createElement("span");O(p,"zap"),p.title="Has conditional logic",p.style.cssText="font-size:.75rem;color:var(--dm-primary);flex-shrink:0;",i.appendChild(p)}i.appendChild(l),i.addEventListener("click",()=>{d.style.display=d.style.display==="none"?"":"none"});const d=zn(e,t,s);return d.style.display="none",n.appendChild(i),n.appendChild(d),n}function zn(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 i=_([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=_([di("Type",`fb-type-${t}`,Nt,e.type||"string"),Oe("Required",`fb-required-${t}`,e.required||!1)]),s=_([P("Placeholder",`fb-placeholder-${t}`,"text",e.placeholder||"","Hint text inside the field")]),l=_([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")]),u=_([P("CSS classes",`fb-class-${t}`,"text",e.class||"","Your own class names, separated by spaces, on the field's wrapper - style them in Custom CSS")]),r=e.formConfig?.span,d=_([P("Column Span",`fb-span-${t}`,"number",r&&r!=="full"?String(r):"1","Columns to span (grid only)"),Oe("Full Width",`fb-fullwidth-${t}`,r==="full")]);d.classList.add("fb-grid-row"),d.style.display=document.getElementById("setting-layout")?.value==="grid"?"flex":"none",n.appendChild(i),n.appendChild(a),n.appendChild(s),n.appendChild(l),n.appendChild(u),n.appendChild(d);const p=n.querySelector(`#fb-label-${t}`),m=n.querySelector(`#fb-name-${t}`);p&&p.addEventListener("input",()=>{o&&(o.textContent=p.value||"(unlabelled)"),m&&!m.dataset.manuallyEdited&&(m.value=$t(p.value))}),m&&m.addEventListener("input",()=>{m.dataset.manuallyEdited="1"});const g=n.querySelector(`#fb-type-${t}`);g&&g.addEventListener("change",()=>{const v=n.closest(".fb-field-card");if(v){const x=v.querySelector("span");x&&(x.textContent=Ft(g.value))}const w=n.querySelector(".fb-field-extras");w&&w.remove();const N=Xt(g.value,e,t);N&&n.appendChild(N)});const f=Xt(e.type,e,t);return f&&n.appendChild(f),n.appendChild(Un(e,t)),n.appendChild(Zn(e,t)),n}const Ne=[{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"}],Je=new Set(["is_empty","is_not_empty"]),It={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 Xe(e){return!!e&&(e.type==="checkbox-group"||!!e.multiple)}function qe(e){const t=document.createElement("p");return t.textContent=e,t.appendChild(B({Visibility:"Choose whether this field starts visible or hidden, then add rules to show or hide it based on answers. The transition and speed control how it appears.","Conditional Requirement":"Make this field required or optional according to another answer. Hidden fields are not required.","Custom Validation":"Regex tests the answer against a regular expression; flags such as i make it case insensitive. Match field compares with another field name, such as password confirmation. Set the error message visitors see if the check fails.","Cascade Options":"Replace this field's choices according to another field's answer. Map source values to option lists and provide default options for unmatched or empty answers."}[e],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 $e(e,t,o){return e.style.flex=t,e.style.minWidth=o,e}function Fe(e,t,o,n,i){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 s=document.createElement("span");s.textContent="When",s.style.cssText="font-size:.73rem;color:var(--dm-text-muted);flex-shrink:0;";const l=document.createElement("select");l.className="form-select fb-logic-cond-field",l.style.cssText="width:100%;min-width:0;",t.forEach(f=>{const v=document.createElement("option");v.value=f.value,v.textContent=f.label,e&&f.value===e.field&&(v.selected=!0),l.appendChild(v)});const u=document.createElement("select");u.className="form-select fb-logic-cond-op",u.style.cssText="width:100%;min-width:0;",Ne.forEach(f=>{const v=document.createElement("option");v.value=f.value,v.textContent=f.label,e&&f.value===e.operator&&(v.selected=!0),u.appendChild(v)});const r=()=>{const f=t.find(v=>v.value===l.value);Array.from(u.options).forEach(v=>{const w=Ne.find(N=>N.value===v.value);v.textContent=f?.multi&&It[v.value]||w?.label||v.value})};r(),l.addEventListener("change",r);const d=document.createElement("input");d.type="text",d.className="form-input fb-logic-cond-val",d.placeholder="value",d.style.cssText="width:100%;min-width:0;",d.value=e?.value||"",u.addEventListener("change",()=>{(d.closest(".fb-trig-f")||d).style.display=Je.has(u.value)?"none":""});const p=document.createElement("span");O(p,"arrow-right"),p.style.cssText="font-size:.73rem;color:var(--dm-text-muted);flex-shrink:0;";const m=document.createElement("select");m.className=`form-select ${n}`,m.style.cssText="width:100%;min-width:0;",o.forEach(f=>{const v=document.createElement("option");v.value=f.value,v.textContent=f.label,f.value===i&&(v.selected=!0),m.appendChild(v)});const g=document.createElement("button");return g.type="button",g.className="btn btn-xs btn-ghost",g.style.cssText="line-height:1;opacity:.6;",O(g,"x"),g.style.flexShrink="0",g.addEventListener("click",()=>a.remove()),a.appendChild(s),a.appendChild($e(L("Field",l,{help:"The answer this rule tests. Select another named field from the form."}),"1 1 140px","140px")),a.appendChild($e(L("Comparison",u,{help:"How to compare the answer. Multi-choice fields test their selected values. Empty and not empty do not need a value."}),"1 1 160px","140px")),a.appendChild($e(L("Value",d,{help:"The stored value to compare against. For one of, enter comma-separated values. For regex, enter a regular expression."}),"1 1 120px","100px")),a.appendChild(p),a.appendChild($e(L("Result",m,{help:"What happens to this field when the condition matches: change its visibility or whether an answer is required."}),"1 1 140px","120px")),a.appendChild(g),e&&Je.has(e.operator)&&(d.closest(".fb-trig-f").style.display="none"),a}function Pn(e,t,o){const n=document.createElement("div");n.dataset.logicSection="visibility",n.appendChild(qe("Visibility"));const i=document.createElement("div");i.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 s=document.createElement("select");s.className="form-select fb-logic-vis-default",s.style.cssText="max-width:240px;",[{value:"visible",label:"Visible"},{value:"hidden",label:"Hidden"}].forEach(b=>{const C=document.createElement("option");C.value=b.value,C.textContent=b.label,b.value===(e.default||"visible")&&(C.selected=!0),s.appendChild(C)}),a.appendChild(B("Whether the field is visible before any rule matches.","Default visibility")),i.appendChild(a),i.appendChild(s),n.appendChild(i);const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.6rem;margin-bottom:.65rem;flex-wrap:wrap;";const u=document.createElement("span");u.textContent="Transition:",u.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;",(window.FormLogicEngine?.FIELD_TRANSITIONS||[{value:"none",label:"None (instant)"},{value:"fade",label:"Fade"},{value:"slide",label:"Slide"},{value:"scale",label:"Scale"}]).forEach(b=>{const C=document.createElement("option");C.value=b.value,C.textContent=b.label,b.value===(e.transition||"none")&&(C.selected=!0),r.appendChild(C)}),u.appendChild(B("The animation used when this field appears or disappears, from a simple fade to a bubble pop. None switches instantly. Use Preview to try it.","Transition")),l.appendChild(u),l.appendChild(r),n.appendChild(l);const d=document.createElement("div");d.style.cssText="display:flex;align-items:center;gap:.6rem;margin-bottom:.65rem;flex-wrap:wrap;";const p=document.createElement("span");p.textContent="Speed:",p.style.cssText="font-size:.8rem;flex-shrink:0;";const m=document.createElement("select");m.className="form-select fb-logic-vis-duration",m.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(b=>{const C=document.createElement("option");C.value=b.value,C.textContent=b.label,b.value===String(e.duration??"")&&(C.selected=!0),m.appendChild(C)}),p.appendChild(B("How long the visibility animation lasts. Default uses the effect timing; shorter times are faster.","Speed")),d.appendChild(p),d.appendChild(m),n.appendChild(d);const g=document.createElement("button");g.type="button",g.className="btn btn-xs btn-ghost fb-logic-vis-preview",g.textContent="Preview";const f=document.createElement("span");f.className="fb-logic-vis-preview-chip",f.textContent="Sample field",f.style.cssText="display:inline-block;padding:.2rem .6rem;border:1px solid var(--dm-border);border-radius:var(--dm-radius, 6px);font-size:.75rem;background:var(--dm-surface);",g.addEventListener("click",()=>{window.FormLogicEngine?.previewTransition?.(f,r.value,m.value===""?void 0:Number(m.value))}),d.appendChild(g),d.appendChild(f);const v=()=>{d.style.display=r.value==="none"?"none":""};v(),r.addEventListener("change",v);const w=document.createElement("div");w.className="fb-logic-vis-rules";const N=o.map(b=>({value:b.name,label:b.label||b.name,multi:Xe(b)})),x=[{value:"visible",label:"Show"},{value:"hidden",label:"Hide"}];if((e.conditions||[]).forEach(b=>{const C=(b.when?.all||b.when?.any||[])[0],$=b.then==="hidden"?"hidden":"visible";N.length>0&&w.appendChild(Fe(C,N,x,"fb-logic-vis-then",$))}),n.appendChild(w),N.length>0){const b=document.createElement("button");b.type="button",b.className="btn btn-xs btn-ghost",b.style.cssText="font-size:.73rem;margin-top:.35rem;",be(b,"plus","Add visibility rule"),b.addEventListener("click",()=>w.appendChild(Fe(null,N,x,"fb-logic-vis-then","visible"))),n.appendChild(b)}return n}function jn(e,t,o){const n=document.createElement("div");n.dataset.logicSection="requirement",n.appendChild(qe("Conditional Requirement"));const i=document.createElement("label");i.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,i.appendChild(a),i.appendChild(document.createTextNode("Required by default")),i.appendChild(B("Whether this field requires an answer before a conditional requirement rule matches.","Required by default")),n.appendChild(i);const s=document.createElement("div");s.className="fb-logic-req-rules";const l=o.map(r=>({value:r.name,label:r.label||r.name,multi:Xe(r)})),u=[{value:"true",label:"Make required"},{value:"false",label:"Make optional"}];if((e.conditions||[]).forEach(r=>{const d=(r.when?.all||r.when?.any||[])[0],p=r.then===!0?"true":"false";l.length>0&&s.appendChild(Fe(d,l,u,"fb-logic-req-then",p))}),n.appendChild(s),l.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;",be(r,"plus","Add requirement rule"),r.addEventListener("click",()=>s.appendChild(Fe(null,l,u,"fb-logic-req-then","true"))),n.appendChild(r)}return n}function Ot(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(l=>{const u=document.createElement("option");u.value=l.value,u.textContent=l.label,l.value===(e?.type||"regex")&&(u.selected=!0),o.appendChild(u)});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 i=document.createElement("input");i.type="text",i.className="form-input fb-logic-val-flags",i.placeholder="flags",i.value=e?.flags||"",i.style.cssText="flex:0 0 55px;",e?.type==="match"&&(i.style.display="none"),o.addEventListener("change",()=>{i.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 s=document.createElement("button");return s.type="button",s.className="btn btn-xs btn-ghost",s.style.cssText="line-height:1;opacity:.6;",O(s,"x"),s.style.flexShrink="0",s.addEventListener("click",()=>t.remove()),t.appendChild(L("Validation",o,{help:"Regex checks a pattern. Match field requires the same answer as another named field."})),t.appendChild(L("Pattern or field name",n,{help:"For Regex, enter a regular expression without enclosing slashes. For Match field, enter the other field name, such as password."})),t.appendChild(L("Flags",i,{help:"Optional regular expression flags, such as i for case insensitive matching. Applies only to Regex."})),t.appendChild(L("Error message",a,{help:"The explanation visitors see when the answer fails this validation rule."})),t.appendChild(s),t}function Wn(e,t,o){const n=document.createElement("div");n.dataset.logicSection="validation",n.appendChild(qe("Custom Validation"));const i=document.createElement("div");i.className="fb-logic-val-rules",(e||[]).forEach(s=>i.appendChild(Ot(s))),n.appendChild(i);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;",be(a,"plus","Add validation rule"),a.addEventListener("click",()=>i.appendChild(Ot(null))),n.appendChild(a),n}function Hn(e,t,o){const n=document.createElement("div");n.dataset.logicSection="cascade",n.appendChild(qe("Cascade Options")),n.lastChild.appendChild(B("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 i=document.createElement("div");i.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 s=document.createElement("select");s.className="form-select fb-logic-cascade-source",s.style.cssText="flex:1;";const l=document.createElement("option");l.value="",l.textContent="- none -",s.appendChild(l),o.forEach(m=>{const g=document.createElement("option");g.value=m.name,g.textContent=m.label||m.name,m.name===e.sourceField&&(g.selected=!0),s.appendChild(g)}),i.appendChild(a),i.appendChild(s),n.appendChild(i);const u=document.createElement("p");u.textContent='Mapping JSON - {"value":[{"value":"...","label":"..."}]}',u.appendChild(B(`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".`)),u.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):"",n.appendChild(u),n.appendChild(r);const d=document.createElement("p");d.textContent="Default options (one per line: value:Label)",d.appendChild(B("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 p=document.createElement("textarea");return p.className="form-input fb-logic-cascade-defaults",p.rows=3,p.style.cssText="font-family:monospace;",p.placeholder=`option1:Option 1
|
|
1
|
+
import{apiRequest as fe}from"/admin/js/api.js";import{makeIconInput as He}from"/admin/js/lib/shortcode-modal.js";import{enhancePickerFields as vt}from"/public/js/forms.js";import{buildWizardSteps as yn}from"/public/js/form-steps.mjs";import{DEFAULT_MAX_FILES as xt,MAX_FILES_LIMIT as We,captureFileFields as wt,destroyDropzones as Ct,fileBlueprint as vn,restoreFileFields as xn,splitFiles as wn,submitBody as Cn,wireFileFields as En}from"/public/js/form-files.mjs";import{applyFormClasses as Et,applySubmitButtons as kn,applyWizardButtons as Sn,buttonSettingsProblems as Tn,formClassProblems as Nn,resolveSubmitAlign as kt}from"/public/js/form-submit.mjs";import{addBannerAction as Ve}from"../lib/plugin-chrome.js";import{helpPopovers as Ln}from"../lib/help-popover.js";import{openMenuAt as St,sidebarCount as qn}from"../lib/tool-kit.js";import{draftBaseOf as $n,draftChoice as An,draftKey as he,draftOf as Fn,duplicateField as Bn,editorDraftQuestion as In,fieldTitle as Ue,fingerprint as Tt,leavingEditor as Nt,moveField as Lt,restoreDraft as On,snapshotOf as Ee}from"../lib/form-editor-arrange.js";import{fmtDateTime as Mn}from"../lib/dates.js";import{richDescription as qt,richTextInlineHtml as Rn,richTextLine as Dn,isRichText as _n}from"../lib/rich-field.js";const $t=[{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"}],Ge=new Set(["select","radio","checkbox-group","chooser"]);let T=[],ke=[],I=null,Se=null,se=null,Te={};function D(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 be(e,t,o,n=14){return D(e,t,n),e.appendChild(document.createTextNode(" "+o)),e}function B(e,t=""){const o=document.createElement("span");return o.setAttribute("data-help",e),t&&o.setAttribute("data-help-title",t),o}const ge={Label:"The name visitors see above this field.","Field Name":"The key stored with this answer. Use a unique name without spaces, such as email_address. Conditions, message tokens and integrations refer to this name.",Type:"The kind of answer this field accepts. Dropdowns, radio buttons and checkbox groups use the Options list below.",Required:"The visitor must answer this field before submitting. Conditional logic can change whether an answer is required.",Placeholder:"An example or short hint inside an empty input. It disappears when the visitor types.","Helper Text":"Instructions shown below the field, even after the visitor enters an answer.",Tooltip:"Help for visitors, shown beside the field label. Enter the explanation you want visitors to read.","Column Span":"How many columns this field occupies in a grid layout. Full Width spans the entire row.","Full Width":"Make this field span every column in the grid layout.","Min Length":"The fewest characters an answer may contain. Leave blank for no minimum; use Required to prevent an empty answer.","Max Length":"The most characters an answer may contain. Leave blank for no maximum.",Min:"The lowest number allowed. Leave blank for no lower limit.",Max:"The highest number allowed. Leave blank for no upper limit."},ye={Action:"Choose what happens when this branch is active. Banners, field changes and submission blocks apply while the condition holds. Toasts, step jumps and celebrations fire when the branch becomes active. Redirects, CMS actions and admin notifications are handled on submission.",Message:"The text visitors see. Use {{field_name}} to insert an answer; password and upload answers are never included.","Reason, shown under the button":"Explain why submission is blocked. Leave blank to use the default refusal message.","Message shown in place of the rest":"Explain why the form ends here. The remaining fields are hidden while this condition holds. You can insert answers with {{field_name}}.","Notification title":"The title of the admin notification created when the submitted answers meet this condition. Leave blank to use the form title. Field tokens are not expanded here.","Button text":"The button used to send the answers given so far when the form ends early. Leave blank for Finish.","Closing message":"Shown after the visitor finishes early. Leave blank for the form success message. You can insert answers with {{field_name}}.",Level:"The visual style of the message: Info, Success, Warning or Error.",Severity:"The level attached to the admin notification: Info, Success, Warning or Error.",Where:"Place the banner above or below the field that owns this trigger, or at the top of the form.","Which fields":"The rest of the form means fields after this trigger's field. Every other field excludes this field. Chosen fields lets you select specific targets.",Fields:"Select the fields this action changes. Use Ctrl-click on Windows or Linux, or Cmd-click on macOS, to select several.",Step:"The wizard step to open when this branch becomes active. Steps count from zero: 0 is the first step, 1 is the second. Add Page Breaks to create steps.","Send them to":"The destination after a successful submission when this condition matches. Use a site path such as /thank-you or a full URL. Field tokens are not expanded.",Theme:"The celebration to play when this branch becomes active. Whatever is in season chooses the seasonal theme automatically.",Intensity:"How much animation the celebration produces. Low is subtle; High adds more activity."};let Ne=null,At=null,Ke=null,ve=null;function Ye(){Ke?.(),clearTimeout(At),At=setTimeout(()=>{Ne&&Ne()},350)}function Ft(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}function Bt(e){return $t.find(t=>t.value===e)?.label||e}function It(e){return(e||[]).some(t=>t.logic||Array.isArray(t.triggers)&&t.triggers.length)}function Ot(e){return e?!!(e.visibility?.conditions?.length||e.requirement?.conditions?.length||e.validation?.length||e.cascade?.sourceField):!1}function zn(e){const t={...T[e]};if(t.type==="spacer")return t;if(t.type==="page-break"){const x=document.getElementById(`fb-pb-label-${e}`),b=document.getElementById(`fb-pb-desc-${e}`);return x&&(t.label=x.value.trim()||t.label),b&&(t.description=b.value.trim()),t}const o=document.getElementById(`fb-label-${e}`),n=document.getElementById(`fb-name-${e}`),i=document.getElementById(`fb-type-${e}`),a=document.getElementById(`fb-required-${e}`),s=document.getElementById(`fb-placeholder-${e}`),l=document.getElementById(`fb-helper-${e}`),d=document.getElementById(`fb-tooltip-${e}`);o&&(t.label=o.value.trim()||t.label),n&&(t.name=n.value.trim()||t.name),i&&(t.type=i.value||t.type),a&&(t.required=a.checked),s&&(t.placeholder=s.value.trim()),l&&(t.helper=l.value.trim()),d&&(t.tooltip=d.value.trim());const r=document.getElementById(`fb-class-${e}`);if(r){const x=r.value.trim();x?t.class=x:delete t.class}if(t.type==="chooser"){const x=document.getElementById(`fb-chooser-variant-${e}`)?.value;x&&(t.variant=x);const b=document.getElementById(`fb-chooser-multiple-${e}`);b&&(t.multiple=b.checked);const C=document.getElementById(`fb-chooser-density-${e}`)?.value;C&&(t.density=C);const $=document.getElementById(`fb-chooser-columns-${e}`)?.value;$!==""&&$!==void 0&&(t.columns=parseInt($,10)||3);const j=document.getElementById(`fb-chooser-accent-${e}`)?.value.trim();j?t.accent=j:delete t.accent;const H=document.getElementById(`fb-chooser-accent-style-${e}`)?.value;H?t.accentStyle=H:delete t.accentStyle;const J=document.getElementById(`fb-chooser-glow-${e}`);J&&(t.glow=J.checked);const O=document.getElementById(`fb-chooser-glow-colour-${e}`)?.value.trim();O?t.glowColour=O:delete t.glowColour;const X=document.getElementById(`fb-chooser-shadow-${e}`)?.value;X&&X!=="none"?t.shadow=X:delete t.shadow;const K=document.getElementById(`fb-chooser-shadow-colour-${e}`)?.value.trim();K?t.shadowColour=K:delete t.shadowColour,Ie(e),T[e]&&Array.isArray(T[e].options)&&(t.options=T[e].options)}else if(Ge.has(t.type)){["variant","density","columns","accent","accentStyle","glow","glowColour","shadow","shadowColour"].forEach(b=>delete t[b]),t.type!=="checkbox-group"&&t.type!=="multiselect"&&delete t.multiple;const x=document.getElementById(`fb-options-${e}`);x&&(t.options=x.value.split(`
|
|
2
|
+
`).filter(b=>b.trim()).map(b=>{const[C,...$]=b.split(":");return{value:C.trim(),label:$.join(":").trim()||C.trim()}}))}for(const x of["prefix","suffix"]){const b=document.getElementById(`fb-${x}-icon-${e}`),C=document.getElementById(`fb-${x}-text-${e}`),$={...t.formConfig||{}};if(b||C){const j=b?.value.trim()||"",H=C?.value.trim()||"";j&&/^[a-z0-9-]+$/i.test(j)?$[x]={icon:j}:H?$[x]={text:H.slice(0,24)}:delete $[x]}else en.includes(t.type)||delete $[x];t.formConfig=Object.keys($).length?$:void 0}{const x={...t.formConfig||{}};for(const b of nt){const C=document.getElementById(`fb-extra-${b.key}-${e}`);C&&b.types.includes(t.type)?C.checked?x[b.key]=!0:delete x[b.key]:b.types.includes(t.type)||delete x[b.key]}t.formConfig=Object.keys(x).length?x:void 0}if(t.type==="file"){const x=document.getElementById(`fb-file-multiple-${e}`);if(x){const b={...t.file||{}};if(x.checked){t.multiple=!0;const C=parseInt(document.getElementById(`fb-file-max-${e}`)?.value,10);C>=1?b.maxFiles=Math.min(C,We):delete b.maxFiles}else delete t.multiple,delete b.maxFiles;t.file=Object.keys(b).length?b:void 0}}if(t.type==="textarea"){const x=parseInt(document.getElementById(`fb-rows-${e}`)?.value,10);x>0&&(t.formConfig={...t.formConfig||{},rows:x})}const u=document.getElementById(`fb-span-${e}`),p=document.getElementById(`fb-fullwidth-${e}`);if(u||p){const x={...t.formConfig||{}};if(p?.checked)x.span="full";else{const b=parseInt(u?.value,10);b>1?x.span=b:delete x.span}t.formConfig=Object.keys(x).length?x:void 0}const m=document.getElementById(`fb-minlength-${e}`)?.value;m&&(t.minLength=parseInt(m,10));const g=document.getElementById(`fb-maxlength-${e}`)?.value;g&&(t.maxLength=parseInt(g,10));const f=document.getElementById(`fb-min-${e}`)?.value;f!==""&&f!==void 0&&(t.min=parseFloat(f));const v=document.getElementById(`fb-max-${e}`)?.value;v!==""&&v!==void 0&&(t.max=parseFloat(v));const w=Pn(e);w?t.logic=w:delete t.logic;const L=li(e);return L?t.triggers=L:delete t.triggers,t}function Pn(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 i=!1;const a=o.querySelector('[data-logic-section="visibility"]');if(a){const r=a.querySelector(".fb-logic-vis-default"),u=a.querySelector(".fb-logic-vis-transition"),p=Array.from(a.querySelectorAll(".fb-logic-cond-row")).map(v=>{const w=v.querySelector(".fb-logic-cond-field"),L=v.querySelector(".fb-logic-cond-op"),x=v.querySelector(".fb-logic-cond-val"),b=v.querySelector(".fb-logic-vis-then");return w?.value?{when:{all:[{field:w.value,operator:L.value,value:x.value}]},then:b.value}:null}).filter(Boolean),m=r?.value||"visible",g=u?.value||"none",f=parseInt(a.querySelector(".fb-logic-vis-duration")?.value||"",10);(m!=="visible"||p.length>0||g!=="none")&&(n.visibility={default:m,conditions:p},g!=="none"&&(n.visibility.transition=g),g!=="none"&&Number.isFinite(f)&&(n.visibility.duration=f),i=!0)}const s=o.querySelector('[data-logic-section="requirement"]');if(s){const r=s.querySelector(".fb-logic-req-default"),u=Array.from(s.querySelectorAll(".fb-logic-cond-row")).map(p=>{const m=p.querySelector(".fb-logic-cond-field"),g=p.querySelector(".fb-logic-cond-op"),f=p.querySelector(".fb-logic-cond-val"),v=p.querySelector(".fb-logic-req-then");return m?.value?{when:{all:[{field:m.value,operator:g.value,value:f.value}]},then:v.value==="true"}:null}).filter(Boolean);u.length>0&&(n.requirement={default:r?.checked===!0,conditions:u},i=!0)}const l=o.querySelector('[data-logic-section="validation"]');if(l){const r=Array.from(l.querySelectorAll(".fb-logic-val-rule")).map(u=>{const p=u.querySelector(".fb-logic-val-type"),m=u.querySelector(".fb-logic-val-pattern"),g=u.querySelector(".fb-logic-val-flags"),f=u.querySelector(".fb-logic-val-message");if(!m?.value.trim())return null;const v=p?.value||"regex",w={type:v,message:f?.value.trim()||"Invalid value."};return v==="regex"?(w.pattern=m.value.trim(),g?.value.trim()&&(w.flags=g.value.trim())):w.field=m.value.trim(),w}).filter(Boolean);r.length>0&&(n.validation=r,i=!0)}const d=o.querySelector('[data-logic-section="cascade"]');if(d){const r=d.querySelector(".fb-logic-cascade-source"),u=d.querySelector(".fb-logic-cascade-mapping"),p=d.querySelector(".fb-logic-cascade-defaults"),m=r?.value?.trim();if(m){let g={};try{g=JSON.parse(u?.value||"{}")}catch{}const f=(p?.value||"").split(`
|
|
3
|
+
`).filter(v=>v.trim()).map(v=>{const[w,...L]=v.split(":");return{value:w.trim(),label:L.join(":").trim()||w.trim()}});n.cascade={sourceField:m,mapping:g,defaultOptions:f},i=!0}}return i?n:void 0}function V(){T=T.map((e,t)=>zn(t))}function jn(e){const t=e.firstElementChild;if(!t||t.querySelector(".fb-drag-grip"))return;const o=document.createElement("span");o.className="fb-drag-grip",o.setAttribute("data-icon","grip-vertical"),o.setAttribute("data-icon-size","16"),o.title="Drag to reorder",t.insertBefore(o,t.firstChild),window.I?.scan?.(t)}function ie(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()),T.length===0){o&&(o.style.display=""),ve?.(t),Ye();return}o&&(o.style.display="none"),T.forEach((n,i)=>{const a=n.type==="page-break"?Hn(n,i,e):n.type==="spacer"?Wn(n,i,e):Vn(n,i,e);jn(a),t.appendChild(a)}),ve?.(t),Ye()}}function Hn(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 i=document.createElement("div");i.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 s=document.createElement("span");s.textContent=e.label||"Untitled Step",s.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 l=document.createElement("div");l.style.cssText="display:flex;gap:.25rem;flex-shrink:0;margin-left:.5rem;";const d=document.createElement("button");d.className="btn btn-xs btn-ghost",d.title="Edit step",D(d,"more-horizontal"),d.addEventListener("click",g=>{g.stopPropagation(),u.style.display=u.style.display==="none"?"":"none"}),l.appendChild(d);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",D(r,"x"),r.addEventListener("click",async g=>{g.stopPropagation(),await E.confirm("Remove this page break?")&&(V(),T.splice(t,1),ie(o))}),l.appendChild(r),i.appendChild(a),i.appendChild(s),i.appendChild(l),i.addEventListener("click",()=>{u.style.display=u.style.display==="none"?"":"none"});const u=document.createElement("div");u.className="fb-field-body",u.style.cssText="padding:.8rem;border-top:1px dashed var(--dm-border);display:none;";const p=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")]),m=p.querySelector(`#fb-pb-label-${t}`);return sn(bi(p.querySelector(`#fb-pb-desc-${t}`))),m&&m.addEventListener("input",()=>{s.textContent=m.value||"Untitled Step"}),u.appendChild(p),n.appendChild(i),n.appendChild(u),n}function Wn(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 i=document.createElement("div");i.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 s=document.createElement("span");s.textContent="Spacer",s.style.cssText="font-size:.7rem;color:var(--dm-text-muted);white-space:nowrap;padding:0 .4rem;font-style:italic;";const l=document.createElement("div");l.style.cssText="flex:1;height:1px;background:var(--dm-border);";const d=document.createElement("div");d.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",D(r,"x"),r.addEventListener("click",async u=>{u.stopPropagation(),V(),T.splice(t,1),ie(o)}),d.appendChild(r),i.appendChild(a),i.appendChild(s),i.appendChild(l),i.appendChild(d),n.appendChild(i),n}function Vn(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 i=document.createElement("div");i.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=Bt(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 s=document.createElement("span");s.textContent=e.label||"(unlabelled)",s.style.cssText="flex:1;font-weight:600;font-size:.9rem;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;";const l=document.createElement("div");l.style.cssText="display:flex;gap:.25rem;flex-shrink:0;margin-left:.5rem;";const d=document.createElement("button");d.className="btn btn-xs btn-ghost",d.title="Edit field",D(d,"more-horizontal"),d.addEventListener("click",p=>{p.stopPropagation(),u.style.display=u.style.display==="none"?"":"none"}),l.appendChild(d);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",D(r,"x"),r.addEventListener("click",async p=>{p.stopPropagation(),await E.confirm("Remove this field?")&&(V(),T.splice(t,1),ie(o))}),l.appendChild(r),i.appendChild(a),i.appendChild(s),e.required){const p=document.createElement("span");p.textContent="required",p.style.cssText="font-size:.7rem;color:var(--dm-danger);flex-shrink:0;",i.appendChild(p)}if(Ot(e.logic)){const p=document.createElement("span");D(p,"zap"),p.title="Has conditional logic",p.style.cssText="font-size:.75rem;color:var(--dm-primary);flex-shrink:0;",i.appendChild(p)}i.appendChild(l),i.addEventListener("click",()=>{u.style.display=u.style.display==="none"?"":"none"});const u=Un(e,t,s);return u.style.display="none",n.appendChild(i),n.appendChild(u),n}function Un(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 i=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([gi("Type",`fb-type-${t}`,$t,e.type||"string"),Oe("Required",`fb-required-${t}`,e.required||!1)]),s=z([P("Placeholder",`fb-placeholder-${t}`,"text",e.placeholder||"","Hint text inside the field")]),l=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")]),d=z([P("CSS classes",`fb-class-${t}`,"text",e.class||"","Your own class names, separated by spaces, on the field's wrapper - style them in Custom CSS")]),r=e.formConfig?.span,u=z([P("Column Span",`fb-span-${t}`,"number",r&&r!=="full"?String(r):"1","Columns to span (grid only)"),Oe("Full Width",`fb-fullwidth-${t}`,r==="full")]);u.classList.add("fb-grid-row"),u.style.display=document.getElementById("setting-layout")?.value==="grid"?"flex":"none",n.appendChild(i),n.appendChild(a),n.appendChild(s),n.appendChild(l),n.appendChild(d),n.appendChild(u);const p=n.querySelector(`#fb-label-${t}`),m=n.querySelector(`#fb-name-${t}`);p&&p.addEventListener("input",()=>{o&&(o.textContent=p.value||"(unlabelled)"),m&&!m.dataset.manuallyEdited&&(m.value=Ft(p.value))}),m&&m.addEventListener("input",()=>{m.dataset.manuallyEdited="1"});const g=n.querySelector(`#fb-type-${t}`);g&&g.addEventListener("change",()=>{const v=n.closest(".fb-field-card");if(v){const x=v.querySelector("span");x&&(x.textContent=Bt(g.value))}const w=n.querySelector(".fb-field-extras");w&&w.remove();const L=Zt(g.value,e,t);L&&n.appendChild(L)});const f=Zt(e.type,e,t);return f&&n.appendChild(f),n.appendChild(Qn(e,t)),n.appendChild(oi(e,t)),n}const Le=[{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"}],Je=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 Xe(e){return!!e&&(e.type==="checkbox-group"||!!e.multiple)}function qe(e){const t=document.createElement("p");return t.textContent=e,t.appendChild(B({Visibility:"Choose whether this field starts visible or hidden, then add rules to show or hide it based on answers. The transition and speed control how it appears.","Conditional Requirement":"Make this field required or optional according to another answer. Hidden fields are not required.","Custom Validation":"Regex tests the answer against a regular expression; flags such as i make it case insensitive. Match field compares with another field name, such as password confirmation. Set the error message visitors see if the check fails.","Cascade Options":"Replace this field's choices according to another field's answer. Map source values to option lists and provide default options for unmatched or empty answers."}[e],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 $e(e,t,o){return e.style.flex=t,e.style.minWidth=o,e}function Ae(e,t,o,n,i){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 s=document.createElement("span");s.textContent="When",s.style.cssText="font-size:.73rem;color:var(--dm-text-muted);flex-shrink:0;";const l=document.createElement("select");l.className="form-select fb-logic-cond-field",l.style.cssText="width:100%;min-width:0;",t.forEach(f=>{const v=document.createElement("option");v.value=f.value,v.textContent=f.label,e&&f.value===e.field&&(v.selected=!0),l.appendChild(v)});const d=document.createElement("select");d.className="form-select fb-logic-cond-op",d.style.cssText="width:100%;min-width:0;",Le.forEach(f=>{const v=document.createElement("option");v.value=f.value,v.textContent=f.label,e&&f.value===e.operator&&(v.selected=!0),d.appendChild(v)});const r=()=>{const f=t.find(v=>v.value===l.value);Array.from(d.options).forEach(v=>{const w=Le.find(L=>L.value===v.value);v.textContent=f?.multi&&Mt[v.value]||w?.label||v.value})};r(),l.addEventListener("change",r);const u=document.createElement("input");u.type="text",u.className="form-input fb-logic-cond-val",u.placeholder="value",u.style.cssText="width:100%;min-width:0;",u.value=e?.value||"",d.addEventListener("change",()=>{(u.closest(".fb-trig-f")||u).style.display=Je.has(d.value)?"none":""});const p=document.createElement("span");D(p,"arrow-right"),p.style.cssText="font-size:.73rem;color:var(--dm-text-muted);flex-shrink:0;";const m=document.createElement("select");m.className=`form-select ${n}`,m.style.cssText="width:100%;min-width:0;",o.forEach(f=>{const v=document.createElement("option");v.value=f.value,v.textContent=f.label,f.value===i&&(v.selected=!0),m.appendChild(v)});const g=document.createElement("button");return g.type="button",g.className="btn btn-xs btn-ghost",g.style.cssText="line-height:1;opacity:.6;",D(g,"x"),g.style.flexShrink="0",g.addEventListener("click",()=>a.remove()),a.appendChild(s),a.appendChild($e(N("Field",l,{help:"The answer this rule tests. Select another named field from the form."}),"1 1 140px","140px")),a.appendChild($e(N("Comparison",d,{help:"How to compare the answer. Multi-choice fields test their selected values. Empty and not empty do not need a value."}),"1 1 160px","140px")),a.appendChild($e(N("Value",u,{help:"The stored value to compare against. For one of, enter comma-separated values. For regex, enter a regular expression."}),"1 1 120px","100px")),a.appendChild(p),a.appendChild($e(N("Result",m,{help:"What happens to this field when the condition matches: change its visibility or whether an answer is required."}),"1 1 140px","120px")),a.appendChild(g),e&&Je.has(e.operator)&&(u.closest(".fb-trig-f").style.display="none"),a}function Gn(e,t,o){const n=document.createElement("div");n.dataset.logicSection="visibility",n.appendChild(qe("Visibility"));const i=document.createElement("div");i.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 s=document.createElement("select");s.className="form-select fb-logic-vis-default",s.style.cssText="max-width:240px;",[{value:"visible",label:"Visible"},{value:"hidden",label:"Hidden"}].forEach(b=>{const C=document.createElement("option");C.value=b.value,C.textContent=b.label,b.value===(e.default||"visible")&&(C.selected=!0),s.appendChild(C)}),a.appendChild(B("Whether the field is visible before any rule matches.","Default visibility")),i.appendChild(a),i.appendChild(s),n.appendChild(i);const l=document.createElement("div");l.style.cssText="display:flex;align-items:center;gap:.6rem;margin-bottom:.65rem;flex-wrap:wrap;";const d=document.createElement("span");d.textContent="Transition:",d.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;",(window.FormLogicEngine?.FIELD_TRANSITIONS||[{value:"none",label:"None (instant)"},{value:"fade",label:"Fade"},{value:"slide",label:"Slide"},{value:"scale",label:"Scale"}]).forEach(b=>{const C=document.createElement("option");C.value=b.value,C.textContent=b.label,b.value===(e.transition||"none")&&(C.selected=!0),r.appendChild(C)}),d.appendChild(B("The animation used when this field appears or disappears, from a simple fade to a bubble pop. None switches instantly. Use Preview to try it.","Transition")),l.appendChild(d),l.appendChild(r),n.appendChild(l);const u=document.createElement("div");u.style.cssText="display:flex;align-items:center;gap:.6rem;margin-bottom:.65rem;flex-wrap:wrap;";const p=document.createElement("span");p.textContent="Speed:",p.style.cssText="font-size:.8rem;flex-shrink:0;";const m=document.createElement("select");m.className="form-select fb-logic-vis-duration",m.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(b=>{const C=document.createElement("option");C.value=b.value,C.textContent=b.label,b.value===String(e.duration??"")&&(C.selected=!0),m.appendChild(C)}),p.appendChild(B("How long the visibility animation lasts. Default uses the effect timing; shorter times are faster.","Speed")),u.appendChild(p),u.appendChild(m),n.appendChild(u);const g=document.createElement("button");g.type="button",g.className="btn btn-xs btn-ghost fb-logic-vis-preview",g.textContent="Preview";const f=document.createElement("span");f.className="fb-logic-vis-preview-chip",f.textContent="Sample field",f.style.cssText="display:inline-block;padding:.2rem .6rem;border:1px solid var(--dm-border);border-radius:var(--dm-radius, 6px);font-size:.75rem;background:var(--dm-surface);",g.addEventListener("click",()=>{window.FormLogicEngine?.previewTransition?.(f,r.value,m.value===""?void 0:Number(m.value))}),u.appendChild(g),u.appendChild(f);const v=()=>{u.style.display=r.value==="none"?"none":""};v(),r.addEventListener("change",v);const w=document.createElement("div");w.className="fb-logic-vis-rules";const L=o.map(b=>({value:b.name,label:b.label||b.name,multi:Xe(b)})),x=[{value:"visible",label:"Show"},{value:"hidden",label:"Hide"}];if((e.conditions||[]).forEach(b=>{const C=(b.when?.all||b.when?.any||[])[0],$=b.then==="hidden"?"hidden":"visible";L.length>0&&w.appendChild(Ae(C,L,x,"fb-logic-vis-then",$))}),n.appendChild(w),L.length>0){const b=document.createElement("button");b.type="button",b.className="btn btn-xs btn-ghost",b.style.cssText="font-size:.73rem;margin-top:.35rem;",be(b,"plus","Add visibility rule"),b.addEventListener("click",()=>w.appendChild(Ae(null,L,x,"fb-logic-vis-then","visible"))),n.appendChild(b)}return n}function Kn(e,t,o){const n=document.createElement("div");n.dataset.logicSection="requirement",n.appendChild(qe("Conditional Requirement"));const i=document.createElement("label");i.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,i.appendChild(a),i.appendChild(document.createTextNode("Required by default")),i.appendChild(B("Whether this field requires an answer before a conditional requirement rule matches.","Required by default")),n.appendChild(i);const s=document.createElement("div");s.className="fb-logic-req-rules";const l=o.map(r=>({value:r.name,label:r.label||r.name,multi:Xe(r)})),d=[{value:"true",label:"Make required"},{value:"false",label:"Make optional"}];if((e.conditions||[]).forEach(r=>{const u=(r.when?.all||r.when?.any||[])[0],p=r.then===!0?"true":"false";l.length>0&&s.appendChild(Ae(u,l,d,"fb-logic-req-then",p))}),n.appendChild(s),l.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;",be(r,"plus","Add requirement rule"),r.addEventListener("click",()=>s.appendChild(Ae(null,l,d,"fb-logic-req-then","true"))),n.appendChild(r)}return n}function Rt(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(l=>{const d=document.createElement("option");d.value=l.value,d.textContent=l.label,l.value===(e?.type||"regex")&&(d.selected=!0),o.appendChild(d)});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 i=document.createElement("input");i.type="text",i.className="form-input fb-logic-val-flags",i.placeholder="flags",i.value=e?.flags||"",i.style.cssText="flex:0 0 55px;",e?.type==="match"&&(i.style.display="none"),o.addEventListener("change",()=>{i.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 s=document.createElement("button");return s.type="button",s.className="btn btn-xs btn-ghost",s.style.cssText="line-height:1;opacity:.6;",D(s,"x"),s.style.flexShrink="0",s.addEventListener("click",()=>t.remove()),t.appendChild(N("Validation",o,{help:"Regex checks a pattern. Match field requires the same answer as another named field."})),t.appendChild(N("Pattern or field name",n,{help:"For Regex, enter a regular expression without enclosing slashes. For Match field, enter the other field name, such as password."})),t.appendChild(N("Flags",i,{help:"Optional regular expression flags, such as i for case insensitive matching. Applies only to Regex."})),t.appendChild(N("Error message",a,{help:"The explanation visitors see when the answer fails this validation rule."})),t.appendChild(s),t}function Yn(e,t,o){const n=document.createElement("div");n.dataset.logicSection="validation",n.appendChild(qe("Custom Validation"));const i=document.createElement("div");i.className="fb-logic-val-rules",(e||[]).forEach(s=>i.appendChild(Rt(s))),n.appendChild(i);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;",be(a,"plus","Add validation rule"),a.addEventListener("click",()=>i.appendChild(Rt(null))),n.appendChild(a),n}function Jn(e,t,o){const n=document.createElement("div");n.dataset.logicSection="cascade",n.appendChild(qe("Cascade Options")),n.lastChild.appendChild(B("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 i=document.createElement("div");i.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 s=document.createElement("select");s.className="form-select fb-logic-cascade-source",s.style.cssText="flex:1;";const l=document.createElement("option");l.value="",l.textContent="- none -",s.appendChild(l),o.forEach(m=>{const g=document.createElement("option");g.value=m.name,g.textContent=m.label||m.name,m.name===e.sourceField&&(g.selected=!0),s.appendChild(g)}),i.appendChild(a),i.appendChild(s),n.appendChild(i);const d=document.createElement("p");d.textContent='Mapping JSON - {"value":[{"value":"...","label":"..."}]}',d.appendChild(B(`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".`)),d.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):"",n.appendChild(d),n.appendChild(r);const u=document.createElement("p");u.textContent="Default options (one per line: value:Label)",u.appendChild(B("Shown before the source field has a value, or when its value has no mapping entry.")),u.style.cssText="font-size:.73rem;color:var(--dm-text-muted);margin:.3rem 0 .2rem;";const p=document.createElement("textarea");return p.className="form-input fb-logic-cascade-defaults",p.rows=3,p.style.cssText="font-family:monospace;",p.placeholder=`option1:Option 1
|
|
4
4
|
option2:Option 2`,p.value=(e.defaultOptions||[]).map(m=>{const g=typeof m=="string"?m:m.value??"",f=typeof m=="string"?m:m.label??g;return g===f?g:`${g}:${f}`}).join(`
|
|
5
|
-
`),n.appendChild(d),n.appendChild(p),n}function Mt(){return window.FormLogicEngine?.FIELD_TRANSITIONS||[{value:"none",label:"None (instant)"}]}function Rt(e){const t=(e.find("#setting-entrance").val()||"none")==="none";e.find("#setting-entrance-speed-group").get(0).style.display=t?"none":"",e.find("#setting-entrance-preview-group").get(0).style.display=t?"none":""}function Qe(e,t){const o=e.find("#setting-entrance").get(0);if(!o)return;o.options.length||(Mt().forEach(i=>{const a=document.createElement("option");a.value=i.value,a.textContent=i.label,o.appendChild(a)}),o.addEventListener("change",()=>Rt(e)),e.find("#setting-entrance-preview").get(0)?.addEventListener("click",()=>{const i=e.find("#setting-entrance-duration").val();window.FormLogicEngine?.animateIn?.(e.find("#setting-entrance-sample").get(0),o.value,i===""?void 0:Number(i))}));const n=t?.entrance||"none";o.value=Mt().some(i=>i.value===n)?n:"none",e.find("#setting-entrance-duration").val(t?.entranceDuration!=null?String(t.entranceDuration):""),Rt(e)}function Vn(e){const t=e.find("#setting-entrance").val()||"none";if(t==="none")return{};const o=parseInt(e.find("#setting-entrance-duration").val()||"",10);return{entrance:t,...Number.isFinite(o)&&{entranceDuration:o}}}function Un(e,t){const o=e.logic||{},n=T.filter((p,m)=>m!==t&&p.type!=="page-break"&&p.type!=="spacer"),i=document.createElement("div");i.className="fb-field-logic",i.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 s=document.createElement("span");s.style.cssText="font-size:.8rem;font-weight:600;color:var(--dm-text-muted);",s.textContent="\u26A1 Conditional Logic";const l=Bt(o),u=document.createElement("button");u.type="button",u.className="btn btn-xs btn-ghost",O(u,l?"chevron-down":"chevron-right",12);const r=document.createElement("div");r.className="fb-logic-body",r.style.cssText="padding:.25rem 0 .25rem;"+(l?"":"display:none;"),a.addEventListener("click",()=>{const p=r.style.display==="none";r.style.display=p?"":"none",O(u,p?"chevron-down":"chevron-right",12)}),a.appendChild(s),a.appendChild(u),i.appendChild(a),r.appendChild(Pn(o.visibility||{},t,n)),r.appendChild(jn(o.requirement||{},t,n)),r.appendChild(Wn(o.validation||[],t,n));const d=document.getElementById(`fb-type-${t}`)?.value||e.type;return Ge.has(d)&&r.appendChild(Hn(o.cascade||{},t,n)),i.appendChild(r),i}const xe=[{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"}],Ae=[{value:"info",label:"Info"},{value:"success",label:"Success"},{value:"warning",label:"Warning"},{value:"error",label:"Error"}],Dt=[{value:"field-below",label:"Below this field"},{value:"field-above",label:"Above this field"},{value:"form-top",label:"Top of the form"}],_t=[{value:"rest",label:"The rest of the form"},{value:"all",label:"Every other field"},{value:"listed",label:"Chosen fields"}],zt=[{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 Pt(e,t=!1){const o=(s,l)=>({value:s.name,label:`${s.label||s.name}${l?" (this field)":""}`,multi:Xe(s)}),n=s=>s&&s.type!=="page-break"&&s.type!=="spacer"&&s.name,i=T.filter((s,l)=>l!==e&&n(s)).map(s=>o(s,!1)),a=T[e];return t&&n(a)?[o(a,!0),...i]:i}function Q(e,t,o){const n=document.createElement("select");return n.className=`form-select ${e}`,t.forEach(i=>{const a=document.createElement("option");a.value=i.value,a.textContent=i.label,i.value===o&&(a.selected=!0),n.appendChild(a)}),n}function re(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 Ze(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)),O(o,"x"),o.addEventListener("click",n=>{n.stopPropagation(),e()}),o}function L(e,t,{full:o=!1,hint:n="",help:i=""}={}){const a=document.createElement("label");a.className=`fb-trig-f${o?" fb-trig-f--full":""}`,a.style.flex="1";const s=document.createElement("span");if(s.className="fb-trig-f-label",s.textContent=e,(i||n||ye[e])&&s.appendChild(B(i||n||ye[e],e)),a.appendChild(s),a.appendChild(t),n){const l=document.createElement("span");l.className="fb-trig-f-hint",l.textContent=n,a.appendChild(l)}return a}function we(e,t,o,n){const i=document.createElement("label");i.className="fb-trig-check";const a=document.createElement("input");return a.type="checkbox",a.className=`form-check ${e}`,a.checked=!!t,i.appendChild(a),i.appendChild(document.createTextNode(o)),i.appendChild(B(n||"Allow the visitor to close this banner while the condition holds. It can appear again when the condition becomes true again.",o)),i}function jt(e,t){const o=document.createElement("div");o.className="fb-trig-cond-row";const n=Q("fb-trig-cond-field",t,e?.field),i=Q("fb-trig-cond-op",Ne,e?.operator),a=re("fb-trig-cond-val",e?.value,"value"),s=L("Value",a,{help:"Compare with the stored value. For one of, separate values with commas; for regex, enter a regular expression."}),l=()=>{const r=t.find(d=>d.value===n.value);Array.from(i.options).forEach(d=>{const p=Ne.find(m=>m.value===d.value);d.textContent=r?.multi&&It[d.value]||p?.label||d.value})},u=()=>{s.hidden=Je.has(i.value)};return l(),u(),n.addEventListener("change",l),i.addEventListener("change",u),o.appendChild(L("Field",n,{help:"The answer to test, including this field or another named field."})),o.appendChild(L("Comparison",i,{help:"How to compare the answer. Multi-choice fields test their selected values. Empty and not empty need no comparison value."})),o.appendChild(s),o.appendChild(Ze(()=>o.remove(),"Remove condition")),o}const Wt=["banner","toast","block-submit","end-form"],Ht=["password","file","image","signature"],Gn="Put an answer in with {{field_name}} - e.g. Hello {{name}}. Pick one from Insert field.";function Kn(){try{H()}catch{}return T.filter(e=>e&&e.name&&e.type!=="page-break"&&e.type!=="spacer"&&!Ht.includes(e.type))}function Vt(e,t,o){const n=re(e,t,o),i=document.createElement("span");i.className="fb-token-row";const a=document.createElement("select");a.className="form-input fb-token-pick",a.title="Insert an answer into the message",a.setAttribute("aria-label","Insert a field's answer into the message");const s=()=>{a.replaceChildren(new Option("Insert field",""));for(const l of Kn())a.appendChild(new Option(`${l.label||l.name} ({{${l.name}}})`,l.name))};return s(),a.addEventListener("focus",s),a.addEventListener("mousedown",s),a.addEventListener("change",()=>{const l=a.value;if(a.value="",!l)return;const u=`{{${l}}}`,r=n.selectionStart??n.value.length,d=n.selectionEnd??r;n.value=n.value.slice(0,r)+u+n.value.slice(d),n.focus(),n.setSelectionRange(r+u.length,r+u.length),n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))}),i.append(n,a),i}function Yn(e){const t=window.FormLogicEngine;if(!t?.triggerTokens)return[];const o=new Map((e||[]).filter(i=>i&&i.name).map(i=>[i.name,i])),n=new Set;for(const i of e||[])for(const a of i?.triggers||[])for(const s of[...a.then||[],...a.otherwise||[]])if(Wt.includes(s?.type))for(const l of[...t.triggerTokens(s.message),...t.triggerTokens(s.doneMessage)]){const u=o.get(l);(!u||Ht.includes(u.type))&&n.add(l)}return[...n]}function Ut(e,t){const o=document.createElement("div");o.className="fb-trig-params";const n=xe.find(u=>u.value===(e.type||"banner"));if(!n)return o;const i=document.createElement("div");i.className="fb-trig-grid";const a=document.createElement("div");a.className="fb-trig-opts";const s=[];for(const u of n.params)switch(u){case"message":i.appendChild(Wt.includes(n.value)?L(n.messageLabel||"Message",Vt("fb-trig-p-message",e.message,n.placeholder||""),{full:!0,hint:Gn,help:ye[n.messageLabel||"Message"]}):L(n.messageLabel||"Message",re("fb-trig-p-message",e.message,n.placeholder||""),{full:!0}));break;case"finish":a.appendChild(we("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 r=L("Button text",re("fb-trig-p-finish",e.finishLabel,"Finish"));s.push(r),i.appendChild(r);break}case"doneMessage":{const r=L("Closing message",Vt("fb-trig-p-done",e.doneMessage,"Blank: the form's own success message"));s.push(r),i.appendChild(r);break}case"record":{const r=we("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.`);s.push(r),a.appendChild(r);break}case"level":i.appendChild(L(n.value==="notify"?"Severity":"Level",Q("fb-trig-p-level",Ae,e.level||"info")));break;case"position":i.appendChild(L("Where",Q("fb-trig-p-position",Dt,e.position||"field-below")));break;case"dismissible":a.appendChild(we("fb-trig-p-dismissible",e.dismissible!==!1,"The visitor can dismiss it"));break;case"target":{const r=Q("fb-trig-p-target",_t,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 p=new Set(e.fields||[]);Pt(t).forEach(f=>{const v=document.createElement("option");v.value=f.value,v.textContent=f.label,p.has(f.value)&&(v.selected=!0),d.appendChild(v)});const m=L("Fields",d,{hint:"Ctrl/Cmd-click to pick several",help:ye.Fields}),g=()=>{m.hidden=r.value!=="listed"};g(),r.addEventListener("change",g),i.appendChild(L("Which fields",r)),i.appendChild(m);break}case"step":{const r=re("fb-trig-p-step",e.step,"0");r.type="number",r.min="0",i.appendChild(L("Step",r,{hint:"Counting from 0",help:ye.Step}));break}case"url":i.appendChild(L("Send them to",re("fb-trig-p-url",e.url,"/thank-you"),{full:!0}));break;case"theme":i.appendChild(L("Theme",Q("fb-trig-p-theme",zt,e.theme||"auto")));break;case"intensity":i.appendChild(L("Intensity",Q("fb-trig-p-intensity",[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}],e.intensity||"medium")));break;case"slug":{const r=[{value:"",label:ke.length?"Choose an action":"No actions available"}].concat(ke.map(d=>({value:d.slug,label:d.title||d.slug})));i.appendChild(L("Action",Q("fb-trig-p-slug",r,e.slug||""),{full:!0,help:"The CMS action to run after a matching submission is saved. Choose an action defined under Data > Actions. Requires Pro with MongoDB."}));break}default:break}n.kind==="event"&&!n.noOnce&&a.appendChild(we("fb-trig-p-once",!!e.once,"Only once","Fire the first time only, rather than every time the answer swings back."));const l=a.querySelector(".fb-trig-p-finish-on");if(l){const u=()=>s.forEach(r=>{r.hidden=!l.checked});u(),l.addEventListener("change",u)}return i.children.length&&o.appendChild(i),a.children.length&&o.appendChild(a),o}function Jn(e){return e?.kindText?e.kindText:e?.kind==="event"?"once, when it becomes true":"while it is true"}const Xn=(e,t=48)=>e.length>t?`${e.slice(0,t-1)}\u2026`:e,ce=(e,t)=>e.find(o=>o.value===t)?.label||t;function Qn(e){if(!e)return"";const t=[],o=i=>i?`"${Xn(i)}"`:"",n=()=>e.target==="listed"?e.fields?.length?e.fields.join(", "):"no fields chosen":ce(_t,e.target||"rest").toLowerCase();switch(e.type){case"banner":t.push(o(e.message)||"No message yet",ce(Ae,e.level||"info"),ce(Dt,e.position||"field-below").toLowerCase());break;case"toast":t.push(o(e.message)||"No message yet",ce(Ae,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(ce(zt,e.theme||"auto"),`${e.intensity||"medium"} intensity`);break;case"run-action":t.push(e.slug?ke.find(i=>i.slug===e.slug)?.title||e.slug:"no action chosen");break;case"notify":t.push(o(e.message)||"titled after the form",ce(Ae,e.level||"info"));break;default:break}return e.once&&t.push("only once"),t.filter(Boolean).join(" \xB7 ")}function et(e,t,{open:o=!1}={}){const n=document.createElement("div");n.className="fb-trig-action-row";const i=document.createElement("div");i.className="fb-trig-action-head",i.tabIndex=0,i.setAttribute("role","button");const a=document.createElement("span");a.className="fb-trig-chevron";const s=document.createElement("span");s.className="fb-trig-action-main";const l=document.createElement("strong"),u=document.createElement("small");u.className="fb-trig-action-summary",s.append(l,u);const r=document.createElement("span");r.className="fb-trig-kind",i.append(a,s,r,Ze(()=>n.remove(),"Remove action"));const d=document.createElement("div");d.className="fb-trig-action-body";const p=Q("fb-trig-action-type",xe,e.type||"banner");d.appendChild(L("Action",p,{full:!0})),d.appendChild(Ut(e,t));const m=()=>{const f=xe.find(v=>v.value===p.value);l.textContent=f?.label||p.value,r.textContent=Jn(f),r.classList.toggle("fb-trig-kind--event",f?.kind==="event"),u.textContent=Qn(Jt(n))},g=f=>{d.hidden=!f,n.classList.toggle("is-open",f),i.setAttribute("aria-expanded",String(f)),O(a,f?"chevron-down":"chevron-right",12)};return i.addEventListener("click",()=>g(d.hidden)),i.addEventListener("keydown",f=>{f.target!==i||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),g(d.hidden))}),p.addEventListener("change",()=>{const f=Ut({type:p.value},t);d.replaceChild(f,d.querySelector(".fb-trig-params")),m(),window.I?.scan?.()}),d.addEventListener("input",m),d.addEventListener("change",m),n.append(i,d),g(o),m(),n}function Gt(e,t,o){const n=document.createElement("section");n.className=`fb-trig-sec fb-trig-sec--${e}`;const i=document.createElement("div");i.className="fb-trig-sec-head";const a=document.createElement("span");if(a.className="fb-trig-sec-title",a.textContent=t,a.appendChild(B({When:"Choose the answers to test. All requires every condition to match; Any requires at least one. Compare stored option values, not their display labels.",Then:"Actions applied when the conditions match.",Otherwise:"Optional actions applied when the conditions do not match. Leave empty to do nothing in this branch."}[t],t)),i.appendChild(a),o){const s=document.createElement("span");s.className="fb-trig-sec-hint",s.textContent=o,i.appendChild(s)}return n.appendChild(i),n}function tt(e,t){const o=document.createElement("button");return o.type="button",o.className="btn btn-xs btn-ghost fb-trig-add",be(o,"plus",e,12),o.addEventListener("click",t),o}function Kt(e,t,o,n){const a=Gt(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 s=document.createElement("div");return s.className="fb-trig-action-list",(o||[]).forEach(l=>s.appendChild(et(l,n))),a.appendChild(s),a.appendChild(tt("Add action",()=>{s.appendChild(et({type:"banner"},n,{open:!0})),window.I?.scan?.()})),a}function Yt(e,t,o){const n=Pt(t,!0),i=document.createElement("div");i.className="fb-trig-card",i.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 s=document.createElement("span");s.className="fb-trig-card-title",s.textContent=`Trigger ${o+1}`,a.appendChild(s);const l=we("fb-trig-enabled",e.enabled!==!1,"Enabled","Untick to keep the trigger but switch it off.");if(a.appendChild(l),a.appendChild(Ze(()=>i.remove(),"Remove trigger")),i.appendChild(a),!n.length){const p=document.createElement("p");return p.className="fb-trig-empty",p.textContent="Give this field a name first - a trigger tests an answer, and it needs something to test.",i.appendChild(p),i}const u=Gt("when","When");u.querySelector(".fb-trig-sec-head").appendChild(Q("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 r=document.createElement("div");r.className="fb-trig-cond-list";const d=e.when?.all||e.when?.any||[];return(d.length?d:[{}]).forEach(p=>r.appendChild(jt(p,n))),u.appendChild(r),u.appendChild(tt("Add condition",()=>{r.appendChild(jt({},n)),window.I?.scan?.()})),i.appendChild(u),i.appendChild(Kt("then","Then",e.then,t)),i.appendChild(Kt("otherwise","Otherwise",e.otherwise,t)),i}function Zn(e,t){const o=Array.isArray(e.triggers)?e.triggers:[],n=document.createElement("div");n.className="fb-field-triggers";const i=document.createElement("div");i.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})`:""}`,a.appendChild(B("Triggers test answers and choose a Then or Otherwise branch. Add conditions and actions below. Enabled switches a trigger on without deleting its settings.","Triggers"));const s=document.createElement("button");s.type="button",s.className="btn btn-xs btn-ghost",O(s,o.length?"chevron-down":"chevron-right",12);const l=document.createElement("div");l.className="fb-triggers-body",l.hidden=!o.length,i.addEventListener("click",()=>{l.hidden=!l.hidden,O(s,l.hidden?"chevron-right":"chevron-down",12)});const u=document.createElement("p");u.className="fb-trig-blurb",u.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.",l.appendChild(u);const r=document.createElement("div");return r.className="fb-trig-list",o.forEach((d,p)=>r.appendChild(Yt(d,t,p))),l.appendChild(r),l.appendChild(tt("Add trigger",()=>{const d=Yt({enabled:!0,then:[]},t,r.children.length);r.appendChild(d),d.querySelector('.fb-trig-branch[data-branch="then"] .fb-trig-action-list')?.appendChild(et({type:"banner"},t,{open:!0})),window.I?.scan?.()})),i.appendChild(a),i.appendChild(s),n.appendChild(i),n.appendChild(l),n}function Jt(e){const t=e.querySelector(".fb-trig-action-type")?.value,o=xe.find(a=>a.value===t);if(!o)return null;const n={type:t},i=a=>e.querySelector(a)?.value?.trim()||"";for(const a of o.params)switch(a){case"message":n.message=i(".fb-trig-p-message");break;case"finishLabel":{const s=i(".fb-trig-p-finish");s&&(n.finishLabel=s);break}case"doneMessage":{const s=i(".fb-trig-p-done");s&&(n.doneMessage=s);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=i(".fb-trig-p-level")||"info";break;case"position":n.position=i(".fb-trig-p-position")||"field-below";break;case"dismissible":n.dismissible=!!e.querySelector(".fb-trig-p-dismissible")?.checked;break;case"target":{const s=i(".fb-trig-p-target")||"rest";n.target=s,s==="listed"&&(n.fields=Array.from(e.querySelectorAll(".fb-trig-p-fields option")).filter(l=>l.selected).map(l=>l.value));break}case"step":{const s=parseInt(i(".fb-trig-p-step"),10);Number.isFinite(s)&&(n.step=s);break}case"url":n.url=i(".fb-trig-p-url");break;case"theme":n.theme=i(".fb-trig-p-theme")||"auto";break;case"intensity":n.intensity=i(".fb-trig-p-intensity")||"medium";break;case"slug":n.slug=i(".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 ei(e){const t=Jt(e);if(!t)return null;const o=xe.find(a=>a.value===t.type),n=t.type,i=["block-submit","end-form","notify"].includes(o.value);return o.params.includes("message")&&!t.message&&!i?(delete t.message,null):(i&&!t.message&&delete t.message,n==="redirect"&&!t.url||n==="run-action"&&!t.slug?null:t)}function ti(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(i=>{const a=Array.from(i.querySelectorAll(".fb-trig-cond-row")).map(p=>{const m=p.querySelector(".fb-trig-cond-field")?.value,g=p.querySelector(".fb-trig-cond-op")?.value;if(!m||!g)return null;const f=p.querySelector(".fb-trig-cond-val")?.value??"";return{field:m,operator:g,value:f}}).filter(Boolean);if(!a.length)return;const s=p=>Array.from(i.querySelectorAll(`.fb-trig-branch[data-branch="${p}"] .fb-trig-action-row`)).map(ei).filter(Boolean),l=s("then"),u=s("otherwise");if(!l.length&&!u.length)return;const r=i.querySelector(".fb-trig-match")?.value==="any"?"any":"all",d={id:i.dataset.triggerId,enabled:!!i.querySelector(".fb-trig-enabled")?.checked,when:{[r]:a}};l.length&&(d.then=l),u.length&&(d.otherwise=u),n.push(d)}),n.length?n:void 0}function Xt(e,t,o){const n=document.createElement("div");if(n.className="fb-field-extras",e==="chooser")n.appendChild(ai(t,o)),n.appendChild(si(t.options||[],o));else if(Ge.has(e)&&n.appendChild(ui(t.options||[],o)),e==="textarea"&&n.appendChild(_([P("Rows",`fb-rows-${o}`,"number",t.formConfig?.rows||4,"Height of textarea")])),(e==="string"||e==="textarea")&&n.appendChild(_([P("Min Length",`fb-minlength-${o}`,"number",t.minLength||"",""),P("Max Length",`fb-maxlength-${o}`,"number",t.maxLength||"","")])),e==="number"&&n.appendChild(_([P("Min",`fb-min-${o}`,"number",t.min??"",""),P("Max",`fb-max-${o}`,"number",t.max??"","")])),e==="file"){const i=P("Most files",`fb-file-max-${o}`,"number",t.file?.maxFiles||"",`${vt} when left empty, ${He} at most`),a=i.querySelector("input");a.min="1",a.max=String(He),a.placeholder=String(vt);const s=Oe("Several files",`fb-file-multiple-${o}`,!!t.multiple),l=()=>{i.hidden=!s.querySelector("input").checked};s.querySelector("input").addEventListener("change",l),l(),n.appendChild(_([i,s]))}return Qt.includes(e)&&n.appendChild(ii(t,o)),n.children.length?n:null}const Qt=["string","email","tel","number","url","date","time","password","select","textarea"],nt=[{key:"reveal",label:"Show / hide button",types:["password"],hint:"Show / hide lets the visitor see what they typed."},{key:"clear",label:"Clear button",types:["string","email","tel","url","textarea"],hint:"Clear adds an x that empties the field."},{key:"stepper",label:"- / + buttons",types:["number"],hint:"The - and + buttons step the number within its min, max and step."},{key:"counter",label:"Character counter",types:["string","textarea"],hint:"The counter shows how many characters are used, against Max Length if one is set."}];function ni(e){return e?typeof e=="string"?{icon:"",text:e}:{icon:e.icon||"",text:e.icon?"":e.text??""}:{icon:"",text:""}}function ii(e,t){const o=document.createElement("div");o.className="fb-addons";const n=(s,l)=>{const u=ni(e.formConfig?.[s]),r=document.createElement("div");r.style.flex="1";const d=document.createElement("span");d.className="form-label",d.style.fontSize=".8rem",d.textContent=l,d.appendChild(B("An icon or short text joined to this side of the input, such as a currency symbol or unit. Choose an icon or enter text; leave both blank for none.",l));const p=We("Icon, e.g. search",u.icon);p.input.id=`fb-${s}-icon-${t}`,p.input.setAttribute("aria-label",`${l}: icon`);const m=document.createElement("input");return m.type="text",m.className="form-input",m.id=`fb-${s}-text-${t}`,m.value=u.text,m.placeholder="or text, e.g. \xA3 or kg",m.maxLength=24,m.setAttribute("aria-label",`${l}: text`),m.style.marginTop=".35rem",p.input.addEventListener("input",()=>{p.input.value.trim()&&(m.value="")}),m.addEventListener("input",()=>{m.value.trim()&&(p.input.value="")}),r.append(d,p.el,m),r};o.appendChild(_([n("prefix","Before the field"),n("suffix","After the field")]));const i=document.createElement("p");i.className="form-hint text-muted",i.style.cssText="font-size:.73rem;margin:-.4rem 0 .75rem;",i.textContent="An icon or a short text joined to the start or end of the input, like \xA3 before a price or kg after a weight. Leave both empty for none.",o.appendChild(i);const a=nt.filter(s=>s.types.includes(e.type));if(a.length){o.appendChild(_(a.map(l=>Oe(l.label,`fb-extra-${l.key}-${t}`,!!e.formConfig?.[l.key]))));const s=document.createElement("p");s.className="form-hint text-muted",s.style.cssText="font-size:.73rem;margin:-.4rem 0 .75rem;",s.textContent=a.map(l=>l.hint).join(" "),o.appendChild(s)}return o}function Zt(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 Be(e,t,o,n,i){const a=document.createElement("div");a.style.flex="1";const s=document.createElement("label");s.htmlFor=e,s.className="form-label",s.textContent=t,i&&s.appendChild(B(i,t)),s.style.fontSize=".8rem";const l=document.createElement("select");if(l.id=e,l.className="form-input",n.forEach(([u,r])=>{const d=document.createElement("option");d.value=u,d.textContent=r,String(u)===String(o)&&(d.selected=!0),l.appendChild(d)}),a.appendChild(s),a.appendChild(l),i){const u=document.createElement("p");u.className="form-hint text-muted",u.textContent=i,u.style.cssText="font-size:.72rem;margin-top:.2rem;",a.appendChild(u)}return a}function en(e,t,o,n){const i=document.createElement("div");i.style.flex="1";const a=document.createElement("label");a.style.cssText="display:inline-flex;align-items:center;gap:.4rem;font-size:.82rem;";const s=document.createElement("input");if(s.id=e,s.type="checkbox",s.checked=!!o,a.appendChild(s),a.appendChild(document.createTextNode(" "+t)),n&&a.appendChild(B(n,t)),i.appendChild(a),n){const l=document.createElement("p");l.className="form-hint text-muted",l.textContent=n,l.style.cssText="font-size:.72rem;margin-top:.2rem;",i.appendChild(l)}return i}function it(e,t,o,n,i){const a=document.createElement("div");a.style.flex="1";const s=document.createElement("label");s.htmlFor=e,s.className="form-label",s.textContent=t,i&&s.appendChild(B(i,t)),s.style.fontSize=".8rem",a.appendChild(s);const l=document.createElement("div");l.style.cssText="display:flex;gap:.4rem;align-items:stretch;";const u=document.createElement("input");u.id=e,u.type="text",u.className="form-input",u.value=o||"",n&&(u.placeholder=n),u.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 d=String(u.value).match(/^#[0-9a-fA-F]{3,8}$/);if(r.value=d?u.value:"#000000",r.addEventListener("input",()=>{u.value=r.value,u.dispatchEvent(new Event("input",{bubbles:!0}))}),l.appendChild(u),l.appendChild(r),a.appendChild(l),i){const p=document.createElement("p");p.className="form-hint text-muted",p.textContent=i,p.style.cssText="font-size:.72rem;margin-top:.2rem;",a.appendChild(p)}return a}function ai(e,t){const o=document.createElement("div");o.style.cssText="margin-top:.5rem; display:flex; flex-direction:column; gap:.4rem;";const n=Zt("Layout");n.body.appendChild(_([Be(`fb-chooser-variant-${t}`,"Variant",e.variant||"card",[["card","Card - rich tiles"],["chip","Chip - compact pills"]],"Card supports description and grid columns; chips wrap."),en(`fb-chooser-multiple-${t}`,"Multi-select",!!e.multiple,"Off = single (radio); on = multi (checkbox).")])),n.body.appendChild(_([Be(`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 i=Zt("Visual");return i.body.appendChild(_([it(`fb-chooser-accent-${t}`,"Accent",e.accent||"","primary / success / #ec4899","Selected highlight colour - semantic name or any CSS colour."),Be(`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.")])),i.body.appendChild(_([en(`fb-chooser-glow-${t}`,"Glow on selected",!!e.glow,"Soft outer glow."),it(`fb-chooser-glow-colour-${t}`,"Glow colour",e.glowColour||"","defaults to accent","Optional; semantic name or CSS colour.")])),i.body.appendChild(_([Be(`fb-chooser-shadow-${t}`,"Shadow",e.shadow||"none",[["none","None"],["sm","Small"],["md","Medium"],["lg","Large"],["xl","Extra Large"]],"Drop shadow on every option."),it(`fb-chooser-shadow-colour-${t}`,"Shadow colour",e.shadowColour||"","rgba(0,0,0,0.1)","Optional shadow tint.")])),o.appendChild(i.wrap),o}function oi(e,t,o,n){const i=document.createElement("div");i.className="fb-chooser-option-row",i.dataset.optIdx=String(o),i.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 s=document.createElement("div");s.style.cssText="display:flex; flex-direction:column; gap:1px;";const l=document.createElement("button");l.type="button",l.className="btn btn-xs btn-ghost",l.title="Move up",O(l,"arrow-up"),l.addEventListener("click",j=>{j.preventDefault(),tn(t,o,-1,n)});const u=document.createElement("button");u.type="button",u.className="btn btn-xs btn-ghost",u.title="Move down",O(u,"arrow-down"),u.addEventListener("click",j=>{j.preventDefault(),tn(t,o,1,n)}),s.appendChild(l),s.appendChild(u),a.appendChild(s);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(L("Value",r,{help:"The value stored with the submission and compared by trigger conditions. Keep it unique within this field."}));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(L("Label",d,{help:"The choice text visitors see. The stored value can be different."}));const p=document.createElement("button");p.type="button",p.className="btn btn-xs btn-ghost",p.style.cssText="line-height:1;opacity:.6;",p.title="Remove option",O(p,"x"),p.addEventListener("click",j=>{j.preventDefault(),ci(t,o,n)}),a.appendChild(p),i.appendChild(a);const m=document.createElement("div");m.style.cssText="display:flex; gap:.4rem;";const g=We("icon name (optional)",e.icon||"");g.input.classList.add("fb-chooser-opt-icon"),g.el.style.flex="1",m.appendChild(L("Icon",g.el,{help:"An optional icon for this choice. Browse for an icon or leave blank for none."}));const f=document.createElement("input");f.type="text",f.className="form-input fb-chooser-opt-description",f.placeholder="description (card + comfortable only)",f.value=e.description||"",f.style.flex="2",m.appendChild(L("Description",f,{help:"Extra explanation shown by the card variant at comfortable density."})),i.appendChild(m);const v=document.createElement("div");v.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",v.appendChild(L("Tooltip",w,{help:"An optional hover hint for this choice."}));const N=document.createElement("input");N.type="text",N.className="form-input fb-chooser-opt-badge-text",N.placeholder="badge text",N.value=e.badge?.text||"",N.style.flex="1",v.appendChild(L("Badge text",N,{help:"A short badge label attached to this choice. Leave blank for no badge."}));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(([j,Y])=>{const U=document.createElement("option");U.value=j,U.textContent=Y,(e.badge?.type||"")===j&&(U.selected=!0),x.appendChild(U)}),v.appendChild(L("Badge style",x,{help:"The theme colour used for the badge."})),i.appendChild(v);const b=document.createElement("div");b.style.cssText="display:flex; gap:1rem; font-size:.8rem;";const C=document.createElement("label");C.style.cssText="display:inline-flex;align-items:center;gap:.3rem;";const $=document.createElement("input");$.type="checkbox",$.className="fb-chooser-opt-recommended",$.checked=!!e.recommended,C.appendChild($),C.appendChild(document.createTextNode(" Recommended")),C.appendChild(B("Highlight this choice as recommended. This does not select it automatically.","Recommended")),b.appendChild(C);const z=document.createElement("label");z.style.cssText="display:inline-flex;align-items:center;gap:.3rem;";const V=document.createElement("input");return V.type="checkbox",V.className="fb-chooser-opt-disabled",V.checked=!!e.disabled,z.appendChild(V),z.appendChild(document.createTextNode(" Disabled")),z.appendChild(B("Show this choice but prevent the visitor from selecting it.","Disabled")),b.appendChild(z),i.appendChild(b),i}function si(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 i=document.createElement("p");i.textContent="Options",i.appendChild(B("Each option has a stored value and a label shown to visitors. Keep values unique and use them in trigger conditions. Add an icon, description, tooltip or badge to explain a choice. Recommended highlights an option; Disabled prevents selection.","Chooser options")),i.style.cssText="font-size:.85rem;font-weight:600;margin:0;",n.appendChild(i);const a=document.createElement("button");a.type="button",a.className="btn btn-xs btn-ghost",be(a,"plus","Add option"),n.appendChild(a),o.appendChild(n);const s=document.createElement("div");s.className="fb-chooser-options-list",s.id=`fb-chooser-options-${t}`,s.style.cssText="display:flex; flex-direction:column; gap:.4rem;",o.appendChild(s);const l=()=>{s.replaceChildren();const u=li(t);(u.length?u:e||[]).forEach((d,p)=>{s.appendChild(oi(d,t,p,l))})};return a.addEventListener("click",u=>{u.preventDefault(),ri(t,l)}),l(),o}function li(e){const t=T[e];return!t||!Array.isArray(t.options)?[]:t.options}function at(e){return T[e]?(Array.isArray(T[e].options)||(T[e].options=[]),T[e].options):[]}function ri(e,t){Ie(e),at(e).push({value:"new",label:"New option"}),t()}function ci(e,t,o){Ie(e),at(e).splice(t,1),o()}function tn(e,t,o,n){Ie(e);const i=at(e),a=t+o;if(a<0||a>=i.length)return;const[s]=i.splice(t,1);i.splice(a,0,s),n()}function Ie(e){const t=document.getElementById(`fb-chooser-options-${e}`);if(!t)return;const o=t.querySelectorAll(".fb-chooser-option-row"),n=[];o.forEach(i=>{const a={value:i.querySelector(".fb-chooser-opt-value")?.value.trim()||"",label:i.querySelector(".fb-chooser-opt-label")?.value.trim()||""},s=i.querySelector(".fb-chooser-opt-icon")?.value.trim();s&&(a.icon=s);const l=i.querySelector(".fb-chooser-opt-description")?.value.trim();l&&(a.description=l);const u=i.querySelector(".fb-chooser-opt-tooltip")?.value.trim();u&&(a.tooltip=u);const r=i.querySelector(".fb-chooser-opt-badge-text")?.value.trim(),d=i.querySelector(".fb-chooser-opt-badge-type")?.value;(r||d)&&(a.badge={},r&&(a.badge.text=r),d&&(a.badge.type=d)),i.querySelector(".fb-chooser-opt-recommended")?.checked&&(a.recommended=!0),i.querySelector(".fb-chooser-opt-disabled")?.checked&&(a.disabled=!0),n.push(a)}),T[e]&&(T[e].options=n)}function _(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,i){const a=document.createElement("div");a.style.flex="1";const s=document.createElement("label");s.htmlFor=t,s.className="form-label",s.textContent=e,s.style.fontSize=".8rem",(ge[e]||i)&&s.appendChild(B(ge[e]||i,e));const l=document.createElement("input");if(l.id=t,l.type=o||"text",l.className="form-input",l.value=n??"",a.appendChild(s),a.appendChild(l),i){const u=document.createElement("p");u.className="form-hint text-muted",u.textContent=i,u.style.cssText="font-size:.73rem;margin-top:.35rem;",a.appendChild(u)}return a}function di(e,t,o,n){const i=document.createElement("div");i.style.flex="1";const a=document.createElement("label");a.htmlFor=t,a.className="form-label",a.textContent=e,a.style.fontSize=".8rem",ge[e]&&a.appendChild(B(ge[e],e));const s=document.createElement("select");return s.id=t,s.className="form-select",o.forEach(l=>{const u=document.createElement("option");u.value=l.value,u.textContent=l.label,l.value===n&&(u.selected=!0),s.appendChild(u)}),i.appendChild(a),i.appendChild(s),i}function Oe(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 i=document.createElement("label");i.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,i.appendChild(a),i.appendChild(document.createTextNode(e)),i.appendChild(B(ge[e]||nt.find(s=>s.label===e)?.hint||e,e)),n.appendChild(i),n}function ui(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 i=document.createElement("textarea");return i.id=`fb-options-${t}`,i.className="form-input",i.rows=4,i.placeholder=`yes:Yes
|
|
5
|
+
`),n.appendChild(u),n.appendChild(p),n}function Dt(){return window.FormLogicEngine?.FIELD_TRANSITIONS||[{value:"none",label:"None (instant)"}]}function _t(e){const t=(e.find("#setting-entrance").val()||"none")==="none";e.find("#setting-entrance-speed-group").get(0).style.display=t?"none":"",e.find("#setting-entrance-preview-group").get(0).style.display=t?"none":""}function Qe(e,t){const o=e.find("#setting-entrance").get(0);if(!o)return;o.options.length||(Dt().forEach(i=>{const a=document.createElement("option");a.value=i.value,a.textContent=i.label,o.appendChild(a)}),o.addEventListener("change",()=>_t(e)),e.find("#setting-entrance-preview").get(0)?.addEventListener("click",()=>{const i=e.find("#setting-entrance-duration").val();window.FormLogicEngine?.animateIn?.(e.find("#setting-entrance-sample").get(0),o.value,i===""?void 0:Number(i))}));const n=t?.entrance||"none";o.value=Dt().some(i=>i.value===n)?n:"none",e.find("#setting-entrance-duration").val(t?.entranceDuration!=null?String(t.entranceDuration):""),_t(e)}function Xn(e){const t=e.find("#setting-entrance").val()||"none";if(t==="none")return{};const o=parseInt(e.find("#setting-entrance-duration").val()||"",10);return{entrance:t,...Number.isFinite(o)&&{entranceDuration:o}}}function Qn(e,t){const o=e.logic||{},n=T.filter((p,m)=>m!==t&&p.type!=="page-break"&&p.type!=="spacer"),i=document.createElement("div");i.className="fb-field-logic",i.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 s=document.createElement("span");s.style.cssText="font-size:.8rem;font-weight:600;color:var(--dm-text-muted);",s.textContent="\u26A1 Conditional Logic";const l=Ot(o),d=document.createElement("button");d.type="button",d.className="btn btn-xs btn-ghost",D(d,l?"chevron-down":"chevron-right",12);const r=document.createElement("div");r.className="fb-logic-body",r.style.cssText="padding:.25rem 0 .25rem;"+(l?"":"display:none;"),a.addEventListener("click",()=>{const p=r.style.display==="none";r.style.display=p?"":"none",D(d,p?"chevron-down":"chevron-right",12)}),a.appendChild(s),a.appendChild(d),i.appendChild(a),r.appendChild(Gn(o.visibility||{},t,n)),r.appendChild(Kn(o.requirement||{},t,n)),r.appendChild(Yn(o.validation||[],t,n));const u=document.getElementById(`fb-type-${t}`)?.value||e.type;return Ge.has(u)&&r.appendChild(Jn(o.cascade||{},t,n)),i.appendChild(r),i}const xe=[{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"}],Fe=[{value:"info",label:"Info"},{value:"success",label:"Success"},{value:"warning",label:"Warning"},{value:"error",label:"Error"}],zt=[{value:"field-below",label:"Below this field"},{value:"field-above",label:"Above this field"},{value:"form-top",label:"Top of the form"}],Pt=[{value:"rest",label:"The rest of the form"},{value:"all",label:"Every other field"},{value:"listed",label:"Chosen fields"}],jt=[{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 Ht(e,t=!1){const o=(s,l)=>({value:s.name,label:`${s.label||s.name}${l?" (this field)":""}`,multi:Xe(s)}),n=s=>s&&s.type!=="page-break"&&s.type!=="spacer"&&s.name,i=T.filter((s,l)=>l!==e&&n(s)).map(s=>o(s,!1)),a=T[e];return t&&n(a)?[o(a,!0),...i]:i}function Z(e,t,o){const n=document.createElement("select");return n.className=`form-select ${e}`,t.forEach(i=>{const a=document.createElement("option");a.value=i.value,a.textContent=i.label,i.value===o&&(a.selected=!0),n.appendChild(a)}),n}function re(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 Ze(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)),D(o,"x"),o.addEventListener("click",n=>{n.stopPropagation(),e()}),o}function N(e,t,{full:o=!1,hint:n="",help:i=""}={}){const a=document.createElement("label");a.className=`fb-trig-f${o?" fb-trig-f--full":""}`,a.style.flex="1";const s=document.createElement("span");if(s.className="fb-trig-f-label",s.textContent=e,(i||n||ye[e])&&s.appendChild(B(i||n||ye[e],e)),a.appendChild(s),a.appendChild(t),n){const l=document.createElement("span");l.className="fb-trig-f-hint",l.textContent=n,a.appendChild(l)}return a}function we(e,t,o,n){const i=document.createElement("label");i.className="fb-trig-check";const a=document.createElement("input");return a.type="checkbox",a.className=`form-check ${e}`,a.checked=!!t,i.appendChild(a),i.appendChild(document.createTextNode(o)),i.appendChild(B(n||"Allow the visitor to close this banner while the condition holds. It can appear again when the condition becomes true again.",o)),i}function Wt(e,t){const o=document.createElement("div");o.className="fb-trig-cond-row";const n=Z("fb-trig-cond-field",t,e?.field),i=Z("fb-trig-cond-op",Le,e?.operator),a=re("fb-trig-cond-val",e?.value,"value"),s=N("Value",a,{help:"Compare with the stored value. For one of, separate values with commas; for regex, enter a regular expression."}),l=()=>{const r=t.find(u=>u.value===n.value);Array.from(i.options).forEach(u=>{const p=Le.find(m=>m.value===u.value);u.textContent=r?.multi&&Mt[u.value]||p?.label||u.value})},d=()=>{s.hidden=Je.has(i.value)};return l(),d(),n.addEventListener("change",l),i.addEventListener("change",d),o.appendChild(N("Field",n,{help:"The answer to test, including this field or another named field."})),o.appendChild(N("Comparison",i,{help:"How to compare the answer. Multi-choice fields test their selected values. Empty and not empty need no comparison value."})),o.appendChild(s),o.appendChild(Ze(()=>o.remove(),"Remove condition")),o}const Vt=["banner","toast","block-submit","end-form"],Ut=["password","file","image","signature"],Zn="Put an answer in with {{field_name}} - e.g. Hello {{name}}. Pick one from Insert field.";function ei(){try{V()}catch{}return T.filter(e=>e&&e.name&&e.type!=="page-break"&&e.type!=="spacer"&&!Ut.includes(e.type))}function Gt(e,t,o){const n=re(e,t,o),i=document.createElement("span");i.className="fb-token-row";const a=document.createElement("select");a.className="form-input fb-token-pick",a.title="Insert an answer into the message",a.setAttribute("aria-label","Insert a field's answer into the message");const s=()=>{a.replaceChildren(new Option("Insert field",""));for(const l of ei())a.appendChild(new Option(`${l.label||l.name} ({{${l.name}}})`,l.name))};return s(),a.addEventListener("focus",s),a.addEventListener("mousedown",s),a.addEventListener("change",()=>{const l=a.value;if(a.value="",!l)return;const d=`{{${l}}}`,r=n.selectionStart??n.value.length,u=n.selectionEnd??r;n.value=n.value.slice(0,r)+d+n.value.slice(u),n.focus(),n.setSelectionRange(r+d.length,r+d.length),n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))}),i.append(n,a),i}function ti(e){const t=window.FormLogicEngine;if(!t?.triggerTokens)return[];const o=new Map((e||[]).filter(i=>i&&i.name).map(i=>[i.name,i])),n=new Set;for(const i of e||[])for(const a of i?.triggers||[])for(const s of[...a.then||[],...a.otherwise||[]])if(Vt.includes(s?.type))for(const l of[...t.triggerTokens(s.message),...t.triggerTokens(s.doneMessage)]){const d=o.get(l);(!d||Ut.includes(d.type))&&n.add(l)}return[...n]}function Kt(e,t){const o=document.createElement("div");o.className="fb-trig-params";const n=xe.find(d=>d.value===(e.type||"banner"));if(!n)return o;const i=document.createElement("div");i.className="fb-trig-grid";const a=document.createElement("div");a.className="fb-trig-opts";const s=[];for(const d of n.params)switch(d){case"message":i.appendChild(Vt.includes(n.value)?N(n.messageLabel||"Message",Gt("fb-trig-p-message",e.message,n.placeholder||""),{full:!0,hint:Zn,help:ye[n.messageLabel||"Message"]}):N(n.messageLabel||"Message",re("fb-trig-p-message",e.message,n.placeholder||""),{full:!0}));break;case"finish":a.appendChild(we("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 r=N("Button text",re("fb-trig-p-finish",e.finishLabel,"Finish"));s.push(r),i.appendChild(r);break}case"doneMessage":{const r=N("Closing message",Gt("fb-trig-p-done",e.doneMessage,"Blank: the form's own success message"));s.push(r),i.appendChild(r);break}case"record":{const r=we("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.`);s.push(r),a.appendChild(r);break}case"level":i.appendChild(N(n.value==="notify"?"Severity":"Level",Z("fb-trig-p-level",Fe,e.level||"info")));break;case"position":i.appendChild(N("Where",Z("fb-trig-p-position",zt,e.position||"field-below")));break;case"dismissible":a.appendChild(we("fb-trig-p-dismissible",e.dismissible!==!1,"The visitor can dismiss it"));break;case"target":{const r=Z("fb-trig-p-target",Pt,e.target||(e.fields?.length?"listed":"rest")),u=document.createElement("select");u.className="form-select fb-trig-p-fields",u.multiple=!0,u.size=4;const p=new Set(e.fields||[]);Ht(t).forEach(f=>{const v=document.createElement("option");v.value=f.value,v.textContent=f.label,p.has(f.value)&&(v.selected=!0),u.appendChild(v)});const m=N("Fields",u,{hint:"Ctrl/Cmd-click to pick several",help:ye.Fields}),g=()=>{m.hidden=r.value!=="listed"};g(),r.addEventListener("change",g),i.appendChild(N("Which fields",r)),i.appendChild(m);break}case"step":{const r=re("fb-trig-p-step",e.step,"0");r.type="number",r.min="0",i.appendChild(N("Step",r,{hint:"Counting from 0",help:ye.Step}));break}case"url":i.appendChild(N("Send them to",re("fb-trig-p-url",e.url,"/thank-you"),{full:!0}));break;case"theme":i.appendChild(N("Theme",Z("fb-trig-p-theme",jt,e.theme||"auto")));break;case"intensity":i.appendChild(N("Intensity",Z("fb-trig-p-intensity",[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}],e.intensity||"medium")));break;case"slug":{const r=[{value:"",label:ke.length?"Choose an action":"No actions available"}].concat(ke.map(u=>({value:u.slug,label:u.title||u.slug})));i.appendChild(N("Action",Z("fb-trig-p-slug",r,e.slug||""),{full:!0,help:"The CMS action to run after a matching submission is saved. Choose an action defined under Data > Actions. Requires Pro with MongoDB."}));break}default:break}n.kind==="event"&&!n.noOnce&&a.appendChild(we("fb-trig-p-once",!!e.once,"Only once","Fire the first time only, rather than every time the answer swings back."));const l=a.querySelector(".fb-trig-p-finish-on");if(l){const d=()=>s.forEach(r=>{r.hidden=!l.checked});d(),l.addEventListener("change",d)}return i.children.length&&o.appendChild(i),a.children.length&&o.appendChild(a),o}function ni(e){return e?.kindText?e.kindText:e?.kind==="event"?"once, when it becomes true":"while it is true"}const ii=(e,t=48)=>e.length>t?`${e.slice(0,t-1)}\u2026`:e,ce=(e,t)=>e.find(o=>o.value===t)?.label||t;function ai(e){if(!e)return"";const t=[],o=i=>i?`"${ii(i)}"`:"",n=()=>e.target==="listed"?e.fields?.length?e.fields.join(", "):"no fields chosen":ce(Pt,e.target||"rest").toLowerCase();switch(e.type){case"banner":t.push(o(e.message)||"No message yet",ce(Fe,e.level||"info"),ce(zt,e.position||"field-below").toLowerCase());break;case"toast":t.push(o(e.message)||"No message yet",ce(Fe,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(ce(jt,e.theme||"auto"),`${e.intensity||"medium"} intensity`);break;case"run-action":t.push(e.slug?ke.find(i=>i.slug===e.slug)?.title||e.slug:"no action chosen");break;case"notify":t.push(o(e.message)||"titled after the form",ce(Fe,e.level||"info"));break;default:break}return e.once&&t.push("only once"),t.filter(Boolean).join(" \xB7 ")}function et(e,t,{open:o=!1}={}){const n=document.createElement("div");n.className="fb-trig-action-row";const i=document.createElement("div");i.className="fb-trig-action-head",i.tabIndex=0,i.setAttribute("role","button");const a=document.createElement("span");a.className="fb-trig-chevron";const s=document.createElement("span");s.className="fb-trig-action-main";const l=document.createElement("strong"),d=document.createElement("small");d.className="fb-trig-action-summary",s.append(l,d);const r=document.createElement("span");r.className="fb-trig-kind",i.append(a,s,r,Ze(()=>n.remove(),"Remove action"));const u=document.createElement("div");u.className="fb-trig-action-body";const p=Z("fb-trig-action-type",xe,e.type||"banner");u.appendChild(N("Action",p,{full:!0})),u.appendChild(Kt(e,t));const m=()=>{const f=xe.find(v=>v.value===p.value);l.textContent=f?.label||p.value,r.textContent=ni(f),r.classList.toggle("fb-trig-kind--event",f?.kind==="event"),d.textContent=ai(Qt(n))},g=f=>{u.hidden=!f,n.classList.toggle("is-open",f),i.setAttribute("aria-expanded",String(f)),D(a,f?"chevron-down":"chevron-right",12)};return i.addEventListener("click",()=>g(u.hidden)),i.addEventListener("keydown",f=>{f.target!==i||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),g(u.hidden))}),p.addEventListener("change",()=>{const f=Kt({type:p.value},t);u.replaceChild(f,u.querySelector(".fb-trig-params")),m(),window.I?.scan?.()}),u.addEventListener("input",m),u.addEventListener("change",m),n.append(i,u),g(o),m(),n}function Yt(e,t,o){const n=document.createElement("section");n.className=`fb-trig-sec fb-trig-sec--${e}`;const i=document.createElement("div");i.className="fb-trig-sec-head";const a=document.createElement("span");if(a.className="fb-trig-sec-title",a.textContent=t,a.appendChild(B({When:"Choose the answers to test. All requires every condition to match; Any requires at least one. Compare stored option values, not their display labels.",Then:"Actions applied when the conditions match.",Otherwise:"Optional actions applied when the conditions do not match. Leave empty to do nothing in this branch."}[t],t)),i.appendChild(a),o){const s=document.createElement("span");s.className="fb-trig-sec-hint",s.textContent=o,i.appendChild(s)}return n.appendChild(i),n}function tt(e,t){const o=document.createElement("button");return o.type="button",o.className="btn btn-xs btn-ghost fb-trig-add",be(o,"plus",e,12),o.addEventListener("click",t),o}function Jt(e,t,o,n){const a=Yt(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 s=document.createElement("div");return s.className="fb-trig-action-list",(o||[]).forEach(l=>s.appendChild(et(l,n))),a.appendChild(s),a.appendChild(tt("Add action",()=>{s.appendChild(et({type:"banner"},n,{open:!0})),window.I?.scan?.()})),a}function Xt(e,t,o){const n=Ht(t,!0),i=document.createElement("div");i.className="fb-trig-card",i.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 s=document.createElement("span");s.className="fb-trig-card-title",s.textContent=`Trigger ${o+1}`,a.appendChild(s);const l=we("fb-trig-enabled",e.enabled!==!1,"Enabled","Untick to keep the trigger but switch it off.");if(a.appendChild(l),a.appendChild(Ze(()=>i.remove(),"Remove trigger")),i.appendChild(a),!n.length){const p=document.createElement("p");return p.className="fb-trig-empty",p.textContent="Give this field a name first - a trigger tests an answer, and it needs something to test.",i.appendChild(p),i}const d=Yt("when","When");d.querySelector(".fb-trig-sec-head").appendChild(Z("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 r=document.createElement("div");r.className="fb-trig-cond-list";const u=e.when?.all||e.when?.any||[];return(u.length?u:[{}]).forEach(p=>r.appendChild(Wt(p,n))),d.appendChild(r),d.appendChild(tt("Add condition",()=>{r.appendChild(Wt({},n)),window.I?.scan?.()})),i.appendChild(d),i.appendChild(Jt("then","Then",e.then,t)),i.appendChild(Jt("otherwise","Otherwise",e.otherwise,t)),i}function oi(e,t){const o=Array.isArray(e.triggers)?e.triggers:[],n=document.createElement("div");n.className="fb-field-triggers";const i=document.createElement("div");i.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})`:""}`,a.appendChild(B("Triggers test answers and choose a Then or Otherwise branch. Add conditions and actions below. Enabled switches a trigger on without deleting its settings.","Triggers"));const s=document.createElement("button");s.type="button",s.className="btn btn-xs btn-ghost",D(s,o.length?"chevron-down":"chevron-right",12);const l=document.createElement("div");l.className="fb-triggers-body",l.hidden=!o.length,i.addEventListener("click",()=>{l.hidden=!l.hidden,D(s,l.hidden?"chevron-right":"chevron-down",12)});const d=document.createElement("p");d.className="fb-trig-blurb",d.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.",l.appendChild(d);const r=document.createElement("div");return r.className="fb-trig-list",o.forEach((u,p)=>r.appendChild(Xt(u,t,p))),l.appendChild(r),l.appendChild(tt("Add trigger",()=>{const u=Xt({enabled:!0,then:[]},t,r.children.length);r.appendChild(u),u.querySelector('.fb-trig-branch[data-branch="then"] .fb-trig-action-list')?.appendChild(et({type:"banner"},t,{open:!0})),window.I?.scan?.()})),i.appendChild(a),i.appendChild(s),n.appendChild(i),n.appendChild(l),n}function Qt(e){const t=e.querySelector(".fb-trig-action-type")?.value,o=xe.find(a=>a.value===t);if(!o)return null;const n={type:t},i=a=>e.querySelector(a)?.value?.trim()||"";for(const a of o.params)switch(a){case"message":n.message=i(".fb-trig-p-message");break;case"finishLabel":{const s=i(".fb-trig-p-finish");s&&(n.finishLabel=s);break}case"doneMessage":{const s=i(".fb-trig-p-done");s&&(n.doneMessage=s);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=i(".fb-trig-p-level")||"info";break;case"position":n.position=i(".fb-trig-p-position")||"field-below";break;case"dismissible":n.dismissible=!!e.querySelector(".fb-trig-p-dismissible")?.checked;break;case"target":{const s=i(".fb-trig-p-target")||"rest";n.target=s,s==="listed"&&(n.fields=Array.from(e.querySelectorAll(".fb-trig-p-fields option")).filter(l=>l.selected).map(l=>l.value));break}case"step":{const s=parseInt(i(".fb-trig-p-step"),10);Number.isFinite(s)&&(n.step=s);break}case"url":n.url=i(".fb-trig-p-url");break;case"theme":n.theme=i(".fb-trig-p-theme")||"auto";break;case"intensity":n.intensity=i(".fb-trig-p-intensity")||"medium";break;case"slug":n.slug=i(".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 si(e){const t=Qt(e);if(!t)return null;const o=xe.find(a=>a.value===t.type),n=t.type,i=["block-submit","end-form","notify"].includes(o.value);return o.params.includes("message")&&!t.message&&!i?(delete t.message,null):(i&&!t.message&&delete t.message,n==="redirect"&&!t.url||n==="run-action"&&!t.slug?null:t)}function li(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(i=>{const a=Array.from(i.querySelectorAll(".fb-trig-cond-row")).map(p=>{const m=p.querySelector(".fb-trig-cond-field")?.value,g=p.querySelector(".fb-trig-cond-op")?.value;if(!m||!g)return null;const f=p.querySelector(".fb-trig-cond-val")?.value??"";return{field:m,operator:g,value:f}}).filter(Boolean);if(!a.length)return;const s=p=>Array.from(i.querySelectorAll(`.fb-trig-branch[data-branch="${p}"] .fb-trig-action-row`)).map(si).filter(Boolean),l=s("then"),d=s("otherwise");if(!l.length&&!d.length)return;const r=i.querySelector(".fb-trig-match")?.value==="any"?"any":"all",u={id:i.dataset.triggerId,enabled:!!i.querySelector(".fb-trig-enabled")?.checked,when:{[r]:a}};l.length&&(u.then=l),d.length&&(u.otherwise=d),n.push(u)}),n.length?n:void 0}function Zt(e,t,o){const n=document.createElement("div");if(n.className="fb-field-extras",e==="chooser")n.appendChild(di(t,o)),n.appendChild(pi(t.options||[],o));else if(Ge.has(e)&&n.appendChild(yi(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??"","")])),e==="file"){const i=P("Most files",`fb-file-max-${o}`,"number",t.file?.maxFiles||"",`${xt} when left empty, ${We} at most`),a=i.querySelector("input");a.min="1",a.max=String(We),a.placeholder=String(xt);const s=Oe("Several files",`fb-file-multiple-${o}`,!!t.multiple),l=()=>{i.hidden=!s.querySelector("input").checked};s.querySelector("input").addEventListener("change",l),l(),n.appendChild(z([i,s]))}return en.includes(e)&&n.appendChild(ci(t,o)),n.children.length?n:null}const en=["string","email","tel","number","url","date","time","password","select","textarea"],nt=[{key:"reveal",label:"Show / hide button",types:["password"],hint:"Show / hide lets the visitor see what they typed."},{key:"clear",label:"Clear button",types:["string","email","tel","url","textarea"],hint:"Clear adds an x that empties the field."},{key:"stepper",label:"- / + buttons",types:["number"],hint:"The - and + buttons step the number within its min, max and step."},{key:"counter",label:"Character counter",types:["string","textarea"],hint:"The counter shows how many characters are used, against Max Length if one is set."}];function ri(e){return e?typeof e=="string"?{icon:"",text:e}:{icon:e.icon||"",text:e.icon?"":e.text??""}:{icon:"",text:""}}function ci(e,t){const o=document.createElement("div");o.className="fb-addons";const n=(s,l)=>{const d=ri(e.formConfig?.[s]),r=document.createElement("div");r.style.flex="1";const u=document.createElement("span");u.className="form-label",u.style.fontSize=".8rem",u.textContent=l,u.appendChild(B("An icon or short text joined to this side of the input, such as a currency symbol or unit. Choose an icon or enter text; leave both blank for none.",l));const p=He("Icon, e.g. search",d.icon);p.input.id=`fb-${s}-icon-${t}`,p.input.setAttribute("aria-label",`${l}: icon`);const m=document.createElement("input");return m.type="text",m.className="form-input",m.id=`fb-${s}-text-${t}`,m.value=d.text,m.placeholder="or text, e.g. \xA3 or kg",m.maxLength=24,m.setAttribute("aria-label",`${l}: text`),m.style.marginTop=".35rem",p.input.addEventListener("input",()=>{p.input.value.trim()&&(m.value="")}),m.addEventListener("input",()=>{m.value.trim()&&(p.input.value="")}),r.append(u,p.el,m),r};o.appendChild(z([n("prefix","Before the field"),n("suffix","After the field")]));const i=document.createElement("p");i.className="form-hint text-muted",i.style.cssText="font-size:.73rem;margin:-.4rem 0 .75rem;",i.textContent="An icon or a short text joined to the start or end of the input, like \xA3 before a price or kg after a weight. Leave both empty for none.",o.appendChild(i);const a=nt.filter(s=>s.types.includes(e.type));if(a.length){o.appendChild(z(a.map(l=>Oe(l.label,`fb-extra-${l.key}-${t}`,!!e.formConfig?.[l.key]))));const s=document.createElement("p");s.className="form-hint text-muted",s.style.cssText="font-size:.73rem;margin:-.4rem 0 .75rem;",s.textContent=a.map(l=>l.hint).join(" "),o.appendChild(s)}return o}function tn(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 Be(e,t,o,n,i){const a=document.createElement("div");a.style.flex="1";const s=document.createElement("label");s.htmlFor=e,s.className="form-label",s.textContent=t,i&&s.appendChild(B(i,t)),s.style.fontSize=".8rem";const l=document.createElement("select");if(l.id=e,l.className="form-input",n.forEach(([d,r])=>{const u=document.createElement("option");u.value=d,u.textContent=r,String(d)===String(o)&&(u.selected=!0),l.appendChild(u)}),a.appendChild(s),a.appendChild(l),i){const d=document.createElement("p");d.className="form-hint text-muted",d.textContent=i,d.style.cssText="font-size:.72rem;margin-top:.2rem;",a.appendChild(d)}return a}function nn(e,t,o,n){const i=document.createElement("div");i.style.flex="1";const a=document.createElement("label");a.style.cssText="display:inline-flex;align-items:center;gap:.4rem;font-size:.82rem;";const s=document.createElement("input");if(s.id=e,s.type="checkbox",s.checked=!!o,a.appendChild(s),a.appendChild(document.createTextNode(" "+t)),n&&a.appendChild(B(n,t)),i.appendChild(a),n){const l=document.createElement("p");l.className="form-hint text-muted",l.textContent=n,l.style.cssText="font-size:.72rem;margin-top:.2rem;",i.appendChild(l)}return i}function it(e,t,o,n,i){const a=document.createElement("div");a.style.flex="1";const s=document.createElement("label");s.htmlFor=e,s.className="form-label",s.textContent=t,i&&s.appendChild(B(i,t)),s.style.fontSize=".8rem",a.appendChild(s);const l=document.createElement("div");l.style.cssText="display:flex;gap:.4rem;align-items:stretch;";const d=document.createElement("input");d.id=e,d.type="text",d.className="form-input",d.value=o||"",n&&(d.placeholder=n),d.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 u=String(d.value).match(/^#[0-9a-fA-F]{3,8}$/);if(r.value=u?d.value:"#000000",r.addEventListener("input",()=>{d.value=r.value,d.dispatchEvent(new Event("input",{bubbles:!0}))}),l.appendChild(d),l.appendChild(r),a.appendChild(l),i){const p=document.createElement("p");p.className="form-hint text-muted",p.textContent=i,p.style.cssText="font-size:.72rem;margin-top:.2rem;",a.appendChild(p)}return a}function di(e,t){const o=document.createElement("div");o.style.cssText="margin-top:.5rem; display:flex; flex-direction:column; gap:.4rem;";const n=tn("Layout");n.body.appendChild(z([Be(`fb-chooser-variant-${t}`,"Variant",e.variant||"card",[["card","Card - rich tiles"],["chip","Chip - compact pills"]],"Card supports description and grid columns; chips wrap."),nn(`fb-chooser-multiple-${t}`,"Multi-select",!!e.multiple,"Off = single (radio); on = multi (checkbox).")])),n.body.appendChild(z([Be(`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 i=tn("Visual");return i.body.appendChild(z([it(`fb-chooser-accent-${t}`,"Accent",e.accent||"","primary / success / #ec4899","Selected highlight colour - semantic name or any CSS colour."),Be(`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.")])),i.body.appendChild(z([nn(`fb-chooser-glow-${t}`,"Glow on selected",!!e.glow,"Soft outer glow."),it(`fb-chooser-glow-colour-${t}`,"Glow colour",e.glowColour||"","defaults to accent","Optional; semantic name or CSS colour.")])),i.body.appendChild(z([Be(`fb-chooser-shadow-${t}`,"Shadow",e.shadow||"none",[["none","None"],["sm","Small"],["md","Medium"],["lg","Large"],["xl","Extra Large"]],"Drop shadow on every option."),it(`fb-chooser-shadow-colour-${t}`,"Shadow colour",e.shadowColour||"","rgba(0,0,0,0.1)","Optional shadow tint.")])),o.appendChild(i.wrap),o}function ui(e,t,o,n){const i=document.createElement("div");i.className="fb-chooser-option-row",i.dataset.optIdx=String(o),i.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 s=document.createElement("div");s.style.cssText="display:flex; flex-direction:column; gap:1px;";const l=document.createElement("button");l.type="button",l.className="btn btn-xs btn-ghost",l.title="Move up",D(l,"arrow-up"),l.addEventListener("click",O=>{O.preventDefault(),an(t,o,-1,n)});const d=document.createElement("button");d.type="button",d.className="btn btn-xs btn-ghost",d.title="Move down",D(d,"arrow-down"),d.addEventListener("click",O=>{O.preventDefault(),an(t,o,1,n)}),s.appendChild(l),s.appendChild(d),a.appendChild(s);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(N("Value",r,{help:"The value stored with the submission and compared by trigger conditions. Keep it unique within this field."}));const u=document.createElement("input");u.type="text",u.className="form-input fb-chooser-opt-label",u.placeholder="label (visible to users)",u.value=e.label||"",u.style.flex="2",a.appendChild(N("Label",u,{help:"The choice text visitors see. The stored value can be different."}));const p=document.createElement("button");p.type="button",p.className="btn btn-xs btn-ghost",p.style.cssText="line-height:1;opacity:.6;",p.title="Remove option",D(p,"x"),p.addEventListener("click",O=>{O.preventDefault(),hi(t,o,n)}),a.appendChild(p),i.appendChild(a);const m=document.createElement("div");m.style.cssText="display:flex; gap:.4rem;";const g=He("icon name (optional)",e.icon||"");g.input.classList.add("fb-chooser-opt-icon"),g.el.style.flex="1",m.appendChild(N("Icon",g.el,{help:"An optional icon for this choice. Browse for an icon or leave blank for none."}));const f=document.createElement("textarea");f.rows=1,f.className="form-input fb-chooser-opt-description",f.placeholder="description (card + comfortable only)",f.value=e.description||"";const v=N("Description",f,{help:"Extra explanation shown by the card variant at comfortable density. Visitors see the words: the chooser draws text only, so formatting is kept for later and not shown yet."});v.style.flex="2",m.appendChild(v),i.appendChild(m),sn(f);const w=document.createElement("div");w.style.cssText="display:flex; gap:.4rem;";const L=document.createElement("input");L.type="text",L.className="form-input fb-chooser-opt-tooltip",L.placeholder="tooltip (hover hint)",L.value=e.tooltip||"",L.style.flex="2",w.appendChild(N("Tooltip",L,{help:"An optional hover hint for this choice."}));const x=document.createElement("input");x.type="text",x.className="form-input fb-chooser-opt-badge-text",x.placeholder="badge text",x.value=e.badge?.text||"",x.style.flex="1",w.appendChild(N("Badge text",x,{help:"A short badge label attached to this choice. Leave blank for no badge."}));const b=document.createElement("select");b.className="form-input fb-chooser-opt-badge-type",b.style.flex="1",[["","no badge"],["primary","primary"],["success","success"],["info","info"],["warning","warning"],["danger","danger"]].forEach(([O,X])=>{const K=document.createElement("option");K.value=O,K.textContent=X,(e.badge?.type||"")===O&&(K.selected=!0),b.appendChild(K)}),w.appendChild(N("Badge style",b,{help:"The theme colour used for the badge."})),i.appendChild(w);const C=document.createElement("div");C.style.cssText="display:flex; gap:1rem; font-size:.8rem;";const $=document.createElement("label");$.style.cssText="display:inline-flex;align-items:center;gap:.3rem;";const j=document.createElement("input");j.type="checkbox",j.className="fb-chooser-opt-recommended",j.checked=!!e.recommended,$.appendChild(j),$.appendChild(document.createTextNode(" Recommended")),$.appendChild(B("Highlight this choice as recommended. This does not select it automatically.","Recommended")),C.appendChild($);const H=document.createElement("label");H.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,H.appendChild(J),H.appendChild(document.createTextNode(" Disabled")),H.appendChild(B("Show this choice but prevent the visitor from selecting it.","Disabled")),C.appendChild(H),i.appendChild(C),i}function pi(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 i=document.createElement("p");i.textContent="Options",i.appendChild(B("Each option has a stored value and a label shown to visitors. Keep values unique and use them in trigger conditions. Add an icon, description, tooltip or badge to explain a choice. Recommended highlights an option; Disabled prevents selection.","Chooser options")),i.style.cssText="font-size:.85rem;font-weight:600;margin:0;",n.appendChild(i);const a=document.createElement("button");a.type="button",a.className="btn btn-xs btn-ghost",be(a,"plus","Add option"),n.appendChild(a),o.appendChild(n);const s=document.createElement("div");s.className="fb-chooser-options-list",s.id=`fb-chooser-options-${t}`,s.style.cssText="display:flex; flex-direction:column; gap:.4rem;",o.appendChild(s);const l=()=>{s.replaceChildren();const d=mi(t);(d.length?d:e||[]).forEach((u,p)=>{s.appendChild(ui(u,t,p,l))})};return a.addEventListener("click",d=>{d.preventDefault(),fi(t,l)}),l(),o}function mi(e){const t=T[e];return!t||!Array.isArray(t.options)?[]:t.options}function at(e){return T[e]?(Array.isArray(T[e].options)||(T[e].options=[]),T[e].options):[]}function fi(e,t){Ie(e),at(e).push({value:"new",label:"New option"}),t()}function hi(e,t,o){Ie(e),at(e).splice(t,1),o()}function an(e,t,o,n){Ie(e);const i=at(e),a=t+o;if(a<0||a>=i.length)return;const[s]=i.splice(t,1);i.splice(a,0,s),n()}function Ie(e){const t=document.getElementById(`fb-chooser-options-${e}`);if(!t)return;const o=t.querySelectorAll(".fb-chooser-option-row"),n=[];o.forEach(i=>{const a={value:i.querySelector(".fb-chooser-opt-value")?.value.trim()||"",label:i.querySelector(".fb-chooser-opt-label")?.value.trim()||""},s=i.querySelector(".fb-chooser-opt-icon")?.value.trim();s&&(a.icon=s);const l=i.querySelector(".fb-chooser-opt-description")?.value.trim();l&&(a.description=l);const d=i.querySelector(".fb-chooser-opt-tooltip")?.value.trim();d&&(a.tooltip=d);const r=i.querySelector(".fb-chooser-opt-badge-text")?.value.trim(),u=i.querySelector(".fb-chooser-opt-badge-type")?.value;(r||u)&&(a.badge={},r&&(a.badge.text=r),u&&(a.badge.type=u)),i.querySelector(".fb-chooser-opt-recommended")?.checked&&(a.recommended=!0),i.querySelector(".fb-chooser-opt-disabled")?.checked&&(a.disabled=!0),n.push(a)}),T[e]&&(T[e].options=n)}const ot=new Map;function on(e=!1){for(const[t,o]of ot){if(!e&&t.isConnected){o.seen=!0;continue}if(!(!e&&!o.seen&&Date.now()-o.at<5e3)){try{o.handle.destroy()}catch{}ot.delete(t)}}}function sn(e){on(),e&&ot.set(e,{handle:qt(e,{compact:!0}),seen:!1,at:Date.now()})}function bi(e){if(!e)return null;const t=document.createElement("textarea");return t.id=e.id,t.className=e.className,t.rows=1,t.value=e.value,e.replaceWith(t),t}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,i){const a=document.createElement("div");a.style.flex="1";const s=document.createElement("label");s.htmlFor=t,s.className="form-label",s.textContent=e,s.style.fontSize=".8rem",(ge[e]||i)&&s.appendChild(B(ge[e]||i,e));const l=document.createElement("input");if(l.id=t,l.type=o||"text",l.className="form-input",l.value=n??"",a.appendChild(s),a.appendChild(l),i){const d=document.createElement("p");d.className="form-hint text-muted",d.textContent=i,d.style.cssText="font-size:.73rem;margin-top:.35rem;",a.appendChild(d)}return a}function gi(e,t,o,n){const i=document.createElement("div");i.style.flex="1";const a=document.createElement("label");a.htmlFor=t,a.className="form-label",a.textContent=e,a.style.fontSize=".8rem",ge[e]&&a.appendChild(B(ge[e],e));const s=document.createElement("select");return s.id=t,s.className="form-select",o.forEach(l=>{const d=document.createElement("option");d.value=l.value,d.textContent=l.label,l.value===n&&(d.selected=!0),s.appendChild(d)}),i.appendChild(a),i.appendChild(s),i}function Oe(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 i=document.createElement("label");i.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,i.appendChild(a),i.appendChild(document.createTextNode(e)),i.appendChild(B(ge[e]||nt.find(s=>s.label===e)?.hint||e,e)),n.appendChild(i),n}function yi(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 i=document.createElement("textarea");return i.id=`fb-options-${t}`,i.className="form-input",i.rows=4,i.placeholder=`yes:Yes
|
|
6
6
|
no:No
|
|
7
7
|
maybe:Maybe`,i.value=(e||[]).map(a=>{const s=typeof a=="string"?a:a.value??"",l=typeof a=="string"?a:a.label??s;return s===l?s:`${s}:${l}`}).join(`
|
|
8
|
-
`),i.style.fontFamily="monospace",n.appendChild(B("Enter one choice per line. Use value:Label, for example yes:Yes please. The value is stored and tested by conditions; the label is shown to visitors. A line without a colon uses the same text for both.","Options")),o.appendChild(n),o.appendChild(i),o}function Me(e){return parseInt(e,10)===3?3:2}const pi=[["#setting-submit-icon-start-slot","setting-submit-icon-start"],["#setting-submit-icon-end-slot","setting-submit-icon-end"],["#setting-second-icon-start-slot","setting-second-icon-start"],["#setting-second-icon-end-slot","setting-second-icon-end"]];function mi(e){pi.forEach(([t,o])=>{const n=e.find(t).get(0);if(!n||n.querySelector(`#${o}`))return;const i=We("none","");i.input.id=o,i.input.classList.add("form-input"),n.appendChild(i.el)})}function nn(e){const t=e.find("#setting-second-kind").val()||"",o=e.find("#second-button-group").get(0);o&&(o.style.display=t?"":"none");const n=e.find("#second-url-group").get(0);n&&(n.style.display=t==="link"?"":"none");const i=e.find("#setting-second-label").get(0);i&&(i.placeholder=t==="link"?"Cancel":"Clear form")}function fi(e){const t=a=>String(e.find(a).val()||"").trim(),o={},n={style:t("#setting-submit-style")||"primary",size:t("#setting-submit-size"),iconStart:t("#setting-submit-icon-start"),iconEnd:t("#setting-submit-icon-end")};(n.style!=="primary"||n.size||n.iconStart||n.iconEnd)&&(o.submitButton=n);const i=t("#setting-second-kind");return(i==="reset"||i==="link")&&(o.secondaryButton={kind:i,label:t("#setting-second-label"),...i==="link"?{url:t("#setting-second-url")}:{},style:t("#setting-second-style")||"secondary",iconStart:t("#setting-second-icon-start"),iconEnd:t("#setting-second-icon-end"),first:t("#setting-second-order")==="first",stack:t("#setting-second-arrange")==="stack"}),o}function an(e,t){const o=t&&t.submitButton||{},n=t&&t.secondaryButton||{};e.find("#setting-submit-style").val(o.style||"primary"),e.find("#setting-submit-size").val(o.size||""),e.find("#setting-submit-icon-start").val(o.iconStart||""),e.find("#setting-submit-icon-end").val(o.iconEnd||""),e.find("#setting-second-kind").val(n.kind==="reset"||n.kind==="link"?n.kind:""),e.find("#setting-second-label").val(n.label||""),e.find("#setting-second-url").val(n.url||""),e.find("#setting-second-style").val(n.style||"secondary"),e.find("#setting-second-icon-start").val(n.iconStart||""),e.find("#setting-second-icon-end").val(n.iconEnd||""),e.find("#setting-second-order").val(n.first?"first":"after"),e.find("#setting-second-arrange").val(n.stack?"stack":"row"),nn(e)}function Ce(e){const t=e.find("#field-project").val()||"";return H(),{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:{...Te||{},project:t||null},fields:T,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:Me(e.find("#setting-columns").val()),submitAlign:e.find("#setting-submit-align").val()||"",...fi(e),...e.find("#setting-form-class").val().trim()&&{class:e.find("#setting-form-class").val().trim()},...e.find("#setting-submit-class").val().trim()&&{submitClass:e.find("#setting-submit-class").val().trim()},...Vn(e),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()},...Se!==null&&{collection:Se}}}}function on(e,t){const o={};return e.forEach(n=>{if(n.type==="page-break"||n.type==="spacer")return;const i={...n.formConfig||{}};i.span==="full"&&t&&(i.span=t);const a=n.type==="chooser"||!!(n.variant&&["select","radio","checkbox-group"].includes(n.type)),l={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},...i}};a&&(n.variant&&(l.variant=n.variant),(n.multiple||n.type==="checkbox-group")&&(l.multiple=!0),n.density&&(l.density=n.density),n.columns&&(l.columns=n.columns),n.accent&&(l.accent=n.accent),n.accentStyle&&(l.accentStyle=n.accentStyle),n.glow&&(l.glow=!0),n.glowColour&&(l.glowColour=n.glowColour),n.shadow&&(l.shadow=n.shadow),n.shadowColour&&(l.shadowColour=n.shadowColour)),o[n.name]=n.type==="file"?hn(n,l):l}),o}function sn(e,t){const o=typeof e=="string"?document.querySelector(e):e;o&&(t||[]).forEach(n=>{if(n.type!=="date"||!n.name)return;const i=o.querySelector(`[name="${n.name}"]`);i&&i.type!=="date"&&(i.type="date")})}function ot(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 ln=e=>String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");let J=null,rn=0,cn=!1;const Re=e=>String(e||"").split("?")[0].replace(/\/$/,"");function hi(){cn||!window.R?.use||(cn=!0,R.use((e,t,o)=>!J||!Tt(t?.path,e?.path)||J.path!==Re(t?.path)||(J.flush(),!J.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(J&&J.path===Re(t?.path)&&Tt(t?.path,e?.path)){const o=J;J=null,o.dispose()}}))}export const formEditorView={templateUrl:"/admin/js/templates/form-editor.html",async onMount(e){if(hi(),J){const c=J;J=null,c.dispose()}const t=Re(location.hash.replace(/^#/,"")),o=++rn,n=()=>o!==rn||!e.get(0)?.isConnected||Re(location.hash.replace(/^#/,""))!==t;T=[],I=null,Se=null,mi(e),e.find("#setting-second-kind").get(0)?.addEventListener("change",()=>nn(e));const i=window.location.hash.match(/\/forms\/edit\/([^/?#]+)/);I=i?i[1]:null;let a=null,s=null;const l=E.loader(e.get(0),{type:"dots"});if(I)try{if(a=await fe(`/forms/${I}`),n()){l.destroy();return}T=a.fields||[],Se=a.actions?.collection??null}catch(c){if(n()){l.destroy();return}s={missing:c?.status===404,message:c?.message||String(c)},E.toast(s.missing?"This form no longer exists.":`Could not load the form: ${s.message}`,{type:"error"})}Te={};try{const c=await fe("/projects").catch(()=>[]);if(n()){l.destroy();return}const h=e.find("#field-project").get(0);h&&(Array.isArray(c)?c:[]).forEach(y=>{const k=document.createElement("option");k.value=y.slug,k.textContent=y.name||y.slug,h.appendChild(k)})}catch{}if(l.destroy(),Qe(e,{}),ot(e.get(0),a?a.title||a.slug:"New form"),I||e.find("#field-title").get(0).addEventListener("input",function(){e.find("#field-slug").val($t(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),Te=a.meta||{},e.find("#field-project").val(a.meta?.project||"");const c=a.settings||{};e.find("#setting-submit-text").val(c.submitText||"Submit"),e.find("#setting-success-message").val(c.successMessage||""),e.find("#setting-layout").val(c.layout||"grid"),e.find("#setting-columns").val(Me(c.columns)),e.find("#setting-submit-align").val(Et(c,c.layout||"grid")),an(e,c),e.find("#setting-form-class").val(c.class||""),e.find("#setting-submit-class").val(c.submitClass||""),Qe(e,c),e.find("#columns-group").get(0).style.display=(c.layout||"grid")==="grid"?"":"none",e.find("#setting-honeypot").prop("checked",c.honeypot!==!1),e.find("#setting-rate-limit").val(c.rateLimitPerMinute||3),e.find("#setting-success-redirect").val(c.successRedirect||"");const h=a.actions?.email||{};e.find("#action-email-enabled").prop("checked",h.enabled||!1),e.find("#action-email-recipients").val(h.recipients||""),e.find("#action-email-subject-prefix").val(h.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 u=a?.settings?.actionSlug||"";try{const c=await fe("/actions").catch(()=>[]);if(n())return;const h=e.find("#action-cms-slug").get(0);if(ke=Array.isArray(c)?c:[],(Array.isArray(c)?c:[]).forEach(y=>{const k=document.createElement("option");k.value=y.slug,k.textContent=y.title||y.slug,y.slug===u&&(k.selected=!0),h.appendChild(k)}),!c.length){const y=document.createElement("option");y.value="",y.textContent="No actions available",y.disabled=!0,h.appendChild(y)}}catch{}const r=c=>{e.find("#columns-group").get(0).style.display=c?"":"none",document.querySelectorAll(".fb-grid-row").forEach(h=>{h.style.display=c?"flex":"none"})};e.find("#setting-layout").get(0)?.addEventListener("change",function(){r(this.value==="grid")}),r(e.find("#setting-layout").val()==="grid"),ne(e);const d=e.find("#add-element-menu").get(0);e.find("#add-element-btn").get(0).addEventListener("click",c=>{c.stopPropagation(),d.style.display=d.style.display==="none"?"":"none"}),se&&document.removeEventListener("click",se),se=()=>{d&&(d.style.display="none")},document.addEventListener("click",se),e.find("#add-field-btn").get(0).addEventListener("click",()=>{d&&(d.style.display="none"),H();const c=T.length;T.push({name:`field_${c+1}`,type:"string",label:"New Field",required:!1,placeholder:""}),ne(e);const h=e.find("#fields-list").get(0)?.lastElementChild;if(h){const y=h.querySelector(".fb-field-body");y&&(y.style.display="")}}),e.find("#add-spacer-btn").get(0).addEventListener("click",()=>{d&&(d.style.display="none"),H(),T.push({type:"spacer"}),ne(e)}),e.find("#add-page-break-btn").get(0).addEventListener("click",()=>{d&&(d.style.display="none"),H();const c=T.filter(h=>h.type==="page-break").length+2;T.push({type:"page-break",label:`Step ${c}`,description:""}),ne(e)}),Le=()=>{const c=Ce(e),h=e.find("#preview-container").get(0);if(!h)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=I?"":"none"),e.find("#preview-card").get(0).style.display="",wt(h),h.textContent="";const q=document.createElement("div");q.id="fb-preview-form",h.appendChild(q);const W=new Map;vn(q,c.fields);const K=I?async D=>{y&&(y.style.display="none",y.textContent="");try{const A=new Map(W);xt(q,A);const te=gn(D,c.fields,A),ae=yn(te.values,te.files),G=await fetch(`/api/forms/submit/${I}`,{method:"POST",headers:ae.headers,body:ae.body}),X=await G.json();if(!G.ok)throw new Error(X.error||"Submission failed.");y&&(y.textContent=X.message||c.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(A){y&&(y.textContent=A.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(A.message,{type:"error"})}return!1}:()=>!1,me=c.fields.some(D=>D.type==="page-break");if(q.addEventListener("click",D=>{const A=D.target.closest?.("a.fb-secondary-btn");A&&(D.preventDefault(),E.toast(`Cancel takes the visitor to ${A.getAttribute("href")}`,{type:"info"}))}),q.addEventListener("dm-form-end",D=>{const A=D.detail?.validation;if(A&&!A.valid){E.toast(`Still to answer: ${A.missing.map(te=>te.label).concat(A.errors).join(", ")}`,{type:"warning"});return}K(D.detail?.values||{})}),typeof F<"u"){const D=Me(c.settings?.columns),A=c.settings?.layout||"grid";if(me&&F.wizard){const te=fn(c.fields,c.title),ae=te.map(oe=>({title:oe.title,description:oe.description,fields:on(oe.fields,D)}));let G=0,X=null,Pe=null;const gt=oe=>{const je=(te[G]||{}).fields||[];wn(q,c.settings),Ct(q,c.settings,je),sn("#fb-preview-form",je),yt(q,je),bn(q,W),oe&&window.FormLogicEngine&&At(c.fields)&&(X?.destroy?.(),X=new window.FormLogicEngine.FormLogicRuntime({fields:c.fields},q,{baseValues:Pe?.getStepData?Pe.getStepData():{}}),X.init())};Pe=F.wizard("#fb-preview-form",{schema:{steps:ae},layout:A,columns:D,finishText:c.settings?.submitText||"Finish",onStepChange:oe=>{xt(q,W),G=oe,queueMicrotask(()=>gt(!0))},onSubmit:K}),gt(!1)}else if(F.render){const te=on(c.fields,D),ae={};c.fields.forEach(G=>{if(!(!G.name||G.type==="page-break"||G.type==="spacer")&&(G.type==="select"||G.type==="multiselect")&&G.required){const X=(G.options||[])[0];X&&(ae[G.name]=typeof X=="object"?X.value:X)}}),F.render("#fb-preview-form",te,ae,{submitText:c.settings?.submitText||"Submit",layout:A,columns:D,onSubmit:K}),xn(q,c.settings,A),Ct(q,c.settings,c.fields),sn("#fb-preview-form",c.fields),yt(q,c.fields)}window.FormLogicEngine&&At(c.fields)&&requestAnimationFrame(()=>{new window.FormLogicEngine.FormLogicRuntime({fields:c.fields},q).init()})}else{const D=document.createElement("p");D.textContent=`${c.fields.filter(A=>A.type!=="page-break").length} field(s): ${c.fields.filter(A=>A.type!=="page-break").map(A=>A.label).join(", ")}`,D.style.cssText="color:var(--dm-text-muted);font-style:italic;",q.appendChild(D)}},Le();const p=e.find("#editor-tabs").get(0),m=e.find("#preview-card").get(0),g=c=>{m&&m.contains(c.target)||Ye()};p&&(p.addEventListener("input",g),p.addEventListener("change",g));const f=e.get(0),v=[],w=c=>(v.push(c),c);let N=!1;const x=M.observable(!1),b=M.observable(!1);let C=I,$=null,z=!1,V=!1,j=!1,Y=Ce(e),U=Ee(Y),ie=Y;const le=()=>{N||!f.isConnected||(ie=Ce(e),x.value=Ee(ie)!==U)};let de=null;Ke=()=>{clearTimeout(de),de=setTimeout(le,150)},w(()=>{clearTimeout(de),Ke=null,ve=null}),w(()=>wt(f.querySelector("#preview-container")));const De=c=>{const h=c.settings||{};e.find("#field-title").val(c.title||""),e.find("#field-slug").val(c.slug||""),e.find("#field-description").val(c.description||""),e.find("#field-bundled").prop("checked",!!c.bundled),Te={...c.meta||{}},e.find("#field-project").val(c.meta?.project||""),e.find("#setting-submit-text").val(h.submitText||"Submit"),e.find("#setting-success-message").val(h.successMessage||""),e.find("#setting-layout").val(h.layout||"grid"),e.find("#setting-columns").val(Me(h.columns)),e.find("#setting-submit-align").val(Et(h,h.layout||"grid")),an(e,h),e.find("#setting-form-class").val(h.class||""),e.find("#setting-submit-class").val(h.submitClass||""),Qe(e,h),e.find("#setting-honeypot").prop("checked",h.honeypot!==!1),e.find("#setting-rate-limit").val(h.rateLimitPerMinute||3),e.find("#setting-success-redirect").val(h.successRedirect||""),e.find("#action-cms-slug").val(h.actionSlug||"");const y=c.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=c.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"),T=JSON.parse(JSON.stringify(c.fields||[])),r((h.layout||"grid")==="grid"),ne(e)};async function _e(){if(b.peek()||N)return;if(s){E.toast("This form did not load, so saving would replace it with an empty one. Reload the page to try again.",{type:"error"});return}const c=Ce(e);if(!c.title){E.toast("Please enter a form title (Form Details).",{type:"error"});return}const h=Cn(c.settings);if(h.length){E.toast(`${h[0]} (Settings > Submit Button)`,{type:"error"});return}const y=En(c.settings,c.fields);if(y.length){E.toast(y[0],{type:"error"});return}const k=Yn(c.fields);k.length&&E.toast(`Some trigger messages use ${k.map(K=>`{{${K}}}`).join(", ")}, which will show as blank: no field has that name, or it is a password, file or image.`,{type:"warning",duration:9e3}),b.value=!0;const q=I,W=he(C);q||(f.inert=!0);try{if(I?(await fe(`/forms/${I}`,{method:"PUT",body:JSON.stringify(c)}),E.toast("Form saved.",{type:"success"})):(I=(await fe("/forms",{method:"POST",body:JSON.stringify(c)})).slug,E.toast("Form created.",{type:"success"})),N){if(!q)try{S.remove?S.remove(W):S.set(W,null)}catch{}return}C=I,Y=c,U=Ee(c),$=null,V=!1,j=!1,clearTimeout(de),le();for(const K of new Set([W,he(I)]))try{S.remove?S.remove(K):S.set(K,null)}catch{}ot(f,c.title),Sn("#/forms"),q||R.navigate(`/forms/edit/${I}`)}catch(K){q||(I=null),E.toast(K.message||"Failed to save form.",{type:"error"})}finally{b.value=!1,f.inert=!1}}async function dn(){x.peek()&&(!await E.confirm("Throw away the changes you have not saved?",{confirmText:"Throw away",cancelText:"Keep editing"})||N||(De(Y),le(),ft()))}Bn("#field-description");const st=f.querySelector(".fex-bar");if(st){const c=M.applyBindings({dirty:x,saving:b},st,{methods:{save:_e,discard:dn}});w(()=>c.dispose())}const ue=new Map,lt=()=>{for(const[c,h]of ue)f.contains(c)||(h(),ue.delete(c));for(const c of f.querySelectorAll("[data-help]:not([data-help-ready])"))ue.set(c,kn(c,{position:"bottom"}))};lt();const rt=new MutationObserver(lt);rt.observe(f,{childList:!0,subtree:!0}),w(()=>{rt.disconnect();for(const c of ue.values())c();ue.clear()}),Ve(e,{id:"form-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>_e()}),Ve(e,{id:"form-editor-back",icon:"arrow-left",title:"All forms",onClick:()=>{location.hash="#/forms"}}),I&&Ve(e,{id:"form-editor-subs",icon:"list",title:"Submissions",onClick:()=>{location.hash=`#/forms/${encodeURIComponent(I)}/submissions`}});const ct=c=>{n()||!(c.ctrlKey||c.metaKey)||String(c.key).toLowerCase()!=="s"||(c.preventDefault(),c.stopImmediatePropagation(),_e())};document.addEventListener("keydown",ct,!0),w(()=>document.removeEventListener("keydown",ct,!0));const Z=e.find("#fields-list").get(0),un=c=>c?.closest?.(".fb-field-card"),dt=c=>Number(c?.dataset.index),ut=c=>c?.querySelector(":scope > .fb-field-body"),pt=c=>{const h=ut(c);h&&(h.style.display=h.style.display==="none"?"":"none")},pe=(c,h)=>{T=c,ne(e),h!=null&&Z?.querySelectorAll(".fb-field-card")[h]?.focus()},pn=async c=>{try{await navigator.clipboard.writeText(c),E.toast(`Copied "${c}".`,{type:"success"})}catch{E.toast(`Copy failed - the name is ${c}.`,{type:"info"})}},mn=c=>{const h=un(c),y=dt(h);H();const k=T[y];if(!k)return[];const q=k.type!=="spacer"&&k.type!=="page-break",W=ut(h),K=W&&W.style.display!=="none";return[{header:Ue(k)},...W?[{label:K?"Close":"Edit",icon:K?"chevron-up":"edit",action:()=>pt(h)}]:[],...q?[{label:"Logic & triggers",icon:"zap",action:()=>{W&&(W.style.display=""),(W?.querySelector(".fb-field-logic")||W)?.scrollIntoView({block:"center",behavior:"smooth"})}}]:[],{label:"Duplicate",icon:"copy",action:()=>{H(),pe(qn(T,y),y+1)}},{type:"divider"},{label:"Move up",icon:"arrow-up",shortcut:"Alt+\u2191",disabled:y===0,action:()=>{H(),pe(Lt(T,y,-1),y-1)}},{label:"Move down",icon:"arrow-down",shortcut:"Alt+\u2193",disabled:y>=T.length-1,action:()=>{H(),pe(Lt(T,y,1),y+1)}},...q&&k.name?[{label:"Copy field name",icon:"clipboard",action:()=>pn(k.name)}]:[],{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:async()=>{if(k.type!=="spacer"&&!await E.confirm(`Remove "${ln(Ue(k))}"?`))return;H();const me=[...T];me.splice(y,1),pe(me,Math.min(y,me.length-1))}}]};if(Z&&typeof E.sortable=="function"){const c=E.sortable(Z,{items:".fb-field-card",handle:".fb-drag-grip",key:null,onSort:({from:h,to:y})=>{H();const k=[...T],[q]=k.splice(h,1);k.splice(y,0,q),pe(k,y)}});w(()=>c.destroy())}let mt=null;if(Z&&E.contextMenu&&(mt=E.contextMenu(Z,{cursor:"glyph",match:".fb-field-card > :first-child",inherit:!1,density:"compact",items:c=>mn(c)}),w(()=>mt?.destroy?.())),ve=c=>{for(const h of c.querySelectorAll(".fb-field-card")){h.tabIndex=0;const y=h.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",H(),k.setAttribute("aria-label",`Actions for ${Ue(T[dt(h)])}`),k.addEventListener("click",q=>{q.stopPropagation(),kt(k)}),y.appendChild(k)}},Z){ve(Z);const c=h=>{const y=h.target?.classList?.contains("fb-field-card")?h.target:null;y&&(h.key==="F10"&&h.shiftKey?(h.preventDefault(),kt(y.firstElementChild)):h.key==="Enter"&&(h.preventDefault(),pt(y)))};Z.addEventListener("keydown",c),w(()=>Z.removeEventListener("keydown",c))}const ft=()=>{try{const c=he(C);S.remove?S.remove(c):S.set(c,null)}catch{}},ht=c=>{if(!s){if(!x.peek()||!c){!z&&!j&&ft();return}try{S.set(he(C),{data:Nn(c),base:Tn($,St(U)),...V?{newFrom:!0}:{},at:new Date().toISOString()})}catch{}}},bt=c=>{le(),x.peek()&&(ht(ie),c.preventDefault(),c.returnValue="")};if(window.addEventListener("beforeunload",bt),w(()=>window.removeEventListener("beforeunload",bt)),w(()=>{se&&(document.removeEventListener("click",se),se=null)}),J={path:t,dirty:()=>x.peek(),flush:()=>{clearTimeout(de),le()},dispose(){N||(ht(ie),N=!0,v.splice(0).reverse().forEach(c=>{try{c?.()}catch{}}))}},s){const c=document.createElement("p");c.className="fex-load-error",c.setAttribute("role","alert"),c.textContent=s.missing?"This form no longer exists - it may have been deleted. Nothing here can be saved over it.":`This form could not be loaded (${s.message}). Saving is off so an empty editor cannot replace it - reload the page to try again.`;const h=f.querySelector(".fex-bar");h?h.before(c):f.prepend(c),w(()=>c.remove())}const ze=he(I);let ee=null;try{ee=S.get(ze)}catch{}if(ee?.data&&(!s||s.missing)){const c=!!s?.missing,h=Ln(ee,{missing:c});z=!0;const y=await E.confirm(ln($n(ee,{current:St(U),missing:c,when:ee.at?An(ee.at):""})),{title:"Unsaved changes",confirmText:"Throw away",cancelText:h==="new"?"Start a new form":h==="refuse"?"Not now":"Keep them"});if(z=!1,y)try{S.remove?S.remove(ze):S.set(ze,null)}catch{}else h==="refuse"?j=!0:N||(c?(I=null,s=null,$="",V=!0,Y=Ce(e),U=Ee(Y),ot(f,"New form"),f.querySelector(".fex-load-error")?.remove(),De(ee.data)):($=ee.base??"",De(Fn(ee.data,Y))),le())}}};
|
|
8
|
+
`),i.style.fontFamily="monospace",n.appendChild(B("Enter one choice per line. Use value:Label, for example yes:Yes please. The value is stored and tested by conditions; the label is shown to visitors. A line without a colon uses the same text for both.","Options")),o.appendChild(n),o.appendChild(i),o}function Me(e){return parseInt(e,10)===3?3:2}const vi=[["#setting-submit-icon-start-slot","setting-submit-icon-start"],["#setting-submit-icon-end-slot","setting-submit-icon-end"],["#setting-second-icon-start-slot","setting-second-icon-start"],["#setting-second-icon-end-slot","setting-second-icon-end"]];function xi(e){vi.forEach(([t,o])=>{const n=e.find(t).get(0);if(!n||n.querySelector(`#${o}`))return;const i=He("none","");i.input.id=o,i.input.classList.add("form-input"),n.appendChild(i.el)})}function ln(e){const t=e.find("#setting-second-kind").val()||"",o=e.find("#second-button-group").get(0);o&&(o.style.display=t?"":"none");const n=e.find("#second-url-group").get(0);n&&(n.style.display=t==="link"?"":"none");const i=e.find("#setting-second-label").get(0);i&&(i.placeholder=t==="link"?"Cancel":"Clear form")}function wi(e){const t=a=>String(e.find(a).val()||"").trim(),o={},n={style:t("#setting-submit-style")||"primary",size:t("#setting-submit-size"),iconStart:t("#setting-submit-icon-start"),iconEnd:t("#setting-submit-icon-end")};(n.style!=="primary"||n.size||n.iconStart||n.iconEnd)&&(o.submitButton=n);const i=t("#setting-second-kind");return(i==="reset"||i==="link")&&(o.secondaryButton={kind:i,label:t("#setting-second-label"),...i==="link"?{url:t("#setting-second-url")}:{},style:t("#setting-second-style")||"secondary",iconStart:t("#setting-second-icon-start"),iconEnd:t("#setting-second-icon-end"),first:t("#setting-second-order")==="first",stack:t("#setting-second-arrange")==="stack"}),o}function rn(e,t){const o=t&&t.submitButton||{},n=t&&t.secondaryButton||{};e.find("#setting-submit-style").val(o.style||"primary"),e.find("#setting-submit-size").val(o.size||""),e.find("#setting-submit-icon-start").val(o.iconStart||""),e.find("#setting-submit-icon-end").val(o.iconEnd||""),e.find("#setting-second-kind").val(n.kind==="reset"||n.kind==="link"?n.kind:""),e.find("#setting-second-label").val(n.label||""),e.find("#setting-second-url").val(n.url||""),e.find("#setting-second-style").val(n.style||"secondary"),e.find("#setting-second-icon-start").val(n.iconStart||""),e.find("#setting-second-icon-end").val(n.iconEnd||""),e.find("#setting-second-order").val(n.first?"first":"after"),e.find("#setting-second-arrange").val(n.stack?"stack":"row"),ln(e)}function Ce(e){const t=e.find("#field-project").val()||"";return V(),{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:{...Te||{},project:t||null},fields:T,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:Me(e.find("#setting-columns").val()),submitAlign:e.find("#setting-submit-align").val()||"",...wi(e),...e.find("#setting-form-class").val().trim()&&{class:e.find("#setting-form-class").val().trim()},...e.find("#setting-submit-class").val().trim()&&{submitClass:e.find("#setting-submit-class").val().trim()},...Xn(e),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()},...Se!==null&&{collection:Se}}}}function cn(e,t){const o={};return e.forEach(n=>{if(n.type==="page-break"||n.type==="spacer")return;const i={...n.formConfig||{}};i.span==="full"&&t&&(i.span=t);const a=n.type==="chooser"||!!(n.variant&&["select","radio","checkbox-group"].includes(n.type)),l={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:Array.isArray(n.options)?n.options.map(d=>_n(d?.description)?{...d,description:Dn(d.description)}:d):n.options,formConfig:{...n.placeholder&&{placeholder:n.placeholder},...n.helper&&{helperText:n.helper},...n.tooltip&&{tooltip:n.tooltip},...i}};a&&(n.variant&&(l.variant=n.variant),(n.multiple||n.type==="checkbox-group")&&(l.multiple=!0),n.density&&(l.density=n.density),n.columns&&(l.columns=n.columns),n.accent&&(l.accent=n.accent),n.accentStyle&&(l.accentStyle=n.accentStyle),n.glow&&(l.glow=!0),n.glowColour&&(l.glowColour=n.glowColour),n.shadow&&(l.shadow=n.shadow),n.shadowColour&&(l.shadowColour=n.shadowColour)),o[n.name]=n.type==="file"?vn(n,l):l}),o}function dn(e,t){const o=typeof e=="string"?document.querySelector(e):e;o&&(t||[]).forEach(n=>{if(n.type!=="date"||!n.name)return;const i=o.querySelector(`[name="${n.name}"]`);i&&i.type!=="date"&&(i.type="date")})}function st(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 un=e=>String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");let Y=null,pn=0,mn=!1;const Re=e=>String(e||"").split("?")[0].replace(/\/$/,"");function Ci(){mn||!window.R?.use||(mn=!0,R.use((e,t,o)=>!Y||!Nt(t?.path,e?.path)||Y.path!==Re(t?.path)||(Y.flush(),!Y.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(Y&&Y.path===Re(t?.path)&&Nt(t?.path,e?.path)){const o=Y;Y=null,o.dispose()}}))}export const formEditorView={templateUrl:"/admin/js/templates/form-editor.html",async onMount(e){if(Ci(),Y){const c=Y;Y=null,c.dispose()}const t=Re(location.hash.replace(/^#/,"")),o=++pn,n=()=>o!==pn||!e.get(0)?.isConnected||Re(location.hash.replace(/^#/,""))!==t;T=[],I=null,Se=null,xi(e),e.find("#setting-second-kind").get(0)?.addEventListener("change",()=>ln(e));const i=window.location.hash.match(/\/forms\/edit\/([^/?#]+)/);I=i?i[1]:null;let a=null,s=null;const l=E.loader(e.get(0),{type:"dots"});if(I)try{if(a=await fe(`/forms/${I}`),n()){l.destroy();return}T=a.fields||[],Se=a.actions?.collection??null}catch(c){if(n()){l.destroy();return}s={missing:c?.status===404,message:c?.message||String(c)},E.toast(s.missing?"This form no longer exists.":`Could not load the form: ${s.message}`,{type:"error"})}Te={};try{const c=await fe("/projects").catch(()=>[]);if(n()){l.destroy();return}const h=e.find("#field-project").get(0);h&&(Array.isArray(c)?c:[]).forEach(y=>{const k=document.createElement("option");k.value=y.slug,k.textContent=y.name||y.slug,h.appendChild(k)})}catch{}if(l.destroy(),Qe(e,{}),st(e.get(0),a?a.title||a.slug:"New form"),I||e.find("#field-title").get(0).addEventListener("input",function(){e.find("#field-slug").val(Ft(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),Te=a.meta||{},e.find("#field-project").val(a.meta?.project||"");const c=a.settings||{};e.find("#setting-submit-text").val(c.submitText||"Submit"),e.find("#setting-success-message").val(c.successMessage||""),e.find("#setting-layout").val(c.layout||"grid"),e.find("#setting-columns").val(Me(c.columns)),e.find("#setting-submit-align").val(kt(c,c.layout||"grid")),rn(e,c),e.find("#setting-form-class").val(c.class||""),e.find("#setting-submit-class").val(c.submitClass||""),Qe(e,c),e.find("#columns-group").get(0).style.display=(c.layout||"grid")==="grid"?"":"none",e.find("#setting-honeypot").prop("checked",c.honeypot!==!1),e.find("#setting-rate-limit").val(c.rateLimitPerMinute||3),e.find("#setting-success-redirect").val(c.successRedirect||"");const h=a.actions?.email||{};e.find("#action-email-enabled").prop("checked",h.enabled||!1),e.find("#action-email-recipients").val(h.recipients||""),e.find("#action-email-subject-prefix").val(h.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 d=a?.settings?.actionSlug||"";try{const c=await fe("/actions").catch(()=>[]);if(n())return;const h=e.find("#action-cms-slug").get(0);if(ke=Array.isArray(c)?c:[],(Array.isArray(c)?c:[]).forEach(y=>{const k=document.createElement("option");k.value=y.slug,k.textContent=y.title||y.slug,y.slug===d&&(k.selected=!0),h.appendChild(k)}),!c.length){const y=document.createElement("option");y.value="",y.textContent="No actions available",y.disabled=!0,h.appendChild(y)}}catch{}const r=c=>{e.find("#columns-group").get(0).style.display=c?"":"none",document.querySelectorAll(".fb-grid-row").forEach(h=>{h.style.display=c?"flex":"none"})};e.find("#setting-layout").get(0)?.addEventListener("change",function(){r(this.value==="grid")}),r(e.find("#setting-layout").val()==="grid"),ie(e);const u=e.find("#add-element-menu").get(0);e.find("#add-element-btn").get(0).addEventListener("click",c=>{c.stopPropagation(),u.style.display=u.style.display==="none"?"":"none"}),se&&document.removeEventListener("click",se),se=()=>{u&&(u.style.display="none")},document.addEventListener("click",se),e.find("#add-field-btn").get(0).addEventListener("click",()=>{u&&(u.style.display="none"),V();const c=T.length;T.push({name:`field_${c+1}`,type:"string",label:"New Field",required:!1,placeholder:""}),ie(e);const h=e.find("#fields-list").get(0)?.lastElementChild;if(h){const y=h.querySelector(".fb-field-body");y&&(y.style.display="")}}),e.find("#add-spacer-btn").get(0).addEventListener("click",()=>{u&&(u.style.display="none"),V(),T.push({type:"spacer"}),ie(e)}),e.find("#add-page-break-btn").get(0).addEventListener("click",()=>{u&&(u.style.display="none"),V();const c=T.filter(h=>h.type==="page-break").length+2;T.push({type:"page-break",label:`Step ${c}`,description:""}),ie(e)}),Ne=()=>{const c=Ce(e),h=e.find("#preview-container").get(0);if(!h)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=I?"":"none"),e.find("#preview-card").get(0).style.display="",Ct(h),h.textContent="";const q=document.createElement("div");q.id="fb-preview-form",h.appendChild(q);const W=new Map;En(q,c.fields);const G=I?async _=>{y&&(y.style.display="none",y.textContent="");try{const A=new Map(W);wt(q,A);const ne=wn(_,c.fields,A),ae=Cn(ne.values,ne.files),U=await fetch(`/api/forms/submit/${I}`,{method:"POST",headers:ae.headers,body:ae.body}),Q=await U.json();if(!U.ok)throw new Error(Q.error||"Submission failed.");y&&(y.textContent=Q.message||c.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(A){y&&(y.textContent=A.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(A.message,{type:"error"})}return!1}:()=>!1,me=c.fields.some(_=>_.type==="page-break");if(q.addEventListener("click",_=>{const A=_.target.closest?.("a.fb-secondary-btn");A&&(_.preventDefault(),E.toast(`Cancel takes the visitor to ${A.getAttribute("href")}`,{type:"info"}))}),q.addEventListener("dm-form-end",_=>{const A=_.detail?.validation;if(A&&!A.valid){E.toast(`Still to answer: ${A.missing.map(ne=>ne.label).concat(A.errors).join(", ")}`,{type:"warning"});return}G(_.detail?.values||{})}),typeof F<"u"){const _=Me(c.settings?.columns),A=c.settings?.layout||"grid";if(me&&F.wizard){const ne=yn(c.fields,c.title),ae=ne.map(oe=>({title:oe.title,description:Rn(oe.description,{legacyHtml:!0}),fields:cn(oe.fields,_)}));let U=0,Q=null,Pe=null;const yt=oe=>{const je=(ne[U]||{}).fields||[];Sn(q,c.settings),Et(q,c.settings,je),dn("#fb-preview-form",je),vt(q,je),xn(q,W),oe&&window.FormLogicEngine&&It(c.fields)&&(Q?.destroy?.(),Q=new window.FormLogicEngine.FormLogicRuntime({fields:c.fields},q,{baseValues:Pe?.getStepData?Pe.getStepData():{}}),Q.init())};Pe=F.wizard("#fb-preview-form",{schema:{steps:ae},layout:A,columns:_,finishText:c.settings?.submitText||"Finish",onStepChange:oe=>{wt(q,W),U=oe,queueMicrotask(()=>yt(!0))},onSubmit:G}),yt(!1)}else if(F.render){const ne=cn(c.fields,_),ae={};c.fields.forEach(U=>{if(!(!U.name||U.type==="page-break"||U.type==="spacer")&&(U.type==="select"||U.type==="multiselect")&&U.required){const Q=(U.options||[])[0];Q&&(ae[U.name]=typeof Q=="object"?Q.value:Q)}}),F.render("#fb-preview-form",ne,ae,{submitText:c.settings?.submitText||"Submit",layout:A,columns:_,onSubmit:G}),kn(q,c.settings,A),Et(q,c.settings,c.fields),dn("#fb-preview-form",c.fields),vt(q,c.fields)}window.FormLogicEngine&&It(c.fields)&&requestAnimationFrame(()=>{new window.FormLogicEngine.FormLogicRuntime({fields:c.fields},q).init()})}else{const _=document.createElement("p");_.textContent=`${c.fields.filter(A=>A.type!=="page-break").length} field(s): ${c.fields.filter(A=>A.type!=="page-break").map(A=>A.label).join(", ")}`,_.style.cssText="color:var(--dm-text-muted);font-style:italic;",q.appendChild(_)}},Ne();const p=e.find("#editor-tabs").get(0),m=e.find("#preview-card").get(0),g=c=>{m&&m.contains(c.target)||Ye()};p&&(p.addEventListener("input",g),p.addEventListener("change",g));const f=e.get(0),v=[],w=c=>(v.push(c),c);let L=!1;const x=M.observable(!1),b=M.observable(!1);let C=I,$=null,j=!1,H=!1,J=!1,O=Ce(e),X=Ee(O),K=O;const le=()=>{L||!f.isConnected||(K=Ce(e),x.value=Ee(K)!==X)};let de=null;Ke=()=>{clearTimeout(de),de=setTimeout(le,150)},w(()=>{clearTimeout(de),Ke=null,ve=null}),w(()=>Ct(f.querySelector("#preview-container")));const De=c=>{const h=c.settings||{};e.find("#field-title").val(c.title||""),e.find("#field-slug").val(c.slug||""),e.find("#field-description").val(c.description||""),e.find("#field-bundled").prop("checked",!!c.bundled),Te={...c.meta||{}},e.find("#field-project").val(c.meta?.project||""),e.find("#setting-submit-text").val(h.submitText||"Submit"),e.find("#setting-success-message").val(h.successMessage||""),e.find("#setting-layout").val(h.layout||"grid"),e.find("#setting-columns").val(Me(h.columns)),e.find("#setting-submit-align").val(kt(h,h.layout||"grid")),rn(e,h),e.find("#setting-form-class").val(h.class||""),e.find("#setting-submit-class").val(h.submitClass||""),Qe(e,h),e.find("#setting-honeypot").prop("checked",h.honeypot!==!1),e.find("#setting-rate-limit").val(h.rateLimitPerMinute||3),e.find("#setting-success-redirect").val(h.successRedirect||""),e.find("#action-cms-slug").val(h.actionSlug||"");const y=c.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=c.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"),T=JSON.parse(JSON.stringify(c.fields||[])),r((h.layout||"grid")==="grid"),ie(e)};async function _e(){if(b.peek()||L)return;if(s){E.toast("This form did not load, so saving would replace it with an empty one. Reload the page to try again.",{type:"error"});return}const c=Ce(e);if(!c.title){E.toast("Please enter a form title (Form Details).",{type:"error"});return}const h=Tn(c.settings);if(h.length){E.toast(`${h[0]} (Settings > Submit Button)`,{type:"error"});return}const y=Nn(c.settings,c.fields);if(y.length){E.toast(y[0],{type:"error"});return}const k=ti(c.fields);k.length&&E.toast(`Some trigger messages use ${k.map(G=>`{{${G}}}`).join(", ")}, which will show as blank: no field has that name, or it is a password, file or image.`,{type:"warning",duration:9e3}),b.value=!0;const q=I,W=he(C);q||(f.inert=!0);try{if(I?(await fe(`/forms/${I}`,{method:"PUT",body:JSON.stringify(c)}),E.toast("Form saved.",{type:"success"})):(I=(await fe("/forms",{method:"POST",body:JSON.stringify(c)})).slug,E.toast("Form created.",{type:"success"})),L){if(!q)try{S.remove?S.remove(W):S.set(W,null)}catch{}return}C=I,O=c,X=Ee(c),$=null,H=!1,J=!1,clearTimeout(de),le();for(const G of new Set([W,he(I)]))try{S.remove?S.remove(G):S.set(G,null)}catch{}st(f,c.title),qn("#/forms"),q||R.navigate(`/forms/edit/${I}`)}catch(G){q||(I=null),E.toast(G.message||"Failed to save form.",{type:"error"})}finally{b.value=!1,f.inert=!1}}async function fn(){x.peek()&&(!await E.confirm("Throw away the changes you have not saved?",{confirmText:"Throw away",cancelText:"Keep editing"})||L||(De(O),le(),ht()))}qt("#field-description"),w(()=>on(!0));const lt=f.querySelector(".fex-bar");if(lt){const c=M.applyBindings({dirty:x,saving:b},lt,{methods:{save:_e,discard:fn}});w(()=>c.dispose())}const ue=new Map,rt=()=>{for(const[c,h]of ue)f.contains(c)||(h(),ue.delete(c));for(const c of f.querySelectorAll("[data-help]:not([data-help-ready])"))ue.set(c,Ln(c,{position:"bottom"}))};rt();const ct=new MutationObserver(rt);ct.observe(f,{childList:!0,subtree:!0}),w(()=>{ct.disconnect();for(const c of ue.values())c();ue.clear()}),Ve(e,{id:"form-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>_e()}),Ve(e,{id:"form-editor-back",icon:"arrow-left",title:"All forms",onClick:()=>{location.hash="#/forms"}}),I&&Ve(e,{id:"form-editor-subs",icon:"list",title:"Submissions",onClick:()=>{location.hash=`#/forms/${encodeURIComponent(I)}/submissions`}});const dt=c=>{n()||!(c.ctrlKey||c.metaKey)||String(c.key).toLowerCase()!=="s"||(c.preventDefault(),c.stopImmediatePropagation(),_e())};document.addEventListener("keydown",dt,!0),w(()=>document.removeEventListener("keydown",dt,!0));const ee=e.find("#fields-list").get(0),hn=c=>c?.closest?.(".fb-field-card"),ut=c=>Number(c?.dataset.index),pt=c=>c?.querySelector(":scope > .fb-field-body"),mt=c=>{const h=pt(c);h&&(h.style.display=h.style.display==="none"?"":"none")},pe=(c,h)=>{T=c,ie(e),h!=null&&ee?.querySelectorAll(".fb-field-card")[h]?.focus()},bn=async c=>{try{await navigator.clipboard.writeText(c),E.toast(`Copied "${c}".`,{type:"success"})}catch{E.toast(`Copy failed - the name is ${c}.`,{type:"info"})}},gn=c=>{const h=hn(c),y=ut(h);V();const k=T[y];if(!k)return[];const q=k.type!=="spacer"&&k.type!=="page-break",W=pt(h),G=W&&W.style.display!=="none";return[{header:Ue(k)},...W?[{label:G?"Close":"Edit",icon:G?"chevron-up":"edit",action:()=>mt(h)}]:[],...q?[{label:"Logic & triggers",icon:"zap",action:()=>{W&&(W.style.display=""),(W?.querySelector(".fb-field-logic")||W)?.scrollIntoView({block:"center",behavior:"smooth"})}}]:[],{label:"Duplicate",icon:"copy",action:()=>{V(),pe(Bn(T,y),y+1)}},{type:"divider"},{label:"Move up",icon:"arrow-up",shortcut:"Alt+\u2191",disabled:y===0,action:()=>{V(),pe(Lt(T,y,-1),y-1)}},{label:"Move down",icon:"arrow-down",shortcut:"Alt+\u2193",disabled:y>=T.length-1,action:()=>{V(),pe(Lt(T,y,1),y+1)}},...q&&k.name?[{label:"Copy field name",icon:"clipboard",action:()=>bn(k.name)}]:[],{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:async()=>{if(k.type!=="spacer"&&!await E.confirm(`Remove "${un(Ue(k))}"?`))return;V();const me=[...T];me.splice(y,1),pe(me,Math.min(y,me.length-1))}}]};if(ee&&typeof E.sortable=="function"){const c=E.sortable(ee,{items:".fb-field-card",handle:".fb-drag-grip",key:null,onSort:({from:h,to:y})=>{V();const k=[...T],[q]=k.splice(h,1);k.splice(y,0,q),pe(k,y)}});w(()=>c.destroy())}let ft=null;if(ee&&E.contextMenu&&(ft=E.contextMenu(ee,{cursor:"glyph",match:".fb-field-card > :first-child",inherit:!1,density:"compact",items:c=>gn(c)}),w(()=>ft?.destroy?.())),ve=c=>{for(const h of c.querySelectorAll(".fb-field-card")){h.tabIndex=0;const y=h.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",V(),k.setAttribute("aria-label",`Actions for ${Ue(T[ut(h)])}`),k.addEventListener("click",q=>{q.stopPropagation(),St(k)}),y.appendChild(k)}},ee){ve(ee);const c=h=>{const y=h.target?.classList?.contains("fb-field-card")?h.target:null;y&&(h.key==="F10"&&h.shiftKey?(h.preventDefault(),St(y.firstElementChild)):h.key==="Enter"&&(h.preventDefault(),mt(y)))};ee.addEventListener("keydown",c),w(()=>ee.removeEventListener("keydown",c))}const ht=()=>{try{const c=he(C);S.remove?S.remove(c):S.set(c,null)}catch{}},bt=c=>{if(!s){if(!x.peek()||!c){!j&&!J&&ht();return}try{S.set(he(C),{data:Fn(c),base:$n($,Tt(X)),...H?{newFrom:!0}:{},at:new Date().toISOString()})}catch{}}},gt=c=>{le(),x.peek()&&(bt(K),c.preventDefault(),c.returnValue="")};if(window.addEventListener("beforeunload",gt),w(()=>window.removeEventListener("beforeunload",gt)),w(()=>{se&&(document.removeEventListener("click",se),se=null)}),Y={path:t,dirty:()=>x.peek(),flush:()=>{clearTimeout(de),le()},dispose(){L||(bt(K),L=!0,v.splice(0).reverse().forEach(c=>{try{c?.()}catch{}}))}},s){const c=document.createElement("p");c.className="fex-load-error",c.setAttribute("role","alert"),c.textContent=s.missing?"This form no longer exists - it may have been deleted. Nothing here can be saved over it.":`This form could not be loaded (${s.message}). Saving is off so an empty editor cannot replace it - reload the page to try again.`;const h=f.querySelector(".fex-bar");h?h.before(c):f.prepend(c),w(()=>c.remove())}const ze=he(I);let te=null;try{te=S.get(ze)}catch{}if(te?.data&&(!s||s.missing)){const c=!!s?.missing,h=An(te,{missing:c});j=!0;const y=await E.confirm(un(In(te,{current:Tt(X),missing:c,when:te.at?Mn(te.at):""})),{title:"Unsaved changes",confirmText:"Throw away",cancelText:h==="new"?"Start a new form":h==="refuse"?"Not now":"Keep them"});if(j=!1,y)try{S.remove?S.remove(ze):S.set(ze,null)}catch{}else h==="refuse"?J=!0:L||(c?(I=null,s=null,$="",H=!0,O=Ce(e),X=Ee(O),st(f,"New form"),f.querySelector(".fex-load-error")?.remove(),De(te.data)):($=te.base??"",De(On(te.data,O))),le())}}};
|