function viewMqttTopicBrowser() {
return `
Topic-Browser
${can('manage_sources') ? `
` : ''}
`;
}
function mqttTopicNodes(topics) {
const root = new Map();
for (const topic of topics) {
let children = root;
const parts = topic.topic.split('/');
const levels = parts.length > 48 ? [...parts.slice(0, 47), parts.slice(47).join('/')] : parts;
for (let index = 0; index < levels.length; index++) {
const label = levels[index];
const path = levels.slice(0, index + 1).join('/');
if (!children.has(label)) children.set(label, { label, path, children: new Map(), selectable: [] });
const node = children.get(label);
if (topic.valueType && !topic.pointId) node.selectable.push(topic.topic);
if (index === levels.length - 1) node.topic = topic;
children = node.children;
}
}
return root;
}
function bindMqttTopicBrowser() {
const browser = document.querySelector('#mqtt-topic-browser');
if (!browser) return;
const model = state.mqttBrowser ??= {
filter: '#', snapshot: null, query: '', picked: new Set(), expanded: new Map(), focused: null, message: ''
};
const nodes = browser.querySelector('[data-topic-tree]');
const detail = browser.querySelector('[data-topic-detail]');
const form = browser.querySelector('[data-broker-filter]');
const search = browser.querySelector('[data-topic-search]');
const message = browser.querySelector('[data-mqtt-browser-message]');
const content = browser.querySelector('.mqtt-browser-content');
const status = browser.querySelector('[data-mqtt-browser-status]');
const importButton = browser.querySelector('[data-topic-import]');
const canImport = !!importButton;
let visibleTopics = [];
let visibleBranches = new Map();
let busy = false;
let timer;
let revision = 0;
search.value = model.query;
const token = value => escapeHtml(encodeURIComponent(value));
const importable = topic => topic.valueType && !topic.pointId;
const displayType = type => ({ Boolean: 'Binär', Double: 'Zahl', String: 'Text', Json: 'JSON' }[type] || '—');
function renderLeaf(topic, name) {
return `
${canImport && importable(topic) ? `` : ''}
${escapeHtml(topic.preview)}
${topic.pointId ? 'übernommen' : ''}
`;
}
function renderBranch(branch) {
const opened = model.expanded.get(branch.path) ?? !!model.query;
visibleBranches.set(branch.path, branch.selectable);
return `
${canImport && branch.selectable.length ? `` : ''}
${opened ? `${branch.topic ? `- ${renderLeaf(branch.topic, branch.label)}
` : ''}
${renderNodes(branch.children)}
` : ''}`;
}
function renderNodes(branches) {
return [...branches.values()].map(branch => branch.children.size ? renderBranch(branch) :
`${renderLeaf(branch.topic, branch.label)}`).join('');
}
function renderDetail() {
const topic = model.snapshot?.topics.find(item => item.topic === model.focused);
detail.innerHTML = topic ? `Topic-Details
${escapeHtml(topic.topic)}
- Werttyp
- ${displayType(topic.valueType)}
- Empfangen
- ${statusTime(topic.receivedAtUtc)}
- Retained
- ${topic.retained ? 'Ja' : '—'}
${escapeHtml(topic.preview)}
${topic.pointId ? 'Als externer Datenpunkt angelegt.
' :
canImport && importable(topic) ? '' :
!topic.valueType ? 'Dieser Nachrichtenwert kann nicht als Datenpunkt übernommen werden.
' : ''}`
: 'Ein Topic auswählen, um Wert und Details zu sehen.
';
}
function syncSelection() {
if (!canImport) return;
nodes.querySelectorAll('[data-topic-pick]').forEach(input => {
input.checked = model.picked.has(decodeURIComponent(input.dataset.topicPick));
});
nodes.querySelectorAll('[data-topic-branch-pick]').forEach(input => {
const topics = visibleBranches.get(decodeURIComponent(input.dataset.topicBranchPick));
const count = topics.filter(topic => model.picked.has(topic)).length;
input.checked = count === topics.length;
input.indeterminate = count > 0 && count < topics.length;
});
browser.querySelector('[data-topic-selected]').textContent = `${model.picked.size} ausgewählt`;
importButton.disabled = busy || !model.picked.size;
browser.querySelector('[data-topic-select-all]').disabled = !visibleTopics.some(importable);
browser.querySelector('[data-topic-clear]').disabled = !model.picked.size;
}
function render() {
const snapshot = model.snapshot;
const query = model.query.trim().toLowerCase();
visibleTopics = (snapshot?.topics || []).filter(topic => topic.topic.toLowerCase().includes(query));
content.hidden = !snapshot;
message.textContent = model.message;
status.textContent = snapshot ? `${snapshot.connected ? 'Verbunden' : 'Getrennt'} · ${visibleTopics.length} von ${snapshot.topics.length} Topics` : '';
if (!snapshot) return;
if (!model.message && snapshot.error) message.textContent = snapshot.error;
if (snapshot.limitReached && !message.textContent) message.textContent = '3.000 Topics erreicht. Mit einem Broker-Filter lässt sich der Bereich eingrenzen.';
const scroll = nodes.scrollTop;
const focused = nodes.contains(document.activeElement) ? document.activeElement : null;
const focusAttribute = ['data-topic-item', 'data-topic-branch', 'data-topic-pick', 'data-topic-branch-pick'].find(attribute => focused?.hasAttribute(attribute));
visibleBranches = new Map();
nodes.innerHTML = visibleTopics.length ? `${renderNodes(mqttTopicNodes(visibleTopics))}
` :
`${query ? 'Keine passenden Topics.' : 'Warte auf Retained- oder neue Nachrichten.'}
`;
if (focusAttribute) {
[...nodes.querySelectorAll(`[${focusAttribute}]`)].find(element =>
element.getAttribute(focusAttribute) === focused.getAttribute(focusAttribute))?.focus({ preventScroll: true });
}
nodes.scrollTop = scroll;
if (!detail.contains(document.activeElement)) renderDetail();
syncSelection();
}
function acceptSnapshot(snapshot) {
model.snapshot = snapshot;
const eligible = new Set(snapshot.topics.filter(importable).map(topic => topic.topic));
for (const topic of model.picked) if (!eligible.has(topic)) model.picked.delete(topic);
render();
}
async function refresh() {
clearTimeout(timer);
if (!browser.isConnected || !model.snapshot) return;
if (!busy && !browser.closest('[data-points-panel]')?.hidden) {
const currentRevision = revision;
try {
const snapshot = await api(`/api/mqtt/browser/${model.snapshot.sessionId}`);
if (browser.isConnected && currentRevision === revision) acceptSnapshot(snapshot);
} catch (error) {
if (currentRevision !== revision || !browser.isConnected) return;
model.message = error.message;
render();
return;
}
}
if (browser.isConnected) timer = setTimeout(refresh, 3000);
}
form.addEventListener('submit', async event => {
event.preventDefault();
if (busy) return;
const button = form.querySelector('button');
button.disabled = busy = true;
const currentRevision = ++revision;
clearTimeout(timer);
model.message = 'Broker-Verbindung wird geöffnet …';
render();
try {
const filter = form.elements.filter.value || '#';
const snapshot = await api('/api/mqtt/browser', { method:'POST', body:JSON.stringify({ filter }) });
if (!browser.isConnected || currentRevision !== revision) return;
if (model.snapshot?.sessionId !== snapshot.sessionId) {
model.focused = null;
model.picked.clear();
model.expanded.clear();
}
model.filter = snapshot.filter;
model.message = '';
acceptSnapshot(snapshot);
} catch (error) {
model.snapshot = null;
model.message = error.message;
render();
} finally {
button.disabled = busy = false;
syncSelection();
if (browser.isConnected && model.snapshot) timer = setTimeout(refresh, 3000);
}
});
search.addEventListener('input', () => { model.query = search.value; model.expanded.clear(); render(); });
nodes.addEventListener('click', event => {
const branch = event.target.closest('[data-topic-branch]');
const item = event.target.closest('[data-topic-item]');
if (branch) {
model.expanded.set(decodeURIComponent(branch.dataset.topicBranch), branch.getAttribute('aria-expanded') !== 'true');
render();
} else if (item) {
model.focused = decodeURIComponent(item.dataset.topicItem);
nodes.querySelectorAll('[data-topic-item]').forEach(button => button.setAttribute('aria-pressed', String(button === item)));
renderDetail();
}
});
nodes.addEventListener('change', event => {
const input = event.target;
const selected = input.dataset.topicPick != null ? [decodeURIComponent(input.dataset.topicPick)] :
input.dataset.topicBranchPick != null ? visibleBranches.get(decodeURIComponent(input.dataset.topicBranchPick)) : [];
for (const topic of selected) input.checked ? model.picked.add(topic) : model.picked.delete(topic);
syncSelection();
});
async function importTopics(topics) {
if (!topics.length || busy || !model.snapshot) return;
busy = true;
++revision;
detail.querySelector('[data-topic-import-one]')?.setAttribute('disabled', '');
syncSelection();
try {
const result = await api('/api/mqtt/browser/import', {
method:'POST', body:JSON.stringify({ sessionId: model.snapshot.sessionId, topics })
});
model.message = `${result.created} angelegt · ${result.existing} bereits vorhanden · ${result.unavailable} ohne importierbaren Wert`;
await loadData();
model.snapshot = await api(`/api/mqtt/browser/${model.snapshot.sessionId}`);
if (browser.isConnected) renderView();
} catch (error) {
model.message = error.message;
render();
} finally {
busy = false;
detail.querySelector('[data-topic-import-one]')?.removeAttribute('disabled');
syncSelection();
clearTimeout(timer);
if (browser.isConnected && model.snapshot) timer = setTimeout(refresh, 3000);
}
}
if (canImport) {
browser.querySelector('[data-topic-select-all]').addEventListener('click', () => {
visibleTopics.filter(importable).forEach(topic => model.picked.add(topic.topic));
syncSelection();
});
browser.querySelector('[data-topic-clear]').addEventListener('click', () => { model.picked.clear(); syncSelection(); });
importButton.addEventListener('click', () => importTopics([...model.picked]));
detail.addEventListener('click', event => {
if (event.target.closest('[data-topic-import-one]')) importTopics([model.focused]);
});
}
if (model.snapshot) {
acceptSnapshot(model.snapshot);
timer = setTimeout(refresh, 3000);
} else render();
}