// ── Per-Field Toggle Bulk Edit Modal ──
function showBulkEditFieldModal(path, colsStr) {
const cols = colsStr.split(",");
const modes = [
{ v: "set", l: "Set Value" }, { v: "pattern", l: "Pattern {i}" },
{ v: "sequence", l: "Sequence" }, { v: "find_replace", l: "Find & Replace" },
{ v: "regex", l: "Regex" }, { v: "increment", l: "Increment" },
{ v: "prefix_suffix", l: "Prefix/Suffix" }, { v: "conditional", l: "Conditional" }
];
const modeOpts = modes.map(m => `${m.l} `).join("");
const colOpts = cols.map(c => `${c} `).join("");
let fieldsHtml = cols.map(c => `
Mode ${modeOpts}
Type String Number
`).join("");
const overlay = document.createElement("div");
overlay.className = "modal-overlay";
overlay.innerHTML = ` Per-Field Bulk Edit
Toggle switches ON for fields you want to edit. Each field gets its own mode and settings.
Placeholders: {i} counter · {idx} index · {total} total · {value} current · {field_name} other field
${fieldsHtml}
Cancel Apply Changes
`;
document.body.appendChild(overlay);
overlay.querySelector("#mdCancel").onclick = () => overlay.remove();
overlay.addEventListener("click", e => { if (e.target === overlay) overlay.remove(); });
overlay.querySelector("#mdConfirm").onclick = async () => {
const fields = {};
cols.forEach(c => {
const el = document.getElementById("fc_" + c);
const chk = el.querySelector("input[type=checkbox]");
if (!chk.checked) return;
const mode = document.getElementById("fc_mode_" + c).value;
const cfg = { enabled: true, mode, value_type: document.getElementById("fc_type_" + c).value };
if (mode === "set") cfg.new_value = document.getElementById("fc_val_" + c).value;
else if (mode === "pattern") { cfg.new_value = document.getElementById("fc_pat_" + c).value; cfg.start_counter = document.getElementById("fc_patstart_" + c).value; }
else if (mode === "sequence") cfg.start_counter = document.getElementById("fc_seqstart_" + c).value;
else if (mode === "find_replace") { cfg.find_text = document.getElementById("fc_find_" + c).value; cfg.replace_text = document.getElementById("fc_repl_" + c).value; }
else if (mode === "regex") { cfg.find_text = document.getElementById("fc_rxfind_" + c).value; cfg.replace_text = document.getElementById("fc_rxrepl_" + c).value; cfg.start_counter = document.getElementById("fc_rxstart_" + c).value; }
else if (mode === "increment") cfg.increment_by = document.getElementById("fc_inc_" + c).value;
else if (mode === "prefix_suffix") { cfg.prefix = document.getElementById("fc_pfx_" + c).value; cfg.suffix = document.getElementById("fc_sfx_" + c).value; }
else if (mode === "conditional") { cfg.condition_field = document.getElementById("fc_condfield_" + c).value; cfg.condition_op = document.getElementById("fc_condop_" + c).value; cfg.condition_value = document.getElementById("fc_condval_" + c).value; cfg.new_value = document.getElementById("fc_condnew_" + c).value; cfg.start_counter = document.getElementById("fc_condstart_" + c).value; }
fields[c] = cfg;
});
if (Object.keys(fields).length === 0) { toast("Enable at least one field", "error"); return; }
const r = await api("/bulk/edit_multi_field", { path, fields });
if (r.success) { loadNode(path); toast(`Edited ${r.modified} items`); overlay.remove(); }
else toast(r.error, "error");
};
}
function toggleFieldConfig(field, checked) {
const el = document.getElementById("fc_" + field);
if (checked) { el.classList.add("active"); el.querySelector(".field-badge").textContent = "editing"; el.querySelector(".field-badge").style.color = "var(--success)"; }
else { el.classList.remove("active"); el.querySelector(".field-badge").textContent = "unchanged"; el.querySelector(".field-badge").style.color = ""; }
}
function updateFieldModeUI(field) {
const mode = document.getElementById("fc_mode_" + field).value;
const allModes = ["set", "pattern", "sequence", "find_replace", "regex", "increment", "prefix_suffix", "conditional"];
allModes.forEach(m => { const el = document.getElementById("fc_" + m + "_" + field); if (el) el.style.display = m === mode ? "block" : "none"; });
}
// ── Edit Item Modal ──
function editItemModal(path, idx) {
api("/node/get", { path }).then(data => {
if (!data.items) return;
const item = data.items[idx], cols = data.columns || Object.keys(item);
let fields = cols.map(c => `${c} `).join("");
showModal(`Edit Item #${idx}`, fields, async () => {
const newItem = {}; cols.forEach(c => newItem[c] = document.getElementById(`mdEI_${c}`).value);
const r = await api("/node/edit_item", { path, index: idx, item: newItem });
if (r.success) { loadNode(path); toast("Updated"); } else toast(r.error, "error");
});
});
}
// ── Multi-Category Add Field + Append Modal ──
let _mcFieldCounter = 0;
async function showMultiCatAddFieldModal() {
const discovery = await api("/discover_arrays", {});
if (!discovery.success) { toast("No data loaded", "error"); return; }
const catTree = discovery.category_tree || [];
const allArrays = discovery.arrays || [];
if (allArrays.length === 0) { toast("No arrays found in JSON", "error"); return; }
_mcFieldCounter = 0;
function buildCatTreeHtml(nodes, indent) {
let h = "";
for (const n of nodes) {
const isArr = n.is_array === true;
const pad = indent * 18;
const icon = isArr ? "fa-layer-group text-info" : "fa-folder text-warning";
const badge = isArr ? `${n.count} ` : "";
const fields = (n.sample_fields || []).length ? `[${n.sample_fields.slice(0,3).join(", ")}${n.sample_fields.length>3?"...":""}] ` : "";
if (isArr) {
h += `
${n.key} ${badge}${fields}
`;
} else {
h += `
${n.key}
`;
}
if (n.children && n.children.length > 0) {
h += `${buildCatTreeHtml(n.children, indent + 1)}
`;
}
}
return h;
}
const treeHtml = buildCatTreeHtml(catTree, 0);
const overlay = document.createElement("div");
overlay.className = "modal-overlay";
overlay.innerHTML = `
Multi-Category Add Field + Append
Select categories/subcategories to target, define fields to add/modify, then optionally append new items.
Placeholders: {i} counter · {idx} index · {total} total
TARGET CATEGORIES
0 arrays selected
FIELDS TO ADD/MODIFY
Add Field
Cancel
Apply to Selected Targets
`;
document.body.appendChild(overlay);
overlay.querySelector("#mcAppendToggle").onchange = function() {
overlay.querySelector("#mcAppendOpts").style.display = this.checked ? "block" : "none";
};
overlay.addEventListener("change", () => {
const count = overlay.querySelectorAll(".mc-target:checked").length;
overlay.querySelector("#mcSelectedCount").textContent = count;
});
addMcField();
overlay.querySelector("#mcCancel").onclick = () => overlay.remove();
overlay.addEventListener("click", e => { if (e.target === overlay) overlay.remove(); });
overlay.querySelector("#mcApply").onclick = async () => {
const targetPaths = [];
overlay.querySelectorAll(".mc-target:checked").forEach(cb => targetPaths.push(cb.value));
if (targetPaths.length === 0) { toast("Select at least one target array", "error"); return; }
const fieldRows = document.querySelectorAll(".mc-field-row");
const fieldDefs = [];
for (const row of fieldRows) {
const name = row.querySelector(".mc-f-name").value.trim();
if (!name) continue;
const distMode = row.querySelector(".mc-f-dist").value;
const def = {
name,
type: row.querySelector(".mc-f-type").value,
value: row.querySelector(".mc-f-val").value,
use_pattern: row.querySelector(".mc-f-pattern").checked,
start: parseInt(row.querySelector(".mc-f-start").value || 1),
dist_mode: distMode
};
if (distMode === "random") {
def.dist_rand_primary = row.querySelector(".mc-f-rand-prim").value;
def.dist_rand_secondary = row.querySelector(".mc-f-rand-sec").value;
def.dist_rand_pct = parseInt(row.querySelector(".mc-f-rand-pct").value || 50);
} else if (distMode === "cyclic") {
def.dist_pattern = row.querySelector(".mc-f-cyclic-pat").value;
}
fieldDefs.push(def);
}
if (fieldDefs.length === 0) { toast("Add at least one field", "error"); return; }
const targets = targetPaths.map(p => ({ path: p, fields: fieldDefs }));
const body = { targets };
if (document.getElementById("mcAppendToggle").checked) {
body.append_items = true;
body.append_count = parseInt(document.getElementById("mcAppendCount").value || 0);
}
const r = await api("/bulk/add_field_multi", body);
if (r.success) {
toast(`Modified ${r.modified} fields across ${r.targets} targets` + (r.appended > 0 ? `, appended ${r.appended} items` : ""));
refreshTree(r.tree);
if (currentPath) loadNode(currentPath);
overlay.remove();
} else toast(r.error, "error");
};
}
function addMcField() {
_mcFieldCounter++;
const id = _mcFieldCounter;
const row = document.createElement("div");
row.className = "mc-field-row field-config active";
row.style.cssText = "padding:8px 10px;margin-bottom:6px";
row.innerHTML = `
`;
document.getElementById("mcFieldList").appendChild(row);
}
function toggleMcFieldDist(sel) {
const row = sel.closest(".mc-field-row");
const mode = sel.value;
const optsWrap = row.querySelector(".mc-f-dist-opts");
const randomOpts = row.querySelector(".mc-f-random-opts");
const cyclicOpts = row.querySelector(".mc-f-cyclic-opts");
if (mode === "static") {
optsWrap.style.display = "none";
} else {
optsWrap.style.display = "block";
randomOpts.style.display = mode === "random" ? "block" : "none";
cyclicOpts.style.display = mode === "cyclic" ? "block" : "none";
}
// When using distribution, disable pattern checkbox and value field
const patternCb = row.querySelector(".mc-f-pattern");
const valInput = row.querySelector(".mc-f-val");
if (mode !== "static") {
patternCb.checked = false;
patternCb.disabled = true;
valInput.disabled = true;
valInput.style.opacity = "0.4";
} else {
patternCb.disabled = false;
valInput.disabled = false;
valInput.style.opacity = "1";
}
}
function toggleCatChildren(checkbox) {
const group = checkbox.closest(".cat-tree-item").nextElementSibling;
if (group && group.classList.contains("mc-cat-group")) {
group.querySelectorAll(".mc-target").forEach(cb => cb.checked = checkbox.checked);
}
}
// ── Multi-Category Append Panel ──
let _apFieldCounter = 0;
async function showAppendPanel(path) {
const anal = await api("/analyze_category", { path });
if (!anal.success) return;
const fields = anal.fields, samples = anal.samples, inappOpts = anal.inapp_options;
const discovery = await api("/discover_arrays", {});
const allArrays = discovery.success ? discovery.arrays : [];
const catTree = discovery.success ? (discovery.category_tree || []) : [];
_apFieldCounter = 0;
const wrap = document.getElementById("appendPanelWrap") || document.getElementById("editorArea");
// Build field rows HTML with per-field distribution
let fHtml = "";
fields.forEach((f, fi) => {
_apFieldCounter++;
const fid = _apFieldCounter;
let v = samples[f] || "";
if (f === "coordinates") v = "{line}";
else if (typeof v === "string" && v.includes("http")) v = v.replace(/(\d+)(?=\.\w+$)/, "{i}");
fHtml += _buildAppendFieldRow(fid, f, v, false);
});
// Build hierarchical category tree for multi-target
let catHtml = "";
if (allArrays.length > 1) {
function buildAppendTree(nodes, indent) {
let h = "";
for (const n of nodes) {
const pad = indent * 16;
if (n.is_array) {
h += `
${n.key} ${n.count}
`;
} else {
h += `
${n.key}
`;
}
if (n.children && n.children.length) {
h += `${buildAppendTree(n.children, indent + 1)}
`;
}
}
return h;
}
catHtml = ` TARGET ARRAYS (multi-select)
`;
}
let panelHtml = `
DATA FILE (optional)
COUNT
Generating 0 items
${catHtml}
FIELD PATTERNS — per-field distribution supported
Each field can be: Static (pattern with {i}), Random % (e.g. 70% free / 30% paid), or Cyclic (e.g. free, free, paid).
${fHtml}
Add Column
Preview
`;
if (document.getElementById("appendPanelWrap")) document.getElementById("appendPanelWrap").innerHTML = panelHtml;
else wrap.innerHTML += panelHtml;
// Events
document.getElementById("apDataFile").addEventListener("change", e => {
const reader = new FileReader();
reader.onload = ev => {
const lines = ev.target.result.split("\n").filter(l => l.trim() && !l.startsWith("#"));
document.getElementById("apFileStatus").textContent = lines.length + " lines found";
document.getElementById("apManualCount").value = lines.length;
updateAppendTotal();
};
reader.readAsText(e.target.files[0]);
});
const updateAppendTotal = () => {
const mc = parseInt(document.getElementById("apManualCount").value || 0);
const lim = parseInt(document.getElementById("apLimit").value || 0);
document.getElementById("apTotal").textContent = lim > 0 ? Math.min(mc, lim) : mc;
};
document.getElementById("apManualCount").oninput = updateAppendTotal;
document.getElementById("apLimit").oninput = updateAppendTotal;
updateAppendTotal();
}
function _buildAppendFieldRow(fid, fieldName, defaultPattern, isNew) {
return ``;
}
function addAppendField() {
_apFieldCounter++;
const fid = _apFieldCounter;
const container = document.getElementById("apFieldsContainer");
const tmp = document.createElement("div");
tmp.innerHTML = _buildAppendFieldRow(fid, "new_field", "", true);
container.appendChild(tmp.firstElementChild);
// Focus the name input
const nameInp = container.lastElementChild.querySelector(".ap-f-name");
if (nameInp) { nameInp.value = ""; nameInp.focus(); }
}
function toggleApFieldDist(sel) {
const row = sel.closest(".ap-field-row");
const mode = sel.value;
const wrap = row.querySelector(".ap-f-dist-wrap");
const randomOpts = row.querySelector(".ap-f-random-opts");
const cyclicOpts = row.querySelector(".ap-f-cyclic-opts");
const patternInput = row.querySelector(".ap-f-pattern");
if (mode === "static") {
wrap.style.display = "none";
patternInput.disabled = false;
patternInput.style.opacity = "1";
} else {
wrap.style.display = "block";
randomOpts.style.display = mode === "random" ? "block" : "none";
cyclicOpts.style.display = mode === "cyclic" ? "block" : "none";
patternInput.disabled = true;
patternInput.style.opacity = "0.4";
}
}
function toggleAllTargets(checked) {
document.querySelectorAll(".ap-target").forEach(cb => cb.checked = checked);
}
async function doPreviewAppend(path) {
const fd = new FormData();
const cf = document.getElementById("apDataFile").files[0];
if (cf) fd.append("data_file", cf);
const mc = parseInt(document.getElementById("apManualCount").value || 10);
const lim = parseInt(document.getElementById("apLimit").value || 0);
fd.append("manual_count", mc);
fd.append("limit_count", lim > 0 ? Math.min(mc, lim) : mc);
// Collect field order, patterns, starts, and per-field distributions
const fieldRows = document.querySelectorAll("#apFieldsContainer .ap-field-row");
const fieldOrder = [];
const fieldDistributions = {};
fieldRows.forEach(row => {
const nameEl = row.querySelector(".ap-f-name");
const fieldName = nameEl ? nameEl.value.trim() : row.dataset.field;
if (!fieldName) return;
// Update name attributes on dynamic fields
const patInput = row.querySelector(".ap-f-pattern");
const startInput = row.querySelector(".ap-f-start");
if (patInput) patInput.name = `pattern_${fieldName}`;
if (startInput) startInput.name = `start_${fieldName}`;
fieldOrder.push(fieldName);
fd.append(`pattern_${fieldName}`, patInput ? patInput.value : "");
fd.append(`start_${fieldName}`, startInput ? startInput.value : "1");
const distMode = row.querySelector(".ap-f-dist").value;
if (distMode !== "static") {
const distEntry = { mode: distMode };
if (distMode === "random") {
distEntry.rand_primary = row.querySelector(".ap-f-rand-prim").value;
distEntry.rand_secondary = row.querySelector(".ap-f-rand-sec").value;
distEntry.rand_pct = parseInt(row.querySelector(".ap-f-rand-pct").value || 50);
} else if (distMode === "cyclic") {
distEntry.pattern = row.querySelector(".ap-f-cyclic-pat").value;
}
fieldDistributions[fieldName] = distEntry;
}
});
fd.append("field_order", fieldOrder.join(","));
fd.append("field_distributions", JSON.stringify(fieldDistributions));
// No longer need legacy dist fields — per-field handles it all
fd.append("dist_field", "");
fd.append("dist_mode", "static");
const r = await api("/preview_append", fd, true);
if (r.success) {
previewData = r.preview;
document.getElementById("apPreviewWrap").style.display = "block";
document.getElementById("apPreviewJSON").textContent = JSON.stringify(r.preview.slice(0, 5), null, 2) + (r.total_count > 5 ? "\n..." : "");
document.getElementById("apPreviewCount").textContent = r.total_count;
if (r.file_lines) document.getElementById("apFileStatus").textContent = r.file_lines + " lines loaded";
} else toast(r.error, "error");
}
async function doCommitAppend(path) {
const targets = [];
document.querySelectorAll(".ap-target:checked").forEach(cb => targets.push(cb.value));
if (targets.length === 0) targets.push(path);
const r = await api("/commit_append", { path, target_paths: targets, items: previewData });
if (r.success) {
toast(`Appended ${r.count} items to ${r.targets} target(s)!`);
refreshTree(r.tree);
loadNode(path);
const ac = document.getElementById("appendCard");
if (ac) ac.remove();
} else toast(r.error, "error");
}
// ── Raw Editor ──
async function toggleRawEditor() {
rawMode = !rawMode;
if (rawMode) {
const r = await fetch("/raw/get").then(r => r.json());
document.getElementById("rawTextarea").value = r.raw;
document.getElementById("rawEditorArea").classList.remove("d-none");
document.getElementById("editorArea").classList.add("d-none");
document.getElementById("emptyState").style.display = "none";
} else {
const r = await api("/raw/set", { content: document.getElementById("rawTextarea").value });
if (r.success) { refreshTree(r.tree); toast("JSON updated"); }
else { toast(r.error, "error"); return; }
document.getElementById("rawEditorArea").classList.add("d-none");
document.getElementById("editorArea").classList.remove("d-none");
if (currentPath) loadNode(currentPath);
}
}
// ── Search ──
let searchTimeout;
function handleSearch(q) {
clearTimeout(searchTimeout);
if (!q.trim()) { renderTree(treeData); return; }
searchTimeout = setTimeout(async () => {
const r = await api("/search", { query: q });
if (r.results && r.results.length) {
const area = document.getElementById("editorArea");
area.classList.remove("d-none");
document.getElementById("emptyState").style.display = "none";
let html = ``;
r.results.forEach(res => {
html += `
${res.match_type}
${res.path}
${res.preview}
`;
});
html += "
";
area.innerHTML = html;
}
}, 300);
}
// ── Modal System ──
function showModal(title, bodyHtml, onConfirm) {
const overlay = document.createElement("div");
overlay.className = "modal-overlay";
overlay.innerHTML = ` ${title}${bodyHtml}
Cancel Confirm
`;
document.body.appendChild(overlay);
overlay.querySelector("#mdCancel").onclick = () => overlay.remove();
overlay.querySelector("#mdConfirm").onclick = async () => { await onConfirm(); overlay.remove(); };
overlay.addEventListener("click", e => { if (e.target === overlay) overlay.remove(); });
setTimeout(() => { const inp = overlay.querySelector("input:not([type=hidden]):not([type=checkbox])"); if (inp) inp.focus(); }, 50);
}
function renameFieldInline(el, path, key) {
const orig = el.textContent;
el.contentEditable = true; el.focus();
const sel = window.getSelection(); sel.selectAllChildren(el);
el.onblur = async () => {
el.contentEditable = false;
if (el.textContent !== orig) {
const r = await api("/node/rename", { path: path + "/" + key, new_name: el.textContent });
if (r.success) { refreshTree(r.tree); loadNode(path); toast("Renamed"); }
else { el.textContent = orig; toast(r.error, "error"); }
}
};
el.onkeydown = e => { if (e.key === "Enter") { e.preventDefault(); el.blur(); } if (e.key === "Escape") { el.textContent = orig; el.blur(); } };
}
// ── Keyboard Shortcuts ──
document.addEventListener("keydown", e => {
if ((e.ctrlKey || e.metaKey) && e.key === "z") { e.preventDefault(); doUndo(); }
if ((e.ctrlKey || e.metaKey) && e.key === "y") { e.preventDefault(); doRedo(); }
if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); saveSession(); }
if ((e.ctrlKey || e.metaKey) && e.key === "f") { e.preventDefault(); document.getElementById("searchInput").focus(); }
});