File size: 16,473 Bytes
5e0b58b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/* Brain-5D Operator Experience
 *
 * Presentation and navigation only. This module never issues runtime control
 * commands and never fabricates scientific state. Values shown in the chrome
 * are copied from already-rendered dashboard state or explicitly marked as UI.
 */

const WORKSPACES = {
  overview: { icon: "◫", label: "Overview", group: "System", hint: "Live body, health and readiness" },
  network: { icon: "⌬", label: "Network", group: "Observe", hint: "Dynamics, topology and populations" },
  control: { icon: "▶", label: "Control", group: "Operate", hint: "Runtime, pacing and approvals" },
  research: { icon: "⌕", label: "Research", group: "Evidence", hint: "Experiments, provenance and files" },
  gate: { icon: "✓", label: "Release", group: "Verify", hint: "Scientific gate and release readiness" },
  settings: { icon: "⚙", label: "Settings", group: "Configure", hint: "Runtime-visible configuration" },
  embodiment: { icon: "◈", label: "Embodiment", group: "Embody", hint: "Body, devices and interoception" },
};

const STORAGE = {
  welcome: "brain5d-experience-welcome-dismissed",
  focus: "brain5d-experience-focus",
};

function ensureStylesheet() {
  // The canonical stylesheet imports the experience layer once.
}

function activeWorkspaceName() {
  const section = document.querySelector(".tab-content.active[id^='tab-']");
  return section?.id?.replace("tab-", "") || "overview";
}

function repairWorkspaceActivation(button) {
  const name = button?.dataset.tab;
  if (!name) return;
  requestAnimationFrame(() => {
    const active = document.querySelector(".tab-content.active[id^='tab-']");
    if (active?.id === `tab-${name}`) return;
    document.querySelectorAll(".tab-btn[data-tab]").forEach((item) => {
      item.classList.toggle("active", item === button);
    });
    document.querySelectorAll(".tab-content[id^='tab-']").forEach((tab) => {
      const selected = tab.id === `tab-${name}`;
      tab.classList.toggle("active", selected);
      tab.hidden = !selected;
    });
    document.body.dataset.currentTab = name;
  });
}

function activateWorkspace(name) {
  const button = document.querySelector(`.tab-btn[data-tab="${name}"]`);
  if (!button) return;
  button.click();
  repairWorkspaceActivation(button);
}

function safeText(selector, fallback = "unknown") {
  const value = document.querySelector(selector)?.textContent?.trim();
  return value || fallback;
}

function makeButton(label, action, title = "") {
  const button = document.createElement("button");
  button.type = "button";
  button.className = "experience-icon-button";
  button.dataset.experienceAction = action;
  button.textContent = label;
  if (title) button.title = title;
  return button;
}

function enhanceTopbar() {
  const topbar = document.querySelector(".topbar");
  if (!topbar || topbar.querySelector(".experience-status-cluster")) return;

  const cluster = document.createElement("div");
  cluster.className = "experience-status-cluster";
  cluster.setAttribute("aria-label", "Operator context");
  cluster.innerHTML = `
    <span class="experience-live-dot" aria-hidden="true"></span>
    <span class="experience-status-copy"><small>WORKSPACE</small><strong data-experience-workspace>Overview</strong></span>
    <span class="experience-status-copy"><small>RUNTIME</small><strong data-experience-runtime>unknown</strong></span>
    <span class="experience-status-copy"><small>TICK</small><strong data-experience-tick>—</strong></span>`;

  const right = topbar.querySelector(".topbar-right");
  topbar.insertBefore(cluster, right || null);

  if (right) {
    right.prepend(makeButton("⌘K", "palette", "Command palette (Ctrl/Cmd+K)"));
    right.prepend(makeButton("◎", "focus", "Focus mode (F)"));
  }
}

function enhanceNavigation() {
  document.querySelectorAll(".tab-btn[data-tab]").forEach((button) => {
    const name = button.dataset.tab;
    const meta = WORKSPACES[name];
    if (!meta || button.dataset.experienceEnhanced === "true") return;
    button.dataset.experienceEnhanced = "true";
    button.innerHTML = `<span class="experience-tab-icon" aria-hidden="true">${meta.icon}</span><span class="experience-tab-copy"><strong>${meta.label}</strong><small>${meta.group}</small></span>`;
    button.title = meta.hint;
  });
}

function addWorkspaceRibbons() {
  Object.entries(WORKSPACES).forEach(([name, meta]) => {
    const tab = document.getElementById(`tab-${name}`);
    if (!tab || tab.querySelector(":scope > .experience-ribbon")) return;
    const utility = tab.querySelector(":scope > .dashboard-utility-bar");
    const ribbon = document.createElement("aside");
    ribbon.className = "experience-ribbon";
    ribbon.setAttribute("aria-label", `${meta.label} workspace context`);
    ribbon.innerHTML = `
      <div class="experience-ribbon-copy">
        <span>${meta.group.toUpperCase()} / ${meta.label.toUpperCase()}</span>
        <strong>${meta.hint}</strong>
      </div>
      <div class="experience-ribbon-actions">
        <button type="button" data-experience-action="palette">⌘ Command</button>
        <button type="button" data-experience-action="shortcuts">? Shortcuts</button>
        <button type="button" data-experience-action="focus">◎ Focus</button>
      </div>`;
    if (utility) utility.insertAdjacentElement("afterend", ribbon);
    else tab.prepend(ribbon);
  });
}

function buildWelcome() {
  if (localStorage.getItem(STORAGE.welcome) === "true") return;
  const overview = document.getElementById("tab-overview");
  if (!overview || overview.querySelector(".experience-welcome")) return;

  const panel = document.createElement("section");
  panel.className = "experience-welcome";
  panel.innerHTML = `
    <div class="experience-welcome-copy">
      <span class="experience-eyebrow">OPERATOR ORIENTATION</span>
      <h2>Vom Systemzustand zur belastbaren Evidenz</h2>
      <p>Brain-5D trennt Beobachtung, Eingriff, Experiment und Freigabe. Diese Oberfläche führt entlang derselben Kausalitätskette; sie erzeugt keine Messwerte und ersetzt keine wissenschaftlichen Nachweise.</p>
    </div>
    <div class="experience-welcome-steps">
      <button type="button" data-jump-workspace="overview"><b>01</b><span><strong>Zustand lesen</strong><small>Health, Aktivität, Speicher</small></span></button>
      <button type="button" data-jump-workspace="network"><b>02</b><span><strong>Dynamik prüfen</strong><small>Spikes, Populationen, Topologie</small></span></button>
      <button type="button" data-jump-workspace="control"><b>03</b><span><strong>Gezielt eingreifen</strong><small>Operator-bestätigte Controls</small></span></button>
      <button type="button" data-jump-workspace="research"><b>04</b><span><strong>Evidenz erzeugen</strong><small>Experiment und Provenienz</small></span></button>
      <button type="button" data-jump-workspace="gate"><b>05</b><span><strong>Freigabe prüfen</strong><small>Gate, CI, Reproduzierbarkeit</small></span></button>
    </div>
    <button type="button" class="experience-dismiss" data-experience-action="dismiss-welcome" aria-label="Einführung schließen">×</button>`;

  const header = overview.querySelector(":scope > .overview-command-bar");
  const anchor = overview.querySelector(":scope > .experience-ribbon") || header;
  anchor?.insertAdjacentElement("afterend", panel);
}

function buildPalette() {
  if (document.getElementById("experience-command-palette")) return;
  const dialog = document.createElement("dialog");
  dialog.id = "experience-command-palette";
  dialog.className = "experience-dialog experience-command-palette";
  dialog.innerHTML = `
    <form method="dialog" class="experience-dialog-frame">
      <header><div><span class="experience-eyebrow">COMMAND PALETTE</span><h2>Navigate Brain-5D</h2></div><button value="cancel" aria-label="Close">×</button></header>
      <label class="experience-command-search"><span>⌕</span><input type="search" autocomplete="off" placeholder="Workspace oder Funktion suchen …" data-experience-search></label>
      <div class="experience-command-results" data-experience-results></div>
      <footer><span><kbd>↑</kbd><kbd>↓</kbd> wählen</span><span><kbd>Enter</kbd> öffnen</span><span><kbd>Esc</kbd> schließen</span></footer>
    </form>`;
  document.body.appendChild(dialog);

  const input = dialog.querySelector("[data-experience-search]");
  input.addEventListener("input", () => renderPaletteResults(input.value));
  dialog.addEventListener("keydown", handlePaletteKeys);
  dialog.addEventListener("close", () => { input.value = ""; renderPaletteResults(""); });
  renderPaletteResults("");
}

function commandItems() {
  const workspaceItems = Object.entries(WORKSPACES).map(([id, meta]) => ({
    id: `workspace:${id}`,
    icon: meta.icon,
    label: meta.label,
    meta: `${meta.group} · ${meta.hint}`,
    run: () => activateWorkspace(id),
  }));
  return [
    ...workspaceItems,
    { id: "action:refresh", icon: "↻", label: "Refresh active view", meta: "Read-only UI refresh", run: () => document.querySelector(".tab-content.active [data-dashboard-action='refresh']")?.click() },
    { id: "action:focus", icon: "◎", label: "Toggle focus mode", meta: "Hide secondary chrome", run: toggleFocus },
    { id: "action:shortcuts", icon: "?", label: "Keyboard shortcuts", meta: "Show operator navigation keys", run: openShortcuts },
  ];
}

function renderPaletteResults(query) {
  const root = document.querySelector("[data-experience-results]");
  if (!root) return;
  const needle = query.trim().toLowerCase();
  const items = commandItems().filter((item) => `${item.label} ${item.meta}`.toLowerCase().includes(needle));
  root.innerHTML = "";
  items.forEach((item, index) => {
    const button = document.createElement("button");
    button.type = "button";
    button.className = "experience-command-item";
    button.dataset.commandId = item.id;
    button.dataset.commandIndex = String(index);
    button.innerHTML = `<span class="experience-command-icon">${item.icon}</span><span><strong>${item.label}</strong><small>${item.meta}</small></span><kbd>↵</kbd>`;
    button.addEventListener("click", () => runCommand(item));
    root.appendChild(button);
  });
  root.querySelector("button")?.classList.add("selected");
}

function runCommand(item) {
  document.getElementById("experience-command-palette")?.close();
  item.run();
}

function handlePaletteKeys(event) {
  if (!["ArrowDown", "ArrowUp", "Enter"].includes(event.key)) return;
  const buttons = [...document.querySelectorAll(".experience-command-item")];
  if (!buttons.length) return;
  const current = Math.max(0, buttons.findIndex((button) => button.classList.contains("selected")));
  event.preventDefault();
  if (event.key === "Enter") {
    buttons[current]?.click();
    return;
  }
  buttons[current]?.classList.remove("selected");
  const delta = event.key === "ArrowDown" ? 1 : -1;
  const next = (current + delta + buttons.length) % buttons.length;
  buttons[next].classList.add("selected");
  buttons[next].scrollIntoView({ block: "nearest" });
}

function buildShortcuts() {
  if (document.getElementById("experience-shortcuts")) return;
  const dialog = document.createElement("dialog");
  dialog.id = "experience-shortcuts";
  dialog.className = "experience-dialog experience-shortcuts";
  dialog.innerHTML = `
    <form method="dialog" class="experience-dialog-frame">
      <header><div><span class="experience-eyebrow">KEYBOARD MAP</span><h2>Operator shortcuts</h2></div><button value="cancel" aria-label="Close">×</button></header>
      <div class="experience-shortcut-grid">
        <div><kbd>Ctrl</kbd><span>+</span><kbd>K</kbd><strong>Command palette</strong></div>
        <div><kbd>?</kbd><strong>Shortcut map</strong></div>
        <div><kbd>F</kbd><strong>Focus mode</strong></div>
        <div><kbd>1</kbd>…<kbd>7</kbd><strong>Workspace wechseln</strong></div>
        <div><kbd>Esc</kbd><strong>Overlay schließen</strong></div>
      </div>
      <p class="experience-integrity-note">Die globalen Shortcuts navigieren ausschließlich in der Oberfläche. Runtime-Aktionen werden nicht automatisch ausgelöst.</p>
    </form>`;
  document.body.appendChild(dialog);
}

function openPalette() {
  const dialog = document.getElementById("experience-command-palette");
  if (!dialog) return;
  dialog.showModal();
  requestAnimationFrame(() => dialog.querySelector("[data-experience-search]")?.focus());
}

function openShortcuts() {
  document.getElementById("experience-shortcuts")?.showModal();
}

function toggleFocus() {
  const enabled = document.body.dataset.experienceFocus !== "true";
  document.body.dataset.experienceFocus = String(enabled);
  localStorage.setItem(STORAGE.focus, String(enabled));
  document.querySelectorAll('[data-experience-action="focus"]').forEach((button) => {
    button.classList.toggle("active", enabled);
  });
}

function syncChrome() {
  const name = activeWorkspaceName();
  const meta = WORKSPACES[name] || WORKSPACES.overview;
  document.querySelectorAll(".experience-status-copy [data-experience-workspace]").forEach((node) => { node.textContent = meta.label; });
  document.querySelectorAll("[data-experience-runtime]").forEach((node) => { node.textContent = safeText("#overview-runtime-status", safeText("#control-workspace-state")); });
  document.querySelectorAll("[data-experience-tick]").forEach((node) => { node.textContent = safeText("#tick", safeText("#control-workspace-tick", "—")); });
  document.body.dataset.experienceWorkspace = name;
}

function enhanceUnknownStates() {
  const markers = ["—", "unknown", "pending", "Waiting for component state", "Keine Live-Verbindung."];
  document.querySelectorAll(".tab-content strong, .tab-content .overview-empty, .tab-content .heatmap-meta").forEach((node) => {
    const text = node.textContent?.trim();
    if (!markers.includes(text)) return;
    node.classList.add("experience-unknown-state");
    if (!node.title) node.title = "Noch kein beobachteter Wert verfügbar";
  });
}

function bindActions() {
  document.addEventListener("click", (event) => {
    const jump = event.target.closest("[data-jump-workspace]");
    if (jump) activateWorkspace(jump.dataset.jumpWorkspace);

    const action = event.target.closest("[data-experience-action]")?.dataset.experienceAction;
    if (!action) return;
    if (action === "palette") openPalette();
    if (action === "shortcuts") openShortcuts();
    if (action === "focus") toggleFocus();
    if (action === "dismiss-welcome") {
      localStorage.setItem(STORAGE.welcome, "true");
      document.querySelector(".experience-welcome")?.remove();
    }
  });

  document.addEventListener("keydown", (event) => {
    const tag = event.target?.tagName?.toLowerCase();
    const typing = tag === "input" || tag === "textarea" || tag === "select" || event.target?.isContentEditable;
    if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") {
      event.preventDefault();
      openPalette();
      return;
    }
    if (typing) return;
    if (event.key === "?") openShortcuts();
    if (event.key.toLowerCase() === "f") toggleFocus();
    if (/^[1-7]$/.test(event.key)) activateWorkspace(Object.keys(WORKSPACES)[Number(event.key) - 1]);
  });

  document.querySelectorAll(".tab-btn[data-tab]").forEach((button) => button.addEventListener("click", () => {
    repairWorkspaceActivation(button);
    requestAnimationFrame(syncChrome);
  }));
}

function observeRenderedState() {
  const observer = new MutationObserver(() => {
    syncChrome();
    enhanceUnknownStates();
  });
  ["overview-runtime-status", "tick", "control-workspace-state", "control-workspace-tick"].forEach((id) => {
    const node = document.getElementById(id);
    if (node) observer.observe(node, { childList: true, characterData: true, subtree: true });
  });
}

function restorePreferences() {
  document.body.dataset.experienceFocus = localStorage.getItem(STORAGE.focus) === "true" ? "true" : "false";
}

function init() {
  ensureStylesheet();
  restorePreferences();
  enhanceTopbar();
  enhanceNavigation();
  addWorkspaceRibbons();
  buildWelcome();
  buildPalette();
  buildShortcuts();
  bindActions();
  observeRenderedState();
  syncChrome();
  enhanceUnknownStates();
  document.body.classList.add("experience-ready");
}

ensureStylesheet();
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init, { once: true });
else init();