grapesjs-forms 0.0.0-stage → 0.1.1

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