: 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 
# CONTEXT.md

Notes on the frontend changes made to this project in a recent session, covering
`index.html`, `logs.css`, and `logs.js`. This is not a full architecture doc —
just a record of what changed and why, so future work (human or AI) doesn't
have to re-derive it from the diff.

## 1. Sticky date dividers

The message list (`#data-list`, and now `#action-list` too) groups messages by
day using a **standalone `<li class="date-divider">`**, not a badge embedded
inside each message row.

- `formatDateBadge(date)` — builds the day/month markup, styled after the
  `#custom-date` `<template>` in `index.html` (kept there as a visual
  reference, not actually cloned at runtime).
- `syncDateDividers(list)` — wipes and rebuilds all `.date-divider` elements
  in a given `<ul>`: walks its `li.msg-list-item` children in DOM order,
  and inserts one divider right before the first message of each new
  calendar day (by `li.dataset.timestamp`).
- CSS: `.date-divider { position: sticky; top: 0; ... }` in `logs.css`.

**Why it's a separate `<li>` and not an embedded badge:** an earlier version
embedded the badge inside each message's flex row and made it
`position: sticky` there. It silently failed to stick — `body` in `style.css`
has `overflow-x: hidden`, which (per the CSS overflow-propagation rule) makes
`body` a scroll-container candidate and put the sticky containing-block
resolution in a bad spot when nested inside a flex item. Promoting the
divider to a **top-level `<li>` sibling** of the message rows sidesteps the
whole problem and is also just the standard pattern for sticky section
headers in a list. Don't re-embed the badge inside message rows.

**Also removed:** an earlier attempt gave `#data-list` its own
`max-height: 75vh; overflow-y: auto` scroll box. That's gone — the list now
scrolls with the page. (A boxed-height list whose content doesn't fill the
box never triggers its own scroll, so the badge just scrolls away with
everything else — that was the actual root cause of "badge doesn't stick"
before the standalone-`<li>` fix above.)

`syncDateDividers(list)` takes the list element as a parameter specifically
so it can run against either `#data-list` or `#action-list`.

## 2. Message rendering: templates + `serverMassage`

The old code had message-type branching (`if (iobDebitMatch) {...} else if
(iobCreditMatch) {...} else {...}`) duplicated across leak-detection,
header-prefix text, and body HTML. That's gone, replaced with a small
template system in `logs.js`:

```
serverMassage(msg, extraRaw)   -> normalizes a raw item into { type, ...fields }
renderMessageBody(data)        -> messageBodyTemplates[data.type](data)
getHeaderLabel(data)           -> reduces a type's own fields to one header string
renderMessageHeader({...})     -> the one common header structure, text injected
createMessageListItem(item)    -> builds one <li> using all of the above
```

### `serverMassage(msg, extraRaw)`

This is **the one function that understands today's raw text `msg` format**.
Everything downstream only ever sees its output — a plain JSON object shaped
differently per type:

- `{ type: "iob-debit", amount, merchant, msg }`
- `{ type: "iob-credit", amount, merchant, msg }`
- `{ type: "sms", msg, sim, otp?, leakage? }` — `otp` / `leakage` keys are
  **only present when actually detected**, not set to `null`/`false`. Don't
  add always-present placeholder fields "for consistency" — the whole point
  is each type only carries what it needs.
- `{ type: "dispatch", status, cargo, vehicleNo, time, invoiceNo, amount }`
  (see §3)

**Important design point:** `msg` is never mutated. All the old inline-text
mutation (wrapping OTP codes in clickable spans *inside* the sentence,
wrapping "LPG leakage" in a red span *inside* the sentence) is gone. Instead,
`serverMassage` extracts those as separate fields (`otp`, `leakage`), and the
`sms` body template renders `msg` as plain escaped text plus separate
elements: `leakageBanner(data.leakage)` above it, `copyableCodeChip(data.otp)`
after it. If a template needs to react to something in the message, extract
it into a field in `serverMassage` — don't regex the raw text again inside a
template.

**Forward path to real JSON from the server:** `serverMassage` first checks
if `msg.trim().startsWith("{")` and, if it parses as JSON with a `type`
field, returns it **as-is**, no further processing:

```js
if (msg.trim().startsWith("{")) {
  try {
    const parsed = JSON.parse(msg);
    if (parsed && typeof parsed === "object" && parsed.type) return parsed;
  } catch (e) { /* not valid JSON, fall through to plain-text parsing */ }
}
```

This means: **when the server starts sending real JSON in `msg` instead of
plain SMS text, no changes are needed here or anywhere else** — it already
takes that path. The `dispatch` type (§3) is already exercised through this
path today (see the sample injector). The iob/otp regex parsing is the
legacy fallback for actual plain-text SMS content and should stay only as
long as the server keeps sending that.

### Templates

`messageBodyTemplates` is a plain object keyed by `type`; each function owns
100% of that type's body markup — nothing outside the template decides how a
body renders. `renderMessageBody` just dispatches:
`messageBodyTemplates[data.type] || messageBodyTemplates.sms`.

`renderMessageHeader({ imgType, sender, headerLabel, timeStr, mid, deviceName })`
is the **one common header** every message type shares (icon, sender, an
optional label, time, device button). Only `getHeaderLabel(data)` varies by
type — it's a tiny switch that says which field on that type's own object
(`merchant`, `sim`, ...) becomes the header's label. Adding a new type that
wants a header label means adding one `case` there, not touching the header
template.

### `createMessageListItem(item)`

Builds one `<li class="msg-list-item">` from a raw `{ sndr, sentstamp, mid,
cid, msg, extra }` item, using `serverMassage` + the header/body templates.
This is shared by:
- `fetchUpdates()` — the real, polling OTP feed into `#data-list`.
- `fetchActionUpdates()` — the real, polling action-required feed into `#action-list` (§3).

Both lists render through the exact same code path. If you add a third
message list, build its items with this same function rather than writing
new markup.

## 3. `#action-list` ("action required" panel) + the `dispatch` type

The right-hand panel used to be a single hand-written `<li>` in `index.html`
with visibly broken inline CSS (`style="/*! display: flex !important; */
align-items: ..."` — the `display: flex` was inside a comment, so it never
applied, which is why the card rendered mangled). That's gone.

- `index.html` now just has `<ul id="action-list" class="sticky-list"></ul>`.
- `messageBodyTemplates.dispatch` renders the status badge, cargo grid,
  details table, and "Acknowledge Invoice" button — same
  body-owns-its-markup pattern as the other types.
- `fetchActionUpdates()` polls `config.endpoint` with `config.actionTable`
  (default: `action`), parses JSON or GT responses, appends/removes rows in
  `#action-list`, and calls `syncDateDividers(list)` so action items get the
  same sticky date-divider treatment as the main list.
- Action polling is wired on `DOMContentLoaded` (not called inline at the
  bottom of the script like `fetchUpdates()`), because `logs.js` is
  `<script src="logs.js">`'d *before* `.content`/`#action-list` exist in the
  DOM. `fetchUpdates()` gets away with running immediately only because its
  own `await fetch(...)` yields control back until well after the parser has
  moved on; action polling checks for `#action-list` synchronously before its
  fetch, so it starts after the real DOM-ready signal.

**Completed follow-up:** the search input above `#action-list` now has
`id="action-filter-search"` and calls `applyActionFilters()`, which filters
only `#action-list .msg-list-item`. `#action-list` is now populated by
`fetchActionUpdates()`, polling `config.endpoint` with `config.actionTable`
(default: `action`) and rendering through `createMessageListItem()`. The old
hardcoded `renderSampleActionItem()` sample path was removed.

## Quick map of what lives where

| Concern | Function(s) | File |
|---|---|---|
| Raw msg -> typed data | `serverMassage` | `logs.js` |
| Body markup per type | `messageBodyTemplates`, `renderMessageBody` | `logs.js` |
| Common header | `renderMessageHeader`, `getHeaderLabel` | `logs.js` |
| Build one `<li>` | `createMessageListItem` | `logs.js` |
| OTP feed polling | `fetchUpdates` | `logs.js` |
| Action-required polling | `fetchActionUpdates` | `logs.js` |
| Date grouping | `formatDateBadge`, `syncDateDividers` | `logs.js` |
| Divider sticky styling | `.date-divider` | `logs.css` |
| Leak/OTP chip styling | `.leakage-alert`, `.copyable-code` (inline) | `logs.css` / `logs.js` |