Files
Assetmanager/app/static/js/mesh-path-picker.js
T
RolandandClaude Opus 5.5 d6de4d9878 Version 0.5.5.95: pick MeshCentral source paths from device JSON
- 🔍 button next to every mapping source path (table and new-mapping
  form) opens a dialog with the stored MeshCentral JSON of a chosen
  asset as an expandable, searchable tree; already mapped paths are
  marked, keys the path syntax cannot express are greyed out, list
  entries produce "list[].key".
- Preview evaluates the path with the row's transformation, multiple
  value mode, separator and "value if empty"/guard using the sync code.
- Coverage check across all assets with stored JSON: devices with a
  value, devices where the mapping writes a value (incl. fallbacks)
  and the most frequent results.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:41:02 +01:00

478 lines
20 KiB
JavaScript

(() => {
// v0.5.5.95: choose a MeshCentral source path by clicking into the stored
// device JSON of an asset. The generated path uses the same syntax as the
// sync (dotted keys, "[]" for all list elements).
const root = document.querySelector('[data-mesh-path-picker]');
const dialog = document.getElementById('mesh-path-picker-dialog');
if (!root || !dialog) return;
const urls = {
assets: root.dataset.assetsUrl,
source: root.dataset.sourceUrl,
preview: root.dataset.previewUrl,
coverage: root.dataset.coverageUrl
};
const label = key => root.dataset[key] || '';
const storageKey = 'assetmanager:mesh-path-picker:asset';
const MAX_CHILDREN = 60;
const MAX_MATCHES = 200;
const els = {
assetSearch: dialog.querySelector('[data-picker-asset-search]'),
assetSelect: dialog.querySelector('[data-picker-asset-select]'),
assetInfo: dialog.querySelector('[data-picker-asset-info]'),
treeSearch: dialog.querySelector('[data-picker-tree-search]'),
tree: dialog.querySelector('[data-picker-tree]'),
path: dialog.querySelector('[data-picker-path]'),
preview: dialog.querySelector('[data-picker-preview]'),
coverageButton: dialog.querySelector('[data-picker-coverage-button]'),
coverage: dialog.querySelector('[data-picker-coverage]'),
apply: dialog.querySelector('[data-picker-apply]'),
cancel: dialog.querySelector('[data-picker-cancel]')
};
let target = null; // { input, settings() }
let sourceData = null;
let mappedPaths = new Set();
let currentAssetId = null;
let selectedRow = null;
let previewTimer = null;
let searchTimer = null;
let assetTimer = null;
const isContainer = value => value !== null && typeof value === 'object';
// Keys the path syntax cannot express: "." and "|" separate parts/alternatives,
// a trailing "[]" would be read as list expansion.
const expressibleKey = key => key !== '' && !/[.|]/.test(key) && !key.endsWith('[]') && key.trim() === key;
function childPath(parentPath, key) {
return parentPath ? `${parentPath}.${key}` : key;
}
function preview(value) {
if (value === null) return 'null';
if (Array.isArray(value)) return `[${value.length}]`;
if (typeof value === 'object') return `{${Object.keys(value).length}}`;
const text = typeof value === 'string' ? `"${value}"` : String(value);
return text.length > 140 ? `${text.slice(0, 140)}…` : text;
}
async function getJson(url) {
const response = await fetch(url, { cache: 'no-store', headers: { 'X-Requested-With': 'AssetManagerPathPicker' } });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
async function postJson(url, body) {
const response = await fetch(url, {
method: 'POST',
cache: 'no-store',
headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'AssetManagerPathPicker' },
body: JSON.stringify(body)
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
// --- mapping settings of the row / form the dialog was opened from --------
function settingsFor(input) {
const row = input.closest('tr');
if (row && input.name.startsWith('mapping_')) {
const prefix = input.name.replace(/source_path$/, '');
const field = name => row.querySelector(`[name="${prefix}${name}"]`)?.value ?? '';
return () => ({
transform: field('transform'), multi_value_mode: field('multi_value_mode'), separator: field('separator'),
empty_value: field('empty_value'), empty_value_guard: field('empty_value_guard')
});
}
const form = input.form;
const field = name => form?.elements.namedItem(name)?.value ?? '';
return () => ({
transform: field('transform'), multi_value_mode: field('multi_value_mode'), separator: field('separator'),
empty_value: field('empty_value'), empty_value_guard: field('empty_value_guard')
});
}
// --- tree ------------------------------------------------------------------
function makeRow({ key, value, path, expressible, depth, isListElement }) {
const row = document.createElement('div');
row.className = 'picker-node';
row.style.setProperty('--depth', String(depth));
const toggle = document.createElement('button');
toggle.type = 'button';
toggle.className = 'picker-toggle';
toggle.textContent = isContainer(value) && (Array.isArray(value) ? value.length : Object.keys(value).length) ? '▸' : '';
toggle.tabIndex = -1;
const name = document.createElement('span');
name.className = 'picker-key';
name.textContent = isListElement ? `[${key}]` : key;
const info = document.createElement('span');
info.className = isContainer(value) ? 'picker-meta' : 'picker-value';
info.textContent = preview(value);
row.append(toggle, name, info);
if (expressible && path && mappedPaths.has(path)) {
const badge = document.createElement('span');
badge.className = 'picker-mapped';
badge.textContent = label('mappedLabel') || 'mapped';
row.appendChild(badge);
}
if (!expressible) {
row.classList.add('is-unavailable');
row.title = label('unavailableHint');
} else {
row.dataset.path = path;
row.tabIndex = 0;
row.title = path;
}
let children = null;
const expand = () => {
if (!isContainer(value)) return;
if (children) {
children.hidden = !children.hidden;
toggle.textContent = children.hidden ? '▸' : '▾';
return;
}
children = document.createElement('div');
children.className = 'picker-children';
renderChildren(children, value, path, expressible, depth + 1);
row.after(children);
toggle.textContent = '▾';
};
toggle.addEventListener('click', event => { event.stopPropagation(); expand(); });
row.addEventListener('click', () => {
if (expressible) select(row, path);
if (isContainer(value) && !children) expand();
});
row.addEventListener('keydown', event => {
if (event.key === 'Enter') { event.preventDefault(); row.click(); }
if (event.key === 'ArrowRight' && isContainer(value) && (!children || children.hidden)) expand();
if (event.key === 'ArrowLeft' && children && !children.hidden) expand();
});
return row;
}
function renderChildren(container, value, path, expressible, depth, offset = 0) {
if (Array.isArray(value)) {
// All elements share one path: "list[]" addresses every element.
const elementPath = path ? `${path}[]` : '';
const elementExpressible = expressible && Boolean(path) && !path.endsWith('[]');
value.slice(offset, offset + MAX_CHILDREN).forEach((item, index) => {
container.appendChild(makeRow({ key: offset + index, value: item, path: elementPath, expressible: elementExpressible, depth, isListElement: true }));
});
if (value.length > offset + MAX_CHILDREN) addMore(container, value, path, expressible, depth, offset + MAX_CHILDREN, value.length);
return;
}
const keys = Object.keys(value);
keys.slice(offset, offset + MAX_CHILDREN).forEach(key => {
const ok = expressible && expressibleKey(key);
container.appendChild(makeRow({ key, value: value[key], path: ok ? childPath(path, key) : '', expressible: ok, depth }));
});
if (keys.length > offset + MAX_CHILDREN) addMore(container, value, path, expressible, depth, offset + MAX_CHILDREN, keys.length);
}
function addMore(container, value, path, expressible, depth, offset, total) {
const more = document.createElement('button');
more.type = 'button';
more.className = 'button button-secondary button-small picker-more';
more.style.setProperty('--depth', String(depth));
more.textContent = (label('moreLabel') || 'Show {count} more').replace('{count}', String(total - offset));
more.addEventListener('click', () => {
more.remove();
renderChildren(container, value, path, expressible, depth, offset);
});
container.appendChild(more);
}
function renderTree() {
els.tree.replaceChildren();
if (!isContainer(sourceData)) return;
renderChildren(els.tree, sourceData, '', true, 0);
}
// Flat result list for the search: key or scalar value matches.
function renderSearch(term) {
const needle = term.toLocaleLowerCase();
const matches = [];
const walk = (value, path, expressible, keyLabel, depth) => {
if (matches.length >= MAX_MATCHES || depth > 40) return;
const keyHit = keyLabel && String(keyLabel).toLocaleLowerCase().includes(needle);
const valueHit = !isContainer(value) && value !== null && String(value).toLocaleLowerCase().includes(needle);
if ((keyHit || valueHit) && path) matches.push({ path, value, expressible });
if (!isContainer(value)) return;
if (Array.isArray(value)) {
const ok = expressible && Boolean(path) && !path.endsWith('[]');
value.forEach(item => walk(item, path ? `${path}[]` : '', ok, '', depth + 1));
} else {
Object.keys(value).forEach(key => {
const ok = expressible && expressibleKey(key);
walk(value[key], ok ? childPath(path, key) : (path ? `${path}.${key}` : key), ok, key, depth + 1);
});
}
};
walk(sourceData, '', true, '', 0);
els.tree.replaceChildren();
if (!matches.length) {
const empty = document.createElement('p');
empty.className = 'muted';
empty.textContent = label('noMatches') || 'No matches.';
els.tree.appendChild(empty);
return;
}
matches.forEach(match => {
const row = document.createElement('div');
row.className = 'picker-node picker-match';
const path = document.createElement('code');
path.textContent = match.path;
const value = document.createElement('span');
value.className = isContainer(match.value) ? 'picker-meta' : 'picker-value';
value.textContent = preview(match.value);
row.append(path, value);
if (match.expressible) {
row.dataset.path = match.path;
row.tabIndex = 0;
if (mappedPaths.has(match.path)) {
const badge = document.createElement('span');
badge.className = 'picker-mapped';
badge.textContent = label('mappedLabel') || 'mapped';
row.appendChild(badge);
}
row.addEventListener('click', () => select(row, match.path));
row.addEventListener('keydown', event => { if (event.key === 'Enter') select(row, match.path); });
} else {
row.classList.add('is-unavailable');
row.title = label('unavailableHint');
}
els.tree.appendChild(row);
});
if (matches.length >= MAX_MATCHES) {
const note = document.createElement('p');
note.className = 'muted';
note.textContent = (label('matchesLimited') || 'Only the first {count} matches are shown.').replace('{count}', String(MAX_MATCHES));
els.tree.appendChild(note);
}
}
function select(row, path) {
selectedRow?.classList.remove('is-selected');
selectedRow = row;
row.classList.add('is-selected');
els.path.value = path;
schedulePreview(0);
}
// --- preview / coverage ------------------------------------------------------
function requestBody() {
return { asset_id: currentAssetId, source_path: els.path.value.trim(), ...(target?.settings() || {}) };
}
function schedulePreview(delay = 300) {
window.clearTimeout(previewTimer);
els.coverage.replaceChildren();
els.apply.disabled = !els.path.value.trim();
previewTimer = window.setTimeout(runPreview, delay);
}
async function runPreview() {
const body = requestBody();
if (!body.source_path || !currentAssetId) { els.preview.replaceChildren(); return; }
els.preview.textContent = label('loading') || '…';
try {
const data = await postJson(urls.preview, body);
els.preview.replaceChildren();
const values = document.createElement('div');
const valuesLabel = document.createElement('strong');
valuesLabel.textContent = `${(label('valuesLabel') || 'Values on this device ({count})').replace('{count}', String(data.value_count))}: `;
const valuesText = document.createElement('span');
valuesText.className = 'picker-value';
valuesText.textContent = data.values.length ? data.values.join(' | ') : (label('noValue') || '—');
values.append(valuesLabel, valuesText);
const result = document.createElement('div');
const resultLabel = document.createElement('strong');
resultLabel.textContent = `${label('resultLabel') || 'Result with these mapping settings'}: `;
const resultText = document.createElement('code');
resultText.textContent = data.has_result ? data.result : (label('noResult') || '(no value, field is not written)');
result.append(resultLabel, resultText);
els.preview.append(values, result);
if (data.fallback_used) {
const note = document.createElement('div');
note.className = 'muted';
note.textContent = label('fallbackNote') || 'The source is empty; the "value if empty" is used.';
els.preview.appendChild(note);
}
} catch (error) {
els.preview.textContent = label('previewError') || 'The preview could not be calculated.';
}
}
async function runCoverage() {
const body = requestBody();
if (!body.source_path) return;
els.coverageButton.disabled = true;
els.coverage.textContent = label('loading') || '…';
try {
const data = await postJson(urls.coverage, body);
els.coverage.replaceChildren();
const summary = document.createElement('p');
summary.textContent = (label('coverageSummary') || 'Value present on {with} of {total} devices; the mapping writes a value on {result} devices.')
.replace('{with}', String(data.with_source))
.replace('{total}', String(data.total))
.replace('{result}', String(data.with_result));
els.coverage.appendChild(summary);
if (data.fallback) {
const fallback = document.createElement('p');
fallback.className = 'muted';
fallback.textContent = (label('coverageFallback') || '{count} of them via "value if empty".').replace('{count}', String(data.fallback));
els.coverage.appendChild(fallback);
}
if (data.top_results.length) {
const list = document.createElement('ul');
list.className = 'compact-list picker-coverage-list';
data.top_results.forEach(item => {
const entry = document.createElement('li');
const code = document.createElement('code');
code.textContent = item.value;
entry.append(code, document.createTextNode(` · ${item.count}`));
list.appendChild(entry);
});
const heading = document.createElement('strong');
heading.textContent = (label('coverageTop') || 'Most frequent results ({count} different)').replace('{count}', String(data.distinct_results));
els.coverage.append(heading, list);
}
} catch (error) {
els.coverage.textContent = label('previewError') || 'The preview could not be calculated.';
} finally {
els.coverageButton.disabled = false;
}
}
// --- assets --------------------------------------------------------------------
async function loadAssets(term = '') {
const url = new URL(urls.assets, window.location.origin);
if (term) url.searchParams.set('q', term);
const data = await getJson(url.toString());
const previous = currentAssetId || Number(window.localStorage.getItem(storageKey) || 0);
els.assetSelect.replaceChildren();
data.assets.forEach(asset => {
const option = document.createElement('option');
option.value = String(asset.id);
option.textContent = asset.name;
els.assetSelect.appendChild(option);
});
if (!data.assets.length) {
const option = document.createElement('option');
option.value = '';
option.textContent = data.total ? (label('noAssetMatch') || 'No matching asset') : (label('noAssets') || 'No asset with stored MeshCentral data yet. Run a sync first.');
els.assetSelect.appendChild(option);
return null;
}
const keep = data.assets.find(asset => asset.id === previous);
els.assetSelect.value = String((keep || data.assets[0]).id);
return Number(els.assetSelect.value);
}
async function loadSource(assetId) {
if (!assetId) {
sourceData = null;
els.tree.replaceChildren();
els.assetInfo.textContent = '';
return;
}
els.tree.textContent = label('loading') || '…';
const url = new URL(urls.source, window.location.origin);
url.searchParams.set('asset_id', String(assetId));
const data = await getJson(url.toString());
currentAssetId = assetId;
window.localStorage.setItem(storageKey, String(assetId));
sourceData = data.data;
mappedPaths = new Set(data.mapped_paths || []);
els.assetInfo.textContent = data.asset.last_sync
? (label('lastSync') || 'Last sync: {time}').replace('{time}', new Date(data.asset.last_sync).toLocaleString())
: '';
selectedRow = null;
if (els.treeSearch.value.trim().length >= 2) renderSearch(els.treeSearch.value.trim());
else renderTree();
if (els.path.value.trim()) schedulePreview(0);
}
// --- open / apply ----------------------------------------------------------------
async function open(input) {
target = { input, settings: settingsFor(input) };
els.path.value = input.value.trim();
els.preview.replaceChildren();
els.coverage.replaceChildren();
els.apply.disabled = !els.path.value;
els.treeSearch.value = '';
if (typeof dialog.showModal === 'function') dialog.showModal(); else dialog.setAttribute('open', '');
try {
const assetId = await loadAssets(els.assetSearch.value.trim());
await loadSource(assetId);
} catch (error) {
els.tree.textContent = label('loadError') || 'The device data could not be loaded.';
}
}
function close() {
if (typeof dialog.close === 'function') dialog.close(); else dialog.removeAttribute('open');
}
els.apply.addEventListener('click', () => {
const path = els.path.value.trim();
if (!target || !path) return;
target.input.value = path;
target.input.dispatchEvent(new Event('input', { bubbles: true }));
target.input.dispatchEvent(new Event('change', { bubbles: true }));
target.input.classList.add('picker-updated');
if (target.input.name.startsWith('mapping_')) {
window.AssetManagerToast?.warning?.(label('saveHint') || 'Path applied. Save the mappings to keep it.');
}
close();
target.input.focus();
});
els.cancel.addEventListener('click', close);
els.coverageButton.addEventListener('click', runCoverage);
els.path.addEventListener('input', () => schedulePreview());
els.assetSelect.addEventListener('change', () => {
loadSource(Number(els.assetSelect.value) || null).catch(() => {
els.tree.textContent = label('loadError') || 'The device data could not be loaded.';
});
});
els.assetSearch.addEventListener('input', () => {
window.clearTimeout(assetTimer);
assetTimer = window.setTimeout(async () => {
try {
const assetId = await loadAssets(els.assetSearch.value.trim());
if (assetId !== currentAssetId) await loadSource(assetId);
} catch (error) {
els.tree.textContent = label('loadError') || 'The device data could not be loaded.';
}
}, 300);
});
els.treeSearch.addEventListener('input', () => {
window.clearTimeout(searchTimer);
searchTimer = window.setTimeout(() => {
const term = els.treeSearch.value.trim();
selectedRow = null;
if (term.length >= 2) renderSearch(term); else renderTree();
}, 250);
});
// A picker button next to every source-path input on the page.
document.querySelectorAll('input.mapping-path, form[action$="/mappings/new"] input[name="source_path"]').forEach(input => {
const button = document.createElement('button');
button.type = 'button';
button.className = 'button button-secondary button-small picker-open';
// Inside the mapping table only the icon fits next to the path field.
const compact = Boolean(input.closest('table'));
button.textContent = compact ? '🔍' : `🔍 ${label('openLabel') || 'From device'}`;
button.title = label('openTitle') || '';
button.setAttribute('aria-label', label('openTitle') || label('openLabel') || 'From device');
if (compact) button.classList.add('picker-open-compact');
button.addEventListener('click', () => open(input));
const wrap = document.createElement('span');
wrap.className = 'picker-input-wrap';
input.replaceWith(wrap);
wrap.append(input, button);
});
})();