grapesjs-forms 0.0.0-stage → 0.1.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.
@@ -0,0 +1,2754 @@
1
+ var Et = Object.defineProperty;
2
+ var _t = (i, e, t) => e in i ? Et(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t;
3
+ var T = (i, e, t) => _t(i, typeof e != "symbol" ? e + "" : e, t);
4
+ const et = /\{\{\s*([A-Za-z_][\w.\-]*)\s*\}\}/g, kt = /* @__PURE__ */ new Set(["form", "page"]);
5
+ function Ct(i, e = {}) {
6
+ return String(i ?? "").replace(et, (t, s) => {
7
+ const [a, ...r] = s.split(".");
8
+ if (!kt.has(a)) return t;
9
+ const l = a === "form" ? e.form : e.page;
10
+ if (a === "page" && !l) return t;
11
+ let o = l;
12
+ for (const u of r) o = o && typeof o == "object" ? o[u] : void 0;
13
+ return o == null || typeof o == "object" ? "" : String(o);
14
+ });
15
+ }
16
+ const At = (i) => !!i && new RegExp(et.source).test(i), Lt = [
17
+ { token: "{{url}}", at: "run" },
18
+ { token: "{{path}}", at: "run" },
19
+ { token: "{{host}}", at: "run" },
20
+ { token: "{{referrer}}", at: "run" },
21
+ { token: "{{title}}", at: "run" },
22
+ { token: "{{lang}}", at: "run" },
23
+ { token: "{{query.utm_source}}", at: "run" },
24
+ { token: "{{cookie.name}}", at: "run" },
25
+ { token: "{{storage.key}}", at: "run" },
26
+ { token: "{{date}}", at: "run" },
27
+ { token: "{{time}}", at: "run" },
28
+ { token: "{{datetime}}", at: "run" },
29
+ { token: "{{timestamp}}", at: "run" },
30
+ { token: "{{uuid}}", at: "run" },
31
+ { token: "{{form.id}}", at: "build" },
32
+ { token: "{{form.name}}", at: "build" },
33
+ { token: "{{page.id}}", at: "build" },
34
+ { token: "{{page.name}}", at: "build" },
35
+ { token: "{{page.slug}}", at: "build" }
36
+ ], je = [
37
+ "text",
38
+ "email",
39
+ "tel",
40
+ "url",
41
+ "number",
42
+ "password",
43
+ "textarea",
44
+ "select",
45
+ "radio",
46
+ "checkbox",
47
+ "checkboxes",
48
+ "date",
49
+ "time",
50
+ "datetime",
51
+ "range",
52
+ "color",
53
+ "file",
54
+ "hidden"
55
+ ], fe = ["heading", "paragraph"], Ft = [...je, ...fe], me = ["select", "radio", "checkboxes"], we = ["text", "email", "tel", "url", "password", "textarea"], $t = ["number", "range", "date", "time", "datetime"], O = (i) => fe.includes(i), tt = (i) => me.includes(i), st = ["full", "1/2", "1/3", "2/3", "1/4", "3/4"], Tt = /^[A-Za-z_][A-Za-z0-9_.\-[\]]{0,63}$/, Ot = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/, Nt = /* @__PURE__ */ new Set(["id", "name", "type", "value", "for", "form", "formaction", "srcdoc", "action", "method"]);
56
+ function W(i) {
57
+ const e = String(i || "").normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64);
58
+ return e ? /^[a-z_]/.test(e) ? e : `f_${e}`.slice(0, 64) : "";
59
+ }
60
+ function re(i, e) {
61
+ if (!e.has(i)) return i;
62
+ let t = 2;
63
+ for (; e.has(`${i}_${t}`.slice(0, 64)); ) t++;
64
+ return `${i}_${t}`.slice(0, 64);
65
+ }
66
+ function ke(i, e = Nt) {
67
+ if (!i || typeof i != "object" || Array.isArray(i)) return;
68
+ const t = {};
69
+ return Object.entries(i).forEach(([s, a]) => {
70
+ const r = String(s).trim();
71
+ if (!Ot.test(r) || /^on/i.test(r) || e.has(r.toLowerCase()) || a == null || typeof a == "object") return;
72
+ const l = String(a);
73
+ /^\s*(javascript|vbscript|data:text\/html)/i.test(l) || (t[r] = l);
74
+ }), Object.keys(t).length ? t : void 0;
75
+ }
76
+ let It = 0;
77
+ const Y = () => `f${Date.now().toString(36)}${(It++).toString(36)}${Math.random().toString(36).slice(2, 6)}`, ae = (i) => i == null || i === "" ? void 0 : typeof i == "string" ? i : typeof i == "number" || typeof i == "boolean" ? String(i) : void 0, Rt = (i) => {
78
+ const e = typeof i == "number" ? i : typeof i == "string" && i.trim() ? Number(i) : NaN;
79
+ return Number.isInteger(e) && e >= 0 ? e : void 0;
80
+ };
81
+ function Dt(i) {
82
+ const e = typeof i == "string" ? i.split(/\r?\n/) : Array.isArray(i) ? i : [], t = [], s = /* @__PURE__ */ new Set();
83
+ return e.forEach((a) => {
84
+ let r, l;
85
+ if (typeof a == "string" || typeof a == "number") {
86
+ const o = String(a).trim(), u = o.indexOf("|");
87
+ u > 0 ? (l = o.slice(0, u).trim(), r = o.slice(u + 1).trim()) : l = r = o;
88
+ } else a && typeof a == "object" && (l = ae(a.value ?? a.label ?? a.text), r = ae(a.label ?? a.text ?? a.value));
89
+ l == null || l === "" || s.has(l) || (s.add(l), t.push({ label: r || l, value: l }));
90
+ }), t;
91
+ }
92
+ function Mt(i) {
93
+ if (!i || typeof i != "object") return null;
94
+ const e = Ft.includes(i.type) ? i.type : "text", t = { id: typeof i.id == "string" && i.id ? i.id : Y(), type: e, name: "" };
95
+ O(e) || (t.name = typeof i.name == "string" && Tt.test(i.name) ? i.name : W(i.name || i.label || "") || e);
96
+ const s = (r) => {
97
+ const l = ae(i[r]);
98
+ l !== void 0 && (t[r] = l);
99
+ };
100
+ ["label", "placeholder", "help", "value", "min", "max", "step", "pattern", "accept", "autocomplete", "text"].forEach(s), ["required", "multiple", "readonly", "disabled"].forEach((r) => {
101
+ i[r] === !0 && (t[r] = !0);
102
+ }), ["minLength", "maxLength", "rows"].forEach((r) => {
103
+ const l = Rt(i[r]);
104
+ l !== void 0 && (t[r] = l);
105
+ }), st.includes(i.width) && i.width !== "full" && (t.width = i.width), tt(e) && (t.options = Dt(i.options));
106
+ const a = ke(i.attrs);
107
+ return a && (t.attrs = a), e === "hidden" && (delete t.required, delete t.placeholder, delete t.width), O(e) && (["required", "placeholder", "value", "help"].forEach((r) => delete t[r]), t.text === void 0 && t.label && (t.text = t.label), delete t.label), t;
108
+ }
109
+ function Pt(i) {
110
+ const e = [], t = /* @__PURE__ */ new Set(), s = /* @__PURE__ */ new Set();
111
+ return (Array.isArray(i) ? i : []).forEach((a) => {
112
+ const r = Mt(a);
113
+ r && (s.has(r.id) && (r.id = Y()), s.add(r.id), O(r.type) || (r.name = re(r.name, t), t.add(r.name)), e.push(r));
114
+ }), e;
115
+ }
116
+ function Ut(i) {
117
+ const e = i && typeof i == "object" ? i : {}, t = {};
118
+ return ["endpoint", "successMessage", "errorMessage", "redirect", "submitLabel"].forEach((s) => {
119
+ const a = ae(e[s]);
120
+ a !== void 0 && a.trim() && (t[s] = a.trim());
121
+ }), t.endpoint && !$e(t.endpoint) && delete t.endpoint, t.redirect && !$e(t.redirect) && delete t.redirect, e.reset === !1 && (t.reset = !1), e.honeypot === !1 && (t.honeypot = !1), t;
122
+ }
123
+ const $e = (i) => /^(https?:\/\/|\/|\.{0,2}\/|\?|#)/i.test(i.trim()) || !/^[a-z][a-z0-9+.-]*:/i.test(i.trim());
124
+ function V(i) {
125
+ const e = i && typeof i == "object" ? i : {}, t = {
126
+ id: ae(e.id) || "",
127
+ name: (ae(e.name) || "").trim() || "Form",
128
+ fields: Pt(e.fields),
129
+ settings: Ut(e.settings)
130
+ }, s = ke(e.attrs);
131
+ return s && (t.attrs = s), e.version !== void 0 && e.version !== null && (t.version = e.version), typeof e.updatedAt == "string" && (t.updatedAt = e.updatedAt), t;
132
+ }
133
+ const it = (i) => i.fields.filter((e) => !O(e.type)), Te = (i) => i.label || i.text || i.name || i.type, Se = "_gjsf_hp", Jt = /^[^\s@<>()[\],;:"]+@[^\s@<>()[\],;:"]+\.[^\s@<>()[\],;:"]{2,}$/, Ht = /^\d{4}-\d{2}-\d{2}$/, zt = /^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/, Bt = /^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/, Vt = /^#[0-9a-f]{6}$/i, Oe = (i) => i == null || i === "" || Array.isArray(i) && i.length === 0 || i === !1, qt = (i) => i == null || i === "" ? [] : Array.isArray(i) ? i.map((e) => String(e)).filter((e) => e !== "") : String(i).split(",").map((e) => e.trim()).filter(Boolean), Yt = (i) => i === !0 || i === 1 || typeof i == "string" && /^(1|true|on|yes)$/i.test(i.trim());
134
+ function Kt(i, e = {}) {
135
+ const t = [], s = {}, a = (o, u) => void t.push({ field: o, code: u }), r = !!e && typeof e[Se] == "string" && e[Se].trim() !== "";
136
+ it(i).forEach((o) => {
137
+ const u = e == null ? void 0 : e[o.name];
138
+ if (o.type === "checkbox") {
139
+ const h = Yt(u);
140
+ o.required && !h && a(o.name, "required"), s[o.name] = h;
141
+ return;
142
+ }
143
+ if (o.type === "checkboxes" || o.type === "select" && o.multiple) {
144
+ const h = qt(u);
145
+ if (!h.length) {
146
+ o.required && a(o.name, "required"), s[o.name] = [];
147
+ return;
148
+ }
149
+ const y = new Set((o.options || []).map((p) => p.value));
150
+ y.size && h.some((p) => !y.has(p)) && a(o.name, "option"), s[o.name] = h;
151
+ return;
152
+ }
153
+ if (o.type === "file") {
154
+ if (Oe(u)) {
155
+ o.required && a(o.name, "required");
156
+ return;
157
+ }
158
+ s[o.name] = u;
159
+ return;
160
+ }
161
+ const n = Oe(u) ? "" : Array.isArray(u) ? String(u[0] ?? "") : String(u), d = o.type === "textarea" || o.type === "password" ? n : n.trim();
162
+ if (!d) {
163
+ o.required && a(o.name, "required"), s[o.name] = o.type === "number" || o.type === "range" ? null : "";
164
+ return;
165
+ }
166
+ if (we.includes(o.type) && (o.minLength != null && d.length < o.minLength && a(o.name, "minLength"), o.maxLength != null && d.length > o.maxLength && a(o.name, "maxLength")), o.type === "email" && !Jt.test(d) && a(o.name, "email"), o.type === "url" && !/^https?:\/\/[^\s]+\.[^\s]+/i.test(d) && a(o.name, "url"), o.type === "color" && !Vt.test(d) && a(o.name, "color"), o.pattern && we.includes(o.type))
167
+ try {
168
+ new RegExp(`^(?:${o.pattern})$`, "u").test(d) || a(o.name, "pattern");
169
+ } catch {
170
+ }
171
+ if (tt(o.type)) {
172
+ const h = new Set((o.options || []).map((y) => y.value));
173
+ h.size && !h.has(d) && a(o.name, "option");
174
+ }
175
+ if (o.type === "number" || o.type === "range") {
176
+ const h = Number(d.replace(",", "."));
177
+ if (!Number.isFinite(h)) {
178
+ a(o.name, "number"), s[o.name] = d;
179
+ return;
180
+ }
181
+ o.min != null && o.min !== "" && h < Number(o.min) && a(o.name, "min"), o.max != null && o.max !== "" && h > Number(o.max) && a(o.name, "max"), s[o.name] = h;
182
+ return;
183
+ }
184
+ const b = o.type === "date" ? Ht : o.type === "time" ? zt : o.type === "datetime" ? Bt : null;
185
+ b && (b.test(d) ? (o.min && d < o.min && a(o.name, "min"), o.max && d > o.max && a(o.name, "max")) : a(o.name, o.type === "time" ? "time" : "date")), s[o.name] = d;
186
+ });
187
+ const l = {};
188
+ return t.forEach((o) => {
189
+ var u;
190
+ return (l[u = o.field] || (l[u] = [])).push(o.code);
191
+ }), { ok: !t.length, problems: t, errors: l, data: s, spam: r };
192
+ }
193
+ const L = {
194
+ form: "gjsf-form",
195
+ field: "gjsf-field",
196
+ label: "gjsf-label",
197
+ req: "gjsf-req",
198
+ input: "gjsf-input",
199
+ options: "gjsf-options",
200
+ option: "gjsf-option",
201
+ check: "gjsf-check",
202
+ optionLabel: "gjsf-option-label",
203
+ help: "gjsf-help",
204
+ error: "gjsf-error",
205
+ heading: "gjsf-heading",
206
+ text: "gjsf-text",
207
+ actions: "gjsf-actions",
208
+ submit: "gjsf-submit",
209
+ message: "gjsf-message",
210
+ hp: "gjsf-hp"
211
+ }, Ne = { "1/2": "gjsf-w-1-2", "1/3": "gjsf-w-1-3", "2/3": "gjsf-w-2-3", "1/4": "gjsf-w-1-4", "3/4": "gjsf-w-3-4" }, Wt = { datetime: "datetime-local" };
212
+ function be(i) {
213
+ const e = { ...i.attrs || {} }, t = (e.class || "").split(/\s+/).filter(Boolean);
214
+ return delete e.class, { attrs: e, classes: t };
215
+ }
216
+ function rt(i, e = {}) {
217
+ var r, l;
218
+ const t = i.settings || {}, s = { ...ke(i.attrs) || {} };
219
+ delete s.class, Object.assign(s, {
220
+ "data-gjsf-form": i.id,
221
+ method: "post",
222
+ "data-gjsf-success": t.successMessage || ((r = e.texts) == null ? void 0 : r.success) || "",
223
+ "data-gjsf-error": t.errorMessage || ((l = e.texts) == null ? void 0 : l.error) || ""
224
+ });
225
+ const a = t.endpoint || e.action || "";
226
+ return a && (s.action = a), i.version != null && (s["data-gjsf-version"] = String(i.version)), t.redirect && (s["data-gjsf-redirect"] = t.redirect), t.reset === !1 && (s["data-gjsf-reset"] = "false"), it(i).some((o) => o.type === "file") && (s.enctype = "multipart/form-data"), e.codes && Object.keys(e.codes).length && (s["data-gjsf-codes"] = JSON.stringify(e.codes)), e.pageId && (s["data-gjsf-page"] = e.pageId), s;
227
+ }
228
+ function at(i, e = {}) {
229
+ var l, o, u;
230
+ const t = { form: { id: i.id, name: i.name }, ...e.ctx || {} }, s = (e.key || i.id.slice(0, 8)).replace(/[^\w-]/g, ""), a = (n, d) => `gjsf-${s}-${n.name.replace(/[^\w-]/g, "_")}${d == null ? "" : `-${d}`}`, r = [];
231
+ return i.fields.forEach((n) => {
232
+ if (O(n.type)) {
233
+ const { attrs: E, classes: x } = be(n);
234
+ r.push(
235
+ n.type === "heading" ? { tag: "h3", part: "heading", classes: [L.heading, ...x], attrs: E, kids: [n.text || ""] } : { tag: "p", part: "text", classes: [L.text, ...x], attrs: E, kids: [n.text || ""] }
236
+ );
237
+ return;
238
+ }
239
+ let d = Ct(n.value || "", t);
240
+ const b = At(d) ? d : "";
241
+ if (b && (d = ""), n.type === "hidden") {
242
+ const { attrs: E } = be(n);
243
+ r.push({
244
+ tag: "input",
245
+ void: !0,
246
+ part: "hidden",
247
+ attrs: { ...E, type: "hidden", name: n.name, value: d, ...b ? { "data-gjsf-value": b } : {} }
248
+ });
249
+ return;
250
+ }
251
+ const { attrs: h, classes: y } = be(n), p = a(n), _ = [L.field, `${L.field}--${n.type}`, ...n.width && Ne[n.width] ? [Ne[n.width]] : [], ...n.required ? ["is-required"] : []], $ = [n.label || n.name];
252
+ n.required && $.push({ tag: "span", part: "req", classes: [L.req], attrs: { "aria-hidden": "true" }, kids: ["*"] });
253
+ const M = n.help ? { tag: "div", part: "help", classes: [L.help], attrs: { id: `${p}-help` }, kids: [n.help] } : null, B = { tag: "div", part: "error", classes: [L.error], attrs: { "data-gjsf-error-for": n.name, "aria-live": "polite" } }, P = {};
254
+ if (n.required && (P.required = ""), n.readonly && (P.readonly = ""), n.disabled && (P.disabled = ""), n.help && (P["aria-describedby"] = `${p}-help`), b && (P["data-gjsf-value"] = b), n.type === "radio" || n.type === "checkboxes") {
255
+ const E = n.type === "checkboxes", x = new Set(d.split(",").map((w) => w.trim()).filter(Boolean)), v = (n.options || []).map((w, j) => ({
256
+ tag: "label",
257
+ part: "option",
258
+ classes: [L.option],
259
+ kids: [
260
+ {
261
+ tag: "input",
262
+ void: !0,
263
+ part: "check",
264
+ classes: [L.check, ...y],
265
+ attrs: {
266
+ ...h,
267
+ type: E ? "checkbox" : "radio",
268
+ name: n.name,
269
+ value: w.value,
270
+ id: a(n, j),
271
+ ...x.has(w.value) ? { checked: "" } : {},
272
+ // A required radio group: one input is enough; checkboxes are checked by the script.
273
+ ...n.required && (!E && j === 0) ? { required: "" } : {},
274
+ ...n.disabled ? { disabled: "" } : {},
275
+ ...b ? { "data-gjsf-value": b } : {}
276
+ }
277
+ },
278
+ { tag: "span", part: "option-label", classes: [L.optionLabel], kids: [w.label] }
279
+ ]
280
+ }));
281
+ r.push({
282
+ tag: "fieldset",
283
+ part: "field",
284
+ classes: _,
285
+ attrs: { "data-gjsf-field": n.name, ...E && n.required ? { "data-gjsf-required": "" } : {}, ...n.help ? { "aria-describedby": `${p}-help` } : {} },
286
+ kids: [{ tag: "legend", part: "label", classes: [L.label], kids: $ }, { tag: "div", part: "options", classes: [L.options], kids: v }, ...M ? [M] : [], B]
287
+ });
288
+ return;
289
+ }
290
+ if (n.type === "checkbox") {
291
+ r.push({
292
+ tag: "div",
293
+ part: "field",
294
+ classes: _,
295
+ attrs: { "data-gjsf-field": n.name },
296
+ kids: [
297
+ {
298
+ tag: "label",
299
+ part: "option",
300
+ classes: [L.option],
301
+ kids: [
302
+ {
303
+ tag: "input",
304
+ void: !0,
305
+ part: "check",
306
+ classes: [L.check, ...y],
307
+ attrs: { ...h, ...P, type: "checkbox", name: n.name, value: "1", id: p, .../^(1|true|on|yes)$/i.test(d) ? { checked: "" } : {} }
308
+ },
309
+ { tag: "span", part: "option-label", classes: [L.optionLabel], kids: $ }
310
+ ]
311
+ },
312
+ ...M ? [M] : [],
313
+ B
314
+ ]
315
+ });
316
+ return;
317
+ }
318
+ let J;
319
+ if (n.type === "textarea")
320
+ J = {
321
+ tag: "textarea",
322
+ part: "input",
323
+ classes: [L.input, ...y],
324
+ attrs: {
325
+ ...h,
326
+ ...P,
327
+ name: n.name,
328
+ id: p,
329
+ ...n.placeholder ? { placeholder: n.placeholder } : {},
330
+ ...n.rows ? { rows: String(n.rows) } : {},
331
+ ...n.minLength != null ? { minlength: String(n.minLength) } : {},
332
+ ...n.maxLength != null ? { maxlength: String(n.maxLength) } : {},
333
+ ...n.autocomplete ? { autocomplete: n.autocomplete } : {}
334
+ },
335
+ kids: d ? [d] : []
336
+ };
337
+ else if (n.type === "select") {
338
+ const E = new Set(d.split(",").map((v) => v.trim()).filter(Boolean)), x = [];
339
+ n.multiple || x.push({ tag: "option", part: "choice", attrs: { value: "", ...E.size ? {} : { selected: "" }, ...n.required ? { disabled: "" } : {} }, kids: [n.placeholder || "—"] }), (n.options || []).forEach((v) => x.push({ tag: "option", part: "choice", attrs: { value: v.value, ...E.has(v.value) ? { selected: "" } : {} }, kids: [v.label] })), J = {
340
+ tag: "select",
341
+ part: "input",
342
+ classes: [L.input, ...y],
343
+ attrs: { ...h, ...P, name: n.name, id: p, ...n.multiple ? { multiple: "" } : {}, ...n.autocomplete ? { autocomplete: n.autocomplete } : {} },
344
+ kids: x
345
+ };
346
+ } else {
347
+ const E = { ...h, ...P, type: Wt[n.type] || n.type, name: n.name, id: p };
348
+ n.placeholder && !["range", "color", "file", "date", "time", "datetime"].includes(n.type) && (E.placeholder = n.placeholder), d && n.type !== "file" && n.type !== "password" && (E.value = d), n.min && (E.min = n.min), n.max && (E.max = n.max), n.step && (E.step = n.step), n.minLength != null && (E.minlength = String(n.minLength)), n.maxLength != null && (E.maxlength = String(n.maxLength)), n.pattern && (E.pattern = n.pattern), n.accept && n.type === "file" && (E.accept = n.accept), n.multiple && n.type === "file" && (E.multiple = ""), n.autocomplete && (E.autocomplete = n.autocomplete), J = { tag: "input", void: !0, part: "input", classes: [L.input, ...y], attrs: E };
349
+ }
350
+ r.push({
351
+ tag: "div",
352
+ part: "field",
353
+ classes: _,
354
+ attrs: { "data-gjsf-field": n.name },
355
+ kids: [{ tag: "label", part: "label", classes: [L.label], attrs: { for: p }, kids: $ }, J, ...M ? [M] : [], B]
356
+ });
357
+ }), ((l = i.settings) == null ? void 0 : l.honeypot) !== !1 && r.push({
358
+ tag: "div",
359
+ part: "hp",
360
+ classes: [L.hp],
361
+ attrs: { "aria-hidden": "true" },
362
+ style: { position: "absolute", left: "-10000px", width: "1px", height: "1px", overflow: "hidden" },
363
+ kids: [{ tag: "input", void: !0, part: "hp-input", attrs: { type: "text", name: Se, tabindex: "-1", autocomplete: "off", value: "" } }]
364
+ }), r.push({
365
+ tag: "div",
366
+ part: "actions",
367
+ classes: [L.actions],
368
+ kids: [{ tag: "button", part: "submit", classes: [L.submit], attrs: { type: "submit" }, kids: [((o = i.settings) == null ? void 0 : o.submitLabel) || ((u = e.texts) == null ? void 0 : u.submit) || "Send"] }]
369
+ }), r.push({ tag: "div", part: "message", classes: [L.message], attrs: { role: "status", "aria-live": "polite" } }), r;
370
+ }
371
+ const Gt = (i) => i.replace(/[&<>]/g, (e) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[e]), Zt = (i) => i.replace(/[&<>"]/g, (e) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[e]), nt = (i, e) => {
372
+ var s;
373
+ const t = { ...(s = i.classes) != null && s.length ? { class: i.classes.join(" ") } : {}, ...i.attrs || {} };
374
+ return e && (t["data-gjsf-part"] = e), i.style && (t.style = Object.entries(i.style).map(([a, r]) => `${a}:${r}`).join(";")), Object.entries(t).map(([a, r]) => r === "" && !["value", "action"].includes(a) ? ` ${a}` : ` ${a}="${Zt(r)}"`).join("");
375
+ };
376
+ function ot(i) {
377
+ if (typeof i == "string") return Gt(i);
378
+ const e = `<${i.tag}${nt(i, i.part)}>`;
379
+ return i.void ? e : `${e}${(i.kids || []).map(ot).join("")}</${i.tag}>`;
380
+ }
381
+ function Ie(i, e = {}) {
382
+ var s;
383
+ const t = [L.form, ...(((s = i.attrs) == null ? void 0 : s.class) || "").split(/\s+/).filter(Boolean), ...e.classes || []];
384
+ return `<form${nt({ classes: t, attrs: rt(i, e) })}>${at(i, e).map(ot).join("")}</form>`;
385
+ }
386
+ const Re = Symbol.for("grapesjs.plugin-controls"), Qt = "plugin:options";
387
+ function Xt(i, e) {
388
+ i.meta = e;
389
+ try {
390
+ const t = globalThis.grapesjs;
391
+ t != null && t.plugins && !t.plugins.get(e.id) && t.plugins.add(e.id, i);
392
+ } catch {
393
+ }
394
+ return i;
395
+ }
396
+ function es(i) {
397
+ const e = i;
398
+ let t = e[Re];
399
+ return t || (t = /* @__PURE__ */ new Map(), Object.defineProperty(e, Re, { value: t, configurable: !0 })), t;
400
+ }
401
+ function ts(i, e, t, s) {
402
+ const a = new Set((e.options || []).filter((o) => o.live).map((o) => o.key)), r = {
403
+ meta: e,
404
+ getOptions: () => t(),
405
+ setOptions(o) {
406
+ var d;
407
+ const u = { applied: [], reload: [] }, n = {};
408
+ return Object.keys(o || {}).forEach((b) => {
409
+ a.has(b) ? (n[b] = o[b], u.applied.push(b)) : u.reload.push(b);
410
+ }), u.applied.length && s(n), (d = i.trigger) == null || d.call(i, Qt, { id: e.id, patch: o, result: u }), u;
411
+ }
412
+ }, l = es(i);
413
+ return l.set(e.id, r), () => {
414
+ l.get(e.id) === r && l.delete(e.id);
415
+ };
416
+ }
417
+ function Ce(i) {
418
+ const e = this;
419
+ if (!e || e.__gjsf || e.tagName !== "FORM") return;
420
+ e.__gjsf = !0;
421
+ const t = e.ownerDocument, s = t.defaultView || window, a = s.location, r = (x) => Array.prototype.slice.call(e.querySelectorAll(x)), l = (x) => e.getAttribute(x) || "";
422
+ let o = {};
423
+ try {
424
+ o = JSON.parse(l("data-gjsf-codes") || "{}") || {};
425
+ } catch {
426
+ o = {};
427
+ }
428
+ const u = (x) => (x < 10 ? "0" : "") + x, n = (x) => {
429
+ const v = (t.cookie || "").split(";");
430
+ for (let w = 0; w < v.length; w++) {
431
+ const j = v[w].trim(), R = j.indexOf("=");
432
+ if (R > 0 && decodeURIComponent(j.slice(0, R)) === x) return decodeURIComponent(j.slice(R + 1));
433
+ }
434
+ return "";
435
+ }, d = () => {
436
+ const x = s.crypto;
437
+ if (x && typeof x.randomUUID == "function")
438
+ try {
439
+ return x.randomUUID();
440
+ } catch {
441
+ }
442
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (v) => {
443
+ const w = Math.random() * 16 | 0;
444
+ return (v === "x" ? w : w & 3 | 8).toString(16);
445
+ });
446
+ }, b = (x) => String(x || "").replace(/\{\{\s*([A-Za-z_][\w.-]*)\s*\}\}/g, (v, w) => {
447
+ const j = w.indexOf("."), R = j < 0 ? w : w.slice(0, j), F = j < 0 ? "" : w.slice(j + 1), N = /* @__PURE__ */ new Date();
448
+ let U = null;
449
+ try {
450
+ U = new URLSearchParams(a.search);
451
+ } catch {
452
+ U = null;
453
+ }
454
+ switch (R) {
455
+ case "url":
456
+ return a.href;
457
+ case "path":
458
+ return a.pathname;
459
+ case "host":
460
+ return a.host;
461
+ case "referrer":
462
+ return t.referrer || "";
463
+ case "title":
464
+ return t.title || "";
465
+ case "lang":
466
+ return t.documentElement.lang || s.navigator && s.navigator.language || "";
467
+ case "query":
468
+ return U && U.get(F) || "";
469
+ case "cookie":
470
+ return n(F);
471
+ case "storage":
472
+ try {
473
+ return s.localStorage.getItem(F) || "";
474
+ } catch {
475
+ return "";
476
+ }
477
+ case "date":
478
+ return N.getFullYear() + "-" + u(N.getMonth() + 1) + "-" + u(N.getDate());
479
+ case "time":
480
+ return u(N.getHours()) + ":" + u(N.getMinutes());
481
+ case "datetime":
482
+ return N.toISOString();
483
+ case "timestamp":
484
+ return String(N.getTime());
485
+ case "uuid":
486
+ return d();
487
+ case "page":
488
+ return F === "url" ? a.href : F === "path" || F === "slug" ? a.pathname : (F === "name" || F === "title") && t.title || "";
489
+ default:
490
+ return "";
491
+ }
492
+ }), h = (x) => {
493
+ r("[data-gjsf-value]").forEach((v) => {
494
+ const w = b(v.getAttribute("data-gjsf-value") || ""), j = (v.getAttribute("type") || "").toLowerCase();
495
+ if (j === "hidden") v.value = w;
496
+ else {
497
+ if (x) return;
498
+ if (j === "checkbox" || j === "radio") {
499
+ const R = w.split(",").map((F) => F.trim());
500
+ v.checked = v.value === "1" && j === "checkbox" ? /^(1|true|on|yes)$/i.test(w) : R.indexOf(v.value) >= 0;
501
+ } else if (v.tagName === "SELECT") {
502
+ const R = w.split(",").map((F) => F.trim());
503
+ Array.prototype.forEach.call(v.options, (F) => F.selected = R.indexOf(F.value) >= 0);
504
+ } else v.value || (v.value = w);
505
+ }
506
+ });
507
+ };
508
+ h(!1);
509
+ const y = e.querySelector(".gjsf-message"), p = r('[type="submit"]'), _ = (x, v) => {
510
+ e.classList.remove("is-sending", "is-success", "is-error"), x && e.classList.add("is-" + x), e.setAttribute("aria-busy", x === "sending" ? "true" : "false"), p.forEach((w) => w.disabled = x === "sending"), y && (y.textContent = v || "", v ? y.removeAttribute("hidden") : y.setAttribute("hidden", ""));
511
+ }, $ = (x) => x.replace(/["\\]/g, "\\$&"), M = (x) => e.querySelector('[data-gjsf-field="' + $(x) + '"]'), B = (x) => {
512
+ const v = M(x);
513
+ v && v.classList.remove("has-error");
514
+ const w = e.querySelector('[data-gjsf-error-for="' + $(x) + '"]');
515
+ w && (w.textContent = ""), r('[name="' + $(x) + '"]').forEach((j) => j.removeAttribute("aria-invalid"));
516
+ }, P = () => {
517
+ r("[data-gjsf-field]").forEach((x) => B(x.getAttribute("data-gjsf-field") || ""));
518
+ }, J = (x) => {
519
+ let v = null, w = !1;
520
+ return Object.keys(x || {}).forEach((j) => {
521
+ const R = [].concat(x[j]).map((U) => o[U] || U), F = M(j), N = e.querySelector('[data-gjsf-error-for="' + $(j) + '"]');
522
+ !F && !N || (w = !0, F && F.classList.add("has-error"), N && (N.textContent = R.join(" ")), r('[name="' + $(j) + '"]').forEach((U) => {
523
+ U.setAttribute("aria-invalid", "true"), v || (v = U);
524
+ }));
525
+ }), v && v.focus(), w;
526
+ };
527
+ e.addEventListener("input", (x) => {
528
+ const v = x.target;
529
+ v && v.name && B(v.name);
530
+ }), e.addEventListener("change", (x) => {
531
+ const v = x.target;
532
+ v && v.name && B(v.name);
533
+ });
534
+ const E = (x, v, w) => {
535
+ const j = new (s.CustomEvent || CustomEvent)(x, { bubbles: !0, cancelable: !!w, detail: v });
536
+ return e.dispatchEvent(j), j;
537
+ };
538
+ e.addEventListener("submit", (x) => {
539
+ if (x.preventDefault(), e.classList.contains("is-sending")) return;
540
+ P(), h(!0);
541
+ const v = {};
542
+ if (r("[data-gjsf-required]").forEach((S) => {
543
+ const C = S.getAttribute("data-gjsf-field") || "";
544
+ S.querySelector("input:checked") || (v[C] = ["required"]);
545
+ }), typeof e.checkValidity == "function" && !e.checkValidity()) {
546
+ typeof e.reportValidity == "function" && e.reportValidity();
547
+ return;
548
+ }
549
+ if (Object.keys(v).length) {
550
+ J(v);
551
+ return;
552
+ }
553
+ const w = new FormData(e), j = {};
554
+ let R = !1;
555
+ w.forEach((S, C) => {
556
+ if (typeof S != "string") {
557
+ if (!S.name && !S.size) return;
558
+ R = !0;
559
+ }
560
+ C in j ? j[C] = [].concat(j[C], S) : j[C] = S;
561
+ }), r("[data-gjsf-field]").forEach((S) => {
562
+ const C = S.getAttribute("data-gjsf-field") || "", X = S.classList;
563
+ X.contains("gjsf-field--checkboxes") || S.querySelector("select[multiple]") ? j[C] = C in j ? [].concat(j[C]) : [] : X.contains("gjsf-field--checkbox") && (j[C] = C in j);
564
+ });
565
+ const F = { url: a.href, referrer: t.referrer || "", lang: t.documentElement.lang || "" };
566
+ l("data-gjsf-page") && (F.page_id = l("data-gjsf-page"));
567
+ const N = l("data-gjsf-form"), U = (S) => {
568
+ E("gjsf:success", { formId: N, data: j, response: S });
569
+ const C = S && S.redirect || l("data-gjsf-redirect");
570
+ if (C) {
571
+ _("success", ""), a.assign(C);
572
+ return;
573
+ }
574
+ l("data-gjsf-reset") !== "false" && (e.reset(), h(!1)), _("success", S && S.message || l("data-gjsf-success"));
575
+ }, Z = (S, C) => {
576
+ C && C.errors && J(C.errors), E("gjsf:error", { formId: N, data: j, status: S, response: C }), _("error", C && (C.error || C.message) || l("data-gjsf-error"));
577
+ }, K = { formId: N, data: j, meta: F, formData: w, promise: null }, Q = E("gjsf:submit", K, !0);
578
+ _("sending");
579
+ let H;
580
+ if (K.promise) H = Promise.resolve(K.promise);
581
+ else if (Q.defaultPrevented) {
582
+ _("");
583
+ return;
584
+ } else {
585
+ const S = e.getAttribute("action");
586
+ if (!S) {
587
+ Z(0, {});
588
+ return;
589
+ }
590
+ let C;
591
+ const X = { Accept: "application/json" };
592
+ R ? (w.append("_meta", JSON.stringify(F)), C = w) : (X["Content-Type"] = "application/json", C = JSON.stringify({ data: j, meta: F })), H = s.fetch(S, { method: "POST", headers: X, body: C, credentials: "same-origin" }).then(
593
+ (se) => se.text().then((ne) => {
594
+ let ee = {};
595
+ try {
596
+ ee = ne ? JSON.parse(ne) : {};
597
+ } catch {
598
+ ee = {};
599
+ }
600
+ if (!se.ok) throw { status: se.status, body: ee };
601
+ return ee;
602
+ })
603
+ );
604
+ }
605
+ H.then(
606
+ (S) => U(S || {}),
607
+ (S) => Z(S && S.status || 0, S && (S.body || (S.errors ? S : null)) || {})
608
+ );
609
+ });
610
+ }
611
+ const q = "gjsf-form", Ee = "gjsf-part", pe = "data-gjsf-form", lt = "data-gjsf-part", ct = {
612
+ removable: !1,
613
+ draggable: !1,
614
+ copyable: !1,
615
+ droppable: !1,
616
+ editable: !1,
617
+ stylable: !0,
618
+ selectable: !0,
619
+ hoverable: !0,
620
+ layerable: !0
621
+ }, ss = ["action", "method", "enctype", "data-gjsf-success", "data-gjsf-error", "data-gjsf-redirect", "data-gjsf-reset", "data-gjsf-version", "data-gjsf-codes", "data-gjsf-page", "data-gjsf-missing"];
622
+ function dt(i) {
623
+ return typeof i == "string" ? { type: "textnode", content: i } : {
624
+ type: Ee,
625
+ tagName: i.tag,
626
+ attributes: { ...i.attrs || {}, [lt]: i.part },
627
+ classes: i.classes || [],
628
+ void: !!i.void,
629
+ components: (i.kids || []).map(dt),
630
+ ...ct
631
+ };
632
+ }
633
+ const De = () => Math.random().toString(36).slice(2, 7), is = `.${L.hp}{position:absolute!important;left:-10000px!important;width:1px;height:1px;overflow:hidden}`, rs = `
634
+ form.${L.form}:empty{min-height:64px;outline:1px dashed rgba(127,127,127,.6);display:flex;align-items:center;justify-content:center}
635
+ form.${L.form}:empty::before{content:attr(data-gjsf-placeholder);opacity:.6;font:13px/1.3 sans-serif}
636
+ form.${L.form}[data-gjsf-missing]{outline:1px dashed #e57373}
637
+ `;
638
+ class as {
639
+ constructor(e, t) {
640
+ T(this, "offs", []);
641
+ this.editor = e, this.host = t;
642
+ const s = e.DomComponents, a = this;
643
+ s.addType(Ee, {
644
+ isComponent: (n) => {
645
+ var d;
646
+ return (d = n == null ? void 0 : n.getAttribute) != null && d.call(n, lt) ? { type: Ee } : !1;
647
+ },
648
+ model: { defaults: { ...ct } }
649
+ }), s.addType(q, {
650
+ isComponent: (n) => (n == null ? void 0 : n.tagName) === "FORM" && n.hasAttribute(pe) ? { type: q, formId: n.getAttribute(pe) || "" } : !1,
651
+ model: {
652
+ defaults: {
653
+ tagName: "form",
654
+ name: "Form",
655
+ droppable: !1,
656
+ classes: [L.form],
657
+ formId: "",
658
+ gjsfKey: "",
659
+ script: Ce,
660
+ "script-props": ["formId"],
661
+ traits: []
662
+ },
663
+ init() {
664
+ this.get("gjsfKey") || this.set("gjsfKey", De()), this.set("traits", a.traits()), this.on("change:formId", () => a.rebuild(this));
665
+ }
666
+ },
667
+ view: {
668
+ events: {
669
+ dblclick: "onEdit",
670
+ submit: "onSubmit"
671
+ },
672
+ onEdit(n) {
673
+ var d;
674
+ (d = n == null ? void 0 : n.stopPropagation) == null || d.call(n), e.runCommand(t.editCommand, { component: this.model });
675
+ },
676
+ onSubmit(n) {
677
+ n.preventDefault();
678
+ }
679
+ }
680
+ });
681
+ const r = (n) => {
682
+ if (!(!n || n.__gjsfGuard) && (n.__gjsfGuard = !0, n.addEventListener(
683
+ "submit",
684
+ (d) => {
685
+ d.preventDefault(), d.stopPropagation();
686
+ },
687
+ !0
688
+ ), !n.getElementById("gjsf-canvas-style"))) {
689
+ const d = n.createElement("style");
690
+ d.id = "gjsf-canvas-style", d.textContent = rs, (n.head || n.documentElement).appendChild(d);
691
+ }
692
+ }, l = (n) => {
693
+ var d, b, h, y;
694
+ return r(((d = n == null ? void 0 : n.window) == null ? void 0 : d.document) || ((y = (h = (b = n == null ? void 0 : n.frame) == null ? void 0 : b.view) == null ? void 0 : h.getDoc) == null ? void 0 : y.call(h)) || e.Canvas.getDocument());
695
+ };
696
+ e.on("canvas:frame:load", l), this.offs.push(() => e.off("canvas:frame:load", l)), e.onReady(() => {
697
+ try {
698
+ r(e.Canvas.getDocument());
699
+ } catch {
700
+ }
701
+ });
702
+ const o = (n) => {
703
+ var d;
704
+ ((d = n == null ? void 0 : n.get) == null ? void 0 : d.call(n, "type")) === q && (n.get("gjsfCreate") ? (n.unset("gjsfCreate"), t.onCreate(n)) : n.get("formId") && !n.components().length && this.rebuild(n), this.ensureCss());
705
+ };
706
+ e.on("component:add", o), this.offs.push(() => e.off("component:add", o));
707
+ const u = (n) => {
708
+ var d;
709
+ ((d = n == null ? void 0 : n.get) == null ? void 0 : d.call(n, "type")) === q && this.refreshTraits(n);
710
+ };
711
+ e.on("component:selected", u), this.offs.push(() => e.off("component:selected", u));
712
+ }
713
+ traits() {
714
+ return [
715
+ { type: "select", name: "formId", label: this.host.labels.chooseForm(), changeProp: !0, options: this.selectOptions() },
716
+ { type: "button", name: "gjsf-edit", label: !1, text: this.host.labels.editForm(), full: !0, command: this.host.editCommand }
717
+ ];
718
+ }
719
+ selectOptions() {
720
+ return [{ id: "", name: this.host.labels.noForm() }, ...this.host.formOptions()];
721
+ }
722
+ /** The trait list of a form component (labels and the list of forms change). */
723
+ refreshTraits(e) {
724
+ var r, l, o, u;
725
+ const t = (r = e.getTrait) == null ? void 0 : r.call(e, "formId");
726
+ t ? (t.set("options", this.selectOptions()), t.set("label", this.host.labels.chooseForm())) : e.set("traits", this.traits());
727
+ const s = (l = e.getTrait) == null ? void 0 : l.call(e, "gjsf-edit");
728
+ if (s == null || s.set("text", this.host.labels.editForm()), this.editor.getSelected() === e)
729
+ try {
730
+ (u = (o = this.editor.TraitManager) == null ? void 0 : o.render) == null || u.call(o);
731
+ } catch {
732
+ }
733
+ }
734
+ /** All form components of the open project. */
735
+ all() {
736
+ const e = [], t = (a) => {
737
+ a.get("type") === q && e.push(a), a.components().forEach(t);
738
+ }, s = this.editor.getWrapper();
739
+ return s && t(s), e;
740
+ }
741
+ /** Adds the rules the site needs once (in the project CSS). */
742
+ ensureCss() {
743
+ const e = this.editor.Css;
744
+ e.getRule(`.${L.hp}`) || e.addRules(is);
745
+ }
746
+ /**
747
+ * Rebuilds a form component from its form: its parts are replaced, the
748
+ * attributes the plugin owns rewritten; the user's classes and own
749
+ * attributes of the `<form>` stay. Not on the undo stack. A component
750
+ * whose form is gone keeps its parts (a copy) and is marked.
751
+ */
752
+ rebuild(e) {
753
+ const t = String(e.get("formId") || ""), s = this.host.form(t), a = { "data-gjsf-placeholder": this.host.labels.noForm() }, r = () => {
754
+ var h;
755
+ const o = { ...e.getAttributes() }, u = e.get("gjsfOwnAttrs") || [];
756
+ if ([...ss, ...u].forEach((y) => delete o[y]), !t) {
757
+ delete o[pe], e.setAttributes({ ...o, ...a }), e.components().reset();
758
+ return;
759
+ }
760
+ if (!s) {
761
+ e.setAttributes({ ...o, [pe]: t, "data-gjsf-missing": "", "data-gjsf-placeholder": this.host.labels.missingForm() });
762
+ return;
763
+ }
764
+ const n = this.host.buildOptions(s, e), d = rt(s, n);
765
+ delete o["data-gjsf-placeholder"];
766
+ const b = Object.keys(s.attrs || {}).filter((y) => y !== "class");
767
+ e.set("gjsfOwnAttrs", b), e.setAttributes({ ...o, ...d, ...a }), (((h = s.attrs) == null ? void 0 : h.class) || "").split(/\s+/).filter(Boolean).forEach((y) => e.addClass(y)), e.components().reset(), e.components().add(at(s, { ...n, key: e.get("gjsfKey") || De() }).map(dt)), this.ensureCss();
768
+ }, l = this.editor.UndoManager;
769
+ l != null && l.skip ? l.skip(r) : r();
770
+ }
771
+ /** Rebuilds the components of one form (all when no id); `stale` — only those built from another version or for another page. */
772
+ rebuildAll(e, t) {
773
+ let s = 0;
774
+ return this.all().forEach((a) => {
775
+ const r = String(a.get("formId") || "");
776
+ if (e && r !== e) return;
777
+ const l = this.host.form(r);
778
+ t && l && !t(a, l) || t && !l && !r || (this.rebuild(a), s++);
779
+ }), s;
780
+ }
781
+ destroy() {
782
+ this.offs.splice(0).forEach((e) => e());
783
+ }
784
+ }
785
+ const ce = {
786
+ /** The forms were (re)read or one changed. Payload: `FormDef[]`. */
787
+ forms: "forms:list",
788
+ /** A form was written. Payload: `FormDef`. */
789
+ saved: "forms:saved",
790
+ /** A form was deleted. Payload: `id`. */
791
+ removed: "forms:removed",
792
+ /** A submission was sent from the editor's preview. Payload: `{ formId, result }`. */
793
+ submitted: "forms:submitted"
794
+ }, ue = {
795
+ /** Opens the forms editor; `{ id }` — on that form. */
796
+ open: "forms:open",
797
+ /** Opens the editor on the form of the selected component (or `{ component }`). */
798
+ edit: "forms:edit"
799
+ }, Cs = {
800
+ submit: "gjsf:submit",
801
+ success: "gjsf:success",
802
+ error: "gjsf:error"
803
+ }, pt = {
804
+ forms: "Forms",
805
+ newForm: "New form",
806
+ defaultFormName: "Form",
807
+ noForms: "No forms yet.",
808
+ formName: "Form name",
809
+ fields: "Fields",
810
+ settings: "Settings",
811
+ preview: "Preview",
812
+ submissions: "Submissions",
813
+ json: "JSON",
814
+ addField: "Add a field",
815
+ noFields: "No fields yet: add one from the list on the left.",
816
+ noFieldSelected: "Select a field to edit it.",
817
+ fieldType: "Type",
818
+ fieldLabel: "Label",
819
+ fieldName: "Name (key)",
820
+ fieldNameHint: "The key of the value in a submission.",
821
+ placeholder: "Placeholder",
822
+ help: "Help text",
823
+ required: "Required",
824
+ defaultValue: "Default value",
825
+ hiddenValue: "Value sent",
826
+ options: "Options",
827
+ optionsHint: "Label and the value sent.",
828
+ addOption: "Add an option",
829
+ optionLabel: "Label",
830
+ optionValue: "Value",
831
+ multiple: "Several values",
832
+ min: "Min",
833
+ max: "Max",
834
+ step: "Step",
835
+ minLength: "Min length",
836
+ maxLength: "Max length",
837
+ pattern: "Pattern (regular expression)",
838
+ accept: "File types",
839
+ autocomplete: "Autocomplete",
840
+ rows: "Rows",
841
+ readonly: "Read only",
842
+ disabled: "Disabled",
843
+ width: "Width",
844
+ attrs: "Attributes",
845
+ addAttr: "Add an attribute",
846
+ attrName: "Name",
847
+ attrValue: "Value",
848
+ text: "Text",
849
+ type_text: "Text",
850
+ type_email: "E-mail",
851
+ type_tel: "Phone",
852
+ type_url: "URL",
853
+ type_number: "Number",
854
+ type_password: "Password",
855
+ type_textarea: "Long text",
856
+ type_select: "Dropdown",
857
+ type_radio: "Radio buttons",
858
+ type_checkbox: "Checkbox",
859
+ type_checkboxes: "Checkboxes",
860
+ type_date: "Date",
861
+ type_time: "Time",
862
+ type_datetime: "Date and time",
863
+ type_range: "Slider",
864
+ type_color: "Colour",
865
+ type_file: "File",
866
+ type_hidden: "Hidden",
867
+ type_heading: "Heading",
868
+ type_paragraph: "Paragraph",
869
+ moveUp: "Move up",
870
+ moveDown: "Move down",
871
+ duplicate: "Duplicate",
872
+ remove: "Remove",
873
+ endpoint: "Submit to (URL)",
874
+ endpointHint: "Empty — %s",
875
+ noEndpoint: "the site handles the gjsf:submit event",
876
+ successMessage: "Message after sending",
877
+ errorMessage: "Message on error",
878
+ redirect: "Redirect after sending (URL)",
879
+ reset: "Clear the form after sending",
880
+ honeypot: "Spam trap (hidden field for bots)",
881
+ submitLabel: "Button text",
882
+ formAttrs: "Form attributes",
883
+ submit: "Send",
884
+ success: "Thank you! Your message has been sent.",
885
+ error: "Could not send the form. Please try again.",
886
+ problem_required: "Please fill in this field.",
887
+ problem_email: "Please enter a valid e-mail address.",
888
+ problem_url: "Please enter a valid URL.",
889
+ problem_number: "Please enter a number.",
890
+ problem_min: "The value is too small.",
891
+ problem_max: "The value is too large.",
892
+ problem_minLength: "The text is too short.",
893
+ problem_maxLength: "The text is too long.",
894
+ problem_pattern: "The value does not match the format.",
895
+ problem_option: "Please choose one of the options.",
896
+ problem_date: "Please enter a valid date.",
897
+ problem_time: "Please enter a valid time.",
898
+ problem_color: "Please choose a colour.",
899
+ placeholders: "Placeholders",
900
+ placeholdersHint: "{{form.*}} and {{page.*}} are filled when the page is built; the rest in the visitor’s browser.",
901
+ noSubmissions: "No submissions yet.",
902
+ submissionsUnsupported: "This backend does not list submissions.",
903
+ date: "Date",
904
+ refresh: "Refresh",
905
+ downloadCsv: "Download CSV",
906
+ loadMore: "Load more",
907
+ shownOf: "%s of %s",
908
+ confirmDeleteSubmission: "Delete this submission?",
909
+ importSurveyJs: "Import SurveyJS JSON",
910
+ exportSurveyJs: "Export as SurveyJS JSON",
911
+ applyJson: "Apply",
912
+ jsonHint: "The form as JSON. Paste a form of this plugin or a SurveyJS survey and press Apply.",
913
+ jsonError: "Not valid JSON: %s",
914
+ skipped: "Skipped (not plain form fields): %s",
915
+ removeForm: "Delete the form",
916
+ confirmRemoveForm: 'Delete the form "%s" and its submissions? Pages that use it keep a copy.',
917
+ duplicateForm: "Duplicate",
918
+ copyOf: "%s (copy)",
919
+ close: "Close",
920
+ saving: "Saving…",
921
+ saved: "Saved",
922
+ saveError: "Not saved: %s",
923
+ conflict: "The form was changed elsewhere (412). It was reloaded.",
924
+ chooseForm: "Form",
925
+ editForm: "Edit the form",
926
+ noForm: "— choose a form —",
927
+ blocksCategory: "Forms",
928
+ newFormBlock: "New form",
929
+ missingForm: "The form was deleted: this is a copy.",
930
+ previewHint: "Styled by the open page. Sending here goes to the forms store.",
931
+ previewSent: "Sent to the store.",
932
+ defaultName: "Name",
933
+ defaultEmail: "E-mail",
934
+ defaultMessage: "Message"
935
+ }, ns = {
936
+ forms: "Формы",
937
+ newForm: "Новая форма",
938
+ defaultFormName: "Форма",
939
+ noForms: "Форм пока нет.",
940
+ formName: "Название формы",
941
+ fields: "Поля",
942
+ settings: "Настройки",
943
+ preview: "Просмотр",
944
+ submissions: "Заявки",
945
+ json: "JSON",
946
+ addField: "Добавить поле",
947
+ noFields: "Полей пока нет: добавьте из списка слева.",
948
+ noFieldSelected: "Выберите поле, чтобы изменить его.",
949
+ fieldType: "Тип",
950
+ fieldLabel: "Подпись",
951
+ fieldName: "Имя (ключ)",
952
+ fieldNameHint: "Ключ значения в заявке.",
953
+ placeholder: "Плейсхолдер",
954
+ help: "Подсказка",
955
+ required: "Обязательное",
956
+ defaultValue: "Значение по умолчанию",
957
+ hiddenValue: "Отправляемое значение",
958
+ options: "Варианты",
959
+ optionsHint: "Подпись и отправляемое значение.",
960
+ addOption: "Добавить вариант",
961
+ optionLabel: "Подпись",
962
+ optionValue: "Значение",
963
+ multiple: "Несколько значений",
964
+ min: "Мин.",
965
+ max: "Макс.",
966
+ step: "Шаг",
967
+ minLength: "Мин. длина",
968
+ maxLength: "Макс. длина",
969
+ pattern: "Шаблон (регулярное выражение)",
970
+ accept: "Типы файлов",
971
+ autocomplete: "Автозаполнение",
972
+ rows: "Строк",
973
+ readonly: "Только чтение",
974
+ disabled: "Отключено",
975
+ width: "Ширина",
976
+ attrs: "Атрибуты",
977
+ addAttr: "Добавить атрибут",
978
+ attrName: "Имя",
979
+ attrValue: "Значение",
980
+ text: "Текст",
981
+ type_text: "Текст",
982
+ type_email: "E-mail",
983
+ type_tel: "Телефон",
984
+ type_url: "Ссылка",
985
+ type_number: "Число",
986
+ type_password: "Пароль",
987
+ type_textarea: "Длинный текст",
988
+ type_select: "Список",
989
+ type_radio: "Переключатели",
990
+ type_checkbox: "Флажок",
991
+ type_checkboxes: "Флажки",
992
+ type_date: "Дата",
993
+ type_time: "Время",
994
+ type_datetime: "Дата и время",
995
+ type_range: "Ползунок",
996
+ type_color: "Цвет",
997
+ type_file: "Файл",
998
+ type_hidden: "Скрытое",
999
+ type_heading: "Заголовок",
1000
+ type_paragraph: "Абзац",
1001
+ moveUp: "Выше",
1002
+ moveDown: "Ниже",
1003
+ duplicate: "Копировать",
1004
+ remove: "Удалить",
1005
+ endpoint: "Куда отправлять (URL)",
1006
+ endpointHint: "Пусто — %s",
1007
+ noEndpoint: "отправку обрабатывает сайт (событие gjsf:submit)",
1008
+ successMessage: "Сообщение после отправки",
1009
+ errorMessage: "Сообщение об ошибке",
1010
+ redirect: "Перейти после отправки (URL)",
1011
+ reset: "Очищать форму после отправки",
1012
+ honeypot: "Ловушка для спама (скрытое поле для ботов)",
1013
+ submitLabel: "Текст кнопки",
1014
+ formAttrs: "Атрибуты формы",
1015
+ submit: "Отправить",
1016
+ success: "Спасибо! Сообщение отправлено.",
1017
+ error: "Не удалось отправить форму. Попробуйте ещё раз.",
1018
+ problem_required: "Заполните это поле.",
1019
+ problem_email: "Введите правильный адрес e-mail.",
1020
+ problem_url: "Введите правильную ссылку.",
1021
+ problem_number: "Введите число.",
1022
+ problem_min: "Значение слишком маленькое.",
1023
+ problem_max: "Значение слишком большое.",
1024
+ problem_minLength: "Текст слишком короткий.",
1025
+ problem_maxLength: "Текст слишком длинный.",
1026
+ problem_pattern: "Значение не подходит под формат.",
1027
+ problem_option: "Выберите один из вариантов.",
1028
+ problem_date: "Введите правильную дату.",
1029
+ problem_time: "Введите правильное время.",
1030
+ problem_color: "Выберите цвет.",
1031
+ placeholders: "Плейсхолдеры",
1032
+ placeholdersHint: "{{form.*}} и {{page.*}} подставляются при сборке страницы, остальные — в браузере посетителя.",
1033
+ noSubmissions: "Заявок пока нет.",
1034
+ submissionsUnsupported: "Это хранилище не отдаёт список заявок.",
1035
+ date: "Дата",
1036
+ refresh: "Обновить",
1037
+ downloadCsv: "Скачать CSV",
1038
+ loadMore: "Ещё",
1039
+ shownOf: "%s из %s",
1040
+ confirmDeleteSubmission: "Удалить эту заявку?",
1041
+ importSurveyJs: "Импорт SurveyJS JSON",
1042
+ exportSurveyJs: "Экспорт в SurveyJS JSON",
1043
+ applyJson: "Применить",
1044
+ jsonHint: "Форма в виде JSON. Вставьте форму этого плагина или опрос SurveyJS и нажмите «Применить».",
1045
+ jsonError: "Неверный JSON: %s",
1046
+ skipped: "Пропущено (не поля обычной формы): %s",
1047
+ removeForm: "Удалить форму",
1048
+ confirmRemoveForm: "Удалить форму «%s» и её заявки? На страницах, где она стоит, останется копия.",
1049
+ duplicateForm: "Копировать",
1050
+ copyOf: "%s (копия)",
1051
+ close: "Закрыть",
1052
+ saving: "Сохранение…",
1053
+ saved: "Сохранено",
1054
+ saveError: "Не сохранено: %s",
1055
+ conflict: "Форму изменили в другом месте (412). Она перечитана.",
1056
+ chooseForm: "Форма",
1057
+ editForm: "Редактировать форму",
1058
+ noForm: "— выберите форму —",
1059
+ blocksCategory: "Формы",
1060
+ newFormBlock: "Новая форма",
1061
+ missingForm: "Форма удалена: это копия.",
1062
+ previewHint: "Со стилями открытой страницы. Отправка отсюда идёт в хранилище форм.",
1063
+ previewSent: "Отправлено в хранилище.",
1064
+ defaultName: "Имя",
1065
+ defaultEmail: "E-mail",
1066
+ defaultMessage: "Сообщение"
1067
+ }, os = {
1068
+ forms: "Форми",
1069
+ newForm: "Нова форма",
1070
+ defaultFormName: "Форма",
1071
+ noForms: "Форм ще немає.",
1072
+ formName: "Назва форми",
1073
+ fields: "Поля",
1074
+ settings: "Налаштування",
1075
+ preview: "Перегляд",
1076
+ submissions: "Заявки",
1077
+ json: "JSON",
1078
+ addField: "Додати поле",
1079
+ noFields: "Полів ще немає: додайте зі списку ліворуч.",
1080
+ noFieldSelected: "Виберіть поле, щоб змінити його.",
1081
+ fieldType: "Тип",
1082
+ fieldLabel: "Підпис",
1083
+ fieldName: "Імʼя (ключ)",
1084
+ fieldNameHint: "Ключ значення в заявці.",
1085
+ placeholder: "Плейсхолдер",
1086
+ help: "Підказка",
1087
+ required: "Обовʼязкове",
1088
+ defaultValue: "Значення за замовчуванням",
1089
+ hiddenValue: "Значення, що надсилається",
1090
+ options: "Варіанти",
1091
+ optionsHint: "Підпис і значення, що надсилається.",
1092
+ addOption: "Додати варіант",
1093
+ optionLabel: "Підпис",
1094
+ optionValue: "Значення",
1095
+ multiple: "Кілька значень",
1096
+ min: "Мін.",
1097
+ max: "Макс.",
1098
+ step: "Крок",
1099
+ minLength: "Мін. довжина",
1100
+ maxLength: "Макс. довжина",
1101
+ pattern: "Шаблон (регулярний вираз)",
1102
+ accept: "Типи файлів",
1103
+ autocomplete: "Автозаповнення",
1104
+ rows: "Рядків",
1105
+ readonly: "Лише читання",
1106
+ disabled: "Вимкнено",
1107
+ width: "Ширина",
1108
+ attrs: "Атрибути",
1109
+ addAttr: "Додати атрибут",
1110
+ attrName: "Імʼя",
1111
+ attrValue: "Значення",
1112
+ text: "Текст",
1113
+ type_text: "Текст",
1114
+ type_email: "E-mail",
1115
+ type_tel: "Телефон",
1116
+ type_url: "Посилання",
1117
+ type_number: "Число",
1118
+ type_password: "Пароль",
1119
+ type_textarea: "Довгий текст",
1120
+ type_select: "Список",
1121
+ type_radio: "Перемикачі",
1122
+ type_checkbox: "Прапорець",
1123
+ type_checkboxes: "Прапорці",
1124
+ type_date: "Дата",
1125
+ type_time: "Час",
1126
+ type_datetime: "Дата й час",
1127
+ type_range: "Повзунок",
1128
+ type_color: "Колір",
1129
+ type_file: "Файл",
1130
+ type_hidden: "Приховане",
1131
+ type_heading: "Заголовок",
1132
+ type_paragraph: "Абзац",
1133
+ moveUp: "Вище",
1134
+ moveDown: "Нижче",
1135
+ duplicate: "Копіювати",
1136
+ remove: "Видалити",
1137
+ endpoint: "Куди надсилати (URL)",
1138
+ endpointHint: "Порожньо — %s",
1139
+ noEndpoint: "надсилання обробляє сайт (подія gjsf:submit)",
1140
+ successMessage: "Повідомлення після надсилання",
1141
+ errorMessage: "Повідомлення про помилку",
1142
+ redirect: "Перейти після надсилання (URL)",
1143
+ reset: "Очищати форму після надсилання",
1144
+ honeypot: "Пастка для спаму (приховане поле для ботів)",
1145
+ submitLabel: "Текст кнопки",
1146
+ formAttrs: "Атрибути форми",
1147
+ submit: "Надіслати",
1148
+ success: "Дякуємо! Повідомлення надіслано.",
1149
+ error: "Не вдалося надіслати форму. Спробуйте ще раз.",
1150
+ problem_required: "Заповніть це поле.",
1151
+ problem_email: "Введіть правильну адресу e-mail.",
1152
+ problem_url: "Введіть правильне посилання.",
1153
+ problem_number: "Введіть число.",
1154
+ problem_min: "Значення замале.",
1155
+ problem_max: "Значення завелике.",
1156
+ problem_minLength: "Текст закороткий.",
1157
+ problem_maxLength: "Текст задовгий.",
1158
+ problem_pattern: "Значення не відповідає формату.",
1159
+ problem_option: "Виберіть один із варіантів.",
1160
+ problem_date: "Введіть правильну дату.",
1161
+ problem_time: "Введіть правильний час.",
1162
+ problem_color: "Виберіть колір.",
1163
+ placeholders: "Плейсхолдери",
1164
+ placeholdersHint: "{{form.*}} і {{page.*}} підставляються під час збирання сторінки, решта — у браузері відвідувача.",
1165
+ noSubmissions: "Заявок ще немає.",
1166
+ submissionsUnsupported: "Це сховище не віддає список заявок.",
1167
+ date: "Дата",
1168
+ refresh: "Оновити",
1169
+ downloadCsv: "Завантажити CSV",
1170
+ loadMore: "Ще",
1171
+ shownOf: "%s з %s",
1172
+ confirmDeleteSubmission: "Видалити цю заявку?",
1173
+ importSurveyJs: "Імпорт SurveyJS JSON",
1174
+ exportSurveyJs: "Експорт у SurveyJS JSON",
1175
+ applyJson: "Застосувати",
1176
+ jsonHint: "Форма у вигляді JSON. Вставте форму цього плагіна або опитування SurveyJS і натисніть «Застосувати».",
1177
+ jsonError: "Неправильний JSON: %s",
1178
+ skipped: "Пропущено (не поля звичайної форми): %s",
1179
+ removeForm: "Видалити форму",
1180
+ confirmRemoveForm: "Видалити форму «%s» і її заявки? На сторінках, де вона стоїть, залишиться копія.",
1181
+ duplicateForm: "Копіювати",
1182
+ copyOf: "%s (копія)",
1183
+ close: "Закрити",
1184
+ saving: "Збереження…",
1185
+ saved: "Збережено",
1186
+ saveError: "Не збережено: %s",
1187
+ conflict: "Форму змінили в іншому місці (412). Її перечитано.",
1188
+ chooseForm: "Форма",
1189
+ editForm: "Редагувати форму",
1190
+ noForm: "— виберіть форму —",
1191
+ blocksCategory: "Форми",
1192
+ newFormBlock: "Нова форма",
1193
+ missingForm: "Форму видалено: це копія.",
1194
+ previewHint: "Зі стилями відкритої сторінки. Надсилання звідси йде до сховища форм.",
1195
+ previewSent: "Надіслано до сховища.",
1196
+ defaultName: "Імʼя",
1197
+ defaultEmail: "E-mail",
1198
+ defaultMessage: "Повідомлення"
1199
+ }, ut = "gjsForms", mt = { en: pt, ru: ns, uk: os }, ls = Object.keys(mt);
1200
+ function cs(i) {
1201
+ const e = i.I18n;
1202
+ if (!e || typeof e.addMessages != "function") return;
1203
+ const t = {};
1204
+ ls.forEach((s) => {
1205
+ t[s] = { [ut]: { ...mt[s] } };
1206
+ }), e.addMessages(t);
1207
+ }
1208
+ function ds(i, e = {}) {
1209
+ return (t) => {
1210
+ var r;
1211
+ const s = e[t];
1212
+ if (typeof s == "string" && s) return s;
1213
+ let a;
1214
+ try {
1215
+ a = (r = i.I18n) == null ? void 0 : r.t(`${ut}.${t}`, { params: { form: "{form}", page: "{page}" } });
1216
+ } catch {
1217
+ a = void 0;
1218
+ }
1219
+ return typeof a == "string" && a ? a : pt[t];
1220
+ };
1221
+ }
1222
+ const te = (i, ...e) => e.reduce((t, s) => t.replace("%s", String(s)), i), I = (i) => i === void 0 ? i : JSON.parse(JSON.stringify(i)), _e = () => {
1223
+ const i = typeof globalThis < "u" ? globalThis.crypto : void 0;
1224
+ if (i && typeof i.randomUUID == "function")
1225
+ try {
1226
+ return i.randomUUID();
1227
+ } catch {
1228
+ }
1229
+ const e = new Uint8Array(16);
1230
+ if (i && typeof i.getRandomValues == "function") i.getRandomValues(e);
1231
+ else for (let s = 0; s < 16; s++) e[s] = Math.floor(Math.random() * 256);
1232
+ e[6] = e[6] & 15 | 64, e[8] = e[8] & 63 | 128;
1233
+ const t = [...e].map((s) => s.toString(16).padStart(2, "0")).join("");
1234
+ return `${t.slice(0, 8)}-${t.slice(8, 12)}-${t.slice(12, 16)}-${t.slice(16, 20)}-${t.slice(20)}`;
1235
+ }, Me = (i) => {
1236
+ console.error("[grapesjs-forms]", i);
1237
+ };
1238
+ class Ae extends Error {
1239
+ constructor(t = "The form was changed elsewhere (412)") {
1240
+ super(t);
1241
+ T(this, "status", 412);
1242
+ this.name = "ConflictError";
1243
+ }
1244
+ }
1245
+ class G extends Error {
1246
+ constructor(e, t, s = {}) {
1247
+ super(e), this.status = t, this.errors = s, this.name = "StoreError";
1248
+ }
1249
+ }
1250
+ class ft {
1251
+ constructor() {
1252
+ T(this, "forms", /* @__PURE__ */ new Map());
1253
+ T(this, "submissions", /* @__PURE__ */ new Map());
1254
+ }
1255
+ /** Hook of persistent subclasses: a key changed (`null` value — deleted). */
1256
+ async changed(e, t) {
1257
+ }
1258
+ async listForms() {
1259
+ return [...this.forms.values()].map(I);
1260
+ }
1261
+ async getForm(e) {
1262
+ const t = this.forms.get(e);
1263
+ return t ? I(t) : void 0;
1264
+ }
1265
+ async saveForm(e, t) {
1266
+ if (!e.id) throw new G("A form needs an id", 422, { id: ["required"] });
1267
+ const s = this.forms.get(e.id);
1268
+ if (t != null && s && String(s.version) !== String(t)) throw new Ae();
1269
+ const a = V({ ...e, version: (Number(s == null ? void 0 : s.version) || 0) + 1, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
1270
+ return this.forms.set(a.id, a), await this.changed(`form:${a.id}`, a), I(a);
1271
+ }
1272
+ async deleteForm(e) {
1273
+ if (this.forms.delete(e)) {
1274
+ await this.changed(`form:${e}`, null);
1275
+ for (const [t, s] of [...this.submissions])
1276
+ s.formId === e && (this.submissions.delete(t), await this.changed(`submission:${t}`, null));
1277
+ }
1278
+ }
1279
+ async submit(e, t, s) {
1280
+ const a = this.forms.get(e);
1281
+ if (!a) throw new G("No such form", 404);
1282
+ const r = Kt(a, t);
1283
+ if (r.spam) return {};
1284
+ if (!r.ok) throw new G("The given data was invalid.", 422, r.errors);
1285
+ const l = (d) => typeof Blob < "u" && d instanceof Blob, o = (d) => l(d) ? { name: d.name || "", size: d.size, type: d.type } : Array.isArray(d) ? d.map(o) : d, u = Object.fromEntries(Object.entries(r.data).map(([d, b]) => [d, o(b)])), n = { id: _e(), formId: e, data: u, createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...s ? { meta: I(s) } : {} };
1286
+ return this.submissions.set(n.id, n), await this.changed(`submission:${n.id}`, n), { id: n.id, createdAt: n.createdAt };
1287
+ }
1288
+ async listSubmissions(e, t = {}) {
1289
+ const s = [...this.submissions.values()].filter((l) => l.formId === e).sort((l, o) => l.createdAt < o.createdAt ? 1 : l.createdAt > o.createdAt ? -1 : 0), a = Math.max(0, t.offset || 0), r = Math.max(1, t.limit || 50);
1290
+ return { items: s.slice(a, a + r).map(I), total: s.length };
1291
+ }
1292
+ async deleteSubmission(e, t) {
1293
+ const s = this.submissions.get(t);
1294
+ !s || s.formId !== e || (this.submissions.delete(t), await this.changed(`submission:${t}`, null));
1295
+ }
1296
+ }
1297
+ const ie = "forms", ps = 1;
1298
+ class ht extends ft {
1299
+ constructor(t = "gjs-forms", s = typeof indexedDB < "u" ? indexedDB : void 0) {
1300
+ super();
1301
+ T(this, "dbp", null);
1302
+ T(this, "loaded", null);
1303
+ this.dbName = t, this.factory = s;
1304
+ }
1305
+ open() {
1306
+ if (this.dbp) return this.dbp;
1307
+ const t = this.factory;
1308
+ return t ? (this.dbp = new Promise((s, a) => {
1309
+ const r = t.open(this.dbName, ps);
1310
+ r.onupgradeneeded = () => {
1311
+ r.result.objectStoreNames.contains(ie) || r.result.createObjectStore(ie, { keyPath: "key" });
1312
+ }, r.onsuccess = () => {
1313
+ const l = r.result;
1314
+ l.onversionchange = () => {
1315
+ l.close(), this.dbp = null;
1316
+ }, s(l);
1317
+ }, r.onerror = () => a(r.error);
1318
+ }), this.dbp.catch(() => this.dbp = null), this.dbp) : Promise.reject(new Error("IndexedDB is not available"));
1319
+ }
1320
+ /** Loads the database into memory once. */
1321
+ load() {
1322
+ return this.loaded || (this.loaded = this.open().then(
1323
+ (t) => new Promise((s, a) => {
1324
+ const r = t.transaction(ie, "readonly").objectStore(ie).getAll();
1325
+ r.onsuccess = () => {
1326
+ r.result.forEach(({ key: l, value: o }) => {
1327
+ l.startsWith("form:") ? this.forms.set(l.slice(5), o) : l.startsWith("submission:") && this.submissions.set(l.slice(11), o);
1328
+ }), s();
1329
+ }, r.onerror = () => a(r.error);
1330
+ })
1331
+ ), this.loaded.catch(() => this.loaded = null)), this.loaded;
1332
+ }
1333
+ async changed(t, s) {
1334
+ const a = await this.open();
1335
+ await new Promise((r, l) => {
1336
+ const o = a.transaction(ie, "readwrite"), u = o.objectStore(ie);
1337
+ s === null ? u.delete(t) : u.put({ key: t, value: s }), o.oncomplete = () => r(), o.onerror = () => l(o.error);
1338
+ });
1339
+ }
1340
+ close() {
1341
+ var t;
1342
+ (t = this.dbp) == null || t.then((s) => s.close()), this.dbp = null, this.loaded = null;
1343
+ }
1344
+ }
1345
+ for (const i of ["listForms", "getForm", "saveForm", "deleteForm", "submit", "listSubmissions", "deleteSubmission"]) {
1346
+ const e = ft.prototype[i];
1347
+ ht.prototype[i] = async function(...t) {
1348
+ return await this.load(), e.apply(this, t);
1349
+ };
1350
+ }
1351
+ const ye = (i) => V({ ...i, updatedAt: i.updated_at }), us = (i) => {
1352
+ if (!i) return;
1353
+ const { page_id: e, ...t } = i;
1354
+ return { ...t, ...e != null ? { pageId: String(e) } : {} };
1355
+ }, Pe = (i) => {
1356
+ if (!i) return;
1357
+ const { pageId: e, ...t } = i;
1358
+ return { ...t, ...e != null ? { page_id: e } : {} };
1359
+ }, ms = (i) => ({
1360
+ id: i.id,
1361
+ formId: i.form_id,
1362
+ data: i.data || {},
1363
+ createdAt: i.created_at,
1364
+ ...i.meta ? { meta: us(i.meta) } : {}
1365
+ }), gt = (i) => typeof Blob < "u" && i instanceof Blob || Array.isArray(i) && i.some(gt), Ue = (i, e) => `${(i || "").trim().replace(/\/+$/, "")}/forms/${encodeURIComponent(e)}/submissions`;
1366
+ class fs {
1367
+ constructor(e) {
1368
+ this.opts = e;
1369
+ }
1370
+ get base() {
1371
+ return (this.opts.url || "").trim().replace(/\/+$/, "");
1372
+ }
1373
+ async request(e, t, { body: s, version: a, raw: r } = {}) {
1374
+ var d, b;
1375
+ const l = { Accept: "application/json" };
1376
+ s !== void 0 && (l["Content-Type"] = "application/json"), a != null && (l["If-Match"] = `"${a}"`), Object.assign(l, ((b = (d = this.opts).headers) == null ? void 0 : b.call(d)) || {});
1377
+ const u = await (this.opts.fetch || globalThis.fetch.bind(globalThis))(this.base + t, {
1378
+ method: e,
1379
+ headers: l,
1380
+ credentials: this.opts.credentials,
1381
+ body: r ?? (s !== void 0 ? JSON.stringify(s) : void 0)
1382
+ });
1383
+ if (u.status === 412) throw new Ae();
1384
+ if (!u.ok) {
1385
+ let h = `${e} ${t}: HTTP ${u.status}`, y = {};
1386
+ try {
1387
+ const p = await u.json();
1388
+ p != null && p.error ? h = p.error : p != null && p.message && (h = p.message), p != null && p.errors && (y = p.errors);
1389
+ } catch {
1390
+ }
1391
+ throw new G(h, u.status, y);
1392
+ }
1393
+ if (u.status === 204) return null;
1394
+ const n = await u.text();
1395
+ return n ? JSON.parse(n) : null;
1396
+ }
1397
+ async listForms() {
1398
+ const e = await this.request("GET", "/forms");
1399
+ return ((e == null ? void 0 : e.items) || []).map(ye);
1400
+ }
1401
+ async getForm(e) {
1402
+ try {
1403
+ return ye(await this.request("GET", `/forms/${encodeURIComponent(e)}`));
1404
+ } catch (t) {
1405
+ if (t instanceof G && t.status === 404) return;
1406
+ throw t;
1407
+ }
1408
+ }
1409
+ async saveForm(e, t) {
1410
+ const s = { name: e.name, fields: e.fields, settings: e.settings };
1411
+ return e.attrs && (s.attrs = e.attrs), ye(await this.request("PUT", `/forms/${encodeURIComponent(e.id)}`, { body: s, version: t }));
1412
+ }
1413
+ async deleteForm(e) {
1414
+ try {
1415
+ await this.request("DELETE", `/forms/${encodeURIComponent(e)}`);
1416
+ } catch (t) {
1417
+ if (!(t instanceof G && t.status === 404)) throw t;
1418
+ }
1419
+ }
1420
+ /** JSON `{ data, meta }`; with files `multipart/form-data` (fields by name, `_meta` as JSON). */
1421
+ async submit(e, t, s) {
1422
+ const a = `/forms/${encodeURIComponent(e)}/submissions`;
1423
+ let r;
1424
+ if (Object.values(t).some(gt)) {
1425
+ const l = new FormData();
1426
+ Object.entries(t).forEach(([o, u]) => (Array.isArray(u) ? u : [u]).forEach((n) => n instanceof Blob ? l.append(o, n) : n != null && l.append(o, String(n)))), s && l.append("_meta", JSON.stringify(Pe(s))), r = await this.request("POST", a, { raw: l });
1427
+ } else r = await this.request("POST", a, { body: { data: t, ...s ? { meta: Pe(s) } : {} } });
1428
+ return {
1429
+ ...r != null && r.id ? { id: r.id } : {},
1430
+ ...r != null && r.created_at ? { createdAt: r.created_at } : {},
1431
+ ...r != null && r.message ? { message: r.message } : {},
1432
+ ...r != null && r.redirect ? { redirect: r.redirect } : {}
1433
+ };
1434
+ }
1435
+ async listSubmissions(e, t = {}) {
1436
+ const s = new URLSearchParams();
1437
+ t.limit && s.set("limit", String(t.limit)), t.offset && s.set("offset", String(t.offset));
1438
+ const a = s.toString(), r = await this.request("GET", `/forms/${encodeURIComponent(e)}/submissions${a ? `?${a}` : ""}`), l = ((r == null ? void 0 : r.items) || []).map(ms);
1439
+ return { items: l, total: typeof (r == null ? void 0 : r.total) == "number" ? r.total : l.length };
1440
+ }
1441
+ async deleteSubmission(e, t) {
1442
+ try {
1443
+ await this.request("DELETE", `/forms/${encodeURIComponent(e)}/submissions/${encodeURIComponent(t)}`);
1444
+ } catch (s) {
1445
+ if (!(s instanceof G && s.status === 404)) throw s;
1446
+ }
1447
+ }
1448
+ }
1449
+ const z = (i) => {
1450
+ if (i != null) {
1451
+ if (typeof i == "string") return i;
1452
+ if (typeof i == "object") {
1453
+ const e = i, t = e.default ?? e.en ?? Object.values(e)[0];
1454
+ return typeof t == "string" ? t : void 0;
1455
+ }
1456
+ return String(i);
1457
+ }
1458
+ }, xe = (i) => i == null ? void 0 : i.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim() || void 0, de = (i) => (Array.isArray(i) ? i : []).map(
1459
+ (e) => e && typeof e == "object" ? { value: String(e.value ?? z(e.text) ?? ""), label: z(e.text) ?? String(e.value ?? "") } : { value: String(e), label: String(e) }
1460
+ ), hs = {
1461
+ text: "text",
1462
+ email: "email",
1463
+ tel: "tel",
1464
+ url: "url",
1465
+ number: "number",
1466
+ password: "password",
1467
+ date: "date",
1468
+ time: "time",
1469
+ "datetime-local": "datetime",
1470
+ range: "range",
1471
+ color: "color"
1472
+ };
1473
+ function gs(i) {
1474
+ const e = [], t = (s) => (Array.isArray(s) ? s : []).forEach((a) => {
1475
+ if (!(!a || typeof a != "object"))
1476
+ if (a.type === "panel" || a.type === "flowpanel") {
1477
+ const r = z(a.title);
1478
+ r && e.push({ type: "html", html: r, __heading: !0 }), t(a.elements || a.questions);
1479
+ } else e.push(a);
1480
+ });
1481
+ return Array.isArray(i.pages) && i.pages.forEach((s) => t((s == null ? void 0 : s.elements) || (s == null ? void 0 : s.questions))), t(i.elements || i.questions), e;
1482
+ }
1483
+ function Je(i, e = "") {
1484
+ const t = [], s = [];
1485
+ gs(i || {}).forEach((r) => {
1486
+ const l = { id: Y(), name: r.name, label: z(r.title) ?? r.name };
1487
+ r.isRequired && (l.required = !0);
1488
+ const o = z(r.placeholder ?? r.placeHolder);
1489
+ o && (l.placeholder = o);
1490
+ const u = z(r.description);
1491
+ u && (l.help = u), r.defaultValue != null && (l.value = Array.isArray(r.defaultValue) ? r.defaultValue.join(",") : String(r.defaultValue)), r.readOnly && (l.readonly = !0);
1492
+ const n = typeof r.width == "string" ? r.width.trim() : "";
1493
+ switch (n === "50%" ? l.width = "1/2" : /^33(\.3+)?%$/.test(n) ? l.width = "1/3" : n === "25%" && (l.width = "1/4"), r.type) {
1494
+ case "text": {
1495
+ const d = hs[r.inputType || "text"];
1496
+ if (!d) {
1497
+ t.push(`${r.name} (text/${r.inputType})`);
1498
+ return;
1499
+ }
1500
+ if (r.visible === !1) {
1501
+ s.push({ id: l.id, type: "hidden", name: r.name, value: l.value });
1502
+ return;
1503
+ }
1504
+ const b = { ...l, type: d };
1505
+ r.min != null && (b.min = String(r.min)), r.max != null && (b.max = String(r.max)), r.step != null && (b.step = String(r.step)), r.maxLength > 0 && (b.maxLength = r.maxLength), r.autocomplete && (b.autocomplete = r.autocomplete);
1506
+ const h = (r.validators || []).find((p) => (p == null ? void 0 : p.type) === "regex" && p.regex);
1507
+ h && (b.pattern = String(h.regex).replace(/^\^|\$$/g, ""));
1508
+ const y = (r.validators || []).find((p) => (p == null ? void 0 : p.type) === "text");
1509
+ (y == null ? void 0 : y.minLength) > 0 && (b.minLength = y.minLength), (y == null ? void 0 : y.maxLength) > 0 && (b.maxLength = y.maxLength), s.push(b);
1510
+ return;
1511
+ }
1512
+ case "comment":
1513
+ s.push({ ...l, type: "textarea", ...r.rows ? { rows: r.rows } : {}, ...r.maxLength > 0 ? { maxLength: r.maxLength } : {} });
1514
+ return;
1515
+ case "dropdown":
1516
+ s.push({ ...l, type: "select", options: de(r.choices) });
1517
+ return;
1518
+ case "tagbox":
1519
+ s.push({ ...l, type: "select", multiple: !0, options: de(r.choices) });
1520
+ return;
1521
+ case "radiogroup":
1522
+ s.push({ ...l, type: "radio", options: de(r.choices) });
1523
+ return;
1524
+ case "checkbox":
1525
+ s.push({ ...l, type: "checkboxes", options: de(r.choices) });
1526
+ return;
1527
+ case "boolean":
1528
+ s.push({ ...l, type: "checkbox", label: z(r.label) ?? l.label, value: r.defaultValue === !0 ? "1" : void 0 });
1529
+ return;
1530
+ case "rating": {
1531
+ const d = Array.isArray(r.rateValues) && r.rateValues.length ? de(r.rateValues) : null, b = Number(r.rateMin ?? 1), h = Number(r.rateMax ?? 5), y = Number(r.rateStep ?? 1) || 1, p = d || Array.from({ length: Math.max(0, Math.floor((h - b) / y) + 1) }, (_, $) => String(b + $ * y)).map((_) => ({ value: _, label: _ }));
1532
+ s.push({ ...l, type: "radio", options: p });
1533
+ return;
1534
+ }
1535
+ case "file":
1536
+ s.push({ ...l, type: "file", ...r.allowMultiple ? { multiple: !0 } : {}, ...r.acceptedTypes ? { accept: r.acceptedTypes } : {} });
1537
+ return;
1538
+ case "html": {
1539
+ const d = xe(z(r.html));
1540
+ d && s.push({ id: l.id, type: r.__heading || /^\s*<h[1-6][\s>]/i.test(z(r.html) || "") ? "heading" : "paragraph", name: "", text: d });
1541
+ return;
1542
+ }
1543
+ case "expression":
1544
+ r.name && t.push(`${r.name} (expression)`);
1545
+ return;
1546
+ default:
1547
+ t.push(`${r.name || "?"} (${r.type})`);
1548
+ }
1549
+ });
1550
+ const a = V({
1551
+ id: e,
1552
+ name: z(i == null ? void 0 : i.title) || "Form",
1553
+ fields: s,
1554
+ settings: {
1555
+ submitLabel: z(i == null ? void 0 : i.completeText),
1556
+ successMessage: xe(z(i == null ? void 0 : i.completedHtml)),
1557
+ redirect: i == null ? void 0 : i.navigateToUrl
1558
+ }
1559
+ });
1560
+ return i != null && i.description && a.fields.unshift({ id: Y(), type: "paragraph", name: "", text: xe(z(i.description)) || "" }), { form: a, skipped: t };
1561
+ }
1562
+ function He(i) {
1563
+ const e = [];
1564
+ i.fields.forEach((s) => {
1565
+ const a = { name: s.name };
1566
+ s.label && (a.title = s.label), s.required && (a.isRequired = !0), s.placeholder && (a.placeholder = s.placeholder), s.help && (a.description = s.help), s.readonly && (a.readOnly = !0), s.value && (a.defaultValue = s.type === "checkboxes" ? s.value.split(",").map((l) => l.trim()) : s.type === "checkbox" ? /^(1|true|on|yes)$/i.test(s.value) : s.value), s.width === "1/2" && (a.width = "50%");
1567
+ const r = (s.options || []).map((l) => l.label === l.value ? l.value : { value: l.value, text: l.label });
1568
+ switch (s.type) {
1569
+ case "heading":
1570
+ case "paragraph":
1571
+ e.push({ type: "html", name: s.id, html: s.type === "heading" ? `<h3>${ve(s.text || "")}</h3>` : `<p>${ve(s.text || "")}</p>` });
1572
+ return;
1573
+ case "hidden":
1574
+ e.push({ type: "text", name: s.name, visible: !1, ...s.value ? { defaultValue: s.value } : {} });
1575
+ return;
1576
+ case "textarea":
1577
+ e.push({ ...a, type: "comment", ...s.rows ? { rows: s.rows } : {}, ...s.maxLength ? { maxLength: s.maxLength } : {} });
1578
+ return;
1579
+ case "select":
1580
+ e.push({ ...a, type: s.multiple ? "tagbox" : "dropdown", choices: r });
1581
+ return;
1582
+ case "radio":
1583
+ e.push({ ...a, type: "radiogroup", choices: r });
1584
+ return;
1585
+ case "checkboxes":
1586
+ e.push({ ...a, type: "checkbox", choices: r });
1587
+ return;
1588
+ case "checkbox":
1589
+ e.push({ ...a, type: "boolean", renderAs: "checkbox", ...s.label ? { label: s.label } : {} });
1590
+ return;
1591
+ case "file":
1592
+ e.push({ ...a, type: "file", ...s.multiple ? { allowMultiple: !0 } : {}, ...s.accept ? { acceptedTypes: s.accept } : {}, storeDataAsText: !1 });
1593
+ return;
1594
+ default: {
1595
+ const l = s.type === "datetime" ? "datetime-local" : s.type, o = { ...a, type: "text", ...l !== "text" ? { inputType: l } : {} };
1596
+ s.min && (o.min = s.min), s.max && (o.max = s.max), s.step && (o.step = s.step), s.maxLength && (o.maxLength = s.maxLength), s.autocomplete && (o.autocomplete = s.autocomplete);
1597
+ const u = [];
1598
+ s.pattern && u.push({ type: "regex", regex: `^${s.pattern}$` }), s.minLength && u.push({ type: "text", minLength: s.minLength }), u.length && (o.validators = u), e.push(o);
1599
+ }
1600
+ }
1601
+ });
1602
+ const t = { title: i.name, pages: [{ name: "page1", elements: e }] };
1603
+ return i.settings.submitLabel && (t.completeText = i.settings.submitLabel), i.settings.successMessage && (t.completedHtml = `<p>${ve(i.settings.successMessage)}</p>`), i.settings.redirect && (t.navigateToUrl = i.settings.redirect), t;
1604
+ }
1605
+ const ve = (i) => i.replace(/[&<>"]/g, (e) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[e]);
1606
+ function f(i, e = {}, ...t) {
1607
+ const s = document.createElement(i);
1608
+ Object.entries(e).forEach(([r, l]) => {
1609
+ l === !1 || l == null || (r === "class" ? s.className = String(l) : r.startsWith("on") && typeof l == "function" ? s.addEventListener(r.slice(2), l) : s.setAttribute(r, l === !0 ? "" : String(l)));
1610
+ });
1611
+ const a = (r) => {
1612
+ if (Array.isArray(r)) return r.forEach(a);
1613
+ r === !1 || r == null || s.append(r instanceof Node ? r : document.createTextNode(String(r)));
1614
+ };
1615
+ return t.forEach(a), s;
1616
+ }
1617
+ const ze = {
1618
+ text: "T",
1619
+ email: "@",
1620
+ tel: "☎",
1621
+ url: "🔗",
1622
+ number: "#",
1623
+ password: "•••",
1624
+ textarea: "¶",
1625
+ select: "▾",
1626
+ radio: "◉",
1627
+ checkbox: "☑",
1628
+ checkboxes: "☷",
1629
+ date: "📅",
1630
+ time: "⏱",
1631
+ datetime: "🗓",
1632
+ range: "⇔",
1633
+ color: "◐",
1634
+ file: "📎",
1635
+ hidden: "👁",
1636
+ heading: "H",
1637
+ paragraph: "≡"
1638
+ }, bs = 50;
1639
+ class ys {
1640
+ constructor(e) {
1641
+ T(this, "root");
1642
+ T(this, "cur", null);
1643
+ T(this, "tab", "fields");
1644
+ T(this, "selField", null);
1645
+ T(this, "statusEl", null);
1646
+ T(this, "body", null);
1647
+ T(this, "listEl", null);
1648
+ T(this, "propsEl", null);
1649
+ T(this, "sideEl", null);
1650
+ T(this, "subs", []);
1651
+ T(this, "subsTotal", 0);
1652
+ T(this, "flashTimer", null);
1653
+ this.d = e, this.root = f("div", { class: "gjsf gjsf-ed" });
1654
+ }
1655
+ get t() {
1656
+ return this.d.t;
1657
+ }
1658
+ /** Opens on a form (the first when none given). */
1659
+ show(e) {
1660
+ var a;
1661
+ const t = this.d.forms(), s = e && this.d.form(e) || this.cur && this.d.form(this.cur.id) || t[0] || null;
1662
+ this.cur = s ? I(s) : null, this.cur && !this.cur.fields.some((r) => r.id === this.selField) && (this.selField = ((a = this.cur.fields[0]) == null ? void 0 : a.id) || null), this.render();
1663
+ }
1664
+ get currentId() {
1665
+ var e;
1666
+ return ((e = this.cur) == null ? void 0 : e.id) || null;
1667
+ }
1668
+ /** The forms changed elsewhere (a save came back, a reload): the list follows; the open form only when `reload`. */
1669
+ setForms(e = !1) {
1670
+ if (this.cur && e) {
1671
+ const t = this.d.form(this.cur.id);
1672
+ this.cur = t ? I(t) : this.d.forms()[0] ? I(this.d.forms()[0]) : null, this.render();
1673
+ return;
1674
+ }
1675
+ if (this.cur && !this.d.form(this.cur.id)) {
1676
+ this.show(null);
1677
+ return;
1678
+ }
1679
+ this.renderSide();
1680
+ }
1681
+ flash(e, t = !1) {
1682
+ this.statusEl && (this.statusEl.textContent = e, this.statusEl.classList.toggle("is-error", t), this.flashTimer && clearTimeout(this.flashTimer), t || (this.flashTimer = setTimeout(() => this.statusEl && (this.statusEl.textContent = ""), 2500)));
1683
+ }
1684
+ destroy() {
1685
+ this.flashTimer && clearTimeout(this.flashTimer), this.root.replaceChildren();
1686
+ }
1687
+ /* ------------------------------------------------------------------ */
1688
+ changed() {
1689
+ this.cur && this.d.change(I(this.cur));
1690
+ }
1691
+ render() {
1692
+ const e = this.t;
1693
+ this.sideEl = f("div", { class: "gjsf-side" });
1694
+ const t = f("div", { class: "gjsf-main" });
1695
+ this.root.replaceChildren(this.sideEl, t), this.renderSide();
1696
+ const s = this.cur;
1697
+ if (!s) {
1698
+ t.append(f("div", { class: "gjsf-empty" }, e("noForms")));
1699
+ return;
1700
+ }
1701
+ const a = f("input", { class: "gjsf-input", value: s.name, "aria-label": e("formName"), "data-role": "form-name" });
1702
+ a.addEventListener("input", () => {
1703
+ s.name = a.value, this.changed(), this.renderSide();
1704
+ }), this.statusEl = f("span", { class: "gjsf-status", "aria-live": "polite" });
1705
+ const r = f(
1706
+ "div",
1707
+ { class: "gjsf-head" },
1708
+ a,
1709
+ this.statusEl,
1710
+ f("button", { class: "gjsf-btn", type: "button", "data-role": "duplicate", title: e("duplicateForm"), onclick: () => this.duplicate() }, "⧉"),
1711
+ f("button", { class: "gjsf-btn is-danger", type: "button", "data-role": "remove-form", title: e("removeForm"), onclick: () => this.removeForm() }, "🗑")
1712
+ ), o = f(
1713
+ "div",
1714
+ { class: "gjsf-tabs", role: "tablist" },
1715
+ ...[
1716
+ ["fields", "fields"],
1717
+ ["settings", "settings"],
1718
+ ["preview", "preview"],
1719
+ ["submissions", "submissions"],
1720
+ ["json", "json"]
1721
+ ].map(
1722
+ ([u, n]) => f(
1723
+ "button",
1724
+ {
1725
+ class: `gjsf-tab${this.tab === u ? " is-active" : ""}`,
1726
+ type: "button",
1727
+ role: "tab",
1728
+ "aria-selected": this.tab === u ? "true" : "false",
1729
+ "data-tab": u,
1730
+ onclick: () => {
1731
+ this.tab = u, this.render();
1732
+ }
1733
+ },
1734
+ e(n)
1735
+ )
1736
+ )
1737
+ );
1738
+ this.body = f("div", { class: "gjsf-body" }), t.append(r, o, this.body), this.tab === "fields" ? this.renderFields() : this.tab === "settings" ? this.renderSettings() : this.tab === "preview" ? this.renderPreview() : this.tab === "submissions" ? this.renderSubmissions(!0) : this.renderJson();
1739
+ }
1740
+ renderSide() {
1741
+ if (!this.sideEl) return;
1742
+ const e = this.t, t = f(
1743
+ "ul",
1744
+ { class: "gjsf-side-list" },
1745
+ ...this.d.forms().map((s) => {
1746
+ var r;
1747
+ const a = this.cur && s.id === this.cur.id ? this.cur.name : s.name;
1748
+ return f(
1749
+ "li",
1750
+ {
1751
+ class: `gjsf-side-item${((r = this.cur) == null ? void 0 : r.id) === s.id ? " is-active" : ""}`,
1752
+ tabindex: "0",
1753
+ "data-form": s.id,
1754
+ onclick: () => this.show(s.id),
1755
+ onkeydown: (l) => l.key === "Enter" && this.show(s.id)
1756
+ },
1757
+ a || s.id
1758
+ );
1759
+ })
1760
+ );
1761
+ this.sideEl.replaceChildren(
1762
+ f(
1763
+ "button",
1764
+ {
1765
+ class: "gjsf-btn is-primary",
1766
+ type: "button",
1767
+ "data-role": "new-form",
1768
+ onclick: () => void this.d.create().then((s) => {
1769
+ this.tab = "fields", this.show(s.id);
1770
+ }).catch(this.d.onError)
1771
+ },
1772
+ `+ ${e("newForm")}`
1773
+ ),
1774
+ t
1775
+ );
1776
+ }
1777
+ duplicate() {
1778
+ this.cur && this.d.duplicate(this.cur.id).then((e) => this.show(e.id)).catch(this.d.onError);
1779
+ }
1780
+ removeForm() {
1781
+ const e = this.cur;
1782
+ !e || !window.confirm(te(this.t("confirmRemoveForm"), e.name)) || this.d.remove(e.id).then(() => {
1783
+ this.cur = null, this.show(null);
1784
+ }).catch(this.d.onError);
1785
+ }
1786
+ /* ------------------------------ fields ----------------------------- */
1787
+ renderFields() {
1788
+ const e = this.t, t = f(
1789
+ "div",
1790
+ { class: "gjsf-palette", "aria-label": e("addField") },
1791
+ f("div", { class: "gjsf-sec" }, e("addField")),
1792
+ ...[...je, ...fe].map(
1793
+ (s) => f(
1794
+ "button",
1795
+ { type: "button", "data-add": s, title: e(`type_${s}`), onclick: () => this.addField(s) },
1796
+ f("span", { class: "gjsf-ico" }, ze[s]),
1797
+ e(`type_${s}`)
1798
+ )
1799
+ )
1800
+ );
1801
+ this.listEl = f("div", { class: "gjsf-list" }), this.propsEl = f("div", { class: "gjsf-props" }), this.body.replaceChildren(f("div", { class: "gjsf-cols" }, t, this.listEl, this.propsEl)), this.renderList(), this.renderProps();
1802
+ }
1803
+ addField(e) {
1804
+ var o, u;
1805
+ const t = this.cur, s = O(e) ? "" : this.t(`type_${e}`), a = new Set(t.fields.map((n) => n.name)), r = { id: Y(), type: e, name: O(e) ? "" : re(W(s) || e, a) };
1806
+ O(e) ? r.text = this.t(`type_${e}`) : e !== "hidden" && (r.label = s), me.includes(e) && (r.options = [1, 2, 3].map((n) => ({ label: `${this.t("optionLabel")} ${n}`, value: `option_${n}` })));
1807
+ const l = this.selField ? t.fields.findIndex((n) => n.id === this.selField) + 1 : t.fields.length;
1808
+ t.fields.splice(l > 0 ? l : t.fields.length, 0, r), this.selField = r.id, this.changed(), this.renderList(), this.renderProps(), (u = (o = this.propsEl) == null ? void 0 : o.querySelector("input,textarea")) == null || u.focus();
1809
+ }
1810
+ renderList() {
1811
+ if (!this.listEl || !this.cur) return;
1812
+ const e = this.t, t = this.cur.fields;
1813
+ if (!t.length) {
1814
+ this.listEl.replaceChildren(f("p", { class: "gjsf-hint" }, e("noFields")));
1815
+ return;
1816
+ }
1817
+ const s = (a, r) => {
1818
+ const l = a + r;
1819
+ l < 0 || l >= t.length || ([t[a], t[l]] = [t[l], t[a]], this.changed(), this.renderList());
1820
+ };
1821
+ this.listEl.replaceChildren(
1822
+ ...t.map(
1823
+ (a, r) => f(
1824
+ "div",
1825
+ {
1826
+ class: `gjsf-row${a.id === this.selField ? " is-active" : ""}`,
1827
+ "data-field": a.id,
1828
+ tabindex: "0",
1829
+ onclick: () => {
1830
+ this.selField = a.id, this.renderList(), this.renderProps();
1831
+ }
1832
+ },
1833
+ f("span", { class: "gjsf-ico", title: e(`type_${a.type}`) }, ze[a.type]),
1834
+ f(
1835
+ "div",
1836
+ { class: "gjsf-row-main" },
1837
+ f("div", { class: "gjsf-row-title" }, Te(a), a.required ? " *" : ""),
1838
+ f("div", { class: "gjsf-row-sub" }, O(a.type) ? e(`type_${a.type}`) : `${a.name} · ${a.type}`)
1839
+ ),
1840
+ this.act("↑", e("moveUp"), r === 0, () => s(r, -1)),
1841
+ this.act("↓", e("moveDown"), r === t.length - 1, () => s(r, 1)),
1842
+ this.act("⧉", e("duplicate"), !1, () => {
1843
+ const l = { ...I(a), id: Y() };
1844
+ O(a.type) || (l.name = re(a.name, new Set(t.map((o) => o.name)))), t.splice(r + 1, 0, l), this.selField = l.id, this.changed(), this.renderList(), this.renderProps();
1845
+ }),
1846
+ this.act("✕", e("remove"), !1, () => {
1847
+ var l;
1848
+ t.splice(r, 1), this.selField === a.id && (this.selField = ((l = t[Math.min(r, t.length - 1)]) == null ? void 0 : l.id) || null), this.changed(), this.renderList(), this.renderProps();
1849
+ })
1850
+ )
1851
+ )
1852
+ );
1853
+ }
1854
+ act(e, t, s, a) {
1855
+ return f(
1856
+ "button",
1857
+ {
1858
+ class: "gjsf-act",
1859
+ type: "button",
1860
+ title: t,
1861
+ "aria-label": t,
1862
+ disabled: s,
1863
+ onclick: (r) => {
1864
+ r.stopPropagation(), a();
1865
+ }
1866
+ },
1867
+ e
1868
+ );
1869
+ }
1870
+ /** The title row of the open field changes as its label / name is typed. */
1871
+ refreshRow(e) {
1872
+ var r;
1873
+ const t = (r = this.listEl) == null ? void 0 : r.querySelector(`[data-field="${e.id}"]`);
1874
+ if (!t) return;
1875
+ const s = t.querySelector(".gjsf-row-title"), a = t.querySelector(".gjsf-row-sub");
1876
+ s && (s.textContent = Te(e) + (e.required ? " *" : "")), a && !O(e.type) && (a.textContent = `${e.name} · ${e.type}`);
1877
+ }
1878
+ /** A labelled input bound to `obj[key]`. */
1879
+ text(e, t, s, a = {}) {
1880
+ const r = t[s], l = {
1881
+ class: `gjsf-input${a.code ? " gjsf-code" : ""}`,
1882
+ "data-prop": s,
1883
+ ...a.placeholder ? { placeholder: a.placeholder } : {}
1884
+ }, o = a.area ? f("textarea", { ...l, rows: "3" }) : f("input", { ...l, type: a.type || "text" });
1885
+ return o.value = r == null ? "" : String(r), o.addEventListener("input", () => {
1886
+ var n;
1887
+ const u = o.value;
1888
+ if (a.num) {
1889
+ const d = u.trim() === "" ? NaN : Number(u);
1890
+ Number.isInteger(d) && d >= 0 ? t[s] = d : delete t[s];
1891
+ } else u === "" ? delete t[s] : t[s] = u;
1892
+ (n = a.onChange) == null || n.call(a), this.changed();
1893
+ }), f("label", { class: "gjsf-f" }, f("span", {}, e), o, a.hint ? f("small", {}, a.hint) : null);
1894
+ }
1895
+ check(e, t, s, a = {}) {
1896
+ const r = f("input", { type: "checkbox", "data-prop": s });
1897
+ return r.checked = a.invert ? t[s] !== !1 : t[s] === !0, r.addEventListener("change", () => {
1898
+ var l;
1899
+ a.invert ? r.checked ? delete t[s] : t[s] = !1 : r.checked ? t[s] = !0 : delete t[s], (l = a.onChange) == null || l.call(a), this.changed();
1900
+ }), f("label", { class: "gjsf-check" }, r, e);
1901
+ }
1902
+ /** Placeholder chips that insert into an input. */
1903
+ chips(e) {
1904
+ const t = this.t;
1905
+ return f(
1906
+ "div",
1907
+ {},
1908
+ f("small", { class: "gjsf-hint" }, `${t("placeholders")}: ${t("placeholdersHint")}`),
1909
+ f(
1910
+ "div",
1911
+ { class: "gjsf-chips" },
1912
+ ...Lt.map(
1913
+ (s) => f(
1914
+ "button",
1915
+ {
1916
+ class: `gjsf-chip${s.at === "build" ? " is-build" : ""}`,
1917
+ type: "button",
1918
+ "data-token": s.token,
1919
+ onclick: () => {
1920
+ const a = e();
1921
+ if (!a) return;
1922
+ const r = a.selectionStart ?? a.value.length, l = a.selectionEnd ?? r;
1923
+ a.value = a.value.slice(0, r) + s.token + a.value.slice(l), a.dispatchEvent(new Event("input", { bubbles: !0 })), a.focus();
1924
+ }
1925
+ },
1926
+ s.token
1927
+ )
1928
+ )
1929
+ )
1930
+ );
1931
+ }
1932
+ /** `{ name: value }` rows. */
1933
+ kv(e, t, s) {
1934
+ const a = this.t, r = f("div", { class: "gjsf-kvs", "data-prop": s }), l = Object.entries(t[s] || {}), o = () => {
1935
+ const n = {};
1936
+ l.forEach(([d, b]) => {
1937
+ d.trim() && (n[d.trim()] = b);
1938
+ }), Object.keys(n).length ? t[s] = n : delete t[s], this.changed();
1939
+ }, u = () => {
1940
+ r.replaceChildren(
1941
+ f("div", { class: "gjsf-sec" }, e),
1942
+ ...l.map((n, d) => {
1943
+ const b = f("input", { class: "gjsf-input gjsf-code", placeholder: a("attrName"), value: n[0], "aria-label": a("attrName") }), h = f("input", { class: "gjsf-input", placeholder: a("attrValue"), value: n[1], "aria-label": a("attrValue") });
1944
+ return b.addEventListener("input", () => {
1945
+ n[0] = b.value, o();
1946
+ }), h.addEventListener("input", () => {
1947
+ n[1] = h.value, o();
1948
+ }), f(
1949
+ "div",
1950
+ { class: "gjsf-kv" },
1951
+ b,
1952
+ h,
1953
+ this.act("✕", a("remove"), !1, () => {
1954
+ l.splice(d, 1), o(), u();
1955
+ })
1956
+ );
1957
+ }),
1958
+ f(
1959
+ "button",
1960
+ {
1961
+ class: "gjsf-btn",
1962
+ type: "button",
1963
+ "data-role": "add-attr",
1964
+ onclick: () => {
1965
+ var n;
1966
+ l.push(["data-", ""]), u(), (n = r.querySelectorAll(".gjsf-kv input")[l.length * 2 - 2]) == null || n.focus();
1967
+ }
1968
+ },
1969
+ `+ ${a("addAttr")}`
1970
+ )
1971
+ );
1972
+ };
1973
+ return u(), r;
1974
+ }
1975
+ optionsEditor(e) {
1976
+ const t = this.t, s = f("div", { class: "gjsf-opts", "data-prop": "options" }), a = e.options || (e.options = []), r = () => {
1977
+ s.replaceChildren(
1978
+ f("div", { class: "gjsf-sec" }, t("options")),
1979
+ f("small", { class: "gjsf-hint" }, t("optionsHint")),
1980
+ ...a.map((l, o) => {
1981
+ const u = f("input", { class: "gjsf-input", value: l.label, placeholder: t("optionLabel"), "aria-label": t("optionLabel") }), n = f("input", { class: "gjsf-input gjsf-code", value: l.value, placeholder: t("optionValue"), "aria-label": t("optionValue") });
1982
+ let d = l.value === W(l.label) || /^option_\d+$/.test(l.value);
1983
+ return u.addEventListener("input", () => {
1984
+ l.label = u.value, d && (l.value = W(u.value) || l.value, n.value = l.value), this.changed();
1985
+ }), n.addEventListener("input", () => {
1986
+ d = !1, l.value = n.value, this.changed();
1987
+ }), f(
1988
+ "div",
1989
+ { class: "gjsf-kv" },
1990
+ u,
1991
+ n,
1992
+ this.act("↑", t("moveUp"), o === 0, () => {
1993
+ [a[o - 1], a[o]] = [a[o], a[o - 1]], this.changed(), r();
1994
+ }),
1995
+ this.act("✕", t("remove"), !1, () => {
1996
+ a.splice(o, 1), this.changed(), r();
1997
+ })
1998
+ );
1999
+ }),
2000
+ f(
2001
+ "button",
2002
+ {
2003
+ class: "gjsf-btn",
2004
+ type: "button",
2005
+ "data-role": "add-option",
2006
+ onclick: () => {
2007
+ const l = a.length + 1;
2008
+ a.push({ label: `${t("optionLabel")} ${l}`, value: `option_${l}` }), this.changed(), r();
2009
+ }
2010
+ },
2011
+ `+ ${t("addOption")}`
2012
+ )
2013
+ );
2014
+ };
2015
+ return r(), s;
2016
+ }
2017
+ renderProps() {
2018
+ if (!this.propsEl || !this.cur) return;
2019
+ const e = this.t, t = this.cur.fields.find((h) => h.id === this.selField);
2020
+ if (!t) {
2021
+ this.propsEl.replaceChildren(f("p", { class: "gjsf-hint" }, e("noFieldSelected")));
2022
+ return;
2023
+ }
2024
+ const s = () => this.refreshRow(t), a = f(
2025
+ "select",
2026
+ { class: "gjsf-input", "data-prop": "type", "aria-label": e("fieldType") },
2027
+ ...[...je, ...fe].map((h) => f("option", { value: h, selected: h === t.type }, e(`type_${h}`)))
2028
+ );
2029
+ a.addEventListener("change", () => {
2030
+ var p;
2031
+ const h = a.value, y = t.type;
2032
+ t.type = h, O(h) && !O(y) ? (t.text = t.label || t.text || "", t.name = "") : !O(h) && O(y) && (t.label = t.text || e(`type_${h}`), t.name = re(W(t.label) || h, new Set(this.cur.fields.filter((_) => _ !== t).map((_) => _.name)))), me.includes(h) && !((p = t.options) != null && p.length) && (t.options = [1, 2].map((_) => ({ label: `${e("optionLabel")} ${_}`, value: `option_${_}` }))), this.changed(), this.renderList(), this.renderProps();
2033
+ });
2034
+ const r = [f("label", { class: "gjsf-f" }, f("span", {}, e("fieldType")), a)];
2035
+ if (O(t.type)) {
2036
+ r.push(this.text(e("text"), t, "text", { area: t.type === "paragraph", onChange: s })), r.push(this.kv(e("attrs"), t, "attrs")), this.propsEl.replaceChildren(...r.filter(Boolean));
2037
+ return;
2038
+ }
2039
+ let l = !!t.name && t.name !== W(t.label || "") && !/^(text|email|tel|url|number|password|textarea|select|radio|checkbox|checkboxes|date|time|datetime|range|color|file|hidden)(_\d+)?$/.test(t.name);
2040
+ const o = this.text(e("fieldName"), t, "name", {
2041
+ code: !0,
2042
+ hint: e("fieldNameHint"),
2043
+ onChange: () => {
2044
+ l = !0, s();
2045
+ }
2046
+ }), u = o.querySelector("input");
2047
+ u.addEventListener("change", () => {
2048
+ const h = new Set(this.cur.fields.filter((p) => p !== t && !O(p.type)).map((p) => p.name)), y = re(W(u.value) || (/^[A-Za-z_]/.test(u.value) ? u.value : "") || t.type, h);
2049
+ (y !== t.name || u.value !== y) && (t.name = y, u.value = y, this.changed(), s());
2050
+ }), t.type !== "hidden" && r.push(
2051
+ this.text(e("fieldLabel"), t, "label", {
2052
+ onChange: () => {
2053
+ if (!l) {
2054
+ const h = new Set(this.cur.fields.filter((p) => p !== t && !O(p.type)).map((p) => p.name)), y = W(t.label || "");
2055
+ y && (t.name = re(y, h), u.value = t.name);
2056
+ }
2057
+ s();
2058
+ }
2059
+ })
2060
+ ), r.push(o);
2061
+ const n = this.text(t.type === "hidden" ? e("hiddenValue") : e("defaultValue"), t, "value", { code: t.type === "hidden" }), d = () => n.querySelector("input");
2062
+ if (t.type === "hidden") {
2063
+ r.push(n, this.chips(d)), r.push(this.kv(e("attrs"), t, "attrs")), this.propsEl.replaceChildren(...r.filter(Boolean));
2064
+ return;
2065
+ }
2066
+ if (["checkbox", "radio", "checkboxes", "range", "color", "file", "date", "time", "datetime"].includes(t.type) || r.push(this.text(e("placeholder"), t, "placeholder")), r.push(this.text(e("help"), t, "help")), r.push(this.check(e("required"), t, "required", { onChange: s })), me.includes(t.type) && r.push(this.optionsEditor(t)), (t.type === "select" || t.type === "file") && r.push(this.check(e("multiple"), t, "multiple")), t.type !== "file" && t.type !== "password" && r.push(n, this.chips(d)), $t.includes(t.type)) {
2067
+ const h = t.type === "number" || t.type === "range" ? "number" : t.type === "datetime" ? "datetime-local" : t.type;
2068
+ r.push(f("div", { class: "gjsf-grid" }, this.text(e("min"), t, "min", { type: h }), this.text(e("max"), t, "max", { type: h }), this.text(e("step"), t, "step", { type: "number" })));
2069
+ }
2070
+ we.includes(t.type) && (r.push(f("div", { class: "gjsf-grid2" }, this.text(e("minLength"), t, "minLength", { type: "number", num: !0 }), this.text(e("maxLength"), t, "maxLength", { type: "number", num: !0 }))), t.type !== "textarea" && r.push(this.text(e("pattern"), t, "pattern", { code: !0, placeholder: "[0-9]{5}" }))), t.type === "textarea" && r.push(this.text(e("rows"), t, "rows", { type: "number", num: !0 })), t.type === "file" && r.push(this.text(e("accept"), t, "accept", { code: !0, placeholder: "image/*,.pdf" })), ["checkbox", "radio", "checkboxes", "file", "range", "color"].includes(t.type) || r.push(this.text(e("autocomplete"), t, "autocomplete", { code: !0, placeholder: t.type === "email" ? "email" : t.type === "tel" ? "tel" : "name" }));
2071
+ const b = f("select", { class: "gjsf-input", "data-prop": "width", "aria-label": e("width") }, ...st.map((h) => f("option", { value: h, selected: (t.width || "full") === h }, h === "full" ? "100%" : h)));
2072
+ b.addEventListener("change", () => {
2073
+ b.value === "full" ? delete t.width : t.width = b.value, this.changed();
2074
+ }), r.push(f("label", { class: "gjsf-f" }, f("span", {}, e("width")), b)), r.push(f("div", { class: "gjsf-grid2" }, this.check(e("readonly"), t, "readonly"), this.check(e("disabled"), t, "disabled"))), r.push(this.kv(e("attrs"), t, "attrs")), this.propsEl.replaceChildren(...r.filter(Boolean));
2075
+ }
2076
+ /* ----------------------------- settings ---------------------------- */
2077
+ renderSettings() {
2078
+ const e = this.t, t = this.cur, s = t.settings, a = this.d.defaultAction(t);
2079
+ this.body.replaceChildren(
2080
+ f(
2081
+ "div",
2082
+ { class: "gjsf-pane" },
2083
+ this.text(e("endpoint"), s, "endpoint", { code: !0, placeholder: a || "https://…", hint: te(e("endpointHint"), a || e("noEndpoint")) }),
2084
+ this.text(e("submitLabel"), s, "submitLabel", { placeholder: e("submit") }),
2085
+ this.text(e("successMessage"), s, "successMessage", { area: !0, placeholder: e("success") }),
2086
+ this.text(e("errorMessage"), s, "errorMessage", { area: !0, placeholder: e("error") }),
2087
+ this.text(e("redirect"), s, "redirect", { code: !0, placeholder: "/thank-you" }),
2088
+ this.check(e("reset"), s, "reset", { invert: !0 }),
2089
+ this.check(e("honeypot"), s, "honeypot", { invert: !0 }),
2090
+ this.kv(e("formAttrs"), t, "attrs")
2091
+ )
2092
+ );
2093
+ }
2094
+ /* ------------------------------ preview ---------------------------- */
2095
+ renderPreview() {
2096
+ const e = this.t, t = this.cur, { css: s, links: a } = this.d.previewStyles(), r = f("iframe", { class: "gjsf-frame", title: e("preview") }), l = f("span", {}, e("previewHint"));
2097
+ this.body.replaceChildren(f("div", { class: "gjsf-frame-bar" }, l), r);
2098
+ const o = (b) => b.replace(/"/g, "&quot;"), u = `<!DOCTYPE html><html><head><meta charset="utf-8">${a.map((b) => `<link rel="stylesheet" href="${o(b)}">`).join("")}<style>${s.replace(/<\/style/gi, "<\\/style")}</style><style>body{padding:16px}</style></head><body>${this.d.previewHtml(t)}</body></html>`, n = () => {
2099
+ const b = r.contentDocument, h = b == null ? void 0 : b.querySelector("form[data-gjsf-form]");
2100
+ !h || h.__gjsf || (h.addEventListener("gjsf:submit", (y) => {
2101
+ const p = y.detail;
2102
+ p.promise = this.d.submit(t.id, p.data, { ...p.meta, url: "editor:preview" }).then((_) => (l.textContent = e("previewSent"), { ..._, message: _.message })).catch((_) => {
2103
+ throw _ instanceof G ? { status: _.status, body: { error: _.message, errors: _.errors } } : { status: 0, body: { error: _ == null ? void 0 : _.message } };
2104
+ });
2105
+ }), Ce.call(h));
2106
+ }, d = r.contentDocument;
2107
+ d && (d.open(), d.write(u), d.close(), n(), r.addEventListener("load", n));
2108
+ }
2109
+ /* ---------------------------- submissions -------------------------- */
2110
+ async renderSubmissions(e) {
2111
+ var y;
2112
+ const t = this.t, s = this.cur, a = f("div", { class: "gjsf-pane", style: "max-width:none" });
2113
+ this.body.replaceChildren(a);
2114
+ const r = this.d.submissions(s.id, { limit: bs, offset: e ? 0 : this.subs.length });
2115
+ if (!r) {
2116
+ a.append(f("p", { class: "gjsf-hint" }, t("submissionsUnsupported")));
2117
+ return;
2118
+ }
2119
+ try {
2120
+ const p = await r;
2121
+ if (((y = this.cur) == null ? void 0 : y.id) !== s.id || this.tab !== "submissions") return;
2122
+ this.subs = e ? p.items : [...this.subs, ...p.items], this.subsTotal = p.total;
2123
+ } catch (p) {
2124
+ a.append(f("p", { class: "gjsf-err" }, p.message));
2125
+ return;
2126
+ }
2127
+ const l = s.fields.filter((p) => !O(p.type)), o = new Set(l.map((p) => p.name)), u = [...new Set(this.subs.flatMap((p) => Object.keys(p.data || {})))].filter((p) => !o.has(p)), n = [...l.map((p) => ({ key: p.name, title: p.label || p.name })), ...u.map((p) => ({ key: p, title: p }))], d = (p) => p == null ? "" : Array.isArray(p) ? p.join(", ") : typeof p == "boolean" ? p ? "✓" : "" : typeof p == "object" ? JSON.stringify(p) : String(p), b = f(
2128
+ "div",
2129
+ { class: "gjsf-bar" },
2130
+ f("button", { class: "gjsf-btn", type: "button", "data-role": "refresh", onclick: () => void this.renderSubmissions(!0) }, `↻ ${t("refresh")}`),
2131
+ f(
2132
+ "button",
2133
+ {
2134
+ class: "gjsf-btn",
2135
+ type: "button",
2136
+ "data-role": "csv",
2137
+ disabled: !this.subs.length,
2138
+ onclick: () => Be(`${s.name || s.id}.csv`, xs([t("date"), ...n.map((p) => p.title)], this.subs.map((p) => [p.createdAt, ...n.map((_) => {
2139
+ var $;
2140
+ return d(($ = p.data) == null ? void 0 : $[_.key]);
2141
+ })])), "text/csv")
2142
+ },
2143
+ `⇩ ${t("downloadCsv")}`
2144
+ ),
2145
+ f("span", { class: "gjsf-hint" }, te(t("shownOf"), this.subs.length, this.subsTotal))
2146
+ );
2147
+ if (a.append(b), !this.subs.length) {
2148
+ a.append(f("p", { class: "gjsf-hint" }, t("noSubmissions")));
2149
+ return;
2150
+ }
2151
+ const h = f(
2152
+ "table",
2153
+ { class: "gjsf-table" },
2154
+ f("thead", {}, f("tr", {}, f("th", {}, t("date")), ...n.map((p) => f("th", {}, p.title)), f("th", {}, ""))),
2155
+ f(
2156
+ "tbody",
2157
+ {},
2158
+ ...this.subs.map(
2159
+ (p) => {
2160
+ var _;
2161
+ return f(
2162
+ "tr",
2163
+ { "data-submission": p.id },
2164
+ f("td", { title: String(((_ = p.meta) == null ? void 0 : _.url) || "") }, new Date(p.createdAt).toLocaleString()),
2165
+ ...n.map(($) => {
2166
+ var M;
2167
+ return f("td", {}, d((M = p.data) == null ? void 0 : M[$.key]));
2168
+ }),
2169
+ f(
2170
+ "td",
2171
+ {},
2172
+ this.act("✕", t("remove"), !1, () => {
2173
+ window.confirm(t("confirmDeleteSubmission")) && this.d.deleteSubmission(s.id, p.id).then(() => this.renderSubmissions(!0)).catch(this.d.onError);
2174
+ })
2175
+ )
2176
+ );
2177
+ }
2178
+ )
2179
+ )
2180
+ );
2181
+ a.append(f("div", { class: "gjsf-table-wrap" }, h)), this.subs.length < this.subsTotal && a.append(f("button", { class: "gjsf-btn", type: "button", "data-role": "more", onclick: () => void this.renderSubmissions(!1) }, t("loadMore")));
2182
+ }
2183
+ /* ------------------------------- JSON ------------------------------ */
2184
+ renderJson() {
2185
+ const e = this.t, t = this.cur, { id: s, version: a, updatedAt: r, ...l } = t, o = f("textarea", { class: "gjsf-input gjsf-code", rows: "22", "data-role": "json", spellcheck: "false" });
2186
+ o.value = JSON.stringify(l, null, 2);
2187
+ const u = f("p", { class: "gjsf-hint", "aria-live": "polite" });
2188
+ this.body.replaceChildren(
2189
+ f(
2190
+ "div",
2191
+ { class: "gjsf-pane", style: "max-width:none" },
2192
+ f("p", { class: "gjsf-hint" }, e("jsonHint")),
2193
+ o,
2194
+ f(
2195
+ "div",
2196
+ { class: "gjsf-bar" },
2197
+ f(
2198
+ "button",
2199
+ {
2200
+ class: "gjsf-btn is-primary",
2201
+ type: "button",
2202
+ "data-role": "apply-json",
2203
+ onclick: () => {
2204
+ let n;
2205
+ try {
2206
+ n = JSON.parse(o.value);
2207
+ } catch (d) {
2208
+ u.textContent = te(e("jsonError"), d.message), u.className = "gjsf-err";
2209
+ return;
2210
+ }
2211
+ this.d.applyJson(t.id, n).then((d) => {
2212
+ var b;
2213
+ this.cur = I(this.d.form(t.id) || t), this.selField = ((b = this.cur.fields[0]) == null ? void 0 : b.id) || null, this.render(), d.length ? this.flash(te(e("skipped"), d.join(", ")), !0) : this.flash(e("saved"));
2214
+ }).catch(this.d.onError);
2215
+ }
2216
+ },
2217
+ e("applyJson")
2218
+ ),
2219
+ f(
2220
+ "button",
2221
+ {
2222
+ class: "gjsf-btn",
2223
+ type: "button",
2224
+ "data-role": "export-surveyjs",
2225
+ onclick: () => Be(`${t.name || t.id}.survey.json`, JSON.stringify(this.d.exportSurveyJs(t.id), null, 2), "application/json")
2226
+ },
2227
+ `⇩ ${e("exportSurveyJs")}`
2228
+ )
2229
+ ),
2230
+ u
2231
+ )
2232
+ );
2233
+ }
2234
+ }
2235
+ function xs(i, e) {
2236
+ const t = (s) => /[",\r\n;]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
2237
+ return "\uFEFF" + [i, ...e].map((s) => s.map((a) => t(String(a ?? ""))).join(",")).join(`\r
2238
+ `);
2239
+ }
2240
+ function Be(i, e, t) {
2241
+ try {
2242
+ const s = URL.createObjectURL(new Blob([e], { type: t })), a = f("a", { href: s, download: i.replace(/[\\/:*?"<>|]+/g, "_") });
2243
+ document.body.append(a), a.click(), a.remove(), setTimeout(() => URL.revokeObjectURL(s), 1e3);
2244
+ } catch {
2245
+ }
2246
+ }
2247
+ const Ve = "gjsf-style", vs = `
2248
+ .gjsf-modal .gjs-mdl-dialog{max-width:1180px;width:96%}
2249
+ .gjsf-modal .gjs-mdl-content{padding:0}
2250
+ .gjsf-ed{display:flex;height:min(78vh,760px);font-size:13px;text-align:start;font-family:var(--gjs-main-font,Helvetica,sans-serif)}
2251
+ .gjsf-ed *{box-sizing:border-box}
2252
+ .gjsf-side{width:200px;flex:none;border-inline-end:1px solid rgba(0,0,0,.25);display:flex;flex-direction:column;overflow:auto}
2253
+ .gjsf-side-list{list-style:none;margin:0;padding:0;flex:1}
2254
+ .gjsf-side-item{padding:8px 12px;cursor:pointer;border-inline-start:3px solid transparent;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
2255
+ .gjsf-side-item:hover{background:rgba(255,255,255,.06)}
2256
+ .gjsf-side-item.is-active{border-inline-start-color:var(--gjs-quaternary-color,#d278c9);background:rgba(255,255,255,.08)}
2257
+ .gjsf-main{flex:1;min-width:0;display:flex;flex-direction:column}
2258
+ .gjsf-head{display:flex;gap:8px;align-items:center;padding:8px 12px;border-bottom:1px solid rgba(0,0,0,.25)}
2259
+ .gjsf-head .gjsf-input{flex:1;font-size:15px;font-weight:600}
2260
+ .gjsf-status{font-size:11px;opacity:.75;white-space:nowrap}
2261
+ .gjsf-status.is-error{color:#ff8a80;opacity:1}
2262
+ .gjsf-tabs{display:flex;gap:2px;padding:0 8px;border-bottom:1px solid rgba(0,0,0,.25)}
2263
+ .gjsf-tab{background:none;border:0;border-bottom:2px solid transparent;color:inherit;padding:8px 12px;cursor:pointer;font:inherit;opacity:.75}
2264
+ .gjsf-tab.is-active{border-bottom-color:var(--gjs-quaternary-color,#d278c9);opacity:1}
2265
+ .gjsf-body{flex:1;min-height:0;overflow:auto}
2266
+ .gjsf-cols{display:flex;height:100%}
2267
+ .gjsf-palette{width:150px;flex:none;padding:8px;border-inline-end:1px solid rgba(0,0,0,.2);overflow:auto}
2268
+ .gjsf-palette button{display:flex;gap:6px;align-items:center;width:100%;text-align:start;margin:0 0 3px;padding:5px 8px;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);border-radius:3px;color:inherit;cursor:pointer;font:inherit}
2269
+ .gjsf-palette button:hover{background:rgba(255,255,255,.14)}
2270
+ .gjsf-ico{display:inline-block;width:18px;text-align:center;opacity:.8;font-size:12px}
2271
+ .gjsf-list{flex:1;min-width:0;padding:8px;overflow:auto;border-inline-end:1px solid rgba(0,0,0,.2)}
2272
+ .gjsf-row{display:flex;gap:6px;align-items:center;padding:6px 8px;margin-bottom:4px;border:1px solid rgba(255,255,255,.12);border-radius:4px;cursor:pointer}
2273
+ .gjsf-row:hover{background:rgba(255,255,255,.05)}
2274
+ .gjsf-row.is-active{border-color:var(--gjs-quaternary-color,#d278c9);background:rgba(255,255,255,.08)}
2275
+ .gjsf-row-main{flex:1;min-width:0}
2276
+ .gjsf-row-title{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
2277
+ .gjsf-row-sub{font-size:10px;opacity:.6;font-family:ui-monospace,Menlo,Consolas,monospace}
2278
+ .gjsf-row .gjsf-act{visibility:hidden}
2279
+ .gjsf-row:hover .gjsf-act,.gjsf-row.is-active .gjsf-act{visibility:visible}
2280
+ .gjsf-act{background:none;border:0;color:inherit;cursor:pointer;padding:2px 5px;border-radius:3px;font-size:12px}
2281
+ .gjsf-act:hover{background:rgba(255,255,255,.15)}
2282
+ .gjsf-act[disabled]{opacity:.3;cursor:default}
2283
+ .gjsf-props{width:330px;flex:none;padding:8px 12px;overflow:auto}
2284
+ .gjsf-pane{padding:12px;max-width:720px}
2285
+ .gjsf-f{display:block;margin:0 0 8px}
2286
+ .gjsf-f>span{display:block;font-size:11px;opacity:.85;margin-bottom:2px}
2287
+ .gjsf-f small{display:block;font-size:10px;opacity:.6;margin-top:2px}
2288
+ .gjsf-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px}
2289
+ .gjsf-grid2{display:grid;grid-template-columns:1fr 1fr;gap:6px}
2290
+ .gjsf-input{display:block;width:100%;margin:0;padding:5px 8px;background:rgba(0,0,0,.25);border:1px solid rgba(255,255,255,.2);color:inherit;border-radius:3px;font:inherit}
2291
+ .gjsf-input option{color:#222}
2292
+ textarea.gjsf-input{resize:vertical;min-height:54px}
2293
+ .gjsf-code{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px}
2294
+ .gjsf-check{display:flex;align-items:center;gap:6px;margin:0 0 6px;cursor:pointer}
2295
+ .gjsf-kv{display:flex;gap:4px;margin-bottom:4px}
2296
+ .gjsf-kv .gjsf-input{flex:1;min-width:0}
2297
+ .gjsf-sec{margin:12px 0 6px;font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;opacity:.7}
2298
+ .gjsf-hint{opacity:.7;font-size:12px;margin:4px 0}
2299
+ .gjsf-chips{display:flex;flex-wrap:wrap;gap:3px;margin-top:4px}
2300
+ .gjsf-chip{background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.15);border-radius:10px;padding:1px 7px;font-size:10px;cursor:pointer;color:inherit;font-family:ui-monospace,Menlo,Consolas,monospace}
2301
+ .gjsf-chip.is-build{border-style:dashed}
2302
+ .gjsf-btn{padding:6px 12px;border-radius:3px;border:0;cursor:pointer;color:inherit;font:inherit;background:rgba(255,255,255,.15)}
2303
+ .gjsf-btn:hover{background:rgba(255,255,255,.22)}
2304
+ .gjsf-btn.is-primary{background:var(--gjs-quaternary-color,#d278c9)}
2305
+ .gjsf-btn.is-danger:hover{background:#c62828}
2306
+ .gjsf-bar{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin:8px 0}
2307
+ .gjsf-side .gjsf-btn{margin:8px}
2308
+ .gjsf-empty{padding:24px;opacity:.7}
2309
+ .gjsf-frame{width:100%;height:calc(100% - 36px);border:0;background:#fff;display:block}
2310
+ .gjsf-frame-bar{display:flex;gap:8px;align-items:center;padding:6px 12px;font-size:11px;opacity:.85;height:36px}
2311
+ .gjsf-table-wrap{overflow:auto;max-height:100%}
2312
+ .gjsf-table{border-collapse:collapse;width:100%;font-size:12px}
2313
+ .gjsf-table th,.gjsf-table td{border-bottom:1px solid rgba(255,255,255,.1);padding:5px 8px;text-align:start;vertical-align:top;max-width:280px;overflow-wrap:anywhere}
2314
+ .gjsf-table th{position:sticky;top:0;background:var(--gjs-primary-color,#444);font-weight:600}
2315
+ .gjsf-err{color:#ff8a80}
2316
+ .gjsf-toggle{position:absolute;top:8px;right:96px;z-index:60;background:var(--gjs-primary-color,#444);color:var(--gjs-font-color,#ddd);border:1px solid rgba(255,255,255,.2);border-radius:4px;padding:6px 10px;cursor:pointer}
2317
+ `;
2318
+ function qe(i = document) {
2319
+ if (i.getElementById(Ve)) return;
2320
+ const e = i.createElement("style");
2321
+ e.id = Ve, e.textContent = vs, i.head.appendChild(e);
2322
+ }
2323
+ const Ye = `
2324
+ .gjsf-form{display:flex;flex-wrap:wrap;gap:16px;position:relative}
2325
+ .gjsf-field{flex:1 1 100%;min-width:0;margin:0;padding:0;border:0}
2326
+ .gjsf-w-1-2{flex-basis:calc(50% - 8px)}
2327
+ .gjsf-w-1-3{flex-basis:calc(33.333% - 11px)}
2328
+ .gjsf-w-2-3{flex-basis:calc(66.666% - 6px)}
2329
+ .gjsf-w-1-4{flex-basis:calc(25% - 12px)}
2330
+ .gjsf-w-3-4{flex-basis:calc(75% - 4px)}
2331
+ .gjsf-label{display:block;margin:0 0 6px;padding:0;font-weight:600}
2332
+ .gjsf-req{margin-left:2px;color:#c62828}
2333
+ .gjsf-input{display:block;width:100%;box-sizing:border-box;padding:10px 12px;font:inherit;color:inherit;background:transparent;border:1px solid rgba(127,127,127,.5);border-radius:4px}
2334
+ .gjsf-input:focus{outline:2px solid rgba(127,127,127,.35);outline-offset:1px}
2335
+ .gjsf-options{display:flex;flex-direction:column;gap:6px}
2336
+ .gjsf-option{display:flex;gap:8px;align-items:center;cursor:pointer;font-weight:400}
2337
+ .gjsf-help{margin-top:4px;font-size:.875em;opacity:.75}
2338
+ .gjsf-error{margin-top:4px;font-size:.875em;color:#c62828}
2339
+ .gjsf-error:empty{display:none}
2340
+ .has-error .gjsf-input{border-color:#c62828}
2341
+ .gjsf-heading{flex-basis:100%;margin:8px 0 0}
2342
+ .gjsf-text{flex-basis:100%;margin:0}
2343
+ .gjsf-actions{flex-basis:100%}
2344
+ .gjsf-submit{font:inherit;padding:10px 24px;cursor:pointer}
2345
+ .gjsf-message{flex-basis:100%}
2346
+ .gjsf-message:empty{display:none}
2347
+ .gjsf-form.is-sending{opacity:.7}
2348
+ .gjsf-form.is-error .gjsf-message{color:#c62828}
2349
+ `, Ke = "gjsf-forms", We = "gjsf-new", Ge = (i) => `gjsf-form-${i}`;
2350
+ function As(i) {
2351
+ return i.Forms;
2352
+ }
2353
+ function Ze(i = {}) {
2354
+ const e = (s, a) => typeof s == "number" && Number.isFinite(s) && s >= 0 ? s : a, t = i.rest && i.rest.url ? i.rest : null;
2355
+ return {
2356
+ store: i.store ?? null,
2357
+ rest: t,
2358
+ submitUrl: (i.submitUrl ?? (t == null ? void 0 : t.url) ?? null) || null,
2359
+ dbName: i.dbName || "gjs-forms",
2360
+ autosaveDelay: e(i.autosaveDelay, 600),
2361
+ blocks: i.blocks !== !1,
2362
+ baseCss: i.baseCss !== !1,
2363
+ panelId: i.panelId || null,
2364
+ labels: { ...i.labels || {} },
2365
+ injectCss: i.injectCss !== !1
2366
+ };
2367
+ }
2368
+ const Qe = (i) => `<svg viewBox="0 0 24 24" style="display:block;width:${i}px;height:${i}px"><path fill="currentColor" d="M4 4h16v2H4zm0 4h10v2H4zm0 5h16v3H4zm0 5h7v2H4zm11 0h5v2h-5z"/></svg>`, Xe = '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M3 4h18v2H3zm0 4h11v2H3zm0 5h18v3H3zm0 5h8v3H3zm11 0h7v3h-7z"/></svg>', js = ["required", "email", "url", "number", "min", "max", "minLength", "maxLength", "pattern", "option", "date", "time", "color"];
2369
+ function ws(i, e = {}) {
2370
+ var Fe;
2371
+ const t = i;
2372
+ (Fe = t.__gjsfCleanup) == null || Fe.call(t);
2373
+ const s = Ze(e);
2374
+ cs(i);
2375
+ const a = ds(i, s.labels), r = s.store || (s.rest ? new fs(s.rest) : new ht(s.dbName)), l = () => t.PagesManager;
2376
+ let o = [], u = null, n = null, d = !1;
2377
+ const b = [], h = (c, m) => {
2378
+ i.on(c, m), b.push(() => i.off(c, m));
2379
+ }, y = (c, ...m) => {
2380
+ d || i.trigger(c, ...m);
2381
+ }, p = (c) => c ? o.find((m) => m.id === c) : void 0, _ = () => void o.sort((c, m) => c.name.localeCompare(m.name) || c.id.localeCompare(m.id)), $ = (c) => {
2382
+ n == null || n.flash(te(a("saveError"), (c == null ? void 0 : c.message) || String(c)), !0), Me(c);
2383
+ }, M = (c) => {
2384
+ var g;
2385
+ const m = typeof c == "string" ? p(c) : c;
2386
+ return m ? ((g = m.settings) == null ? void 0 : g.endpoint) || (s.submitUrl ? Ue(s.submitUrl, m.id) : "") : "";
2387
+ }, B = () => Object.fromEntries(js.map((c) => [c, a(`problem_${c}`)])), P = () => ({ submit: a("submit"), success: a("success"), error: a("error") }), J = () => u && typeof u.id == "string" ? u.id : null, E = new as(i, {
2388
+ form: p,
2389
+ formOptions: () => o.map((c) => ({ id: c.id, name: c.name })),
2390
+ buildOptions: (c) => ({ action: M(c), ctx: { page: u }, texts: P(), codes: B(), pageId: J() }),
2391
+ labels: { chooseForm: () => a("chooseForm"), editForm: () => a("editForm"), noForm: () => a("noForm"), missingForm: () => a("missingForm") },
2392
+ editCommand: ue.edit,
2393
+ onCreate: (c) => void Q().then((m) => {
2394
+ c.set("formId", m.id), oe(m.id);
2395
+ }).catch($)
2396
+ }), x = (c, m) => {
2397
+ const g = c.getAttributes();
2398
+ if (g["data-gjsf-version"] !== String(m.version ?? "") || "data-gjsf-missing" in g) return !0;
2399
+ const k = J();
2400
+ return (g["data-gjsf-page"] || null) !== k;
2401
+ }, v = () => {
2402
+ d || E.rebuildAll(null, x);
2403
+ };
2404
+ let w = !1;
2405
+ const j = () => {
2406
+ var m;
2407
+ if (!s.baseCss || w || !E.all().length) return;
2408
+ w = !0;
2409
+ const c = i.Css.getRule(".gjsf-input");
2410
+ (!c || !Object.keys(((m = c.getStyle) == null ? void 0 : m.call(c)) || {}).length) && i.Css.addRules(Ye);
2411
+ }, R = () => {
2412
+ if (!s.blocks || d) return;
2413
+ const c = i.Blocks, m = a("blocksCategory"), g = /* @__PURE__ */ new Set([We, ...o.map((A) => Ge(A.id))]);
2414
+ c.getAll().filter((A) => String(A.id).startsWith("gjsf-") && !g.has(A.id)).forEach((A) => c.remove(A.id));
2415
+ const k = (A, D) => {
2416
+ const le = c.get(A);
2417
+ le ? le.set(D) : c.add(A, D);
2418
+ };
2419
+ k(We, { label: `+ ${a("newFormBlock")}`, category: m, media: Xe, content: { type: q, gjsfCreate: !0 }, select: !0 }), o.forEach((A) => k(Ge(A.id), { label: A.name, category: m, media: Xe, content: { type: q, formId: A.id }, select: !0 }));
2420
+ }, F = () => {
2421
+ if (d) return;
2422
+ _(), R();
2423
+ const c = i.getSelected();
2424
+ (c == null ? void 0 : c.get("type")) === q && E.refreshTraits(c), y(ce.forms, o);
2425
+ }, N = async () => (o = (await r.listForms()).map(V), F(), n == null || n.setForms(!0), v(), o), U = () => [
2426
+ { id: Y(), type: "text", name: "name", label: a("defaultName"), required: !0, autocomplete: "name", width: "1/2" },
2427
+ { id: Y(), type: "email", name: "email", label: a("defaultEmail"), required: !0, autocomplete: "email", width: "1/2" },
2428
+ { id: Y(), type: "textarea", name: "message", label: a("defaultMessage"), rows: 5 }
2429
+ ], Z = (c) => ({ id: c.id, name: c.name, fields: c.fields, settings: c.settings, ...c.attrs ? { attrs: c.attrs } : {} }), K = (c) => {
2430
+ const m = V(c);
2431
+ o = p(m.id) ? o.map((g) => g.id === m.id ? m : g) : [...o, m];
2432
+ }, Q = async (c = {}) => {
2433
+ const m = a("defaultFormName");
2434
+ let g = o.length + 1;
2435
+ for (; o.some((D) => D.name === `${m} ${g}`); ) g++;
2436
+ const k = V({ id: c.id || _e(), name: c.name || `${m} ${g}`, fields: c.fields || U(), settings: c.settings || {}, attrs: c.attrs }), A = await r.saveForm(Z(k));
2437
+ return K(A), F(), n == null || n.setForms(), y(ce.saved, p(A.id)), p(A.id);
2438
+ }, H = /* @__PURE__ */ new Map();
2439
+ let S = null;
2440
+ const C = async () => {
2441
+ S && clearTimeout(S), S = null;
2442
+ const c = [...H.values()];
2443
+ H.clear();
2444
+ for (const m of c) {
2445
+ const g = p(m.id);
2446
+ n == null || n.flash(a("saving"));
2447
+ try {
2448
+ const k = await r.saveForm(Z(V(m)), (g == null ? void 0 : g.version) ?? null);
2449
+ K(k), n == null || n.flash(a("saved")), y(ce.saved, p(k.id)), E.rebuildAll(k.id);
2450
+ } catch (k) {
2451
+ if (k instanceof Ae) {
2452
+ const A = await r.getForm(m.id).catch(() => {
2453
+ });
2454
+ A && K(A), n == null || n.setForms(!0), n == null || n.flash(a("conflict"), !0), E.rebuildAll(m.id);
2455
+ } else throw k;
2456
+ }
2457
+ }
2458
+ c.length && F(), n == null || n.setForms();
2459
+ }, X = (c) => {
2460
+ const m = p(c.id);
2461
+ m && K({ ...I(c), version: m.version, updatedAt: m.updatedAt }), H.set(c.id, I(c)), S && clearTimeout(S), S = setTimeout(() => void C().catch($), s.autosaveDelay);
2462
+ }, se = async (c, m) => {
2463
+ H.has(c) && await C();
2464
+ const g = p(c);
2465
+ if (!g) throw new Error(`grapesjs-forms: no form ${c}`);
2466
+ return H.set(c, V({ ...I(g), ...I(m), id: c })), await C(), p(c);
2467
+ }, ne = async (c) => {
2468
+ H.delete(c), await r.deleteForm(c), o = o.filter((m) => m.id !== c), F(), n == null || n.setForms(), E.rebuildAll(c), y(ce.removed, c);
2469
+ }, ee = async (c) => {
2470
+ H.has(c) && await C();
2471
+ const m = p(c);
2472
+ if (!m) throw new Error(`grapesjs-forms: no form ${c}`);
2473
+ return Q({ name: te(a("copyOf"), m.name), fields: I(m.fields).map((g) => ({ ...g, id: Y() })), settings: I(m.settings), attrs: m.attrs && I(m.attrs) });
2474
+ }, he = async (c, m) => {
2475
+ const g = !Array.isArray(m.fields) && (Array.isArray(m.pages) || Array.isArray(m.elements) || Array.isArray(m.questions));
2476
+ let k, A = [];
2477
+ if (g) {
2478
+ const D = Je(m, c);
2479
+ k = D.form, A = D.skipped;
2480
+ } else k = V({ ...m, id: c });
2481
+ return await se(c, { name: k.name, fields: k.fields, settings: k.settings, attrs: k.attrs }), A;
2482
+ }, yt = () => {
2483
+ var k;
2484
+ const c = [];
2485
+ try {
2486
+ const A = i.Canvas.getDocument();
2487
+ A == null || A.querySelectorAll('link[rel="stylesheet"]').forEach((D) => D.href && c.push(D.href));
2488
+ } catch {
2489
+ }
2490
+ const m = (k = i.getConfig().canvas) == null ? void 0 : k.styles;
2491
+ (Array.isArray(m) ? m : []).forEach((A) => {
2492
+ const D = typeof A == "string" ? A : A == null ? void 0 : A.href;
2493
+ D && !c.includes(D) && c.push(D);
2494
+ });
2495
+ let g = "";
2496
+ try {
2497
+ g = i.getCss() || "";
2498
+ } catch {
2499
+ g = "";
2500
+ }
2501
+ return s.baseCss && !/\.gjsf-form\s*\{/.test(g) && (g = Ye + g), { css: g, links: c };
2502
+ }, xt = () => new ys({
2503
+ t: a,
2504
+ forms: () => o,
2505
+ form: p,
2506
+ create: () => Q(),
2507
+ duplicate: ee,
2508
+ remove: ne,
2509
+ change: X,
2510
+ defaultAction: (c) => s.submitUrl ? Ue(s.submitUrl, c.id) : "",
2511
+ previewHtml: (c) => Ie(V(c), { action: "", ctx: { page: u }, texts: P(), codes: B(), key: "preview" }),
2512
+ previewStyles: yt,
2513
+ submit: async (c, m, g) => {
2514
+ H.has(c) && await C();
2515
+ const k = await r.submit(c, m, { ...g || {}, ...J() ? { pageId: J() } : {} });
2516
+ return y(ce.submitted, { formId: c, result: k }), k;
2517
+ },
2518
+ submissions: (c, m) => r.listSubmissions ? r.listSubmissions(c, m) : null,
2519
+ deleteSubmission: (c, m) => {
2520
+ var g;
2521
+ return ((g = r.deleteSubmission) == null ? void 0 : g.call(r, c, m)) ?? Promise.resolve();
2522
+ },
2523
+ applyJson: he,
2524
+ exportSurveyJs: (c) => He(p(c) || V({ id: c })),
2525
+ onError: $
2526
+ }), oe = (c) => {
2527
+ var g;
2528
+ if (d) return;
2529
+ s.injectCss && qe(), n || (n = xt()), n.show(c || null);
2530
+ const m = i.Modal;
2531
+ m.open({ title: a("forms"), content: n.root, attributes: { class: "gjsf-modal" } }), (g = m.onceClose) == null || g.call(m, () => {
2532
+ C().catch($);
2533
+ });
2534
+ }, vt = () => {
2535
+ var c, m;
2536
+ n && ((m = (c = i.Modal).isOpen) != null && m.call(c)) && i.Modal.close();
2537
+ };
2538
+ i.Commands.add(ue.open, {
2539
+ run(c, m, g = {}) {
2540
+ oe(g == null ? void 0 : g.id);
2541
+ }
2542
+ }), i.Commands.add(ue.edit, {
2543
+ run(c, m, g = {}) {
2544
+ var D, le;
2545
+ const k = (g == null ? void 0 : g.component) || ((D = g == null ? void 0 : g.trait) == null ? void 0 : D.target) || c.getSelected(), A = (g == null ? void 0 : g.id) || (((le = k == null ? void 0 : k.get) == null ? void 0 : le.call(k, "type")) === q ? String(k.get("formId") || "") : "");
2546
+ oe(A || null);
2547
+ }
2548
+ });
2549
+ const jt = {
2550
+ store: r,
2551
+ list: () => o,
2552
+ get: (c) => p(c),
2553
+ reload: N,
2554
+ create: Q,
2555
+ update: se,
2556
+ remove: ne,
2557
+ duplicate: ee,
2558
+ open: (c) => oe(c),
2559
+ close: vt,
2560
+ actionOf: M,
2561
+ html: (c, m = {}) => {
2562
+ const g = p(c);
2563
+ if (!g) throw new Error(`grapesjs-forms: no form ${c}`);
2564
+ return Ie(g, { action: M(g), ctx: { page: u }, texts: P(), codes: B(), pageId: J(), ...m });
2565
+ },
2566
+ submit: async (c, m, g) => (H.has(c) && await C(), r.submit(c, m, g)),
2567
+ rebuild: (c) => E.rebuildAll(c || null),
2568
+ importSurveyJs: async (c, m) => {
2569
+ if (m) {
2570
+ const A = await he(m, c);
2571
+ return { form: p(m), skipped: A };
2572
+ }
2573
+ const g = Je(c, _e());
2574
+ return { form: await Q({ id: g.form.id, name: g.form.name, fields: g.form.fields, settings: g.form.settings }), skipped: g.skipped };
2575
+ },
2576
+ exportSurveyJs: (c) => {
2577
+ const m = p(c);
2578
+ if (!m) throw new Error(`grapesjs-forms: no form ${c}`);
2579
+ return He(m);
2580
+ },
2581
+ flush: C
2582
+ };
2583
+ t.Forms = jt, h("pages-manager:open", (c) => {
2584
+ u = c && typeof c == "object" ? { ...c } : null, setTimeout(() => {
2585
+ v(), j();
2586
+ }, 0);
2587
+ }), h("pages-manager:detach", () => {
2588
+ u = null;
2589
+ }), h("component:add", (c) => {
2590
+ var m;
2591
+ ((m = c == null ? void 0 : c.get) == null ? void 0 : m.call(c, "type")) === q && setTimeout(j, 0);
2592
+ });
2593
+ const wt = () => {
2594
+ const c = i.Panels, m = c.getPanel(s.panelId || "options") || c.getPanel("options") || c.getPanel("commands");
2595
+ if (m) {
2596
+ c.addButton(m.id, {
2597
+ id: Ke,
2598
+ label: Qe(18),
2599
+ command: ue.open,
2600
+ togglable: !1,
2601
+ attributes: { title: a("forms") }
2602
+ }), b.push(() => {
2603
+ try {
2604
+ c.removeButton(m.id, Ke);
2605
+ } catch {
2606
+ }
2607
+ });
2608
+ return;
2609
+ }
2610
+ const g = i.getContainer();
2611
+ if (!g) return;
2612
+ s.injectCss && qe();
2613
+ const k = f("button", { class: "gjsf-toggle", type: "button", title: a("forms"), onclick: () => oe() });
2614
+ k.innerHTML = Qe(14), getComputedStyle(g).position === "static" && (g.style.position = "relative"), g.appendChild(k), b.push(() => k.remove());
2615
+ };
2616
+ h(
2617
+ "i18n:locale i18n:update",
2618
+ () => setTimeout(() => {
2619
+ var m, g;
2620
+ if (d) return;
2621
+ R();
2622
+ const c = i.getSelected();
2623
+ (c == null ? void 0 : c.get("type")) === q && E.refreshTraits(c), n && ((g = (m = i.Modal).isOpen) != null && g.call(m)) && n.render();
2624
+ }, 0)
2625
+ );
2626
+ const ge = () => {
2627
+ d || (d = !0, S && clearTimeout(S), E.destroy(), n == null || n.destroy(), b.splice(0).forEach((c) => c()), t.__gjsfCleanup === ge && delete t.__gjsfCleanup);
2628
+ };
2629
+ t.__gjsfCleanup = ge;
2630
+ const St = ts(i, bt, () => _s(s), (c) => {
2631
+ var m;
2632
+ "autosaveDelay" in c && (s.autosaveDelay = Ze({ autosaveDelay: c.autosaveDelay }).autosaveDelay), "submitUrl" in c && (s.submitUrl = c.submitUrl || ((m = s.rest) == null ? void 0 : m.url) || null, E.rebuildAll(null));
2633
+ });
2634
+ h("destroy", St), h("destroy", ge);
2635
+ const Le = () => void C().catch(Me);
2636
+ window.addEventListener("beforeunload", Le), b.push(() => window.removeEventListener("beforeunload", Le)), i.onReady(() => {
2637
+ d || (wt(), N().then(async () => {
2638
+ var g;
2639
+ const c = l();
2640
+ c != null && c.whenReady && await c.whenReady();
2641
+ const m = (g = c == null ? void 0 : c.getActiveId) == null ? void 0 : g.call(c);
2642
+ c && m && !u && (u = await c.store.get(m).catch(() => {
2643
+ }) || null), d || (v(), j());
2644
+ }).catch($));
2645
+ });
2646
+ }
2647
+ const Ss = "grapesjs-forms", Es = "0.1.0", bt = {
2648
+ id: Ss,
2649
+ version: Es,
2650
+ title: "Forms",
2651
+ description: "A form editor of its own; a form is a component styled by the site; submissions go to a REST API.",
2652
+ options: [
2653
+ { key: "rest", type: "json", default: null, title: "REST backend", description: '{ "url": "/api/forms-admin" } (openapi.yaml); null — IndexedDB in the browser.' },
2654
+ { key: "submitUrl", type: "string", default: "", title: "Submit URL of the site", description: "Base the published forms post to (<url>/forms/<id>/submissions). Empty — rest.url.", live: !0 },
2655
+ { key: "dbName", type: "string", default: "gjs-forms", title: "IndexedDB database", advanced: !0 },
2656
+ { key: "autosaveDelay", type: "number", default: 600, title: "Autosave delay, ms", live: !0 },
2657
+ { key: "blocks", type: "boolean", default: !0, title: "Blocks of the forms" },
2658
+ { key: "baseCss", type: "boolean", default: !0, title: "Base form styles", description: "Adds a small stylesheet for forms to the project CSS once." },
2659
+ { key: "panelId", type: "string", default: "", title: 'Panel of the "Forms" button', description: "Empty — options.", advanced: !0 },
2660
+ { key: "labels", type: "json", default: {}, title: "Texts", advanced: !0 },
2661
+ { key: "injectCss", type: "boolean", default: !0, title: "Inject CSS", advanced: !0 }
2662
+ ]
2663
+ };
2664
+ function _s(i) {
2665
+ return {
2666
+ rest: i.rest ? { url: i.rest.url, ...i.rest.credentials ? { credentials: i.rest.credentials } : {} } : null,
2667
+ submitUrl: i.submitUrl || "",
2668
+ dbName: i.dbName,
2669
+ autosaveDelay: i.autosaveDelay,
2670
+ blocks: i.blocks,
2671
+ baseCss: i.baseCss,
2672
+ panelId: i.panelId || "",
2673
+ labels: i.labels,
2674
+ injectCss: i.injectCss
2675
+ };
2676
+ }
2677
+ const Ls = Xt(ws, bt);
2678
+ function Fs(i = document) {
2679
+ let e = 0;
2680
+ return i.querySelectorAll("form[data-gjsf-form]").forEach((t) => {
2681
+ t.__gjsf || (Ce.call(t), e++);
2682
+ }), e;
2683
+ }
2684
+ export {
2685
+ Ye as BASE_FORM_CSS,
2686
+ me as CHOICE_TYPES,
2687
+ L as CLS,
2688
+ ue as COMMANDS,
2689
+ fe as CONTENT_TYPES,
2690
+ Ae as ConflictError,
2691
+ Cs as DOM_EVENTS,
2692
+ ce as EVENTS,
2693
+ Ft as FIELD_TYPES,
2694
+ pe as FORM_ATTR,
2695
+ q as FORM_TYPE,
2696
+ as as FormComponents,
2697
+ Se as HONEYPOT,
2698
+ ut as I18N_NS,
2699
+ je as INPUT_TYPES,
2700
+ ht as IndexedDbFormStore,
2701
+ bt as META,
2702
+ ft as MemoryFormStore,
2703
+ Tt as NAME_RE,
2704
+ We as NEW_BLOCK_ID,
2705
+ Ke as PANEL_BUTTON_ID,
2706
+ lt as PART_ATTR,
2707
+ Ee as PART_TYPE,
2708
+ Lt as PLACEHOLDERS,
2709
+ Ss as PLUGIN_ID,
2710
+ $t as RANGE_TYPES,
2711
+ fs as RestFormStore,
2712
+ ls as SUPPORTED_LOCALES,
2713
+ G as StoreError,
2714
+ we as TEXT_LIKE,
2715
+ et as TOKEN_RE,
2716
+ Es as VERSION,
2717
+ st as WIDTHS,
2718
+ Ge as blockIdOf,
2719
+ at as buildChildren,
2720
+ ke as cleanAttrs,
2721
+ Ls as default,
2722
+ ot as elHtml,
2723
+ Fs as enhanceForms,
2724
+ Y as fieldId,
2725
+ W as fieldName,
2726
+ Te as fieldTitle,
2727
+ rt as formAttrs,
2728
+ Ie as formHtml,
2729
+ Ce as formScript,
2730
+ Ls as formsPlugin,
2731
+ Je as fromSurveyJs,
2732
+ As as getForms,
2733
+ tt as hasOptions,
2734
+ At as hasTokens,
2735
+ it as inputFields,
2736
+ O as isContent,
2737
+ $e as isSafeUrl,
2738
+ mt as locales,
2739
+ Mt as normalizeField,
2740
+ Pt as normalizeFields,
2741
+ V as normalizeForm,
2742
+ Dt as normalizeOptions,
2743
+ Ut as normalizeSettings,
2744
+ _s as publicOptions,
2745
+ Ct as resolveBuild,
2746
+ Ze as resolveOptions,
2747
+ Ue as submitUrlOf,
2748
+ dt as toComponent,
2749
+ xs as toCsv,
2750
+ He as toSurveyJs,
2751
+ re as uniqueName,
2752
+ Kt as validateSubmission
2753
+ };
2754
+ //# sourceMappingURL=grapesjs-forms.js.map