@superdoc-dev/template-builder
Version:
React template builder component for SuperDoc
1,113 lines (1,112 loc) • 33.4 kB
JavaScript
import Oe, { useState as z, useEffect as de, useMemo as he, useCallback as _, forwardRef as Ae, useRef as Z, useImperativeHandle as Pe } from "react";
var ce = { exports: {} }, se = {};
/**
* @license React
* react-jsx-runtime.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ye;
function Ie() {
if (ye) return se;
ye = 1;
var l = Symbol.for("react.transitional.element"), b = Symbol.for("react.fragment");
function m(c, o, a) {
var F = null;
if (a !== void 0 && (F = "" + a), o.key !== void 0 && (F = "" + o.key), "key" in o) {
a = {};
for (var I in o)
I !== "key" && (a[I] = o[I]);
} else a = o;
return o = a.ref, {
$$typeof: l,
type: c,
key: F,
ref: o !== void 0 ? o : null,
props: a
};
}
return se.Fragment = b, se.jsx = m, se.jsxs = m, se;
}
var ae = {};
/**
* @license React
* react-jsx-runtime.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ve;
function De() {
return ve || (ve = 1, process.env.NODE_ENV !== "production" && (function() {
function l(e) {
if (e == null) return null;
if (typeof e == "function")
return e.$$typeof === ue ? null : e.displayName || e.name || null;
if (typeof e == "string") return e;
switch (e) {
case O:
return "Fragment";
case v:
return "Profiler";
case K:
return "StrictMode";
case x:
return "Suspense";
case E:
return "SuspenseList";
case M:
return "Activity";
}
if (typeof e == "object")
switch (typeof e.tag == "number" && console.error(
"Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
), e.$$typeof) {
case J:
return "Portal";
case P:
return e.displayName || "Context";
case V:
return (e._context.displayName || "Context") + ".Consumer";
case i:
var s = e.render;
return e = e.displayName, e || (e = s.displayName || s.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
case j:
return s = e.displayName || null, s !== null ? s : l(e.type) || "Memo";
case k:
s = e._payload, e = e._init;
try {
return l(e(s));
} catch {
}
}
return null;
}
function b(e) {
return "" + e;
}
function m(e) {
try {
b(e);
var s = !1;
} catch {
s = !0;
}
if (s) {
s = console;
var f = s.error, d = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
return f.call(
s,
"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
d
), b(e);
}
}
function c(e) {
if (e === O) return "<>";
if (typeof e == "object" && e !== null && e.$$typeof === k)
return "<...>";
try {
var s = l(e);
return s ? "<" + s + ">" : "<...>";
} catch {
return "<...>";
}
}
function o() {
var e = ee.A;
return e === null ? null : e.getOwner();
}
function a() {
return Error("react-stack-top-frame");
}
function F(e) {
if (ie.call(e, "key")) {
var s = Object.getOwnPropertyDescriptor(e, "key").get;
if (s && s.isReactWarning) return !1;
}
return e.key !== void 0;
}
function I(e, s) {
function f() {
L || (L = !0, console.error(
"%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
s
));
}
f.isReactWarning = !0, Object.defineProperty(e, "key", {
get: f,
configurable: !0
});
}
function H() {
var e = l(this.type);
return re[e] || (re[e] = !0, console.error(
"Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
)), e = this.props.ref, e !== void 0 ? e : null;
}
function U(e, s, f, d, $, oe) {
var g = f.ref;
return e = {
$$typeof: D,
type: e,
key: s,
props: f,
_owner: d
}, (g !== void 0 ? g : null) !== null ? Object.defineProperty(e, "ref", {
enumerable: !1,
get: H
}) : Object.defineProperty(e, "ref", { enumerable: !1, value: null }), e._store = {}, Object.defineProperty(e._store, "validated", {
configurable: !1,
enumerable: !1,
writable: !0,
value: 0
}), Object.defineProperty(e, "_debugInfo", {
configurable: !1,
enumerable: !1,
writable: !0,
value: null
}), Object.defineProperty(e, "_debugStack", {
configurable: !1,
enumerable: !1,
writable: !0,
value: $
}), Object.defineProperty(e, "_debugTask", {
configurable: !1,
enumerable: !1,
writable: !0,
value: oe
}), Object.freeze && (Object.freeze(e.props), Object.freeze(e)), e;
}
function A(e, s, f, d, $, oe) {
var g = s.children;
if (g !== void 0)
if (d)
if (te(g)) {
for (d = 0; d < g.length; d++)
N(g[d]);
Object.freeze && Object.freeze(g);
} else
console.error(
"React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
);
else N(g);
if (ie.call(s, "key")) {
g = l(e);
var w = Object.keys(s).filter(function(fe) {
return fe !== "key";
});
d = 0 < w.length ? "{key: someKey, " + w.join(": ..., ") + ": ...}" : "{key: someKey}", q[g + d] || (w = 0 < w.length ? "{" + w.join(": ..., ") + ": ...}" : "{}", console.error(
`A props object containing a "key" prop is being spread into JSX:
let props = %s;
<%s {...props} />
React keys must be passed directly to JSX without using spread:
let props = %s;
<%s key={someKey} {...props} />`,
d,
g,
w,
g
), q[g + d] = !0);
}
if (g = null, f !== void 0 && (m(f), g = "" + f), F(s) && (m(s.key), g = "" + s.key), "key" in s) {
f = {};
for (var G in s)
G !== "key" && (f[G] = s[G]);
} else f = s;
return g && I(
f,
typeof e == "function" ? e.displayName || e.name || "Unknown" : e
), U(
e,
g,
f,
o(),
$,
oe
);
}
function N(e) {
T(e) ? e._store && (e._store.validated = 1) : typeof e == "object" && e !== null && e.$$typeof === k && (e._payload.status === "fulfilled" ? T(e._payload.value) && e._payload.value._store && (e._payload.value._store.validated = 1) : e._store && (e._store.validated = 1));
}
function T(e) {
return typeof e == "object" && e !== null && e.$$typeof === D;
}
var Y = Oe, D = Symbol.for("react.transitional.element"), J = Symbol.for("react.portal"), O = Symbol.for("react.fragment"), K = Symbol.for("react.strict_mode"), v = Symbol.for("react.profiler"), V = Symbol.for("react.consumer"), P = Symbol.for("react.context"), i = Symbol.for("react.forward_ref"), x = Symbol.for("react.suspense"), E = Symbol.for("react.suspense_list"), j = Symbol.for("react.memo"), k = Symbol.for("react.lazy"), M = Symbol.for("react.activity"), ue = Symbol.for("react.client.reference"), ee = Y.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, ie = Object.prototype.hasOwnProperty, te = Array.isArray, R = console.createTask ? console.createTask : function() {
return null;
};
Y = {
react_stack_bottom_frame: function(e) {
return e();
}
};
var L, re = {}, B = Y.react_stack_bottom_frame.bind(
Y,
a
)(), ne = R(c(a)), q = {};
ae.Fragment = O, ae.jsx = function(e, s, f) {
var d = 1e4 > ee.recentlyCreatedOwnerStacks++;
return A(
e,
s,
f,
!1,
d ? Error("react-stack-top-frame") : B,
d ? R(c(e)) : ne
);
}, ae.jsxs = function(e, s, f) {
var d = 1e4 > ee.recentlyCreatedOwnerStacks++;
return A(
e,
s,
f,
!0,
d ? Error("react-stack-top-frame") : B,
d ? R(c(e)) : ne
);
};
})()), ae;
}
var Ee;
function Me() {
return Ee || (Ee = 1, process.env.NODE_ENV === "production" ? ce.exports = Ie() : ce.exports = De()), ce.exports;
}
var n = Me();
const Le = ({
isVisible: l,
position: b,
availableFields: m,
filteredFields: c,
filterQuery: o,
allowCreate: a,
onSelect: F,
onClose: I,
onCreateField: H
}) => {
const [U, A] = z(!1), [N, T] = z("");
de(() => {
l || (A(!1), T(""));
}, [l]);
const Y = he(() => ({
position: "absolute",
left: b?.left,
top: b?.top,
zIndex: 1e3,
background: "white",
border: "1px solid #ddd",
borderRadius: "4px",
boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
padding: "8px 0",
minWidth: "200px"
}), [b]), D = c ?? m, J = !!o, O = he(() => {
const i = [], x = /* @__PURE__ */ new Map();
return D.forEach((E) => {
const j = E.category?.trim() || "Uncategorized", k = x.get(j);
if (k !== void 0) {
i[k].fields.push(E);
return;
}
x.set(j, i.length), i.push({ category: j, fields: [E] });
}), i;
}, [D]), [K, v] = z({});
de(() => {
v((i) => {
if (O.length === 0)
return Object.keys(i).length === 0 ? i : {};
const x = {};
let E = Object.keys(i).length !== O.length;
return O.forEach(({ category: j }, k) => {
const M = J ? !0 : i[j] ?? k === 0;
x[j] = M, !E && i[j] !== M && (E = !0);
}), E ? x : i;
});
}, [O, J]);
const V = _((i) => {
v((x) => ({
...x,
[i]: !x[i]
}));
}, []);
if (!l) return null;
const P = async () => {
const i = N.trim();
if (!i) return;
const x = {
id: `custom_${Date.now()}`,
label: i,
category: "Custom"
};
try {
if (H) {
const E = await H(x);
F(E || x);
} else
F(x);
} finally {
A(!1), T("");
}
};
return /* @__PURE__ */ n.jsxs("div", { className: "superdoc-field-menu", style: Y, children: [
J && /* @__PURE__ */ n.jsx(
"div",
{
style: {
padding: "8px 16px",
borderBottom: "1px solid #f0f0f0",
marginBottom: "4px"
},
children: /* @__PURE__ */ n.jsxs("div", { style: { fontSize: "12px", color: "#6b7280" }, children: [
"Filtering results for",
/* @__PURE__ */ n.jsx(
"span",
{
style: { fontWeight: 600, color: "#111827", marginLeft: "4px" },
children: o
}
)
] })
}
),
a && !U && /* @__PURE__ */ n.jsx(
"div",
{
className: "field-menu-item",
onClick: () => A(!0),
style: {
padding: "8px 16px",
cursor: "pointer",
color: "#0066cc",
fontWeight: 500
},
children: "+ Create New Field"
}
),
a && U && /* @__PURE__ */ n.jsxs("div", { style: { padding: "8px 16px" }, children: [
/* @__PURE__ */ n.jsx(
"input",
{
type: "text",
value: N,
placeholder: "Field name...",
onChange: (i) => T(i.target.value),
onKeyDown: (i) => {
i.key === "Enter" && P(), i.key === "Escape" && (A(!1), T(""));
},
autoFocus: !0,
style: {
width: "100%",
padding: "4px 8px",
border: "1px solid #ddd",
borderRadius: "3px"
}
}
),
/* @__PURE__ */ n.jsxs(
"div",
{
style: {
marginTop: "8px",
display: "flex",
gap: "8px"
},
children: [
/* @__PURE__ */ n.jsx(
"button",
{
onClick: P,
disabled: !N.trim(),
style: {
padding: "4px 12px",
background: N.trim() ? "#0066cc" : "#ccc",
color: "white",
border: "none",
borderRadius: "3px",
cursor: N.trim() ? "pointer" : "not-allowed"
},
children: "Create"
}
),
/* @__PURE__ */ n.jsx(
"button",
{
onClick: () => {
A(!1), T("");
},
style: {
padding: "4px 12px",
background: "white",
border: "1px solid #ddd",
borderRadius: "3px",
cursor: "pointer"
},
children: "Cancel"
}
)
]
}
)
] }),
a && m.length > 0 && /* @__PURE__ */ n.jsx(
"div",
{
style: {
borderTop: "1px solid #eee",
margin: "4px 0"
}
}
),
O.length === 0 ? /* @__PURE__ */ n.jsx(
"div",
{
style: {
padding: "16px",
fontSize: "13px",
color: "#6b7280",
textAlign: "center"
},
children: "No matching fields"
}
) : O.map(({ category: i, fields: x }, E) => {
const j = !!K[i], k = `${Math.max(x.length * 40, 0)}px`;
return /* @__PURE__ */ n.jsxs(
"div",
{
style: {
borderTop: E === 0 && a ? void 0 : "1px solid #f0f0f0"
},
children: [
/* @__PURE__ */ n.jsxs(
"button",
{
type: "button",
onClick: () => V(i),
style: {
width: "100%",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
padding: "8px 16px",
background: "transparent",
border: "none",
cursor: "pointer",
fontWeight: 500,
textAlign: "left"
},
children: [
/* @__PURE__ */ n.jsxs("span", { children: [
i,
" (",
x.length,
")"
] }),
/* @__PURE__ */ n.jsx(
"span",
{
"aria-hidden": !0,
style: {
display: "inline-block",
width: "8px",
height: "8px",
borderRight: "2px solid #666",
borderBottom: "2px solid #666",
transform: j ? "rotate(45deg)" : "rotate(-45deg)",
transition: "transform 0.2s ease",
marginLeft: "12px"
}
}
)
]
}
),
/* @__PURE__ */ n.jsx(
"div",
{
"data-category": i,
"aria-hidden": !j,
style: {
overflow: "hidden",
maxHeight: j ? k : "0px",
opacity: j ? 1 : 0,
transition: "max-height 0.2s ease, opacity 0.2s ease",
pointerEvents: j ? "auto" : "none"
},
children: /* @__PURE__ */ n.jsx("div", { style: { padding: j ? "4px 0" : 0 }, children: x.map((M) => /* @__PURE__ */ n.jsx(
"div",
{
className: "field-menu-item",
onClick: () => F(M),
style: {
padding: "8px 16px",
cursor: "pointer",
display: "flex",
alignItems: "center",
justifyContent: "space-between"
},
children: /* @__PURE__ */ n.jsx("span", { style: { fontWeight: 500 }, children: M.label })
},
M.id
)) })
}
)
]
},
i
);
}),
/* @__PURE__ */ n.jsx(
"div",
{
style: {
borderTop: "1px solid #eee",
marginTop: "4px"
},
children: /* @__PURE__ */ n.jsx(
"button",
{
onClick: I,
style: {
width: "100%",
padding: "6px 16px",
background: "#f3f4f6",
border: "none",
borderRadius: "0 0 4px 4px",
cursor: "pointer"
},
children: "Close"
}
)
}
)
] });
}, Be = ({
fields: l,
onSelect: b,
onDelete: m,
selectedFieldId: c
}) => /* @__PURE__ */ n.jsxs(
"div",
{
className: "superdoc-field-list",
style: {
width: "250px",
background: "white",
border: "1px solid #e5e7eb",
borderRadius: "8px",
padding: "16px"
},
children: [
/* @__PURE__ */ n.jsxs("h3", { style: { margin: "0 0 16px 0", fontSize: "16px", fontWeight: "600" }, children: [
"Template Fields (",
l.length,
")"
] }),
l.length === 0 ? /* @__PURE__ */ n.jsxs(
"div",
{
style: {
color: "#9ca3af",
fontSize: "14px",
textAlign: "center",
padding: "20px 0"
},
children: [
"No fields yet. Type ",
"{{",
" to add a field."
]
}
) : /* @__PURE__ */ n.jsx("div", { style: { display: "flex", flexDirection: "column", gap: "8px" }, children: l.map((o) => /* @__PURE__ */ n.jsxs(
"div",
{
onClick: () => b(o),
style: {
position: "relative",
padding: "12px",
background: c === o.id ? "#eff6ff" : "#f9fafb",
border: c === o.id ? "1px solid #3b82f6" : "1px solid #e5e7eb",
borderRadius: "6px",
cursor: "pointer",
transition: "all 0.2s"
},
onMouseEnter: (a) => {
c !== o.id && (a.currentTarget.style.background = "#f3f4f6");
},
onMouseLeave: (a) => {
c !== o.id && (a.currentTarget.style.background = "#f9fafb");
},
title: o.alias,
children: [
/* @__PURE__ */ n.jsx(
"button",
{
onClick: (a) => {
a.stopPropagation(), m(o.id);
},
style: {
position: "absolute",
top: "8px",
right: "8px",
padding: "4px",
background: "transparent",
border: "none",
cursor: "pointer",
color: "#9ca3af",
transition: "color 0.2s",
display: "flex",
alignItems: "center",
justifyContent: "center"
},
onMouseEnter: (a) => {
a.currentTarget.style.color = "#ef4444";
},
onMouseLeave: (a) => {
a.currentTarget.style.color = "#9ca3af";
},
title: "Delete field",
children: /* @__PURE__ */ n.jsx(
"svg",
{
width: "16",
height: "16",
viewBox: "0 0 16 16",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
children: /* @__PURE__ */ n.jsx(
"path",
{
d: "M6 2V1.5C6 1.22386 6.22386 1 6.5 1H9.5C9.77614 1 10 1.22386 10 1.5V2M2 4H14M12.6667 4L12.1991 11.0129C12.129 12.065 12.0939 12.5911 11.8667 12.99C11.6666 13.3412 11.3648 13.6235 11.0011 13.7998C10.588 14 10.0607 14 9.00623 14H6.99377C5.93927 14 5.41202 14 4.99889 13.7998C4.63517 13.6235 4.33339 13.3412 4.13332 12.99C3.90607 12.5911 3.871 12.065 3.80086 11.0129L3.33333 4",
stroke: "currentColor",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round"
}
)
}
)
}
),
/* @__PURE__ */ n.jsxs("div", { style: { paddingRight: "24px" }, children: [
/* @__PURE__ */ n.jsx(
"div",
{
style: {
fontWeight: "500",
fontSize: "14px",
marginBottom: o.alias && o.alias !== o.id ? "4px" : "0"
},
children: o.id
}
),
o.alias && o.alias !== o.id && /* @__PURE__ */ n.jsx(
"div",
{
style: {
fontSize: "12px",
color: "#4b5563"
},
children: o.alias
}
)
] })
]
},
o.id
)) })
]
}
), Re = (l) => {
const b = l.helpers?.structuredContentCommands;
return b?.getStructuredContentTags ? (b.getStructuredContentTags(l.state) || []).map((c) => {
const a = (c?.node ?? c)?.attrs ?? {};
return {
id: a.id,
alias: a.alias || a.label || "",
tag: a.tag
};
}).filter((c) => !!c.id) : [];
}, Te = (l, b) => {
if (l === b) return !0;
if (l.length !== b.length) return !1;
for (let m = 0; m < l.length; m += 1) {
const c = l[m], o = b[m];
if (!o || c.id !== o.id || c.alias !== o.alias || c.tag !== o.tag || c.position !== o.position)
return !1;
}
return !0;
}, $e = (l) => {
if (!l) return null;
if (l === !0)
return {
selector: "#superdoc-toolbar",
config: {},
renderDefaultContainer: !0
};
if (typeof l == "string")
return {
selector: l,
config: {},
renderDefaultContainer: !1
};
const { selector: b, ...m } = l;
return {
selector: b || "#superdoc-toolbar",
config: m,
renderDefaultContainer: b === void 0
};
}, We = Ae((l, b) => {
const {
document: m,
fields: c = {},
menu: o = {},
list: a = {},
toolbar: F,
onReady: I,
onTrigger: H,
onFieldInsert: U,
onFieldUpdate: A,
onFieldDelete: N,
onFieldsChange: T,
onFieldSelect: Y,
onFieldCreate: D,
className: J,
style: O,
documentHeight: K = "600px"
} = l, [v, V] = z(
c.initial || []
), [P, i] = z(null), [x, E] = z(!1), [j, k] = z(), [M, ue] = z(""), [ee, ie] = z(() => c.available || []), te = Z(null), R = Z(null), L = Z(null), re = Z(c);
re.current = c;
const B = Z(null), ne = Z(x);
de(() => {
ne.current = x;
}, [x]);
const q = o.trigger || "{{", e = re.current.available || [], s = _(
(t) => {
const r = t.trim().toLowerCase();
return r ? e.filter((h) => {
const y = h.label.toLowerCase(), S = h.category?.toLowerCase() || "";
return y.includes(r) || S.includes(r);
}) : e;
},
[e]
), f = _(
(t) => {
ue(t), ie(s(t));
},
[s]
), d = _(() => {
f("");
}, [f]), $ = _(
(t, r) => {
if (!R.current?.activeEditor) return !1;
const h = R.current.activeEditor, y = `field_${Date.now()}`, S = t === "inline" ? h.commands.insertStructuredContentInline?.({
attrs: {
id: y,
alias: r.alias,
tag: r.metadata ? JSON.stringify(r.metadata) : r.category
},
text: r.defaultValue || r.alias
}) : h.commands.insertStructuredContentBlock?.({
attrs: {
id: y,
alias: r.alias,
tag: r.metadata ? JSON.stringify(r.metadata) : r.category
},
text: r.defaultValue || r.alias
});
if (S) {
const C = {
id: y,
alias: r.alias,
tag: r.category
};
V((p) => {
const u = [...p, C];
return T?.(u), u;
}), U?.(C);
}
return S;
},
[U, T]
), oe = _(
(t, r) => {
if (!R.current?.activeEditor) return !1;
const y = R.current.activeEditor.commands.updateStructuredContentById?.(t, {
attrs: r
});
return y && V((S) => {
const C = S.map(
(u) => u.id === t ? { ...u, ...r } : u
);
T?.(C);
const p = C.find((u) => u.id === t);
return p && A?.(p), C;
}), y;
},
[A, T]
), g = _(
(t) => {
const r = R.current?.activeEditor;
if (!r) {
console.warn(
"[SuperDocTemplateBuilder] deleteField called without active editor"
);
let p = !1;
return V((u) => {
if (!u.some((W) => W.id === t)) return u;
const Q = u.filter((W) => W.id !== t);
return p = !0, T?.(Q), Q;
}), p && (N?.(t), i((u) => u === t ? null : u)), p;
}
let h = !1;
try {
h = r.commands.deleteStructuredContentById?.(t) ?? !1;
} catch (p) {
console.error(
"[SuperDocTemplateBuilder] Delete command failed:",
p
);
}
let y = Re(r);
const S = y.some((p) => p.id === t);
!h && S && (y = y.filter((p) => p.id !== t));
let C = !1;
return V((p) => {
if (Te(p, y))
return p;
const u = p.some((W) => W.id === t), Q = y.some((W) => W.id === t);
return u && !Q && (C = !0), T?.(y), y;
}), C && (N?.(t), i((p) => p === t ? null : p)), h || C;
},
[N, T]
), w = _(
(t) => {
if (!R.current?.activeEditor) return;
R.current.activeEditor.commands.selectStructuredContentById?.(t), i(t);
const h = v.find((y) => y.id === t);
h && Y?.(h);
},
[v, Y]
), G = _(
(t) => {
if (!t) return;
const r = Re(t);
V((h) => Te(h, r) ? h : (T?.(r), r));
},
[T]
);
de(() => te.current ? ((async () => {
const { SuperDoc: r } = await import("superdoc"), h = {
selector: te.current,
document: m?.source,
documentMode: m?.mode || "editing",
onReady: () => {
if (y.activeEditor) {
const S = y.activeEditor;
S.on("update", ({ editor: C }) => {
const { state: p } = C, { from: u } = p.selection;
if (u >= q.length) {
const pe = u - q.length;
if (p.doc.textBetween(pe, u) === q) {
const xe = C.view.coordsAtPos(u), ge = new DOMRect(xe.left, xe.top, 0, 0), be = () => {
const le = R.current?.activeEditor;
if (!le) return;
const Fe = le.state.selection.from, Ne = le.state.tr.delete(pe, Fe);
le.view.dispatch(Ne);
};
L.current = be, B.current = u, k(ge), E(!0), d(), H?.({
position: { from: pe, to: u },
bounds: ge,
cleanup: be
});
return;
}
}
if (!ne.current)
return;
if (B.current == null) {
E(!1), d();
return;
}
if (u < B.current) {
E(!1), B.current = null, d();
return;
}
const Q = p.doc.textBetween(
B.current,
u
);
f(Q);
const W = C.view.coordsAtPos(u), Se = new DOMRect(W.left, W.top, 0, 0);
k(Se);
}), S.on("update", () => {
G(S);
}), G(S);
}
I?.();
}
}, y = new r({
...h,
...X && {
toolbar: X.selector,
modules: {
toolbar: {
selector: X.selector,
toolbarGroups: X.config.toolbarGroups || ["center"],
excludeItems: X.config.excludeItems || [],
...X.config
}
}
}
});
R.current = y;
})(), () => {
R.current && (typeof R.current.destroy == "function" && R.current.destroy(), R.current = null);
}) : void 0, [
m?.source,
m?.mode,
q,
G,
I,
H,
F
]);
const fe = _(
async (t) => {
if (L.current && (L.current(), L.current = null), B.current = null, d(), t.id.startsWith("custom_") && D)
try {
const r = await D(t);
if (r) {
$("inline", {
alias: r.label,
category: r.category,
metadata: r.metadata,
defaultValue: r.defaultValue
}), E(!1);
return;
}
} catch (r) {
console.error("Field creation failed:", r);
}
$("inline", {
alias: t.label,
category: t.category,
metadata: t.metadata,
defaultValue: t.defaultValue
}), E(!1);
},
[$, D, d]
), je = _(() => {
E(!1), B.current = null, d(), L.current && (L.current(), L.current = null);
}, [d]), we = _(() => {
if (!R.current?.activeEditor || v.length === 0)
return;
const t = v.findIndex(
(h) => h.id === P
), r = t >= 0 ? (t + 1) % v.length : 0;
w(v[r].id);
}, [v, P, w]), Ce = _(() => {
if (!R.current?.activeEditor || v.length === 0)
return;
const t = v.findIndex(
(h) => h.id === P
), r = t > 0 ? t - 1 : v.length - 1;
w(v[r].id);
}, [v, P, w]), _e = _(
async (t) => {
try {
await R.current?.export({
exportType: ["docx"],
exportedName: t?.fileName ? t?.fileName : "document"
});
} catch (r) {
throw console.error("Failed to export DOCX", r), r;
}
},
[]
);
Pe(b, () => ({
insertField: (t) => $("inline", t),
insertBlockField: (t) => $("block", t),
updateField: oe,
deleteField: g,
selectField: w,
nextField: we,
previousField: Ce,
getFields: () => v,
exportTemplate: _e
}));
const ke = o.component || Le, me = a.component || Be, X = $e(F);
return /* @__PURE__ */ n.jsxs(
"div",
{
className: `superdoc-template-builder ${J || ""}`,
style: O,
children: [
/* @__PURE__ */ n.jsxs("div", { style: { display: "flex", gap: "20px" }, children: [
a.position === "left" && /* @__PURE__ */ n.jsx("div", { className: "superdoc-template-builder-sidebar", children: /* @__PURE__ */ n.jsx(
me,
{
fields: v,
onSelect: (t) => w(t.id),
onDelete: g,
selectedFieldId: P || void 0
}
) }),
/* @__PURE__ */ n.jsxs("div", { className: "superdoc-template-builder-document", style: { flex: 1 }, children: [
X?.renderDefaultContainer && /* @__PURE__ */ n.jsx(
"div",
{
id: "superdoc-toolbar",
className: "superdoc-template-builder-toolbar",
"data-testid": "template-builder-toolbar"
}
),
/* @__PURE__ */ n.jsx(
"div",
{
ref: te,
className: "superdoc-template-builder-editor",
style: { height: K },
"data-testid": "template-builder-editor"
}
)
] }),
a.position === "right" && /* @__PURE__ */ n.jsx("div", { className: "superdoc-template-builder-sidebar", children: /* @__PURE__ */ n.jsx(
me,
{
fields: v,
onSelect: (t) => w(t.id),
onDelete: g,
selectedFieldId: P || void 0
}
) })
] }),
/* @__PURE__ */ n.jsx(
ke,
{
isVisible: x,
position: j,
availableFields: c.available || [],
filteredFields: ee,
filterQuery: M,
allowCreate: c.allowCreate || !1,
onSelect: fe,
onClose: je,
onCreateField: D
}
)
]
}
);
});
We.displayName = "SuperDocTemplateBuilder";
export {
Be as FieldList,
Le as FieldMenu,
We as default
};