@dmitryvim/form-builder 0.2.18 → 0.2.20

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.
@@ -223,6 +223,11 @@ function pathJoin(base, key) {
223
223
  function clear(node) {
224
224
  while (node.firstChild) node.removeChild(node.firstChild);
225
225
  }
226
+ function formatFileSize(bytes) {
227
+ if (bytes < 1024) return `${bytes} B`;
228
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
229
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
230
+ }
226
231
 
227
232
  // src/utils/enable-conditions.ts
228
233
  function getValueByPath(data, path) {
@@ -4772,205 +4777,2530 @@ function updateGroupField(element, fieldPath, value, context) {
4772
4777
  return updateContainerField(containerElement, fieldPath, value, context);
4773
4778
  }
4774
4779
 
4775
- // src/components/index.ts
4776
- function showTooltip(tooltipId, button) {
4777
- const tooltip = document.getElementById(tooltipId);
4778
- if (!tooltip) return;
4779
- const isCurrentlyVisible = !tooltip.classList.contains("hidden");
4780
- document.querySelectorAll('[id^="tooltip-"]').forEach((t2) => {
4781
- t2.classList.add("hidden");
4782
- });
4783
- if (isCurrentlyVisible) {
4784
- return;
4785
- }
4786
- const rect = button.getBoundingClientRect();
4787
- const viewportWidth = window.innerWidth;
4788
- const viewportHeight = window.innerHeight;
4789
- if (tooltip && tooltip.parentElement !== document.body) {
4790
- document.body.appendChild(tooltip);
4791
- }
4792
- tooltip.style.visibility = "hidden";
4793
- tooltip.style.position = "fixed";
4794
- tooltip.classList.remove("hidden");
4795
- const tooltipRect = tooltip.getBoundingClientRect();
4796
- tooltip.classList.add("hidden");
4797
- tooltip.style.visibility = "visible";
4798
- let left = rect.left;
4799
- let top = rect.bottom + 5;
4800
- if (left + tooltipRect.width > viewportWidth) {
4801
- left = rect.right - tooltipRect.width;
4802
- }
4803
- if (top + tooltipRect.height > viewportHeight) {
4804
- top = rect.top - tooltipRect.height - 5;
4805
- }
4806
- if (left < 10) {
4807
- left = 10;
4808
- }
4809
- if (top < 10) {
4810
- top = rect.bottom + 5;
4811
- }
4812
- tooltip.style.left = `${left}px`;
4813
- tooltip.style.top = `${top}px`;
4814
- tooltip.classList.remove("hidden");
4815
- setTimeout(() => {
4816
- tooltip.classList.add("hidden");
4817
- }, 25e3);
4780
+ // src/components/table.ts
4781
+ function createEmptyCells(rows, cols) {
4782
+ return Array.from(
4783
+ { length: rows },
4784
+ () => Array.from({ length: cols }, () => "")
4785
+ );
4818
4786
  }
4819
- if (typeof document !== "undefined") {
4820
- document.addEventListener("click", (e) => {
4821
- const target = e.target;
4822
- const isInfoButton = target.closest("button") && target.closest("button").onclick;
4823
- const isTooltip = target.closest('[id^="tooltip-"]');
4824
- if (!isInfoButton && !isTooltip) {
4825
- document.querySelectorAll('[id^="tooltip-"]').forEach((tooltip) => {
4826
- tooltip.classList.add("hidden");
4827
- });
4787
+ function getShadowingMerge(row, col, merges) {
4788
+ for (const m of merges) {
4789
+ if (m.row === row && m.col === col) {
4790
+ return null;
4791
+ }
4792
+ if (row >= m.row && row < m.row + m.rowspan && col >= m.col && col < m.col + m.colspan) {
4793
+ return m;
4828
4794
  }
4795
+ }
4796
+ return null;
4797
+ }
4798
+ function getMergeAt(row, col, merges) {
4799
+ var _a;
4800
+ return (_a = merges.find((m) => m.row === row && m.col === col)) != null ? _a : null;
4801
+ }
4802
+ function selectionRange(sel) {
4803
+ var _a;
4804
+ if (!sel.anchor) return null;
4805
+ const focus = (_a = sel.focus) != null ? _a : sel.anchor;
4806
+ return {
4807
+ r1: Math.min(sel.anchor.row, focus.row),
4808
+ c1: Math.min(sel.anchor.col, focus.col),
4809
+ r2: Math.max(sel.anchor.row, focus.row),
4810
+ c2: Math.max(sel.anchor.col, focus.col)
4811
+ };
4812
+ }
4813
+ function makeOverlayCircleBtn(opts) {
4814
+ const btn = document.createElement("button");
4815
+ btn.type = "button";
4816
+ btn.textContent = opts.label;
4817
+ btn.title = opts.title;
4818
+ btn.style.cssText = `
4819
+ position: absolute;
4820
+ width: ${opts.size}px;
4821
+ height: ${opts.size}px;
4822
+ border-radius: 50%;
4823
+ border: none;
4824
+ background: ${opts.color};
4825
+ color: ${opts.textColor};
4826
+ font-size: ${Math.floor(opts.size * 0.6)}px;
4827
+ line-height: ${opts.size}px;
4828
+ text-align: center;
4829
+ cursor: pointer;
4830
+ z-index: 10;
4831
+ padding: 0;
4832
+ display: flex;
4833
+ align-items: center;
4834
+ justify-content: center;
4835
+ box-shadow: 0 1px 4px rgba(0,0,0,0.2);
4836
+ transition: transform 0.1s, opacity 0.1s;
4837
+ pointer-events: all;
4838
+ `;
4839
+ btn.addEventListener("mouseenter", () => {
4840
+ btn.style.transform = "scale(1.15)";
4841
+ });
4842
+ btn.addEventListener("mouseleave", () => {
4843
+ btn.style.transform = "scale(1)";
4844
+ });
4845
+ btn.addEventListener("click", (e) => {
4846
+ e.stopPropagation();
4847
+ opts.onClick(e);
4829
4848
  });
4849
+ return btn;
4830
4850
  }
4831
- function shouldDisableElement(element, ctx) {
4832
- var _a, _b, _c;
4833
- if (!element.enableIf) {
4834
- return false;
4835
- }
4836
- try {
4837
- const rootFormData = (_b = (_a = ctx.formData) != null ? _a : ctx.prefill) != null ? _b : {};
4838
- const scope = (_c = element.enableIf.scope) != null ? _c : "relative";
4839
- const containerData = scope === "relative" && ctx.path ? ctx.prefill : void 0;
4840
- const shouldEnable = evaluateEnableCondition(
4841
- element.enableIf,
4842
- rootFormData,
4843
- containerData
4844
- );
4845
- return !shouldEnable;
4846
- } catch (error) {
4847
- console.error(
4848
- `Error evaluating enableIf for field "${element.key}":`,
4849
- error
4850
- );
4851
- }
4852
- return false;
4851
+ function renderReadonlyTable(data, wrapper) {
4852
+ const { cells, merges = [] } = data;
4853
+ if (cells.length === 0) return;
4854
+ const numCols = cells[0].length;
4855
+ const tableEl = document.createElement("table");
4856
+ tableEl.style.cssText = `
4857
+ width: 100%;
4858
+ border-collapse: collapse;
4859
+ border: var(--fb-border-width) solid var(--fb-border-color);
4860
+ border-radius: var(--fb-border-radius);
4861
+ font-size: var(--fb-font-size);
4862
+ font-family: var(--fb-font-family);
4863
+ color: var(--fb-text-color);
4864
+ `;
4865
+ cells.forEach((rowData, rIdx) => {
4866
+ var _a, _b;
4867
+ const section = rIdx === 0 ? tableEl.createTHead() : (_a = tableEl.tBodies[0]) != null ? _a : tableEl.createTBody();
4868
+ const tr = section.insertRow();
4869
+ for (let cIdx = 0; cIdx < numCols; cIdx++) {
4870
+ if (getShadowingMerge(rIdx, cIdx, merges)) {
4871
+ continue;
4872
+ }
4873
+ const merge = getMergeAt(rIdx, cIdx, merges);
4874
+ const td = document.createElement(rIdx === 0 ? "th" : "td");
4875
+ if (merge) {
4876
+ if (merge.rowspan > 1) td.rowSpan = merge.rowspan;
4877
+ if (merge.colspan > 1) td.colSpan = merge.colspan;
4878
+ }
4879
+ td.textContent = (_b = rowData[cIdx]) != null ? _b : "";
4880
+ td.style.cssText = `
4881
+ padding: 6px 10px;
4882
+ border: var(--fb-border-width) solid var(--fb-border-color);
4883
+ text-align: left;
4884
+ vertical-align: top;
4885
+ ${rIdx === 0 ? "background-color: var(--fb-background-hover-color); font-weight: 600;" : ""}
4886
+ `;
4887
+ tr.appendChild(td);
4888
+ }
4889
+ });
4890
+ const scrollWrapper = document.createElement("div");
4891
+ scrollWrapper.style.cssText = "overflow-x: auto; max-width: 100%;";
4892
+ scrollWrapper.appendChild(tableEl);
4893
+ wrapper.appendChild(scrollWrapper);
4853
4894
  }
4854
- function extractDOMValue(fieldPath, formRoot) {
4855
- const input = formRoot.querySelector(
4856
- `[name="${fieldPath}"]`
4857
- );
4858
- if (!input) {
4859
- return void 0;
4895
+ function startCellEditing(span, r, c, getCells, persistValue, selectCell) {
4896
+ if (span.contentEditable === "true") return;
4897
+ span.contentEditable = "true";
4898
+ span.focus();
4899
+ const domRange = document.createRange();
4900
+ const winSel = window.getSelection();
4901
+ domRange.selectNodeContents(span);
4902
+ domRange.collapse(false);
4903
+ winSel == null ? void 0 : winSel.removeAllRanges();
4904
+ winSel == null ? void 0 : winSel.addRange(domRange);
4905
+ function commit() {
4906
+ var _a;
4907
+ span.contentEditable = "inherit";
4908
+ const cells = getCells();
4909
+ if (cells[r]) {
4910
+ cells[r][c] = (_a = span.textContent) != null ? _a : "";
4911
+ }
4912
+ persistValue();
4913
+ }
4914
+ function onKeyDown(e) {
4915
+ var _a, _b, _c, _d;
4916
+ const cells = getCells();
4917
+ const numCols = (_b = (_a = cells[0]) == null ? void 0 : _a.length) != null ? _b : 0;
4918
+ if (e.key === "Escape") {
4919
+ span.contentEditable = "inherit";
4920
+ span.textContent = (_d = (_c = cells[r]) == null ? void 0 : _c[c]) != null ? _d : "";
4921
+ span.removeEventListener("keydown", onKeyDown);
4922
+ span.removeEventListener("blur", onBlur);
4923
+ return;
4924
+ }
4925
+ if (e.key === "Enter" && !e.shiftKey) {
4926
+ e.preventDefault();
4927
+ e.stopPropagation();
4928
+ commit();
4929
+ span.removeEventListener("keydown", onKeyDown);
4930
+ span.removeEventListener("blur", onBlur);
4931
+ const nextRow = r + 1 < cells.length ? r + 1 : r;
4932
+ selectCell(nextRow, c);
4933
+ return;
4934
+ }
4935
+ if (e.key === "Tab") {
4936
+ e.preventDefault();
4937
+ e.stopPropagation();
4938
+ commit();
4939
+ span.removeEventListener("keydown", onKeyDown);
4940
+ span.removeEventListener("blur", onBlur);
4941
+ let nr = r;
4942
+ let nc = e.shiftKey ? c - 1 : c + 1;
4943
+ if (nc < 0) {
4944
+ nc = numCols - 1;
4945
+ nr = Math.max(0, r - 1);
4946
+ }
4947
+ if (nc >= numCols) {
4948
+ nc = 0;
4949
+ nr = Math.min(cells.length - 1, r + 1);
4950
+ }
4951
+ selectCell(nr, nc);
4952
+ }
4860
4953
  }
4861
- if (input instanceof HTMLSelectElement) {
4862
- return input.value;
4863
- } else if (input instanceof HTMLInputElement) {
4864
- if (input.type === "checkbox") {
4865
- return input.checked;
4866
- } else if (input.type === "radio") {
4867
- const checked = formRoot.querySelector(
4868
- `[name="${fieldPath}"]:checked`
4869
- );
4870
- return checked ? checked.value : void 0;
4871
- } else {
4872
- return input.value;
4954
+ function onBlur() {
4955
+ if (span.contentEditable === "true") {
4956
+ commit();
4957
+ span.removeEventListener("keydown", onKeyDown);
4958
+ span.removeEventListener("blur", onBlur);
4873
4959
  }
4874
- } else if (input instanceof HTMLTextAreaElement) {
4875
- return input.value;
4876
4960
  }
4877
- return void 0;
4961
+ span.addEventListener("keydown", onKeyDown);
4962
+ span.addEventListener("blur", onBlur);
4878
4963
  }
4879
- function reevaluateEnableIf(wrapper, element, ctx) {
4964
+ function renderEditTable(element, initialData, pathKey, ctx, wrapper) {
4880
4965
  var _a, _b;
4881
- if (!element.enableIf) {
4882
- return;
4883
- }
4884
- const formRoot = ctx.state.formRoot;
4885
- if (!formRoot) {
4886
- console.error(`Cannot re-evaluate enableIf: formRoot is null`);
4887
- return;
4888
- }
4889
- const condition = element.enableIf;
4890
- const scope = (_a = condition.scope) != null ? _a : "relative";
4891
- let rootFormData = {};
4892
- const containerData = {};
4893
- const effectiveScope = !ctx.path || ctx.path === "" ? "absolute" : scope;
4894
- if (effectiveScope === "relative" && ctx.path) {
4895
- const containerMatch = ctx.path.match(/^(.+)\[(\d+)\]$/);
4896
- if (containerMatch) {
4897
- const containerKey = containerMatch[1];
4898
- const containerIndex = parseInt(containerMatch[2], 10);
4899
- const containerItemElement = formRoot.querySelector(
4900
- `[data-container-item="${containerKey}[${containerIndex}]"]`
4966
+ const state = ctx.state;
4967
+ const instance = ctx.instance;
4968
+ const cells = initialData.cells.length > 0 ? initialData.cells.map((r) => [...r]) : createEmptyCells((_a = element.rows) != null ? _a : 3, (_b = element.columns) != null ? _b : 3);
4969
+ let merges = initialData.merges ? [...initialData.merges] : [];
4970
+ const sel = { anchor: null, focus: null, dragging: false };
4971
+ const hiddenInput = document.createElement("input");
4972
+ hiddenInput.type = "hidden";
4973
+ hiddenInput.name = pathKey;
4974
+ hiddenInput.value = JSON.stringify({ cells, merges });
4975
+ wrapper.appendChild(hiddenInput);
4976
+ function persistValue() {
4977
+ hiddenInput.value = JSON.stringify({ cells, merges });
4978
+ if (instance) {
4979
+ instance.triggerOnChange(pathKey, { cells, merges });
4980
+ }
4981
+ }
4982
+ hiddenInput._applyExternalUpdate = (data) => {
4983
+ cells.length = 0;
4984
+ data.cells.forEach((row) => cells.push([...row]));
4985
+ merges.length = 0;
4986
+ if (data.merges) {
4987
+ data.merges.forEach((m) => merges.push({ ...m }));
4988
+ }
4989
+ sel.anchor = null;
4990
+ sel.focus = null;
4991
+ persistValue();
4992
+ rebuild();
4993
+ };
4994
+ const tableWrapper = document.createElement("div");
4995
+ tableWrapper.style.cssText = "position: relative; padding: 20px 20px 20px 24px; overflow-x: auto; max-width: 100%;";
4996
+ const tableEl = document.createElement("table");
4997
+ tableEl.style.cssText = `
4998
+ border-collapse: collapse;
4999
+ font-size: var(--fb-font-size);
5000
+ font-family: var(--fb-font-family);
5001
+ color: var(--fb-text-color);
5002
+ table-layout: fixed;
5003
+ `;
5004
+ tableWrapper.appendChild(tableEl);
5005
+ wrapper.appendChild(tableWrapper);
5006
+ const contextMenu = document.createElement("div");
5007
+ contextMenu.style.cssText = `
5008
+ position: fixed;
5009
+ display: none;
5010
+ background: white;
5011
+ border: 1px solid var(--fb-border-color);
5012
+ border-radius: var(--fb-border-radius);
5013
+ box-shadow: 0 2px 8px rgba(0,0,0,0.15);
5014
+ padding: 4px;
5015
+ z-index: 1000;
5016
+ gap: 4px;
5017
+ flex-direction: column;
5018
+ `;
5019
+ wrapper.appendChild(contextMenu);
5020
+ function makeContextMenuBtn(label, onClick) {
5021
+ const btn = document.createElement("button");
5022
+ btn.type = "button";
5023
+ btn.textContent = label;
5024
+ btn.style.cssText = `
5025
+ padding: 4px 10px;
5026
+ font-size: var(--fb-font-size-small);
5027
+ color: var(--fb-text-color);
5028
+ border: 1px solid var(--fb-border-color);
5029
+ border-radius: var(--fb-border-radius);
5030
+ background: transparent;
5031
+ cursor: pointer;
5032
+ white-space: nowrap;
5033
+ text-align: left;
5034
+ `;
5035
+ btn.addEventListener("mouseenter", () => {
5036
+ btn.style.background = "var(--fb-background-hover-color)";
5037
+ });
5038
+ btn.addEventListener("mouseleave", () => {
5039
+ btn.style.background = "transparent";
5040
+ });
5041
+ btn.addEventListener("click", () => {
5042
+ hideContextMenu();
5043
+ onClick();
5044
+ });
5045
+ return btn;
5046
+ }
5047
+ function showContextMenu(x, y) {
5048
+ contextMenu.innerHTML = "";
5049
+ contextMenu.style.display = "flex";
5050
+ const range = selectionRange(sel);
5051
+ const isMultiCell = range && (range.r1 !== range.r2 || range.c1 !== range.c2);
5052
+ const isSingleMerged = sel.anchor && getMergeAt(sel.anchor.row, sel.anchor.col, merges);
5053
+ if (isMultiCell) {
5054
+ contextMenu.appendChild(
5055
+ makeContextMenuBtn(t("tableMergeCells", state), mergeCells)
4901
5056
  );
4902
- if (containerItemElement) {
4903
- const inputs = containerItemElement.querySelectorAll(
4904
- "input, select, textarea"
4905
- );
4906
- inputs.forEach((input) => {
4907
- const fieldName = input.getAttribute("name");
4908
- if (fieldName) {
4909
- const fieldKeyMatch = fieldName.match(/\.([^.[\]]+)$/);
4910
- if (fieldKeyMatch) {
4911
- const fieldKey = fieldKeyMatch[1];
4912
- if (input instanceof HTMLSelectElement) {
4913
- containerData[fieldKey] = input.value;
4914
- } else if (input instanceof HTMLInputElement) {
4915
- if (input.type === "checkbox") {
4916
- containerData[fieldKey] = input.checked;
4917
- } else if (input.type === "radio") {
4918
- if (input.checked) {
4919
- containerData[fieldKey] = input.value;
4920
- }
4921
- } else {
4922
- containerData[fieldKey] = input.value;
4923
- }
4924
- } else if (input instanceof HTMLTextAreaElement) {
4925
- containerData[fieldKey] = input.value;
4926
- }
4927
- }
4928
- }
4929
- });
4930
- }
4931
5057
  }
4932
- } else {
4933
- const dependencyKey = condition.key;
4934
- const dependencyValue = extractDOMValue(dependencyKey, formRoot);
4935
- if (dependencyValue !== void 0) {
4936
- rootFormData[dependencyKey] = dependencyValue;
4937
- } else {
4938
- rootFormData = (_b = ctx.formData) != null ? _b : ctx.prefill;
5058
+ if (isSingleMerged) {
5059
+ contextMenu.appendChild(
5060
+ makeContextMenuBtn(t("tableSplitCell", state), splitCell)
5061
+ );
4939
5062
  }
4940
- }
4941
- try {
4942
- const shouldEnable = evaluateEnableCondition(
4943
- condition,
4944
- rootFormData,
4945
- containerData
4946
- );
4947
- if (shouldEnable) {
4948
- wrapper.style.display = "";
4949
- wrapper.classList.remove("fb-field-wrapper-disabled");
4950
- wrapper.removeAttribute("data-conditionally-disabled");
4951
- } else {
4952
- wrapper.style.display = "none";
4953
- wrapper.classList.add("fb-field-wrapper-disabled");
4954
- wrapper.setAttribute("data-conditionally-disabled", "true");
5063
+ if (!contextMenu.firstChild) {
5064
+ hideContextMenu();
5065
+ return;
4955
5066
  }
4956
- } catch (error) {
4957
- console.error(`Error re-evaluating enableIf for field "${element.key}":`, error);
5067
+ const menuWidth = 140;
5068
+ const menuHeight = contextMenu.children.length * 32 + 8;
5069
+ const vw = window.innerWidth;
5070
+ const vh = window.innerHeight;
5071
+ const left = x + menuWidth > vw ? x - menuWidth : x;
5072
+ const top = y + menuHeight > vh ? y - menuHeight : y;
5073
+ contextMenu.style.left = `${left}px`;
5074
+ contextMenu.style.top = `${top}px`;
5075
+ }
5076
+ function hideContextMenu() {
5077
+ contextMenu.style.display = "none";
5078
+ }
5079
+ const menuDismissCtrl = new AbortController();
5080
+ document.addEventListener("mousedown", (e) => {
5081
+ if (!wrapper.isConnected) {
5082
+ menuDismissCtrl.abort();
5083
+ return;
5084
+ }
5085
+ if (!contextMenu.contains(e.target)) {
5086
+ hideContextMenu();
5087
+ }
5088
+ }, { signal: menuDismissCtrl.signal });
5089
+ function applySelectionStyles() {
5090
+ const range = selectionRange(sel);
5091
+ const allTds = tableEl.querySelectorAll("td[data-row]");
5092
+ allTds.forEach((td) => {
5093
+ const r = parseInt(td.getAttribute("data-row") || "0", 10);
5094
+ const c = parseInt(td.getAttribute("data-col") || "0", 10);
5095
+ const isAnchor = sel.anchor !== null && sel.anchor.row === r && sel.anchor.col === c;
5096
+ const inRange = range !== null && r >= range.r1 && r <= range.r2 && c >= range.c1 && c <= range.c2;
5097
+ td.style.outline = isAnchor ? "2px solid var(--fb-primary-color, #0066cc)" : "";
5098
+ td.style.outlineOffset = isAnchor ? "-2px" : "";
5099
+ if (r === 0) {
5100
+ td.style.backgroundColor = "var(--fb-background-hover-color)";
5101
+ } else {
5102
+ td.style.backgroundColor = inRange && !isAnchor ? "rgba(0,102,204,0.08)" : "";
5103
+ }
5104
+ });
4958
5105
  }
4959
- }
4960
- function setupEnableIfListeners(wrapper, element, ctx) {
4961
- var _a;
4962
- if (!element.enableIf) {
4963
- return;
5106
+ function selectCell(row, col) {
5107
+ sel.anchor = { row, col };
5108
+ sel.focus = null;
5109
+ applySelectionStyles();
5110
+ tableEl.focus();
4964
5111
  }
4965
- const formRoot = ctx.state.formRoot;
4966
- if (!formRoot) {
4967
- console.error(`Cannot setup enableIf listeners: formRoot is null`);
4968
- return;
5112
+ function editCell(row, col) {
5113
+ const td = tableEl.querySelector(
5114
+ `td[data-row="${row}"][data-col="${col}"]`
5115
+ );
5116
+ if (!td) return;
5117
+ const span = td.querySelector("span");
5118
+ if (!span) return;
5119
+ sel.anchor = { row, col };
5120
+ sel.focus = null;
5121
+ applySelectionStyles();
5122
+ startCellEditing(span, row, col, () => cells, persistValue, selectCell);
5123
+ }
5124
+ function addRow(afterIndex) {
5125
+ var _a2;
5126
+ const numCols = cells.length > 0 ? cells[0].length : (_a2 = element.columns) != null ? _a2 : 3;
5127
+ const newRow = Array(numCols).fill("");
5128
+ const insertAt = afterIndex !== void 0 ? afterIndex + 1 : cells.length;
5129
+ cells.splice(insertAt, 0, newRow);
5130
+ merges = merges.map((m) => {
5131
+ if (m.row >= insertAt) {
5132
+ return { ...m, row: m.row + 1 };
5133
+ }
5134
+ if (m.row < insertAt && m.row + m.rowspan > insertAt) {
5135
+ return { ...m, rowspan: m.rowspan + 1 };
5136
+ }
5137
+ return m;
5138
+ });
5139
+ persistValue();
5140
+ rebuild();
4969
5141
  }
4970
- const condition = element.enableIf;
4971
- const scope = (_a = condition.scope) != null ? _a : "relative";
4972
- const dependencyKey = condition.key;
4973
- let dependencyFieldPath;
5142
+ function removeRow(targetRow) {
5143
+ if (cells.length <= 1) return;
5144
+ const rowToRemove = targetRow !== void 0 ? targetRow : sel.anchor ? sel.anchor.row : cells.length - 1;
5145
+ merges = merges.map((m) => {
5146
+ const mEndRow = m.row + m.rowspan - 1;
5147
+ if (m.row === rowToRemove && m.rowspan === 1) return null;
5148
+ if (m.row === rowToRemove) {
5149
+ return { ...m, row: m.row + 1, rowspan: m.rowspan - 1 };
5150
+ }
5151
+ if (mEndRow === rowToRemove) {
5152
+ return { ...m, rowspan: m.rowspan - 1 };
5153
+ }
5154
+ if (m.row < rowToRemove && mEndRow > rowToRemove) {
5155
+ return { ...m, rowspan: m.rowspan - 1 };
5156
+ }
5157
+ if (m.row > rowToRemove) {
5158
+ return { ...m, row: m.row - 1 };
5159
+ }
5160
+ return m;
5161
+ }).filter((m) => m !== null);
5162
+ cells.splice(rowToRemove, 1);
5163
+ if (sel.anchor && sel.anchor.row >= cells.length) {
5164
+ sel.anchor = { row: cells.length - 1, col: sel.anchor.col };
5165
+ }
5166
+ persistValue();
5167
+ rebuild();
5168
+ }
5169
+ function addColumn(afterIndex) {
5170
+ var _a2, _b2;
5171
+ const insertAt = afterIndex !== void 0 ? afterIndex + 1 : (_b2 = (_a2 = cells[0]) == null ? void 0 : _a2.length) != null ? _b2 : 0;
5172
+ cells.forEach((row) => row.splice(insertAt, 0, ""));
5173
+ merges = merges.map((m) => {
5174
+ if (m.col >= insertAt) {
5175
+ return { ...m, col: m.col + 1 };
5176
+ }
5177
+ if (m.col < insertAt && m.col + m.colspan > insertAt) {
5178
+ return { ...m, colspan: m.colspan + 1 };
5179
+ }
5180
+ return m;
5181
+ });
5182
+ persistValue();
5183
+ rebuild();
5184
+ }
5185
+ function removeColumn(targetCol) {
5186
+ if (cells.length === 0 || cells[0].length <= 1) return;
5187
+ const colToRemove = targetCol !== void 0 ? targetCol : sel.anchor ? sel.anchor.col : cells[0].length - 1;
5188
+ merges = merges.map((m) => {
5189
+ const mEndCol = m.col + m.colspan - 1;
5190
+ if (m.col === colToRemove && m.colspan === 1) return null;
5191
+ if (m.col === colToRemove) {
5192
+ return { ...m, col: m.col + 1, colspan: m.colspan - 1 };
5193
+ }
5194
+ if (mEndCol === colToRemove) {
5195
+ return { ...m, colspan: m.colspan - 1 };
5196
+ }
5197
+ if (m.col < colToRemove && mEndCol > colToRemove) {
5198
+ return { ...m, colspan: m.colspan - 1 };
5199
+ }
5200
+ if (m.col > colToRemove) {
5201
+ return { ...m, col: m.col - 1 };
5202
+ }
5203
+ return m;
5204
+ }).filter((m) => m !== null);
5205
+ cells.forEach((row) => row.splice(colToRemove, 1));
5206
+ if (sel.anchor && sel.anchor.col >= cells[0].length) {
5207
+ sel.anchor = { row: sel.anchor.row, col: cells[0].length - 1 };
5208
+ }
5209
+ persistValue();
5210
+ rebuild();
5211
+ }
5212
+ function mergeCells() {
5213
+ const range = selectionRange(sel);
5214
+ if (!range) return;
5215
+ const { r1, c1, r2, c2 } = range;
5216
+ if (r1 === r2 && c1 === c2) return;
5217
+ merges = merges.filter((m) => {
5218
+ const mEndRow = m.row + m.rowspan - 1;
5219
+ const mEndCol = m.col + m.colspan - 1;
5220
+ const overlaps = m.row <= r2 && mEndRow >= r1 && m.col <= c2 && mEndCol >= c1;
5221
+ return !overlaps;
5222
+ });
5223
+ const anchorText = cells[r1][c1];
5224
+ for (let r = r1; r <= r2; r++) {
5225
+ for (let c = c1; c <= c2; c++) {
5226
+ if (r !== r1 || c !== c1) {
5227
+ cells[r][c] = "";
5228
+ }
5229
+ }
5230
+ }
5231
+ cells[r1][c1] = anchorText;
5232
+ merges.push({ row: r1, col: c1, rowspan: r2 - r1 + 1, colspan: c2 - c1 + 1 });
5233
+ sel.anchor = { row: r1, col: c1 };
5234
+ sel.focus = null;
5235
+ persistValue();
5236
+ rebuild();
5237
+ }
5238
+ function splitCell() {
5239
+ if (!sel.anchor) return;
5240
+ const { row, col } = sel.anchor;
5241
+ const mIdx = merges.findIndex((m) => m.row === row && m.col === col);
5242
+ if (mIdx === -1) return;
5243
+ merges.splice(mIdx, 1);
5244
+ sel.focus = null;
5245
+ persistValue();
5246
+ rebuild();
5247
+ }
5248
+ function rebuild() {
5249
+ var _a2, _b2;
5250
+ tableEl.innerHTML = "";
5251
+ const numRows = cells.length;
5252
+ const numCols = numRows > 0 ? cells[0].length : 0;
5253
+ const range = selectionRange(sel);
5254
+ for (let rIdx = 0; rIdx < numRows; rIdx++) {
5255
+ const section = rIdx === 0 ? (_a2 = tableEl.tHead) != null ? _a2 : tableEl.createTHead() : (_b2 = tableEl.tBodies[0]) != null ? _b2 : tableEl.createTBody();
5256
+ const tr = section.insertRow();
5257
+ for (let cIdx = 0; cIdx < numCols; cIdx++) {
5258
+ if (getShadowingMerge(rIdx, cIdx, merges)) {
5259
+ continue;
5260
+ }
5261
+ const merge = getMergeAt(rIdx, cIdx, merges);
5262
+ const td = document.createElement("td");
5263
+ td.setAttribute("data-row", String(rIdx));
5264
+ td.setAttribute("data-col", String(cIdx));
5265
+ if (merge) {
5266
+ if (merge.rowspan > 1) td.rowSpan = merge.rowspan;
5267
+ if (merge.colspan > 1) td.colSpan = merge.colspan;
5268
+ }
5269
+ const inRange = range !== null && rIdx >= range.r1 && rIdx <= range.r2 && cIdx >= range.c1 && cIdx <= range.c2;
5270
+ const isAnchor = sel.anchor !== null && sel.anchor.row === rIdx && sel.anchor.col === cIdx;
5271
+ td.style.cssText = [
5272
+ "border: var(--fb-border-width) solid var(--fb-border-color);",
5273
+ "padding: 4px 8px;",
5274
+ "min-width: 80px;",
5275
+ "vertical-align: top;",
5276
+ "cursor: text;",
5277
+ "position: relative;",
5278
+ rIdx === 0 ? "background-color: var(--fb-background-hover-color); font-weight: 600;" : "",
5279
+ inRange && !isAnchor ? "background-color: rgba(0,102,204,0.08);" : "",
5280
+ isAnchor ? "outline: 2px solid var(--fb-primary-color, #0066cc); outline-offset: -2px;" : ""
5281
+ ].join(" ");
5282
+ const content = document.createElement("span");
5283
+ content.textContent = cells[rIdx][cIdx];
5284
+ content.style.cssText = "display: block; min-height: 1.4em; white-space: pre-wrap; word-break: break-word; outline: none;";
5285
+ td.appendChild(content);
5286
+ const capturedR = rIdx;
5287
+ const capturedC = cIdx;
5288
+ td.addEventListener("mousedown", (e) => {
5289
+ if (e.target.tagName === "BUTTON") return;
5290
+ if (e.target.contentEditable === "true") return;
5291
+ if (e.button === 2) {
5292
+ const range2 = selectionRange(sel);
5293
+ if (range2 && capturedR >= range2.r1 && capturedR <= range2.r2 && capturedC >= range2.c1 && capturedC <= range2.c2) {
5294
+ return;
5295
+ }
5296
+ }
5297
+ if (e.shiftKey && sel.anchor) {
5298
+ e.preventDefault();
5299
+ sel.focus = { row: capturedR, col: capturedC };
5300
+ sel.dragging = false;
5301
+ applySelectionStyles();
5302
+ } else {
5303
+ sel.anchor = { row: capturedR, col: capturedC };
5304
+ sel.focus = null;
5305
+ sel.dragging = true;
5306
+ applySelectionStyles();
5307
+ }
5308
+ });
5309
+ td.addEventListener("mouseup", (e) => {
5310
+ if (e.target.tagName === "BUTTON") return;
5311
+ if (sel.dragging) {
5312
+ sel.dragging = false;
5313
+ const currentRange = selectionRange(sel);
5314
+ const isSingleCell = !currentRange || currentRange.r1 === currentRange.r2 && currentRange.c1 === currentRange.c2;
5315
+ if (isSingleCell) {
5316
+ editCell(capturedR, capturedC);
5317
+ }
5318
+ }
5319
+ });
5320
+ td.addEventListener("mousemove", (e) => {
5321
+ if (sel.dragging && e.buttons === 1) {
5322
+ const currentAnchor = sel.anchor;
5323
+ if (currentAnchor && (currentAnchor.row !== capturedR || currentAnchor.col !== capturedC)) {
5324
+ sel.focus = { row: capturedR, col: capturedC };
5325
+ applySelectionStyles();
5326
+ }
5327
+ }
5328
+ });
5329
+ td.addEventListener("contextmenu", (e) => {
5330
+ const currentRange = selectionRange(sel);
5331
+ const isMulti = currentRange && (currentRange.r1 !== currentRange.r2 || currentRange.c1 !== currentRange.c2);
5332
+ const isMerged = sel.anchor && getMergeAt(sel.anchor.row, sel.anchor.col, merges);
5333
+ if (isMulti || isMerged) {
5334
+ e.preventDefault();
5335
+ showContextMenu(e.clientX, e.clientY);
5336
+ }
5337
+ });
5338
+ tr.appendChild(td);
5339
+ }
5340
+ }
5341
+ buildInsertOverlays();
5342
+ tableEl.setAttribute("tabindex", "0");
5343
+ tableEl.onkeydown = (e) => {
5344
+ var _a3, _b3;
5345
+ const editing = tableEl.querySelector("[contenteditable='true']");
5346
+ if (editing) return;
5347
+ const anchor = sel.anchor;
5348
+ if (!anchor) return;
5349
+ const numRows2 = cells.length;
5350
+ const numCols2 = numRows2 > 0 ? cells[0].length : 0;
5351
+ const navDeltas = {
5352
+ ArrowUp: [-1, 0],
5353
+ ArrowDown: [1, 0],
5354
+ ArrowLeft: [0, -1],
5355
+ ArrowRight: [0, 1]
5356
+ };
5357
+ if (navDeltas[e.key]) {
5358
+ e.preventDefault();
5359
+ const [dr, dc] = navDeltas[e.key];
5360
+ const newRow = Math.max(0, Math.min(numRows2 - 1, anchor.row + dr));
5361
+ const newCol = Math.max(0, Math.min(numCols2 - 1, anchor.col + dc));
5362
+ if (e.shiftKey) {
5363
+ sel.focus = { row: newRow, col: newCol };
5364
+ applySelectionStyles();
5365
+ } else {
5366
+ selectCell(newRow, newCol);
5367
+ }
5368
+ return;
5369
+ }
5370
+ if (e.key === "Enter") {
5371
+ e.preventDefault();
5372
+ editCell(anchor.row, anchor.col);
5373
+ return;
5374
+ }
5375
+ if (e.key === "Tab") {
5376
+ e.preventDefault();
5377
+ const numCols3 = (_b3 = (_a3 = cells[0]) == null ? void 0 : _a3.length) != null ? _b3 : 0;
5378
+ let nr = anchor.row;
5379
+ let nc = e.shiftKey ? anchor.col - 1 : anchor.col + 1;
5380
+ if (nc < 0) {
5381
+ nc = numCols3 - 1;
5382
+ nr = Math.max(0, nr - 1);
5383
+ }
5384
+ if (nc >= numCols3) {
5385
+ nc = 0;
5386
+ nr = Math.min(cells.length - 1, nr + 1);
5387
+ }
5388
+ selectCell(nr, nc);
5389
+ return;
5390
+ }
5391
+ if (e.key === "m" && e.ctrlKey && !e.shiftKey) {
5392
+ e.preventDefault();
5393
+ mergeCells();
5394
+ return;
5395
+ }
5396
+ if (e.key === "M" && e.ctrlKey && e.shiftKey) {
5397
+ e.preventDefault();
5398
+ splitCell();
5399
+ }
5400
+ };
5401
+ tableEl.oncopy = (e) => {
5402
+ var _a3, _b3, _c, _d;
5403
+ const range2 = selectionRange(sel);
5404
+ if (!range2) return;
5405
+ e.preventDefault();
5406
+ const { r1, c1, r2, c2 } = range2;
5407
+ const tsvRows = [];
5408
+ const htmlRows = [];
5409
+ for (let r = r1; r <= r2; r++) {
5410
+ const tsvCols = [];
5411
+ const htmlCols = [];
5412
+ for (let c = c1; c <= c2; c++) {
5413
+ const val = (_b3 = (_a3 = cells[r]) == null ? void 0 : _a3[c]) != null ? _b3 : "";
5414
+ tsvCols.push(val);
5415
+ const escaped = val.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5416
+ htmlCols.push(`<td>${escaped}</td>`);
5417
+ }
5418
+ tsvRows.push(tsvCols.join(" "));
5419
+ htmlRows.push(`<tr>${htmlCols.join("")}</tr>`);
5420
+ }
5421
+ const tsvText = tsvRows.join("\n");
5422
+ const htmlText = `<table>${htmlRows.join("")}</table>`;
5423
+ (_c = e.clipboardData) == null ? void 0 : _c.setData("text/plain", tsvText);
5424
+ (_d = e.clipboardData) == null ? void 0 : _d.setData("text/html", htmlText);
5425
+ };
5426
+ tableEl.onpaste = (e) => {
5427
+ var _a3, _b3, _c, _d, _e, _f, _g, _h, _i;
5428
+ const anchor = sel.anchor;
5429
+ if (!anchor) return;
5430
+ const text = (_b3 = (_a3 = e.clipboardData) == null ? void 0 : _a3.getData("text/plain")) != null ? _b3 : "";
5431
+ const isMultiCell = text.includes(" ") || text.split(/\r?\n/).filter((l) => l).length > 1;
5432
+ const editing = tableEl.querySelector("[contenteditable='true']");
5433
+ if (editing && !isMultiCell) return;
5434
+ e.preventDefault();
5435
+ if (editing) {
5436
+ editing.contentEditable = "inherit";
5437
+ const r = parseInt(
5438
+ (_d = (_c = editing.closest("td")) == null ? void 0 : _c.getAttribute("data-row")) != null ? _d : "0",
5439
+ 10
5440
+ );
5441
+ const c = parseInt(
5442
+ (_f = (_e = editing.closest("td")) == null ? void 0 : _e.getAttribute("data-col")) != null ? _f : "0",
5443
+ 10
5444
+ );
5445
+ if (cells[r]) {
5446
+ cells[r][c] = (_g = editing.textContent) != null ? _g : "";
5447
+ }
5448
+ }
5449
+ if (!text.trim()) return;
5450
+ const pasteRows = text.split(/\r?\n/).map((line) => line.split(" "));
5451
+ if (pasteRows.length > 1 && pasteRows[pasteRows.length - 1].length === 1 && pasteRows[pasteRows.length - 1][0] === "") {
5452
+ pasteRows.pop();
5453
+ }
5454
+ const startR = anchor.row;
5455
+ const startC = anchor.col;
5456
+ const neededRows = startR + pasteRows.length;
5457
+ while (cells.length < neededRows) {
5458
+ cells.push(Array((_i = (_h = cells[0]) == null ? void 0 : _h.length) != null ? _i : 1).fill(""));
5459
+ }
5460
+ const maxPasteCols = Math.max(...pasteRows.map((r) => r.length));
5461
+ const neededCols = startC + maxPasteCols;
5462
+ if (cells[0] && neededCols > cells[0].length) {
5463
+ const extraCols = neededCols - cells[0].length;
5464
+ cells.forEach((row) => {
5465
+ for (let i = 0; i < extraCols; i++) row.push("");
5466
+ });
5467
+ }
5468
+ for (let pr = 0; pr < pasteRows.length; pr++) {
5469
+ for (let pc = 0; pc < pasteRows[pr].length; pc++) {
5470
+ const tr = startR + pr;
5471
+ const tc = startC + pc;
5472
+ if (cells[tr]) {
5473
+ cells[tr][tc] = pasteRows[pr][pc];
5474
+ }
5475
+ }
5476
+ }
5477
+ persistValue();
5478
+ rebuild();
5479
+ };
5480
+ }
5481
+ const insertColBtn = makeOverlayCircleBtn({
5482
+ label: "+",
5483
+ title: t("tableAddColumn", state),
5484
+ size: 20,
5485
+ color: "var(--fb-primary-color, #0066cc)",
5486
+ textColor: "white",
5487
+ onClick: () => {
5488
+ var _a2;
5489
+ const afterIdx = parseInt((_a2 = insertColBtn.dataset.afterCol) != null ? _a2 : "0", 10);
5490
+ addColumn(afterIdx);
5491
+ }
5492
+ });
5493
+ insertColBtn.style.position = "absolute";
5494
+ insertColBtn.style.display = "none";
5495
+ tableWrapper.appendChild(insertColBtn);
5496
+ const insertRowBtn = makeOverlayCircleBtn({
5497
+ label: "+",
5498
+ title: t("tableAddRow", state),
5499
+ size: 20,
5500
+ color: "var(--fb-primary-color, #0066cc)",
5501
+ textColor: "white",
5502
+ onClick: () => {
5503
+ var _a2;
5504
+ const afterIdx = parseInt((_a2 = insertRowBtn.dataset.afterRow) != null ? _a2 : "0", 10);
5505
+ addRow(afterIdx);
5506
+ }
5507
+ });
5508
+ insertRowBtn.style.position = "absolute";
5509
+ insertRowBtn.style.display = "none";
5510
+ tableWrapper.appendChild(insertRowBtn);
5511
+ let colRemoveBtns = [];
5512
+ let rowRemoveBtns = [];
5513
+ const addLastColBtn = makeOverlayCircleBtn({
5514
+ label: "+",
5515
+ title: t("tableAddColumn", state),
5516
+ size: 20,
5517
+ color: "var(--fb-primary-color, #0066cc)",
5518
+ textColor: "white",
5519
+ onClick: () => addColumn()
5520
+ });
5521
+ addLastColBtn.style.position = "absolute";
5522
+ addLastColBtn.style.display = "none";
5523
+ tableWrapper.appendChild(addLastColBtn);
5524
+ const addLastRowBtn = makeOverlayCircleBtn({
5525
+ label: "+",
5526
+ title: t("tableAddRow", state),
5527
+ size: 20,
5528
+ color: "var(--fb-primary-color, #0066cc)",
5529
+ textColor: "white",
5530
+ onClick: () => addRow()
5531
+ });
5532
+ addLastRowBtn.style.position = "absolute";
5533
+ addLastRowBtn.style.display = "none";
5534
+ tableWrapper.appendChild(addLastRowBtn);
5535
+ function buildInsertOverlays() {
5536
+ var _a2, _b2;
5537
+ colRemoveBtns.forEach((b) => b.remove());
5538
+ colRemoveBtns = [];
5539
+ rowRemoveBtns.forEach((b) => b.remove());
5540
+ rowRemoveBtns = [];
5541
+ const numCols = cells.length > 0 ? cells[0].length : 0;
5542
+ const numRows = cells.length;
5543
+ if (numCols > 1) {
5544
+ const headerCells = Array.from(
5545
+ tableEl.querySelectorAll("thead td[data-col]")
5546
+ );
5547
+ for (const hc of headerCells) {
5548
+ const colIdx = parseInt((_a2 = hc.getAttribute("data-col")) != null ? _a2 : "0", 10);
5549
+ const btn = makeOverlayCircleBtn({
5550
+ label: "\xD7",
5551
+ title: t("tableRemoveColumn", state),
5552
+ size: 16,
5553
+ color: "var(--fb-error-color, #dc3545)",
5554
+ textColor: "white",
5555
+ onClick: () => removeColumn(colIdx)
5556
+ });
5557
+ btn.setAttribute("data-action", "remove-col");
5558
+ btn.setAttribute("data-col", String(colIdx));
5559
+ btn.style.position = "absolute";
5560
+ btn.style.display = "none";
5561
+ tableWrapper.appendChild(btn);
5562
+ colRemoveBtns.push(btn);
5563
+ }
5564
+ }
5565
+ if (numRows > 1) {
5566
+ const allRowElements = [
5567
+ ...tableEl.tHead ? Array.from(tableEl.tHead.rows) : [],
5568
+ ...tableEl.tBodies[0] ? Array.from(tableEl.tBodies[0].rows) : []
5569
+ ].filter((r) => r.querySelector("td[data-row]"));
5570
+ for (const rowEl of allRowElements) {
5571
+ const firstTd = rowEl.querySelector("td[data-row]");
5572
+ if (!firstTd) continue;
5573
+ const rowIdx = parseInt((_b2 = firstTd.getAttribute("data-row")) != null ? _b2 : "0", 10);
5574
+ const btn = makeOverlayCircleBtn({
5575
+ label: "\xD7",
5576
+ title: t("tableRemoveRow", state),
5577
+ size: 16,
5578
+ color: "var(--fb-error-color, #dc3545)",
5579
+ textColor: "white",
5580
+ onClick: () => removeRow(rowIdx)
5581
+ });
5582
+ btn.setAttribute("data-action", "remove-row");
5583
+ btn.setAttribute("data-row", String(rowIdx));
5584
+ btn.style.position = "absolute";
5585
+ btn.style.display = "none";
5586
+ tableWrapper.appendChild(btn);
5587
+ rowRemoveBtns.push(btn);
5588
+ }
5589
+ }
5590
+ function updateTopZoneOverlays(mx, wr, tblR, scrollL, active) {
5591
+ var _a3;
5592
+ const headerCells = active ? Array.from(tableEl.querySelectorAll("thead td[data-col]")) : [];
5593
+ let closestColIdx = -1;
5594
+ let closestColDist = Infinity;
5595
+ let closestBorderX = -1;
5596
+ let closestAfterCol = -1;
5597
+ let closestBorderDist = Infinity;
5598
+ for (let i = 0; i < headerCells.length; i++) {
5599
+ const cellRect = headerCells[i].getBoundingClientRect();
5600
+ const centerX = (cellRect.left + cellRect.right) / 2;
5601
+ const dist = Math.abs(mx - centerX);
5602
+ if (dist < closestColDist) {
5603
+ closestColDist = dist;
5604
+ closestColIdx = i;
5605
+ }
5606
+ const borderDist = Math.abs(mx - cellRect.right);
5607
+ if (borderDist < closestBorderDist && borderDist < 20) {
5608
+ closestBorderDist = borderDist;
5609
+ closestBorderX = cellRect.right - wr.left + scrollL;
5610
+ closestAfterCol = parseInt((_a3 = headerCells[i].getAttribute("data-col")) != null ? _a3 : "0", 10);
5611
+ }
5612
+ }
5613
+ colRemoveBtns.forEach((btn, idx) => {
5614
+ if (!active || idx !== closestColIdx) {
5615
+ btn.style.display = "none";
5616
+ return;
5617
+ }
5618
+ const cellRect = headerCells[idx].getBoundingClientRect();
5619
+ const centerX = (cellRect.left + cellRect.right) / 2 - wr.left + scrollL;
5620
+ btn.style.left = `${centerX - 8}px`;
5621
+ btn.style.top = "2px";
5622
+ btn.style.display = "flex";
5623
+ });
5624
+ if (active && closestAfterCol >= 0) {
5625
+ insertColBtn.style.display = "flex";
5626
+ insertColBtn.style.left = `${closestBorderX - 10}px`;
5627
+ insertColBtn.style.top = `${tblR.top - wr.top - 10}px`;
5628
+ insertColBtn.dataset.afterCol = String(closestAfterCol);
5629
+ } else {
5630
+ insertColBtn.style.display = "none";
5631
+ }
5632
+ }
5633
+ function updateLeftZoneOverlays(my, wr, tblR, scrollL, active) {
5634
+ var _a3;
5635
+ const allRowEls = [];
5636
+ if (active) {
5637
+ if (tableEl.tHead) {
5638
+ for (const row of Array.from(tableEl.tHead.rows)) {
5639
+ if (row.querySelector("td[data-row]")) allRowEls.push(row);
5640
+ }
5641
+ }
5642
+ if (tableEl.tBodies[0]) {
5643
+ for (const row of Array.from(tableEl.tBodies[0].rows)) {
5644
+ if (row.querySelector("td[data-row]")) allRowEls.push(row);
5645
+ }
5646
+ }
5647
+ }
5648
+ let closestRowIdx = -1;
5649
+ let closestRowDist = Infinity;
5650
+ let closestBorderY = -1;
5651
+ let closestAfterRow = -1;
5652
+ let closestRowBorderDist = Infinity;
5653
+ for (let i = 0; i < allRowEls.length; i++) {
5654
+ const trRect = allRowEls[i].getBoundingClientRect();
5655
+ const centerY = (trRect.top + trRect.bottom) / 2;
5656
+ const dist = Math.abs(my - centerY);
5657
+ if (dist < closestRowDist) {
5658
+ closestRowDist = dist;
5659
+ closestRowIdx = i;
5660
+ }
5661
+ const borderDist = Math.abs(my - trRect.bottom);
5662
+ if (borderDist < closestRowBorderDist && borderDist < 14) {
5663
+ closestRowBorderDist = borderDist;
5664
+ closestBorderY = trRect.bottom - wr.top;
5665
+ const firstTd = allRowEls[i].querySelector("td[data-row]");
5666
+ closestAfterRow = parseInt((_a3 = firstTd == null ? void 0 : firstTd.getAttribute("data-row")) != null ? _a3 : "0", 10);
5667
+ }
5668
+ }
5669
+ rowRemoveBtns.forEach((btn, idx) => {
5670
+ if (!active || idx !== closestRowIdx) {
5671
+ btn.style.display = "none";
5672
+ return;
5673
+ }
5674
+ const trRect = allRowEls[idx].getBoundingClientRect();
5675
+ const centerY = (trRect.top + trRect.bottom) / 2 - wr.top;
5676
+ btn.style.left = "4px";
5677
+ btn.style.top = `${centerY - 8}px`;
5678
+ btn.style.display = "flex";
5679
+ });
5680
+ if (active && closestAfterRow >= 0) {
5681
+ insertRowBtn.style.display = "flex";
5682
+ insertRowBtn.style.top = `${closestBorderY - 10}px`;
5683
+ insertRowBtn.style.left = `${tblR.left - wr.left + scrollL - 10}px`;
5684
+ insertRowBtn.dataset.afterRow = String(closestAfterRow);
5685
+ } else {
5686
+ insertRowBtn.style.display = "none";
5687
+ }
5688
+ }
5689
+ let rafPending = false;
5690
+ tableWrapper.onmousemove = (e) => {
5691
+ const target = e.target;
5692
+ if (target.tagName === "BUTTON" && target.parentElement === tableWrapper) return;
5693
+ if (rafPending) return;
5694
+ rafPending = true;
5695
+ const mx = e.clientX;
5696
+ const my = e.clientY;
5697
+ requestAnimationFrame(() => {
5698
+ rafPending = false;
5699
+ const wr = tableWrapper.getBoundingClientRect();
5700
+ const tblR = tableEl.getBoundingClientRect();
5701
+ const scrollL = tableWrapper.scrollLeft;
5702
+ const inTopZone = my >= wr.top && my < tblR.top + 4;
5703
+ const inLeftZone = mx >= wr.left && mx < tblR.left + 4;
5704
+ const visibleRight = Math.min(tblR.right, wr.right);
5705
+ const inRightZone = mx > visibleRight - 20 && mx <= wr.right;
5706
+ const inBottomZone = my > tblR.bottom - 4 && my <= wr.bottom + 20;
5707
+ updateTopZoneOverlays(mx, wr, tblR, scrollL, inTopZone);
5708
+ updateLeftZoneOverlays(my, wr, tblR, scrollL, inLeftZone);
5709
+ addLastColBtn.style.display = inRightZone ? "flex" : "none";
5710
+ if (inRightZone) {
5711
+ addLastColBtn.style.left = `${wr.right - wr.left + scrollL - 20}px`;
5712
+ addLastColBtn.style.top = `${(tblR.top + tblR.bottom) / 2 - wr.top - 10}px`;
5713
+ }
5714
+ addLastRowBtn.style.display = inBottomZone ? "flex" : "none";
5715
+ if (inBottomZone) {
5716
+ const visibleCenterX = (wr.left + wr.right) / 2 - wr.left + scrollL;
5717
+ addLastRowBtn.style.left = `${visibleCenterX - 10}px`;
5718
+ addLastRowBtn.style.top = `${tblR.bottom - wr.top - 10}px`;
5719
+ }
5720
+ });
5721
+ };
5722
+ tableWrapper.onmouseleave = () => {
5723
+ colRemoveBtns.forEach((btn) => {
5724
+ btn.style.display = "none";
5725
+ });
5726
+ rowRemoveBtns.forEach((btn) => {
5727
+ btn.style.display = "none";
5728
+ });
5729
+ insertColBtn.style.display = "none";
5730
+ insertRowBtn.style.display = "none";
5731
+ addLastColBtn.style.display = "none";
5732
+ addLastRowBtn.style.display = "none";
5733
+ };
5734
+ }
5735
+ rebuild();
5736
+ }
5737
+ function defaultTableData(element) {
5738
+ var _a, _b;
5739
+ return {
5740
+ cells: createEmptyCells((_a = element.rows) != null ? _a : 3, (_b = element.columns) != null ? _b : 3),
5741
+ merges: []
5742
+ };
5743
+ }
5744
+ function isTableData(v) {
5745
+ return v !== null && typeof v === "object" && "cells" in v && Array.isArray(v.cells);
5746
+ }
5747
+ function renderTableElement(element, ctx, wrapper, pathKey) {
5748
+ const state = ctx.state;
5749
+ const rawPrefill = ctx.prefill[element.key];
5750
+ const initialData = isTableData(rawPrefill) ? rawPrefill : isTableData(element.default) ? element.default : defaultTableData(element);
5751
+ if (state.config.readonly) {
5752
+ renderReadonlyTable(initialData, wrapper);
5753
+ } else {
5754
+ renderEditTable(element, initialData, pathKey, ctx, wrapper);
5755
+ }
5756
+ }
5757
+ function validateTableElement(element, key, context) {
5758
+ const { scopeRoot, skipValidation } = context;
5759
+ const errors = [];
5760
+ const hiddenInput = scopeRoot.querySelector(
5761
+ `[name="${key}"]`
5762
+ );
5763
+ if (!hiddenInput) {
5764
+ return { value: null, errors };
5765
+ }
5766
+ let value = null;
5767
+ try {
5768
+ value = JSON.parse(hiddenInput.value);
5769
+ } catch {
5770
+ errors.push(`${key}: invalid table data`);
5771
+ return { value: null, errors };
5772
+ }
5773
+ if (!skipValidation && element.required) {
5774
+ const hasContent = value.cells.some(
5775
+ (row) => row.some((cell) => cell.trim() !== "")
5776
+ );
5777
+ if (!hasContent) {
5778
+ errors.push(`${key}: ${t("required", context.state)}`);
5779
+ }
5780
+ }
5781
+ return { value, errors };
5782
+ }
5783
+ function updateTableField(_element, fieldPath, value, context) {
5784
+ const { scopeRoot } = context;
5785
+ const hiddenInput = scopeRoot.querySelector(
5786
+ `[name="${fieldPath}"]`
5787
+ );
5788
+ if (!hiddenInput) {
5789
+ console.warn(
5790
+ `updateTableField: no hidden input found for "${fieldPath}". Re-render to reflect new data.`
5791
+ );
5792
+ return;
5793
+ }
5794
+ if (isTableData(value) && hiddenInput._applyExternalUpdate) {
5795
+ hiddenInput._applyExternalUpdate(value);
5796
+ } else {
5797
+ hiddenInput.value = JSON.stringify(value);
5798
+ }
5799
+ }
5800
+
5801
+ // src/components/richinput.ts
5802
+ function applyAutoExpand2(textarea, backdrop) {
5803
+ textarea.style.overflow = "hidden";
5804
+ textarea.style.resize = "none";
5805
+ const lineCount = (textarea.value.match(/\n/g) || []).length + 1;
5806
+ textarea.rows = Math.max(3, lineCount);
5807
+ const resize = () => {
5808
+ if (!textarea.isConnected) return;
5809
+ textarea.style.height = "0";
5810
+ textarea.style.height = `${textarea.scrollHeight}px`;
5811
+ if (backdrop) {
5812
+ backdrop.style.height = `${textarea.scrollHeight}px`;
5813
+ }
5814
+ };
5815
+ textarea.addEventListener("input", resize);
5816
+ setTimeout(() => {
5817
+ if (textarea.isConnected) resize();
5818
+ }, 0);
5819
+ }
5820
+ function buildFileLabels(files, state) {
5821
+ var _a, _b, _c, _d;
5822
+ const labels = /* @__PURE__ */ new Map();
5823
+ const nameCount = /* @__PURE__ */ new Map();
5824
+ for (const rid of files) {
5825
+ const meta = state.resourceIndex.get(rid);
5826
+ const name = (_a = meta == null ? void 0 : meta.name) != null ? _a : rid;
5827
+ nameCount.set(name, ((_b = nameCount.get(name)) != null ? _b : 0) + 1);
5828
+ }
5829
+ for (const rid of files) {
5830
+ const meta = state.resourceIndex.get(rid);
5831
+ const name = (_c = meta == null ? void 0 : meta.name) != null ? _c : rid;
5832
+ if (((_d = nameCount.get(name)) != null ? _d : 1) > 1 && meta) {
5833
+ labels.set(rid, `${name} (${formatFileSize(meta.size)})`);
5834
+ } else {
5835
+ labels.set(rid, name);
5836
+ }
5837
+ }
5838
+ return labels;
5839
+ }
5840
+ function isImageMeta(meta) {
5841
+ if (!meta) return false;
5842
+ return meta.type.startsWith("image/");
5843
+ }
5844
+ function buildNameToRid(files, state) {
5845
+ const labels = buildFileLabels(files, state);
5846
+ const map = /* @__PURE__ */ new Map();
5847
+ for (const rid of files) {
5848
+ const label = labels.get(rid);
5849
+ if (label) map.set(label, rid);
5850
+ }
5851
+ return map;
5852
+ }
5853
+ function formatMention(name) {
5854
+ if (/\s/.test(name) || name.includes('"')) {
5855
+ return `@"${name.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
5856
+ }
5857
+ return `@${name}`;
5858
+ }
5859
+ function findAtTokens(text) {
5860
+ const tokens = [];
5861
+ const len = text.length;
5862
+ let i = 0;
5863
+ while (i < len) {
5864
+ if (text[i] === "@") {
5865
+ if (i > 0 && !/\s/.test(text[i - 1])) {
5866
+ i++;
5867
+ continue;
5868
+ }
5869
+ const start = i;
5870
+ i++;
5871
+ if (i < len && text[i] === '"') {
5872
+ i++;
5873
+ let name = "";
5874
+ while (i < len && text[i] !== '"') {
5875
+ if (text[i] === "\\" && i + 1 < len) {
5876
+ name += text[i + 1];
5877
+ i += 2;
5878
+ } else {
5879
+ name += text[i];
5880
+ i++;
5881
+ }
5882
+ }
5883
+ if (i < len && text[i] === '"') {
5884
+ i++;
5885
+ if (i >= len || /\s/.test(text[i])) {
5886
+ tokens.push({ start, end: i, raw: text.slice(start, i), name });
5887
+ }
5888
+ }
5889
+ } else if (i < len && !/\s/.test(text[i])) {
5890
+ const wordStart = i;
5891
+ while (i < len && !/\s/.test(text[i])) {
5892
+ i++;
5893
+ }
5894
+ const name = text.slice(wordStart, i);
5895
+ tokens.push({ start, end: i, raw: text.slice(start, i), name });
5896
+ }
5897
+ } else {
5898
+ i++;
5899
+ }
5900
+ }
5901
+ return tokens;
5902
+ }
5903
+ function findMentions(text, nameToRid) {
5904
+ if (nameToRid.size === 0) return [];
5905
+ const tokens = findAtTokens(text);
5906
+ const results = [];
5907
+ for (const token of tokens) {
5908
+ const rid = nameToRid.get(token.name);
5909
+ if (rid) {
5910
+ results.push({
5911
+ start: token.start,
5912
+ end: token.end,
5913
+ name: token.name,
5914
+ rid
5915
+ });
5916
+ }
5917
+ }
5918
+ return results;
5919
+ }
5920
+ function replaceFilenamesWithRids(text, nameToRid) {
5921
+ const mentions = findMentions(text, nameToRid);
5922
+ if (mentions.length === 0) return text;
5923
+ let result = "";
5924
+ let lastIdx = 0;
5925
+ for (const m of mentions) {
5926
+ result += text.slice(lastIdx, m.start);
5927
+ result += `@${m.rid}`;
5928
+ lastIdx = m.end;
5929
+ }
5930
+ result += text.slice(lastIdx);
5931
+ return result;
5932
+ }
5933
+ function replaceRidsWithFilenames(text, files, state) {
5934
+ const labels = buildFileLabels(files, state);
5935
+ const ridToLabel = /* @__PURE__ */ new Map();
5936
+ for (const rid of files) {
5937
+ const label = labels.get(rid);
5938
+ if (label) ridToLabel.set(rid, label);
5939
+ }
5940
+ const tokens = findAtTokens(text);
5941
+ if (tokens.length === 0) return text;
5942
+ let result = "";
5943
+ let lastIdx = 0;
5944
+ for (const token of tokens) {
5945
+ result += text.slice(lastIdx, token.start);
5946
+ const label = ridToLabel.get(token.name);
5947
+ if (label) {
5948
+ result += formatMention(label);
5949
+ } else {
5950
+ result += token.raw;
5951
+ }
5952
+ lastIdx = token.end;
5953
+ }
5954
+ result += text.slice(lastIdx);
5955
+ return result;
5956
+ }
5957
+ function renderThumbContent(thumb, rid, meta, state) {
5958
+ clear(thumb);
5959
+ if ((meta == null ? void 0 : meta.file) && isImageMeta(meta)) {
5960
+ const img = document.createElement("img");
5961
+ img.alt = meta.name;
5962
+ img.style.cssText = "width: 100%; height: 100%; object-fit: cover; display: block;";
5963
+ const reader = new FileReader();
5964
+ reader.onload = (e) => {
5965
+ var _a;
5966
+ img.src = ((_a = e.target) == null ? void 0 : _a.result) || "";
5967
+ };
5968
+ reader.readAsDataURL(meta.file);
5969
+ thumb.appendChild(img);
5970
+ } else if (state.config.getThumbnail) {
5971
+ state.config.getThumbnail(rid).then((url) => {
5972
+ var _a;
5973
+ if (!url || !thumb.isConnected) return;
5974
+ const img = document.createElement("img");
5975
+ img.alt = (_a = meta == null ? void 0 : meta.name) != null ? _a : rid;
5976
+ img.src = url;
5977
+ img.style.cssText = "width: 100%; height: 100%; object-fit: cover; display: block;";
5978
+ clear(thumb);
5979
+ thumb.appendChild(img);
5980
+ }).catch((err) => {
5981
+ var _a, _b;
5982
+ (_b = (_a = state.config).onThumbnailError) == null ? void 0 : _b.call(_a, err, rid);
5983
+ });
5984
+ const placeholder = document.createElement("div");
5985
+ placeholder.style.cssText = "width: 100%; height: 100%; background: var(--fb-background-hover-color, #f3f4f6); display: flex; align-items: center; justify-content: center;";
5986
+ placeholder.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>';
5987
+ thumb.appendChild(placeholder);
5988
+ } else {
5989
+ const icon = document.createElement("div");
5990
+ icon.style.cssText = "width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; padding: 2px; box-sizing: border-box;";
5991
+ icon.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>';
5992
+ if (meta == null ? void 0 : meta.name) {
5993
+ const nameEl = document.createElement("span");
5994
+ nameEl.style.cssText = "font-size: 9px; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 44px; color: var(--fb-text-color, #111827);";
5995
+ nameEl.textContent = meta.name;
5996
+ icon.appendChild(nameEl);
5997
+ }
5998
+ thumb.appendChild(icon);
5999
+ }
6000
+ }
6001
+ function renderImagePreview(hoverEl, rid, meta, state) {
6002
+ clear(hoverEl);
6003
+ if ((meta == null ? void 0 : meta.file) && isImageMeta(meta)) {
6004
+ const img = document.createElement("img");
6005
+ img.alt = meta.name;
6006
+ img.style.cssText = "max-width: 120px; max-height: 120px; object-fit: contain; display: block;";
6007
+ const reader = new FileReader();
6008
+ reader.onload = (e) => {
6009
+ var _a;
6010
+ img.src = ((_a = e.target) == null ? void 0 : _a.result) || "";
6011
+ };
6012
+ reader.readAsDataURL(meta.file);
6013
+ hoverEl.appendChild(img);
6014
+ } else if (state.config.getThumbnail) {
6015
+ state.config.getThumbnail(rid).then((url) => {
6016
+ var _a;
6017
+ if (!url || !hoverEl.isConnected) return;
6018
+ const img = document.createElement("img");
6019
+ img.alt = (_a = meta == null ? void 0 : meta.name) != null ? _a : rid;
6020
+ img.src = url;
6021
+ img.style.cssText = "max-width: 120px; max-height: 120px; object-fit: contain; display: block;";
6022
+ clear(hoverEl);
6023
+ hoverEl.appendChild(img);
6024
+ }).catch((err) => {
6025
+ var _a, _b;
6026
+ (_b = (_a = state.config).onThumbnailError) == null ? void 0 : _b.call(_a, err, rid);
6027
+ });
6028
+ }
6029
+ }
6030
+ function positionPortalTooltip(tooltip, anchor) {
6031
+ const rect = anchor.getBoundingClientRect();
6032
+ const ttRect = tooltip.getBoundingClientRect();
6033
+ const left = Math.max(
6034
+ 4,
6035
+ Math.min(
6036
+ rect.left + rect.width / 2 - ttRect.width / 2,
6037
+ window.innerWidth - ttRect.width - 4
6038
+ )
6039
+ );
6040
+ const topAbove = rect.top - ttRect.height - 8;
6041
+ const topBelow = rect.bottom + 8;
6042
+ const top = topAbove >= 4 ? topAbove : topBelow;
6043
+ tooltip.style.left = `${left}px`;
6044
+ tooltip.style.top = `${Math.max(4, top)}px`;
6045
+ }
6046
+ function showMentionTooltip(anchor, rid, state) {
6047
+ const meta = state.resourceIndex.get(rid);
6048
+ const tooltip = document.createElement("div");
6049
+ tooltip.className = "fb-richinput-portal-tooltip fb-richinput-mention-tooltip";
6050
+ tooltip.style.cssText = `
6051
+ position: fixed;
6052
+ z-index: 99999;
6053
+ background: #fff;
6054
+ border: 1px solid var(--fb-border-color, #d1d5db);
6055
+ border-radius: 8px;
6056
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
6057
+ padding: 4px;
6058
+ pointer-events: none;
6059
+ min-width: 60px;
6060
+ max-width: 140px;
6061
+ `;
6062
+ const preview = document.createElement("div");
6063
+ preview.style.cssText = "min-height: 60px; max-height: 120px; display: flex; align-items: center; justify-content: center;";
6064
+ renderImagePreview(preview, rid, meta, state);
6065
+ tooltip.appendChild(preview);
6066
+ document.body.appendChild(tooltip);
6067
+ positionPortalTooltip(tooltip, anchor);
6068
+ return tooltip;
6069
+ }
6070
+ function showFileTooltip(anchor, opts) {
6071
+ var _a, _b;
6072
+ const { rid, state, isReadonly, onMention, onRemove } = opts;
6073
+ const meta = state.resourceIndex.get(rid);
6074
+ const filename = (_a = meta == null ? void 0 : meta.name) != null ? _a : rid;
6075
+ const tooltip = document.createElement("div");
6076
+ tooltip.className = "fb-richinput-portal-tooltip fb-richinput-file-tooltip";
6077
+ tooltip.style.cssText = `
6078
+ position: fixed;
6079
+ z-index: 99999;
6080
+ background: #fff;
6081
+ border: 1px solid var(--fb-border-color, #d1d5db);
6082
+ border-radius: 8px;
6083
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
6084
+ padding: 4px;
6085
+ pointer-events: auto;
6086
+ min-width: 80px;
6087
+ max-width: 260px;
6088
+ `;
6089
+ const preview = document.createElement("div");
6090
+ preview.style.cssText = "min-height: 60px; max-height: 120px; display: flex; align-items: center; justify-content: center;";
6091
+ renderImagePreview(preview, rid, meta, state);
6092
+ tooltip.appendChild(preview);
6093
+ const nameEl = document.createElement("div");
6094
+ nameEl.style.cssText = "padding: 4px 6px 2px; font-size: 12px; color: var(--fb-text-color, #111827); word-break: break-word; border-top: 1px solid var(--fb-border-color, #d1d5db);";
6095
+ nameEl.textContent = filename;
6096
+ tooltip.appendChild(nameEl);
6097
+ const actionsRow = document.createElement("div");
6098
+ actionsRow.style.cssText = "display: flex; align-items: center; gap: 2px; padding: 3px 4px 2px; border-top: 1px solid var(--fb-border-color, #d1d5db); justify-content: center;";
6099
+ const btnStyle = "background: none; border: none; cursor: pointer; padding: 3px 5px; border-radius: 4px; color: var(--fb-text-muted-color, #6b7280); display: flex; align-items: center; transition: background 0.1s, color 0.1s;";
6100
+ const btnHoverIn = (btn) => {
6101
+ btn.style.background = "var(--fb-background-hover-color, #f3f4f6)";
6102
+ btn.style.color = "var(--fb-text-color, #111827)";
6103
+ };
6104
+ const btnHoverOut = (btn) => {
6105
+ btn.style.background = "none";
6106
+ btn.style.color = "var(--fb-text-muted-color, #6b7280)";
6107
+ };
6108
+ if (!isReadonly && onMention) {
6109
+ const mentionBtn = document.createElement("button");
6110
+ mentionBtn.type = "button";
6111
+ mentionBtn.title = "Mention";
6112
+ mentionBtn.style.cssText = btnStyle;
6113
+ mentionBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="4"/><path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-3.92 7.94"/></svg>';
6114
+ mentionBtn.addEventListener("mouseenter", () => btnHoverIn(mentionBtn));
6115
+ mentionBtn.addEventListener("mouseleave", () => btnHoverOut(mentionBtn));
6116
+ mentionBtn.addEventListener("click", (e) => {
6117
+ e.stopPropagation();
6118
+ onMention();
6119
+ tooltip.remove();
6120
+ });
6121
+ actionsRow.appendChild(mentionBtn);
6122
+ }
6123
+ if (state.config.downloadFile) {
6124
+ const dlBtn = document.createElement("button");
6125
+ dlBtn.type = "button";
6126
+ dlBtn.title = "Download";
6127
+ dlBtn.style.cssText = btnStyle;
6128
+ dlBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';
6129
+ dlBtn.addEventListener("mouseenter", () => btnHoverIn(dlBtn));
6130
+ dlBtn.addEventListener("mouseleave", () => btnHoverOut(dlBtn));
6131
+ dlBtn.addEventListener("click", (e) => {
6132
+ var _a2, _b2;
6133
+ e.stopPropagation();
6134
+ (_b2 = (_a2 = state.config).downloadFile) == null ? void 0 : _b2.call(_a2, rid, filename);
6135
+ });
6136
+ actionsRow.appendChild(dlBtn);
6137
+ }
6138
+ const hasOpenUrl = !!((_b = state.config.getDownloadUrl) != null ? _b : state.config.getThumbnail);
6139
+ if (hasOpenUrl) {
6140
+ const openBtn = document.createElement("button");
6141
+ openBtn.type = "button";
6142
+ openBtn.title = "Open in new window";
6143
+ openBtn.style.cssText = btnStyle;
6144
+ openBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';
6145
+ openBtn.addEventListener("mouseenter", () => btnHoverIn(openBtn));
6146
+ openBtn.addEventListener("mouseleave", () => btnHoverOut(openBtn));
6147
+ openBtn.addEventListener("click", (e) => {
6148
+ var _a2, _b2, _c, _d;
6149
+ e.stopPropagation();
6150
+ if (state.config.getDownloadUrl) {
6151
+ const url = state.config.getDownloadUrl(rid);
6152
+ if (url) {
6153
+ window.open(url, "_blank");
6154
+ } else {
6155
+ (_b2 = (_a2 = state.config).getThumbnail) == null ? void 0 : _b2.call(_a2, rid).then((thumbUrl) => {
6156
+ if (thumbUrl) window.open(thumbUrl, "_blank");
6157
+ }).catch(() => {
6158
+ });
6159
+ }
6160
+ } else {
6161
+ (_d = (_c = state.config).getThumbnail) == null ? void 0 : _d.call(_c, rid).then((url) => {
6162
+ if (url) window.open(url, "_blank");
6163
+ }).catch(() => {
6164
+ });
6165
+ }
6166
+ });
6167
+ actionsRow.appendChild(openBtn);
6168
+ }
6169
+ if (!isReadonly && onRemove) {
6170
+ const removeBtn = document.createElement("button");
6171
+ removeBtn.type = "button";
6172
+ removeBtn.title = "Remove";
6173
+ removeBtn.style.cssText = btnStyle;
6174
+ removeBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>';
6175
+ removeBtn.addEventListener("mouseenter", () => {
6176
+ removeBtn.style.background = "var(--fb-background-hover-color, #f3f4f6)";
6177
+ removeBtn.style.color = "var(--fb-error-color, #ef4444)";
6178
+ });
6179
+ removeBtn.addEventListener("mouseleave", () => btnHoverOut(removeBtn));
6180
+ removeBtn.addEventListener("click", (e) => {
6181
+ e.stopPropagation();
6182
+ tooltip.remove();
6183
+ onRemove();
6184
+ });
6185
+ actionsRow.appendChild(removeBtn);
6186
+ }
6187
+ const hasActions = actionsRow.children.length > 0;
6188
+ if (hasActions) {
6189
+ tooltip.appendChild(actionsRow);
6190
+ }
6191
+ document.body.appendChild(tooltip);
6192
+ positionPortalTooltip(tooltip, anchor);
6193
+ return tooltip;
6194
+ }
6195
+ function createTooltipHandle() {
6196
+ return { element: null, hideTimer: null };
6197
+ }
6198
+ function scheduleHideTooltip(handle, delayMs = 150) {
6199
+ if (handle.hideTimer !== null) return;
6200
+ handle.hideTimer = setTimeout(() => {
6201
+ handle.hideTimer = null;
6202
+ if (handle.element) {
6203
+ handle.element.remove();
6204
+ handle.element = null;
6205
+ }
6206
+ }, delayMs);
6207
+ }
6208
+ function cancelHideTooltip(handle) {
6209
+ if (handle.hideTimer !== null) {
6210
+ clearTimeout(handle.hideTimer);
6211
+ handle.hideTimer = null;
6212
+ }
6213
+ }
6214
+ function removePortalTooltip(tooltip) {
6215
+ if (tooltip) tooltip.remove();
6216
+ return null;
6217
+ }
6218
+ function getAtTrigger(textarea) {
6219
+ var _a;
6220
+ const cursorPos = (_a = textarea.selectionStart) != null ? _a : 0;
6221
+ const textBefore = textarea.value.slice(0, cursorPos);
6222
+ for (let i = textBefore.length - 1; i >= 0; i--) {
6223
+ if (textBefore[i] === "@") {
6224
+ if (i === 0 || /\s/.test(textBefore[i - 1])) {
6225
+ let query = textBefore.slice(i + 1);
6226
+ if (query.startsWith('"')) {
6227
+ query = query.slice(1);
6228
+ }
6229
+ return { query, pos: i };
6230
+ }
6231
+ return null;
6232
+ }
6233
+ }
6234
+ return null;
6235
+ }
6236
+ function filterFilesForDropdown(query, files, labels) {
6237
+ const lq = query.toLowerCase();
6238
+ return files.filter((rid) => {
6239
+ var _a;
6240
+ const label = (_a = labels.get(rid)) != null ? _a : rid;
6241
+ return label.toLowerCase().includes(lq);
6242
+ });
6243
+ }
6244
+ var TEXTAREA_FONT = "font-size: var(--fb-font-size, 14px); font-family: var(--fb-font-family, inherit); line-height: 1.6;";
6245
+ var TEXTAREA_PADDING = "padding: 12px 52px 12px 14px;";
6246
+ function renderEditMode(element, ctx, wrapper, pathKey, initialValue) {
6247
+ var _a;
6248
+ const state = ctx.state;
6249
+ const files = [...initialValue.files];
6250
+ const dropdownState = {
6251
+ open: false,
6252
+ query: "",
6253
+ triggerPos: -1,
6254
+ selectedIndex: 0
6255
+ };
6256
+ const docListenerCtrl = new AbortController();
6257
+ const hiddenInput = document.createElement("input");
6258
+ hiddenInput.type = "hidden";
6259
+ hiddenInput.name = pathKey;
6260
+ function getCurrentValue() {
6261
+ var _a2, _b;
6262
+ const rawText = textarea.value;
6263
+ const nameToRid = buildNameToRid(files, state);
6264
+ const submissionText = rawText ? replaceFilenamesWithRids(rawText, nameToRid) : null;
6265
+ const textKey = (_a2 = element.textKey) != null ? _a2 : "text";
6266
+ const filesKey = (_b = element.filesKey) != null ? _b : "files";
6267
+ return {
6268
+ [textKey]: rawText === "" ? null : submissionText,
6269
+ [filesKey]: [...files]
6270
+ };
6271
+ }
6272
+ function writeHidden() {
6273
+ hiddenInput.value = JSON.stringify(getCurrentValue());
6274
+ }
6275
+ const outerDiv = document.createElement("div");
6276
+ outerDiv.className = "fb-richinput-wrapper";
6277
+ outerDiv.style.cssText = `
6278
+ position: relative;
6279
+ border: 1px solid var(--fb-border-color, #d1d5db);
6280
+ border-radius: 16px;
6281
+ background: var(--fb-background-color, #f9fafb);
6282
+ transition: box-shadow 0.15s, border-color 0.15s;
6283
+ `;
6284
+ outerDiv.addEventListener("focusin", () => {
6285
+ outerDiv.style.borderColor = "var(--fb-primary-color, #0066cc)";
6286
+ outerDiv.style.boxShadow = "0 0 0 2px color-mix(in srgb, var(--fb-primary-color, #0066cc) 25%, transparent)";
6287
+ });
6288
+ outerDiv.addEventListener("focusout", () => {
6289
+ outerDiv.style.borderColor = "var(--fb-border-color, #d1d5db)";
6290
+ outerDiv.style.boxShadow = "none";
6291
+ });
6292
+ let dragCounter = 0;
6293
+ outerDiv.addEventListener("dragenter", (e) => {
6294
+ e.preventDefault();
6295
+ dragCounter++;
6296
+ outerDiv.style.borderColor = "var(--fb-primary-color, #0066cc)";
6297
+ outerDiv.style.boxShadow = "0 0 0 2px color-mix(in srgb, var(--fb-primary-color, #0066cc) 25%, transparent)";
6298
+ });
6299
+ outerDiv.addEventListener("dragover", (e) => {
6300
+ e.preventDefault();
6301
+ });
6302
+ outerDiv.addEventListener("dragleave", (e) => {
6303
+ e.preventDefault();
6304
+ dragCounter--;
6305
+ if (dragCounter <= 0) {
6306
+ dragCounter = 0;
6307
+ outerDiv.style.borderColor = "var(--fb-border-color, #d1d5db)";
6308
+ outerDiv.style.boxShadow = "none";
6309
+ }
6310
+ });
6311
+ outerDiv.addEventListener("drop", (e) => {
6312
+ var _a2, _b;
6313
+ e.preventDefault();
6314
+ dragCounter = 0;
6315
+ outerDiv.style.borderColor = "var(--fb-border-color, #d1d5db)";
6316
+ outerDiv.style.boxShadow = "none";
6317
+ const droppedFiles = (_a2 = e.dataTransfer) == null ? void 0 : _a2.files;
6318
+ if (!droppedFiles || !state.config.uploadFile) return;
6319
+ const maxFiles = (_b = element.maxFiles) != null ? _b : Infinity;
6320
+ for (let i = 0; i < droppedFiles.length && files.length < maxFiles; i++) {
6321
+ uploadFile(droppedFiles[i]);
6322
+ }
6323
+ });
6324
+ const filesRow = document.createElement("div");
6325
+ filesRow.className = "fb-richinput-files";
6326
+ filesRow.style.cssText = "display: none; flex-wrap: wrap; gap: 6px; padding: 10px 14px 0; align-items: center;";
6327
+ const fileInput = document.createElement("input");
6328
+ fileInput.type = "file";
6329
+ fileInput.multiple = true;
6330
+ fileInput.style.display = "none";
6331
+ if (element.accept) {
6332
+ if (typeof element.accept === "string") {
6333
+ fileInput.accept = element.accept;
6334
+ } else {
6335
+ fileInput.accept = element.accept.extensions.map((ext) => ext.startsWith(".") ? ext : `.${ext}`).join(",");
6336
+ }
6337
+ }
6338
+ const textareaArea = document.createElement("div");
6339
+ textareaArea.style.cssText = "position: relative;";
6340
+ const backdrop = document.createElement("div");
6341
+ backdrop.className = "fb-richinput-backdrop";
6342
+ backdrop.style.cssText = `
6343
+ position: absolute;
6344
+ top: 0; left: 0; right: 0; bottom: 0;
6345
+ ${TEXTAREA_PADDING}
6346
+ ${TEXTAREA_FONT}
6347
+ white-space: pre-wrap;
6348
+ word-break: break-word;
6349
+ color: transparent;
6350
+ pointer-events: none;
6351
+ overflow: hidden;
6352
+ border-radius: inherit;
6353
+ box-sizing: border-box;
6354
+ z-index: 2;
6355
+ `;
6356
+ const textarea = document.createElement("textarea");
6357
+ textarea.name = `${pathKey}__text`;
6358
+ textarea.placeholder = element.placeholder || t("richinputPlaceholder", state);
6359
+ const rawInitialText = (_a = initialValue.text) != null ? _a : "";
6360
+ textarea.value = rawInitialText ? replaceRidsWithFilenames(rawInitialText, files, state) : "";
6361
+ textarea.style.cssText = `
6362
+ width: 100%;
6363
+ ${TEXTAREA_PADDING}
6364
+ ${TEXTAREA_FONT}
6365
+ background: transparent;
6366
+ border: none;
6367
+ outline: none;
6368
+ resize: none;
6369
+ color: var(--fb-text-color, #111827);
6370
+ box-sizing: border-box;
6371
+ position: relative;
6372
+ z-index: 1;
6373
+ caret-color: var(--fb-text-color, #111827);
6374
+ `;
6375
+ applyAutoExpand2(textarea, backdrop);
6376
+ textarea.addEventListener("scroll", () => {
6377
+ backdrop.scrollTop = textarea.scrollTop;
6378
+ });
6379
+ let mentionTooltip = null;
6380
+ backdrop.addEventListener("mouseover", (e) => {
6381
+ var _a2, _b;
6382
+ const mark = (_b = (_a2 = e.target).closest) == null ? void 0 : _b.call(_a2, "mark");
6383
+ if (!(mark == null ? void 0 : mark.dataset.rid)) return;
6384
+ mentionTooltip = removePortalTooltip(mentionTooltip);
6385
+ mentionTooltip = showMentionTooltip(mark, mark.dataset.rid, state);
6386
+ });
6387
+ backdrop.addEventListener("mouseout", (e) => {
6388
+ var _a2, _b, _c;
6389
+ const mark = (_b = (_a2 = e.target).closest) == null ? void 0 : _b.call(_a2, "mark");
6390
+ if (!mark) return;
6391
+ const related = e.relatedTarget;
6392
+ if ((_c = related == null ? void 0 : related.closest) == null ? void 0 : _c.call(related, "mark")) return;
6393
+ mentionTooltip = removePortalTooltip(mentionTooltip);
6394
+ });
6395
+ backdrop.addEventListener("mousedown", (e) => {
6396
+ var _a2, _b;
6397
+ const mark = (_b = (_a2 = e.target).closest) == null ? void 0 : _b.call(_a2, "mark");
6398
+ if (!mark) return;
6399
+ mentionTooltip = removePortalTooltip(mentionTooltip);
6400
+ const marks = backdrop.querySelectorAll("mark");
6401
+ marks.forEach((m) => m.style.pointerEvents = "none");
6402
+ const under = document.elementFromPoint(e.clientX, e.clientY);
6403
+ if (under) {
6404
+ under.dispatchEvent(
6405
+ new MouseEvent("mousedown", {
6406
+ bubbles: true,
6407
+ cancelable: true,
6408
+ view: window,
6409
+ clientX: e.clientX,
6410
+ clientY: e.clientY,
6411
+ button: e.button,
6412
+ buttons: e.buttons,
6413
+ detail: e.detail
6414
+ })
6415
+ );
6416
+ }
6417
+ document.addEventListener(
6418
+ "mouseup",
6419
+ () => {
6420
+ marks.forEach((m) => m.style.pointerEvents = "auto");
6421
+ },
6422
+ { once: true }
6423
+ );
6424
+ });
6425
+ function updateBackdrop() {
6426
+ const text = textarea.value;
6427
+ const nameToRid = buildNameToRid(files, state);
6428
+ const tokens = findAtTokens(text);
6429
+ if (tokens.length === 0) {
6430
+ backdrop.innerHTML = escapeHtml(text) + "\n";
6431
+ return;
6432
+ }
6433
+ let html = "";
6434
+ let lastIdx = 0;
6435
+ for (const token of tokens) {
6436
+ html += escapeHtml(text.slice(lastIdx, token.start));
6437
+ const rid = nameToRid.get(token.name);
6438
+ if (rid) {
6439
+ html += `<mark data-rid="${escapeHtml(rid)}" style="background: color-mix(in srgb, var(--fb-primary-color, #0066cc) 15%, transparent); color: transparent; border-radius: 8px; padding: 0; border: none; box-shadow: 0 0 0 2px color-mix(in srgb, var(--fb-primary-color, #0066cc) 15%, transparent), 0 0 0 3px color-mix(in srgb, var(--fb-primary-color, #0066cc) 30%, transparent); box-decoration-break: clone; -webkit-box-decoration-break: clone; pointer-events: auto; cursor: text;">${escapeHtml(text.slice(token.start, token.end))}</mark>`;
6440
+ } else {
6441
+ html += `<mark style="color: transparent; background: none; padding: 0; border: none; text-decoration-line: underline; text-decoration-style: wavy; text-decoration-color: rgba(239, 68, 68, 0.45); text-underline-offset: 2px;">${escapeHtml(text.slice(token.start, token.end))}</mark>`;
6442
+ }
6443
+ lastIdx = token.end;
6444
+ }
6445
+ html += escapeHtml(text.slice(lastIdx));
6446
+ backdrop.innerHTML = html + "\n";
6447
+ }
6448
+ const paperclipBtn = document.createElement("button");
6449
+ paperclipBtn.type = "button";
6450
+ paperclipBtn.title = t("richinputAttachFile", state);
6451
+ paperclipBtn.style.cssText = `
6452
+ position: absolute;
6453
+ right: 10px;
6454
+ bottom: 10px;
6455
+ z-index: 2;
6456
+ width: 32px;
6457
+ height: 32px;
6458
+ border: none;
6459
+ border-radius: 8px;
6460
+ background: transparent;
6461
+ cursor: pointer;
6462
+ display: flex;
6463
+ align-items: center;
6464
+ justify-content: center;
6465
+ color: var(--fb-text-muted-color, #9ca3af);
6466
+ transition: color 0.15s, background 0.15s;
6467
+ `;
6468
+ paperclipBtn.innerHTML = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>';
6469
+ paperclipBtn.addEventListener("mouseenter", () => {
6470
+ paperclipBtn.style.color = "var(--fb-primary-color, #0066cc)";
6471
+ paperclipBtn.style.background = "var(--fb-background-hover-color, #f3f4f6)";
6472
+ });
6473
+ paperclipBtn.addEventListener("mouseleave", () => {
6474
+ paperclipBtn.style.color = "var(--fb-text-muted-color, #9ca3af)";
6475
+ paperclipBtn.style.background = "transparent";
6476
+ });
6477
+ paperclipBtn.addEventListener("click", () => {
6478
+ var _a2;
6479
+ const maxFiles = (_a2 = element.maxFiles) != null ? _a2 : Infinity;
6480
+ if (files.length < maxFiles) {
6481
+ fileInput.click();
6482
+ }
6483
+ });
6484
+ const dropdown = document.createElement("div");
6485
+ dropdown.className = "fb-richinput-dropdown";
6486
+ dropdown.style.cssText = `
6487
+ display: none;
6488
+ position: absolute;
6489
+ bottom: 100%;
6490
+ left: 0;
6491
+ z-index: 1000;
6492
+ background: #fff;
6493
+ border: 1px solid var(--fb-border-color, #d1d5db);
6494
+ border-radius: var(--fb-border-radius, 6px);
6495
+ box-shadow: 0 4px 12px rgba(0,0,0,0.12);
6496
+ min-width: 180px;
6497
+ max-width: 320px;
6498
+ max-height: 200px;
6499
+ overflow-y: auto;
6500
+ margin-bottom: 4px;
6501
+ ${TEXTAREA_FONT}
6502
+ `;
6503
+ function buildFileLabelsFromClosure() {
6504
+ return buildFileLabels(files, state);
6505
+ }
6506
+ function renderDropdownItems(filtered) {
6507
+ clear(dropdown);
6508
+ const labels = buildFileLabelsFromClosure();
6509
+ if (filtered.length === 0) {
6510
+ dropdown.style.display = "none";
6511
+ dropdownState.open = false;
6512
+ return;
6513
+ }
6514
+ filtered.forEach((rid, idx) => {
6515
+ var _a2;
6516
+ const meta = state.resourceIndex.get(rid);
6517
+ const item = document.createElement("div");
6518
+ item.className = "fb-richinput-dropdown-item";
6519
+ item.dataset.rid = rid;
6520
+ item.style.cssText = `
6521
+ padding: 5px 10px;
6522
+ cursor: pointer;
6523
+ color: var(--fb-text-color, #111827);
6524
+ background: ${idx === dropdownState.selectedIndex ? "var(--fb-background-hover-color, #f3f4f6)" : "transparent"};
6525
+ display: flex;
6526
+ align-items: center;
6527
+ gap: 8px;
6528
+ `;
6529
+ const thumb = document.createElement("div");
6530
+ thumb.style.cssText = "width: 24px; height: 24px; border-radius: 4px; overflow: hidden; flex-shrink: 0; background: var(--fb-background-hover-color, #f3f4f6); display: flex; align-items: center; justify-content: center;";
6531
+ if ((meta == null ? void 0 : meta.file) && isImageMeta(meta)) {
6532
+ const img = document.createElement("img");
6533
+ img.style.cssText = "width: 100%; height: 100%; object-fit: cover; display: block;";
6534
+ const reader = new FileReader();
6535
+ reader.onload = (ev) => {
6536
+ var _a3;
6537
+ img.src = ((_a3 = ev.target) == null ? void 0 : _a3.result) || "";
6538
+ };
6539
+ reader.readAsDataURL(meta.file);
6540
+ thumb.appendChild(img);
6541
+ } else if (state.config.getThumbnail) {
6542
+ state.config.getThumbnail(rid).then((url) => {
6543
+ if (!url || !thumb.isConnected) return;
6544
+ const img = document.createElement("img");
6545
+ img.style.cssText = "width: 100%; height: 100%; object-fit: cover; display: block;";
6546
+ img.src = url;
6547
+ clear(thumb);
6548
+ thumb.appendChild(img);
6549
+ }).catch(() => {
6550
+ });
6551
+ thumb.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>';
6552
+ } else {
6553
+ thumb.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>';
6554
+ }
6555
+ item.appendChild(thumb);
6556
+ const nameSpan = document.createElement("span");
6557
+ nameSpan.style.cssText = "overflow: hidden; text-overflow: ellipsis; white-space: nowrap;";
6558
+ nameSpan.textContent = (_a2 = labels.get(rid)) != null ? _a2 : rid;
6559
+ item.appendChild(nameSpan);
6560
+ dropdown.appendChild(item);
6561
+ });
6562
+ dropdown.onmousemove = (e) => {
6563
+ var _a2, _b, _c;
6564
+ const target = (_b = (_a2 = e.target).closest) == null ? void 0 : _b.call(
6565
+ _a2,
6566
+ ".fb-richinput-dropdown-item"
6567
+ );
6568
+ if (!target) return;
6569
+ const newIdx = filtered.indexOf((_c = target.dataset.rid) != null ? _c : "");
6570
+ if (newIdx === -1 || newIdx === dropdownState.selectedIndex) return;
6571
+ const items = dropdown.querySelectorAll(
6572
+ ".fb-richinput-dropdown-item"
6573
+ );
6574
+ items.forEach((el, i) => {
6575
+ el.style.background = i === newIdx ? "var(--fb-background-hover-color, #f3f4f6)" : "transparent";
6576
+ });
6577
+ dropdownState.selectedIndex = newIdx;
6578
+ };
6579
+ dropdown.onmousedown = (e) => {
6580
+ var _a2, _b;
6581
+ e.preventDefault();
6582
+ e.stopPropagation();
6583
+ const target = (_b = (_a2 = e.target).closest) == null ? void 0 : _b.call(
6584
+ _a2,
6585
+ ".fb-richinput-dropdown-item"
6586
+ );
6587
+ if (!(target == null ? void 0 : target.dataset.rid)) return;
6588
+ insertMention(target.dataset.rid);
6589
+ };
6590
+ dropdown.style.display = "block";
6591
+ dropdownState.open = true;
6592
+ }
6593
+ function openDropdown() {
6594
+ const trigger = getAtTrigger(textarea);
6595
+ if (!trigger) {
6596
+ closeDropdown();
6597
+ return;
6598
+ }
6599
+ dropdownState.query = trigger.query;
6600
+ dropdownState.triggerPos = trigger.pos;
6601
+ dropdownState.selectedIndex = 0;
6602
+ const labels = buildFileLabelsFromClosure();
6603
+ const filtered = filterFilesForDropdown(trigger.query, files, labels);
6604
+ renderDropdownItems(filtered);
6605
+ }
6606
+ function closeDropdown() {
6607
+ dropdown.style.display = "none";
6608
+ dropdownState.open = false;
6609
+ }
6610
+ function insertMention(rid) {
6611
+ var _a2, _b, _c, _d;
6612
+ const labels = buildFileLabelsFromClosure();
6613
+ const label = (_c = (_b = labels.get(rid)) != null ? _b : (_a2 = state.resourceIndex.get(rid)) == null ? void 0 : _a2.name) != null ? _c : rid;
6614
+ const cursorPos = (_d = textarea.selectionStart) != null ? _d : 0;
6615
+ const before = textarea.value.slice(0, dropdownState.triggerPos);
6616
+ const after = textarea.value.slice(cursorPos);
6617
+ const mention = `${formatMention(label)} `;
6618
+ textarea.value = `${before}${mention}${after}`;
6619
+ const newPos = before.length + mention.length;
6620
+ textarea.setSelectionRange(newPos, newPos);
6621
+ textarea.dispatchEvent(new Event("input"));
6622
+ closeDropdown();
6623
+ }
6624
+ textarea.addEventListener("input", () => {
6625
+ var _a2;
6626
+ updateBackdrop();
6627
+ writeHidden();
6628
+ (_a2 = ctx.instance) == null ? void 0 : _a2.triggerOnChange(pathKey, getCurrentValue());
6629
+ if (files.length > 0) {
6630
+ openDropdown();
6631
+ } else {
6632
+ closeDropdown();
6633
+ }
6634
+ });
6635
+ function updateDropdownHighlight() {
6636
+ const items = dropdown.querySelectorAll(
6637
+ ".fb-richinput-dropdown-item"
6638
+ );
6639
+ items.forEach((el, i) => {
6640
+ el.style.background = i === dropdownState.selectedIndex ? "var(--fb-background-hover-color, #f3f4f6)" : "transparent";
6641
+ });
6642
+ }
6643
+ textarea.addEventListener("keydown", (e) => {
6644
+ if (!dropdownState.open) return;
6645
+ const labels = buildFileLabelsFromClosure();
6646
+ const filtered = filterFilesForDropdown(
6647
+ dropdownState.query,
6648
+ files,
6649
+ labels
6650
+ );
6651
+ if (e.key === "ArrowDown") {
6652
+ e.preventDefault();
6653
+ dropdownState.selectedIndex = Math.min(
6654
+ dropdownState.selectedIndex + 1,
6655
+ filtered.length - 1
6656
+ );
6657
+ updateDropdownHighlight();
6658
+ } else if (e.key === "ArrowUp") {
6659
+ e.preventDefault();
6660
+ dropdownState.selectedIndex = Math.max(
6661
+ dropdownState.selectedIndex - 1,
6662
+ 0
6663
+ );
6664
+ updateDropdownHighlight();
6665
+ } else if (e.key === "Enter" && filtered.length > 0) {
6666
+ e.preventDefault();
6667
+ insertMention(filtered[dropdownState.selectedIndex]);
6668
+ } else if (e.key === "Escape") {
6669
+ closeDropdown();
6670
+ }
6671
+ });
6672
+ document.addEventListener(
6673
+ "click",
6674
+ (e) => {
6675
+ if (!outerDiv.contains(e.target) && !dropdown.contains(e.target)) {
6676
+ closeDropdown();
6677
+ }
6678
+ },
6679
+ { signal: docListenerCtrl.signal }
6680
+ );
6681
+ function renderFilesRow() {
6682
+ clear(filesRow);
6683
+ if (files.length === 0) {
6684
+ filesRow.style.display = "none";
6685
+ return;
6686
+ }
6687
+ filesRow.style.display = "flex";
6688
+ files.forEach((rid) => {
6689
+ const meta = state.resourceIndex.get(rid);
6690
+ const thumbWrapper = document.createElement("div");
6691
+ thumbWrapper.className = "fb-richinput-file-thumb";
6692
+ thumbWrapper.style.cssText = `
6693
+ position: relative;
6694
+ width: 48px;
6695
+ height: 48px;
6696
+ border: 1px solid var(--fb-border-color, #d1d5db);
6697
+ border-radius: 8px;
6698
+ overflow: hidden;
6699
+ flex-shrink: 0;
6700
+ cursor: pointer;
6701
+ background: #fff;
6702
+ `;
6703
+ const thumbInner = document.createElement("div");
6704
+ thumbInner.style.cssText = "width: 48px; height: 48px; border-radius: inherit; overflow: hidden;";
6705
+ renderThumbContent(thumbInner, rid, meta, state);
6706
+ thumbWrapper.appendChild(thumbInner);
6707
+ const tooltipHandle = createTooltipHandle();
6708
+ const doMention = () => {
6709
+ var _a2, _b, _c;
6710
+ const cursorPos = (_a2 = textarea.selectionStart) != null ? _a2 : textarea.value.length;
6711
+ const labels = buildFileLabelsFromClosure();
6712
+ const label = (_c = (_b = labels.get(rid)) != null ? _b : meta == null ? void 0 : meta.name) != null ? _c : rid;
6713
+ const before = textarea.value.slice(0, cursorPos);
6714
+ const after = textarea.value.slice(cursorPos);
6715
+ const prefix = before.length > 0 && !/[\s\n]$/.test(before) ? "\n" : "";
6716
+ const mention = `${prefix}${formatMention(label)} `;
6717
+ textarea.value = `${before}${mention}${after}`;
6718
+ const newPos = cursorPos + mention.length;
6719
+ textarea.setSelectionRange(newPos, newPos);
6720
+ textarea.focus();
6721
+ textarea.dispatchEvent(new Event("input"));
6722
+ };
6723
+ const doRemove = () => {
6724
+ var _a2;
6725
+ const idx = files.indexOf(rid);
6726
+ if (idx !== -1) files.splice(idx, 1);
6727
+ renderFilesRow();
6728
+ updateBackdrop();
6729
+ writeHidden();
6730
+ (_a2 = ctx.instance) == null ? void 0 : _a2.triggerOnChange(pathKey, getCurrentValue());
6731
+ };
6732
+ thumbWrapper.addEventListener("mouseenter", () => {
6733
+ cancelHideTooltip(tooltipHandle);
6734
+ if (!tooltipHandle.element) {
6735
+ tooltipHandle.element = showFileTooltip(thumbWrapper, {
6736
+ rid,
6737
+ state,
6738
+ isReadonly: false,
6739
+ onMention: doMention,
6740
+ onRemove: doRemove
6741
+ });
6742
+ tooltipHandle.element.addEventListener("mouseenter", () => {
6743
+ cancelHideTooltip(tooltipHandle);
6744
+ });
6745
+ tooltipHandle.element.addEventListener("mouseleave", () => {
6746
+ scheduleHideTooltip(tooltipHandle);
6747
+ });
6748
+ }
6749
+ });
6750
+ thumbWrapper.addEventListener("mouseleave", () => {
6751
+ scheduleHideTooltip(tooltipHandle);
6752
+ });
6753
+ filesRow.appendChild(thumbWrapper);
6754
+ });
6755
+ }
6756
+ function uploadFile(file) {
6757
+ if (!state.config.uploadFile) return;
6758
+ const tempId = `temp-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
6759
+ state.resourceIndex.set(tempId, {
6760
+ name: file.name,
6761
+ type: file.type,
6762
+ size: file.size,
6763
+ uploadedAt: /* @__PURE__ */ new Date(),
6764
+ file
6765
+ });
6766
+ files.push(tempId);
6767
+ renderFilesRow();
6768
+ const thumbs = filesRow.querySelectorAll(
6769
+ ".fb-richinput-file-thumb"
6770
+ );
6771
+ const loadingThumb = thumbs[thumbs.length - 1];
6772
+ if (loadingThumb) loadingThumb.style.opacity = "0.5";
6773
+ state.config.uploadFile(file).then((resourceId) => {
6774
+ var _a2;
6775
+ const idx = files.indexOf(tempId);
6776
+ if (idx !== -1) files[idx] = resourceId;
6777
+ state.resourceIndex.delete(tempId);
6778
+ state.resourceIndex.set(resourceId, {
6779
+ name: file.name,
6780
+ type: file.type,
6781
+ size: file.size,
6782
+ uploadedAt: /* @__PURE__ */ new Date(),
6783
+ file
6784
+ });
6785
+ renderFilesRow();
6786
+ updateBackdrop();
6787
+ writeHidden();
6788
+ (_a2 = ctx.instance) == null ? void 0 : _a2.triggerOnChange(pathKey, getCurrentValue());
6789
+ }).catch((err) => {
6790
+ var _a2, _b;
6791
+ const idx = files.indexOf(tempId);
6792
+ if (idx !== -1) files.splice(idx, 1);
6793
+ state.resourceIndex.delete(tempId);
6794
+ renderFilesRow();
6795
+ (_b = (_a2 = state.config).onUploadError) == null ? void 0 : _b.call(_a2, err, file);
6796
+ });
6797
+ }
6798
+ fileInput.addEventListener("change", () => {
6799
+ var _a2;
6800
+ const selected = fileInput.files;
6801
+ if (!selected || selected.length === 0) return;
6802
+ const maxFiles = (_a2 = element.maxFiles) != null ? _a2 : Infinity;
6803
+ for (let i = 0; i < selected.length && files.length < maxFiles; i++) {
6804
+ uploadFile(selected[i]);
6805
+ }
6806
+ fileInput.value = "";
6807
+ });
6808
+ textareaArea.appendChild(backdrop);
6809
+ textareaArea.appendChild(textarea);
6810
+ textareaArea.appendChild(paperclipBtn);
6811
+ textareaArea.appendChild(dropdown);
6812
+ outerDiv.appendChild(filesRow);
6813
+ outerDiv.appendChild(textareaArea);
6814
+ if (element.minLength != null || element.maxLength != null) {
6815
+ const counterRow = document.createElement("div");
6816
+ counterRow.style.cssText = "position: relative; padding: 2px 14px 6px; text-align: right;";
6817
+ const counter = createCharCounter(element, textarea, false);
6818
+ counter.style.cssText = `
6819
+ position: static;
6820
+ display: inline-block;
6821
+ font-size: var(--fb-font-size-small);
6822
+ color: var(--fb-text-secondary-color);
6823
+ pointer-events: none;
6824
+ `;
6825
+ counterRow.appendChild(counter);
6826
+ outerDiv.appendChild(counterRow);
6827
+ }
6828
+ outerDiv.appendChild(hiddenInput);
6829
+ outerDiv.appendChild(fileInput);
6830
+ writeHidden();
6831
+ updateBackdrop();
6832
+ hiddenInput._applyExternalUpdate = (value) => {
6833
+ var _a2;
6834
+ const rawText = (_a2 = value.text) != null ? _a2 : "";
6835
+ textarea.value = rawText ? replaceRidsWithFilenames(rawText, files, state) : "";
6836
+ textarea.dispatchEvent(new Event("input"));
6837
+ files.length = 0;
6838
+ for (const rid of value.files) files.push(rid);
6839
+ renderFilesRow();
6840
+ updateBackdrop();
6841
+ writeHidden();
6842
+ };
6843
+ wrapper.appendChild(outerDiv);
6844
+ renderFilesRow();
6845
+ const observer = new MutationObserver(() => {
6846
+ if (!outerDiv.isConnected) {
6847
+ docListenerCtrl.abort();
6848
+ mentionTooltip = removePortalTooltip(mentionTooltip);
6849
+ observer.disconnect();
6850
+ }
6851
+ });
6852
+ if (outerDiv.parentElement) {
6853
+ observer.observe(outerDiv.parentElement, { childList: true });
6854
+ }
6855
+ }
6856
+ function renderReadonlyMode(_element, ctx, wrapper, _pathKey, value) {
6857
+ var _a, _b;
6858
+ const state = ctx.state;
6859
+ const { text, files } = value;
6860
+ const ridToName = /* @__PURE__ */ new Map();
6861
+ for (const rid of files) {
6862
+ const meta = state.resourceIndex.get(rid);
6863
+ if (meta == null ? void 0 : meta.name) ridToName.set(rid, meta.name);
6864
+ }
6865
+ if (files.length > 0) {
6866
+ const filesRow = document.createElement("div");
6867
+ filesRow.style.cssText = "display: flex; flex-wrap: wrap; gap: 6px; padding-bottom: 8px;";
6868
+ files.forEach((rid) => {
6869
+ const meta = state.resourceIndex.get(rid);
6870
+ const thumbWrapper = document.createElement("div");
6871
+ thumbWrapper.style.cssText = `
6872
+ position: relative;
6873
+ width: 48px; height: 48px;
6874
+ border: 1px solid var(--fb-border-color, #d1d5db);
6875
+ border-radius: 8px;
6876
+ overflow: hidden;
6877
+ flex-shrink: 0;
6878
+ background: #fff;
6879
+ cursor: default;
6880
+ `;
6881
+ const thumbInner = document.createElement("div");
6882
+ thumbInner.style.cssText = "width: 48px; height: 48px; border-radius: inherit; overflow: hidden;";
6883
+ renderThumbContent(thumbInner, rid, meta, state);
6884
+ thumbWrapper.appendChild(thumbInner);
6885
+ const tooltipHandle = createTooltipHandle();
6886
+ thumbWrapper.addEventListener("mouseenter", () => {
6887
+ cancelHideTooltip(tooltipHandle);
6888
+ if (!tooltipHandle.element) {
6889
+ tooltipHandle.element = showFileTooltip(thumbWrapper, {
6890
+ rid,
6891
+ state,
6892
+ isReadonly: true
6893
+ });
6894
+ tooltipHandle.element.addEventListener("mouseenter", () => {
6895
+ cancelHideTooltip(tooltipHandle);
6896
+ });
6897
+ tooltipHandle.element.addEventListener("mouseleave", () => {
6898
+ scheduleHideTooltip(tooltipHandle);
6899
+ });
6900
+ }
6901
+ });
6902
+ thumbWrapper.addEventListener("mouseleave", () => {
6903
+ scheduleHideTooltip(tooltipHandle);
6904
+ });
6905
+ filesRow.appendChild(thumbWrapper);
6906
+ });
6907
+ wrapper.appendChild(filesRow);
6908
+ }
6909
+ if (text) {
6910
+ const textDiv = document.createElement("div");
6911
+ textDiv.style.cssText = `
6912
+ ${TEXTAREA_FONT}
6913
+ color: var(--fb-text-color, #111827);
6914
+ white-space: pre-wrap;
6915
+ word-break: break-word;
6916
+ `;
6917
+ const tokens = findAtTokens(text);
6918
+ const resolvedTokens = tokens.filter(
6919
+ (tok) => ridToName.has(tok.name) || [...ridToName.values()].includes(tok.name)
6920
+ );
6921
+ if (resolvedTokens.length === 0) {
6922
+ textDiv.textContent = text;
6923
+ } else {
6924
+ let lastIndex = 0;
6925
+ for (const token of resolvedTokens) {
6926
+ if (token.start > lastIndex) {
6927
+ textDiv.appendChild(
6928
+ document.createTextNode(text.slice(lastIndex, token.start))
6929
+ );
6930
+ }
6931
+ const span = document.createElement("span");
6932
+ span.style.cssText = `
6933
+ display: inline;
6934
+ background: color-mix(in srgb, var(--fb-primary-color, #0066cc) 15%, transparent);
6935
+ color: var(--fb-primary-color, #0066cc);
6936
+ border-radius: 8px;
6937
+ padding: 1px 6px;
6938
+ font-weight: 500;
6939
+ cursor: default;
6940
+ `;
6941
+ const rid = ridToName.has(token.name) ? token.name : (_a = [...ridToName.entries()].find(([, n]) => n === token.name)) == null ? void 0 : _a[0];
6942
+ const displayName = (_b = ridToName.get(token.name)) != null ? _b : token.name;
6943
+ span.textContent = `@${displayName}`;
6944
+ if (rid) {
6945
+ let spanTooltip = null;
6946
+ const mentionRid = rid;
6947
+ span.addEventListener("mouseenter", () => {
6948
+ spanTooltip = removePortalTooltip(spanTooltip);
6949
+ spanTooltip = showMentionTooltip(span, mentionRid, state);
6950
+ });
6951
+ span.addEventListener("mouseleave", () => {
6952
+ spanTooltip = removePortalTooltip(spanTooltip);
6953
+ });
6954
+ }
6955
+ textDiv.appendChild(span);
6956
+ lastIndex = token.end;
6957
+ }
6958
+ if (lastIndex < text.length) {
6959
+ textDiv.appendChild(document.createTextNode(text.slice(lastIndex)));
6960
+ }
6961
+ }
6962
+ wrapper.appendChild(textDiv);
6963
+ }
6964
+ if (!text && files.length === 0) {
6965
+ const empty = document.createElement("div");
6966
+ empty.style.cssText = "color: var(--fb-text-muted-color, #6b7280); font-size: var(--fb-font-size, 14px);";
6967
+ empty.textContent = "\u2014";
6968
+ wrapper.appendChild(empty);
6969
+ }
6970
+ }
6971
+ function renderRichInputElement(element, ctx, wrapper, pathKey) {
6972
+ var _a, _b, _c, _d;
6973
+ const state = ctx.state;
6974
+ const textKey = (_a = element.textKey) != null ? _a : "text";
6975
+ const filesKey = (_b = element.filesKey) != null ? _b : "files";
6976
+ const rawPrefill = ctx.prefill[element.key];
6977
+ let initialValue;
6978
+ if (rawPrefill && typeof rawPrefill === "object" && !Array.isArray(rawPrefill)) {
6979
+ const obj = rawPrefill;
6980
+ const textVal = (_c = obj[textKey]) != null ? _c : obj["text"];
6981
+ const filesVal = (_d = obj[filesKey]) != null ? _d : obj["files"];
6982
+ initialValue = {
6983
+ text: typeof textVal === "string" ? textVal : null,
6984
+ files: Array.isArray(filesVal) ? filesVal : []
6985
+ };
6986
+ } else if (typeof rawPrefill === "string") {
6987
+ initialValue = { text: rawPrefill || null, files: [] };
6988
+ } else {
6989
+ initialValue = { text: null, files: [] };
6990
+ }
6991
+ for (const rid of initialValue.files) {
6992
+ if (!state.resourceIndex.has(rid)) {
6993
+ state.resourceIndex.set(rid, {
6994
+ name: rid,
6995
+ type: "application/octet-stream",
6996
+ size: 0,
6997
+ uploadedAt: /* @__PURE__ */ new Date(),
6998
+ file: void 0
6999
+ });
7000
+ }
7001
+ }
7002
+ if (state.config.readonly) {
7003
+ renderReadonlyMode(element, ctx, wrapper, pathKey, initialValue);
7004
+ } else {
7005
+ if (!state.config.uploadFile) {
7006
+ throw new Error(
7007
+ `RichInput field "${element.key}" requires uploadFile handler in config`
7008
+ );
7009
+ }
7010
+ renderEditMode(element, ctx, wrapper, pathKey, initialValue);
7011
+ }
7012
+ }
7013
+ function validateRichInputElement(element, key, context) {
7014
+ var _a, _b;
7015
+ const { scopeRoot, state, skipValidation } = context;
7016
+ const errors = [];
7017
+ const textKey = (_a = element.textKey) != null ? _a : "text";
7018
+ const filesKey = (_b = element.filesKey) != null ? _b : "files";
7019
+ const hiddenInput = scopeRoot.querySelector(
7020
+ `[name="${key}"]`
7021
+ );
7022
+ if (!hiddenInput) {
7023
+ return { value: null, errors };
7024
+ }
7025
+ let rawValue = {};
7026
+ try {
7027
+ const parsed = JSON.parse(hiddenInput.value);
7028
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
7029
+ rawValue = parsed;
7030
+ } else {
7031
+ errors.push(`${key}: invalid richinput data`);
7032
+ return { value: null, errors };
7033
+ }
7034
+ } catch {
7035
+ errors.push(`${key}: invalid richinput data`);
7036
+ return { value: null, errors };
7037
+ }
7038
+ const textVal = rawValue[textKey];
7039
+ const filesVal = rawValue[filesKey];
7040
+ const text = textVal === null || typeof textVal === "string" ? textVal : null;
7041
+ const files = Array.isArray(filesVal) ? filesVal : [];
7042
+ const value = {
7043
+ [textKey]: text != null ? text : null,
7044
+ [filesKey]: files
7045
+ };
7046
+ if (!skipValidation) {
7047
+ const textEmpty = !text || text.trim() === "";
7048
+ const filesEmpty = files.length === 0;
7049
+ if (element.required && textEmpty && filesEmpty) {
7050
+ errors.push(`${key}: ${t("required", state)}`);
7051
+ }
7052
+ if (!textEmpty && text) {
7053
+ if (element.minLength != null && text.length < element.minLength) {
7054
+ errors.push(
7055
+ `${key}: ${t("minLength", state, { min: element.minLength })}`
7056
+ );
7057
+ }
7058
+ if (element.maxLength != null && text.length > element.maxLength) {
7059
+ errors.push(
7060
+ `${key}: ${t("maxLength", state, { max: element.maxLength })}`
7061
+ );
7062
+ }
7063
+ }
7064
+ if (element.maxFiles != null && files.length > element.maxFiles) {
7065
+ errors.push(
7066
+ `${key}: ${t("maxFiles", state, { max: element.maxFiles })}`
7067
+ );
7068
+ }
7069
+ }
7070
+ return { value, errors };
7071
+ }
7072
+ function updateRichInputField(element, fieldPath, value, context) {
7073
+ var _a, _b, _c, _d;
7074
+ const { scopeRoot } = context;
7075
+ const hiddenInput = scopeRoot.querySelector(
7076
+ `[name="${fieldPath}"]`
7077
+ );
7078
+ if (!hiddenInput) {
7079
+ console.warn(
7080
+ `updateRichInputField: no hidden input found for "${fieldPath}". Re-render to reflect new data.`
7081
+ );
7082
+ return;
7083
+ }
7084
+ let normalized = null;
7085
+ if (value && typeof value === "object" && !Array.isArray(value)) {
7086
+ const obj = value;
7087
+ const textKey = (_a = element.textKey) != null ? _a : "text";
7088
+ const filesKey = (_b = element.filesKey) != null ? _b : "files";
7089
+ const textVal = (_c = obj[textKey]) != null ? _c : obj["text"];
7090
+ const filesVal = (_d = obj[filesKey]) != null ? _d : obj["files"];
7091
+ if (textVal !== void 0 || filesVal !== void 0) {
7092
+ normalized = {
7093
+ text: typeof textVal === "string" ? textVal : null,
7094
+ files: Array.isArray(filesVal) ? filesVal : []
7095
+ };
7096
+ }
7097
+ }
7098
+ if (normalized && hiddenInput._applyExternalUpdate) {
7099
+ hiddenInput._applyExternalUpdate(normalized);
7100
+ } else if (normalized) {
7101
+ hiddenInput.value = JSON.stringify(normalized);
7102
+ }
7103
+ }
7104
+
7105
+ // src/components/index.ts
7106
+ function showTooltip(tooltipId, button) {
7107
+ const tooltip = document.getElementById(tooltipId);
7108
+ if (!tooltip) return;
7109
+ const isCurrentlyVisible = !tooltip.classList.contains("hidden");
7110
+ document.querySelectorAll('[id^="tooltip-"]').forEach((t2) => {
7111
+ t2.classList.add("hidden");
7112
+ });
7113
+ if (isCurrentlyVisible) {
7114
+ return;
7115
+ }
7116
+ const rect = button.getBoundingClientRect();
7117
+ const viewportWidth = window.innerWidth;
7118
+ const viewportHeight = window.innerHeight;
7119
+ if (tooltip && tooltip.parentElement !== document.body) {
7120
+ document.body.appendChild(tooltip);
7121
+ }
7122
+ tooltip.style.visibility = "hidden";
7123
+ tooltip.style.position = "fixed";
7124
+ tooltip.classList.remove("hidden");
7125
+ const tooltipRect = tooltip.getBoundingClientRect();
7126
+ tooltip.classList.add("hidden");
7127
+ tooltip.style.visibility = "visible";
7128
+ let left = rect.left;
7129
+ let top = rect.bottom + 5;
7130
+ if (left + tooltipRect.width > viewportWidth) {
7131
+ left = rect.right - tooltipRect.width;
7132
+ }
7133
+ if (top + tooltipRect.height > viewportHeight) {
7134
+ top = rect.top - tooltipRect.height - 5;
7135
+ }
7136
+ if (left < 10) {
7137
+ left = 10;
7138
+ }
7139
+ if (top < 10) {
7140
+ top = rect.bottom + 5;
7141
+ }
7142
+ tooltip.style.left = `${left}px`;
7143
+ tooltip.style.top = `${top}px`;
7144
+ tooltip.classList.remove("hidden");
7145
+ setTimeout(() => {
7146
+ tooltip.classList.add("hidden");
7147
+ }, 25e3);
7148
+ }
7149
+ if (typeof document !== "undefined") {
7150
+ document.addEventListener("click", (e) => {
7151
+ const target = e.target;
7152
+ const isInfoButton = target.closest("button") && target.closest("button").onclick;
7153
+ const isTooltip = target.closest('[id^="tooltip-"]');
7154
+ if (!isInfoButton && !isTooltip) {
7155
+ document.querySelectorAll('[id^="tooltip-"]').forEach((tooltip) => {
7156
+ tooltip.classList.add("hidden");
7157
+ });
7158
+ }
7159
+ });
7160
+ }
7161
+ function shouldDisableElement(element, ctx) {
7162
+ var _a, _b, _c;
7163
+ if (!element.enableIf) {
7164
+ return false;
7165
+ }
7166
+ try {
7167
+ const rootFormData = (_b = (_a = ctx.formData) != null ? _a : ctx.prefill) != null ? _b : {};
7168
+ const scope = (_c = element.enableIf.scope) != null ? _c : "relative";
7169
+ const containerData = scope === "relative" && ctx.path ? ctx.prefill : void 0;
7170
+ const shouldEnable = evaluateEnableCondition(
7171
+ element.enableIf,
7172
+ rootFormData,
7173
+ containerData
7174
+ );
7175
+ return !shouldEnable;
7176
+ } catch (error) {
7177
+ console.error(
7178
+ `Error evaluating enableIf for field "${element.key}":`,
7179
+ error
7180
+ );
7181
+ }
7182
+ return false;
7183
+ }
7184
+ function extractDOMValue(fieldPath, formRoot) {
7185
+ const input = formRoot.querySelector(
7186
+ `[name="${fieldPath}"]`
7187
+ );
7188
+ if (!input) {
7189
+ return void 0;
7190
+ }
7191
+ if (input instanceof HTMLSelectElement) {
7192
+ return input.value;
7193
+ } else if (input instanceof HTMLInputElement) {
7194
+ if (input.type === "checkbox") {
7195
+ return input.checked;
7196
+ } else if (input.type === "radio") {
7197
+ const checked = formRoot.querySelector(
7198
+ `[name="${fieldPath}"]:checked`
7199
+ );
7200
+ return checked ? checked.value : void 0;
7201
+ } else {
7202
+ return input.value;
7203
+ }
7204
+ } else if (input instanceof HTMLTextAreaElement) {
7205
+ return input.value;
7206
+ }
7207
+ return void 0;
7208
+ }
7209
+ function reevaluateEnableIf(wrapper, element, ctx) {
7210
+ var _a, _b;
7211
+ if (!element.enableIf) {
7212
+ return;
7213
+ }
7214
+ const formRoot = ctx.state.formRoot;
7215
+ if (!formRoot) {
7216
+ console.error(`Cannot re-evaluate enableIf: formRoot is null`);
7217
+ return;
7218
+ }
7219
+ const condition = element.enableIf;
7220
+ const scope = (_a = condition.scope) != null ? _a : "relative";
7221
+ let rootFormData = {};
7222
+ const containerData = {};
7223
+ const effectiveScope = !ctx.path || ctx.path === "" ? "absolute" : scope;
7224
+ if (effectiveScope === "relative" && ctx.path) {
7225
+ const containerMatch = ctx.path.match(/^(.+)\[(\d+)\]$/);
7226
+ if (containerMatch) {
7227
+ const containerKey = containerMatch[1];
7228
+ const containerIndex = parseInt(containerMatch[2], 10);
7229
+ const containerItemElement = formRoot.querySelector(
7230
+ `[data-container-item="${containerKey}[${containerIndex}]"]`
7231
+ );
7232
+ if (containerItemElement) {
7233
+ const inputs = containerItemElement.querySelectorAll(
7234
+ "input, select, textarea"
7235
+ );
7236
+ inputs.forEach((input) => {
7237
+ const fieldName = input.getAttribute("name");
7238
+ if (fieldName) {
7239
+ const fieldKeyMatch = fieldName.match(/\.([^.[\]]+)$/);
7240
+ if (fieldKeyMatch) {
7241
+ const fieldKey = fieldKeyMatch[1];
7242
+ if (input instanceof HTMLSelectElement) {
7243
+ containerData[fieldKey] = input.value;
7244
+ } else if (input instanceof HTMLInputElement) {
7245
+ if (input.type === "checkbox") {
7246
+ containerData[fieldKey] = input.checked;
7247
+ } else if (input.type === "radio") {
7248
+ if (input.checked) {
7249
+ containerData[fieldKey] = input.value;
7250
+ }
7251
+ } else {
7252
+ containerData[fieldKey] = input.value;
7253
+ }
7254
+ } else if (input instanceof HTMLTextAreaElement) {
7255
+ containerData[fieldKey] = input.value;
7256
+ }
7257
+ }
7258
+ }
7259
+ });
7260
+ }
7261
+ }
7262
+ } else {
7263
+ const dependencyKey = condition.key;
7264
+ const dependencyValue = extractDOMValue(dependencyKey, formRoot);
7265
+ if (dependencyValue !== void 0) {
7266
+ rootFormData[dependencyKey] = dependencyValue;
7267
+ } else {
7268
+ rootFormData = (_b = ctx.formData) != null ? _b : ctx.prefill;
7269
+ }
7270
+ }
7271
+ try {
7272
+ const shouldEnable = evaluateEnableCondition(
7273
+ condition,
7274
+ rootFormData,
7275
+ containerData
7276
+ );
7277
+ if (shouldEnable) {
7278
+ wrapper.style.display = "";
7279
+ wrapper.classList.remove("fb-field-wrapper-disabled");
7280
+ wrapper.removeAttribute("data-conditionally-disabled");
7281
+ } else {
7282
+ wrapper.style.display = "none";
7283
+ wrapper.classList.add("fb-field-wrapper-disabled");
7284
+ wrapper.setAttribute("data-conditionally-disabled", "true");
7285
+ }
7286
+ } catch (error) {
7287
+ console.error(`Error re-evaluating enableIf for field "${element.key}":`, error);
7288
+ }
7289
+ }
7290
+ function setupEnableIfListeners(wrapper, element, ctx) {
7291
+ var _a;
7292
+ if (!element.enableIf) {
7293
+ return;
7294
+ }
7295
+ const formRoot = ctx.state.formRoot;
7296
+ if (!formRoot) {
7297
+ console.error(`Cannot setup enableIf listeners: formRoot is null`);
7298
+ return;
7299
+ }
7300
+ const condition = element.enableIf;
7301
+ const scope = (_a = condition.scope) != null ? _a : "relative";
7302
+ const dependencyKey = condition.key;
7303
+ let dependencyFieldPath;
4974
7304
  if (scope === "relative" && ctx.path) {
4975
7305
  dependencyFieldPath = `${ctx.path}.${dependencyKey}`;
4976
7306
  } else {
@@ -5121,6 +7451,12 @@ function dispatchToRenderer(element, ctx, wrapper, pathKey) {
5121
7451
  renderSingleContainerElement(element, ctx, wrapper, pathKey);
5122
7452
  }
5123
7453
  break;
7454
+ case "table":
7455
+ renderTableElement(element, ctx, wrapper, pathKey);
7456
+ break;
7457
+ case "richinput":
7458
+ renderRichInputElement(element, ctx, wrapper, pathKey);
7459
+ break;
5124
7460
  default: {
5125
7461
  const unsupported = document.createElement("div");
5126
7462
  unsupported.className = "text-red-500 text-sm";
@@ -5211,7 +7547,17 @@ var defaultConfig = {
5211
7547
  minFiles: "Minimum {min} files required",
5212
7548
  maxFiles: "Maximum {max} files allowed",
5213
7549
  unsupportedFieldType: "Unsupported field type: {type}",
5214
- invalidOption: "Invalid option"
7550
+ invalidOption: "Invalid option",
7551
+ tableAddRow: "Add row",
7552
+ tableAddColumn: "Add column",
7553
+ tableRemoveRow: "Remove row",
7554
+ tableRemoveColumn: "Remove column",
7555
+ tableMergeCells: "Merge cells (Ctrl+M)",
7556
+ tableSplitCell: "Split cell (Ctrl+Shift+M)",
7557
+ richinputPlaceholder: "Type text...",
7558
+ richinputAttachFile: "Attach file",
7559
+ richinputMention: "Mention",
7560
+ richinputRemoveFile: "Remove"
5215
7561
  },
5216
7562
  ru: {
5217
7563
  // UI texts
@@ -5257,7 +7603,17 @@ var defaultConfig = {
5257
7603
  minFiles: "\u041C\u0438\u043D\u0438\u043C\u0443\u043C {min} \u0444\u0430\u0439\u043B\u043E\u0432",
5258
7604
  maxFiles: "\u041C\u0430\u043A\u0441\u0438\u043C\u0443\u043C {max} \u0444\u0430\u0439\u043B\u043E\u0432",
5259
7605
  unsupportedFieldType: "\u041D\u0435\u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u043C\u044B\u0439 \u0442\u0438\u043F \u043F\u043E\u043B\u044F: {type}",
5260
- invalidOption: "\u041D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"
7606
+ invalidOption: "\u041D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435",
7607
+ tableAddRow: "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u0442\u0440\u043E\u043A\u0443",
7608
+ tableAddColumn: "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u0442\u043E\u043B\u0431\u0435\u0446",
7609
+ tableRemoveRow: "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0442\u0440\u043E\u043A\u0443",
7610
+ tableRemoveColumn: "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0442\u043E\u043B\u0431\u0435\u0446",
7611
+ tableMergeCells: "\u041E\u0431\u044A\u0435\u0434\u0438\u043D\u0438\u0442\u044C \u044F\u0447\u0435\u0439\u043A\u0438 (Ctrl+M)",
7612
+ tableSplitCell: "\u0420\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u044C \u044F\u0447\u0435\u0439\u043A\u0443 (Ctrl+Shift+M)",
7613
+ richinputPlaceholder: "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0442\u0435\u043A\u0441\u0442...",
7614
+ richinputAttachFile: "\u041F\u0440\u0438\u043A\u0440\u0435\u043F\u0438\u0442\u044C \u0444\u0430\u0439\u043B",
7615
+ richinputMention: "\u0423\u043F\u043E\u043C\u044F\u043D\u0443\u0442\u044C",
7616
+ richinputRemoveFile: "\u0423\u0434\u0430\u043B\u0438\u0442\u044C"
5261
7617
  }
5262
7618
  },
5263
7619
  theme: {}
@@ -5531,6 +7887,14 @@ var componentRegistry = {
5531
7887
  // Deprecated type - delegates to container
5532
7888
  validate: validateGroupElement,
5533
7889
  update: updateGroupField
7890
+ },
7891
+ table: {
7892
+ validate: validateTableElement,
7893
+ update: updateTableField
7894
+ },
7895
+ richinput: {
7896
+ validate: validateRichInputElement,
7897
+ update: updateRichInputField
5534
7898
  }
5535
7899
  };
5536
7900
  function getComponentOperations(elementType) {