: asapien/superpulse

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 
// Browser regression check (Node 22+, no npm dependencies).
// Start Chrome with --headless --remote-debugging-port=9333 --user-data-dir=/tmp/logs-scroll-test
// Then: node tests/scroll.test.mjs
// Requires CDN access for Chart.js, or CHART_JS_PATH pointing to a local copy.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';

const root = new URL('../', import.meta.url);
const chart = process.env.CHART_JS_PATH
  ? await readFile(process.env.CHART_JS_PATH)
  : await (await fetch('https://cdn.jsdelivr.net/npm/chart.js')).text();
const rows = Array.from({ length: 160 }, (_, i) => ({
  sndr: i % 2 ? 'complaints' : 'Test',
  sentstamp: 1791500000 - i * 3600,
  mid: 1, cid: 1,
  msg: `Scrolling message ${i} — text must disappear behind sticky headers.`,
}));
const server = createServer(async (req, res) => {
  try {
    const path = req.url.split('?')[0];
    let body;
    if (path === '/chart.js') body = chart;
    else if (path === '/kidang.fcgi') body = JSON.stringify(rows);
    else if (path.startsWith('/api/devices/')) body = JSON.stringify({ name: 'Test device' });
    else body = await readFile(new URL(`.${path === '/' ? '/index.html' : path}`, root));
    if (path === '/') body = body.toString()
      .replace('https://cdn.jsdelivr.net/npm/chart.js', '/chart.js')
      .replace('out/tva-control.js', 'tva-control.js')
      .replace('out/logs.js', 'logs.js');
    res.setHeader('Content-Type', path.endsWith('.css') ? 'text/css'
      : path.endsWith('.js') ? 'text/javascript' : 'text/html');
    res.end(body);
  } catch {
    res.writeHead(404).end();
  }
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const debugging = process.env.CHROME_DEBUG_URL || 'http://127.0.0.1:9333';
let ws, target;
try {
  target = await (await fetch(`${debugging}/json/new?about:blank`, { method: 'PUT' })).json();
  ws = new WebSocket(target.webSocketDebuggerUrl);
  await new Promise(resolve => { ws.onopen = resolve; });
  let sequence = 0;
  const pending = new Map();
  ws.onmessage = event => {
    const message = JSON.parse(event.data);
    pending.get(message.id)?.(message);
    pending.delete(message.id);
  };
  const command = (method, params = {}) => new Promise((resolve, reject) => {
    const id = ++sequence;
    const timeout = setTimeout(() => reject(new Error(`Timed out: ${method}`)), 10000);
    pending.set(id, message => {
      clearTimeout(timeout);
      if (message.error) reject(new Error(JSON.stringify(message.error)));
      else resolve(message.result);
    });
    ws.send(JSON.stringify({ id, method, params }));
  });
  const evaluate = async expression => {
    const response = await command('Runtime.evaluate', { expression, returnByValue: true });
    assert.ok(!response.exceptionDetails, JSON.stringify(response.exceptionDetails));
    return response.result.value;
  };
  const settle = () => new Promise(resolve => setTimeout(resolve, 500));
  const check = async (label, segment = 1) => {
    const state = await evaluate(`(() => {
      const header = document.querySelector('.app-chart-header');
      const tabs = document.querySelector('.mobile-panel-switch');
      const panel = document.querySelector('[data-segment="${segment}"]');
      const filter = panel.querySelector('.log-filter-bar');
      const date = panel.querySelector('.date-divider');
      const h = header.getBoundingClientRect(), t = tabs.getBoundingClientRect();
      const f = filter.getBoundingClientRect(), d = date.getBoundingClientRect();
      const visibleDate = [...panel.querySelectorAll('.date-divider')].reverse()
        .find(el => Math.abs(el.getBoundingClientRect().top - d.top) < 1);
      const barHeight = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--superpulse-sticky-offset'));
      return {
        y: scrollY,
        messagesVisible: Array.from({ length: 12 }, (_, i) =>
          document.elementFromPoint(f.left + 30, d.bottom + 20 + i * 35)
            ?.closest('.msg-list-item')).some(Boolean),
        sticky: [header, filter, date].every(el => getComputedStyle(el).position === 'sticky'),
        aligned: Math.abs(h.top) < 1 && f.top >= barHeight + t.height - 1 && d.top >= f.bottom - 1 && d.top <= f.bottom + 9,
        chartVisible: header.contains(document.elementFromPoint(h.left + 20, 40)),
        filterCoversMessages: filter.contains(document.elementFromPoint(f.right - 10, f.top + 5)),
        dateCoversMessages: !!visibleDate?.contains(document.elementFromPoint(d.right - 10, d.top + 5)),
        opaque: [header, filter, date].every(el => /^rgb\\(/.test(getComputedStyle(el).backgroundColor)),
      };
    })()`);
    assert.ok(state.y > 0, `${label}: not actually scrolled`);
    for (const key of ['messagesVisible', 'sticky', 'aligned', 'chartVisible', 'filterCoversMessages', 'dateCoversMessages', 'opaque'])
      assert.equal(state[key], true, `${label}: ${key}: ${JSON.stringify(state)}`);
    console.log(`PASS ${label}`);
  };
  for (const width of [1280, 390]) {
    await command('Emulation.setDeviceMetricsOverride', { width, height: 850, deviceScaleFactor: 1, mobile: false });
    await command('Page.navigate', { url: `http://127.0.0.1:${server.address().port}/` });
    await settle();
    await settle();
    const boundary = await evaluate(`(() => {
      const tabs = document.querySelector('.mobile-panel-switch');
      const height = tabs.getBoundingClientRect().height;
      return document.querySelector('.segment-container').getBoundingClientRect().top
        - (height ? height + parseFloat(getComputedStyle(tabs).marginBottom) : 0)
        - parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--superpulse-sticky-offset'));
    })()`);
    const sample = async y => {
      await evaluate(`scrollTo(0, ${y})`);
      await settle();
      return evaluate(`(() => {
        const header = document.querySelector('.app-chart-header');
        const panel = document.querySelector('.segment-container');
        const p = panel.getBoundingClientRect();
        return {
          y: scrollY, panelTop: p.top,
          headerHeight: header.getBoundingClientRect().height, minHeight: header.style.minHeight,
          messageTop: document.querySelector('#data-list .msg-list-item').getBoundingClientRect().top,
          graphHeight: document.querySelector('#tvaReactiveChart').getBoundingClientRect().height,
          bar: !!header.querySelector('.tva-pulse-bar'),
          messagesVisible: Array.from({ length: 12 }, (_, i) =>
            document.elementFromPoint(p.left + 30, 250 + i * 45)
              ?.closest('.msg-list-item')).some(Boolean),
          panelCoversGraph: panel.contains(document.elementFromPoint(p.left + 20, p.top + 5)),
        };
      })()`);
    };
    const early = await sample(60);
    await evaluate(`window.stickyStyleWrites = 0;
      window.stickyStyleObserver = new MutationObserver(records => window.stickyStyleWrites += records.length);
      [document.documentElement, ...document.querySelectorAll('.segment')].forEach(el =>
        window.stickyStyleObserver.observe(el, { attributes: true, attributeFilter: ['style'] }));`);
    const middle = await sample(120);
    assert.equal(await evaluate('window.stickyStyleWrites'), 0, 'Ordinary scrolling must not rewrite layer measurements');
    await evaluate('window.stickyStyleObserver.disconnect()');
    assert.ok(!early.bar && !middle.bar, 'Keep PulseGraph during partial coverage');
    assert.equal(early.graphHeight, middle.graphHeight, 'Cover the graph, do not squash it');
    assert.ok(Math.abs(early.panelTop - middle.panelTop - 60) < 1, 'Panel must rise continuously with scroll');
    assert.ok(middle.panelCoversGraph, 'The moving panel must paint over the graph');
    const before = await sample(boundary - 1);
    const after = await sample(boundary + 1);
    assert.ok(after.messagesVisible, `Messages must remain visible after scrolling: ${JSON.stringify(after)}`);
    assert.ok(!before.bar && after.bar, 'Switch to PulseBar only when covered');
    assert.ok(Math.abs(before.messageTop - after.messageTop - 2) < 1, 'Mode switch must not jump the messages');
    assert.ok(Math.abs(after.y - before.y - 2) < 1, 'Mode switch must not jump the scroll position');
    const reverse = await sample(boundary - 1);
    assert.ok(!reverse.bar, `Reveal PulseGraph when scrolling back: ${JSON.stringify({ boundary, before, after, reverse })}`);
    assert.ok(Math.abs(reverse.messageTop - before.messageTop) < 1, 'Reverse handoff must not jump');
    console.log(`PASS ${width}: progressive coverage and reversible handoff`);
    await evaluate('scrollTo(0, 100)');
    await settle();
    await check(`${width}: PulseGraph`);
    await evaluate("document.querySelector('.tva-pulse-bar-toggle').click()");
    await settle();
    await check(`${width}: manual PulseBar, without another scroll`);
    await evaluate('scrollTo(0, 1200)');
    await settle();
    await check(`${width}: PulseBar scrolled`);
    await evaluate("document.body.classList.replace('logs-light', 'logs-dark')");
    await check(`${width}: dark theme`);
    await command('Emulation.setDeviceMetricsOverride', { width: width + 80, height: 850, deviceScaleFactor: 1, mobile: false });
    await settle();
    await check(`${width}: resized while scrolled`);
    if (width < 800) await evaluate('showMobileSegment(2)');
    await settle();
    await check(`${width}: action panel`, 2);
    await evaluate('scrollTo(0, 0)');
    await settle();
    await evaluate("document.querySelector('.tva-pulse-bar-toggle').click()");
    await settle();
    assert.equal(await evaluate("!!document.querySelector('.tva-pulse-bar')"), false);
    await evaluate('scrollTo(0, 800)');
    await settle();
    assert.equal(await evaluate("!!document.querySelector('.tva-pulse-bar')"), true);
    await check(`${width}: automatic collapse`, width < 800 ? 2 : 1);
    await evaluate("document.querySelector('.tva-pulse-graph-max-toggle').click()");
    await settle();
    await evaluate('scrollTo(0, 900)');
    await settle();
    assert.equal(await evaluate(`(() => {
      const chart = document.querySelector('.tva-pulse-graph-max');
      return !!chart?.contains(document.elementFromPoint(innerWidth / 2, 100));
    })()`), true, 'PulseGraphMax must stay above the covering panel');
    console.log(`PASS ${width}: PulseGraphMax`);
  }
} finally {
  ws?.close();
  if (target) await fetch(`${debugging}/json/close/${target.id}`);
  server.closeAllConnections();
  server.close();
}