File size: 14,200 Bytes
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
4cfab62
 
 
 
816fa8a
 
 
 
 
 
 
4cfab62
 
 
 
816fa8a
 
 
4cfab62
816fa8a
4cfab62
 
 
 
 
 
 
816fa8a
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
4cfab62
 
 
 
 
816fa8a
4cfab62
 
 
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
// ---------------------------------------------------------------------------
// publish / PublishedView.tsx β€” ⭐⭐ wave-33 item 8b (ruling R5, ticket W33-T26).
//
// The page an ANONYMOUS person lands on at `#/v/<token>`. Shell mounts it BEFORE
// the auth wall, exactly where `FormPublic` is mounted; everything below assumes
// there is no session, no workspace, no nav and no viewer.
//
// β›” IT IMPORTS NOTHING FROM `customer-grid/**`, AND THAT IS A REQUIREMENT RATHER
// THAN A PREFERENCE β€” the same one `FormPublic` carries and for a sharper reason
// here. `customer-grid` drags `glide-data-grid` (hundreds of kilobytes of canvas
// spreadsheet) into whatever chunk touches it, and MapView, CatalogView and
// SwipeView all live in that directory. So this page cannot reuse them, and the
// honest answer is not to import them anyway: it renders its own read-only
// presentation per mode. One convenience import β€” even a type from `types.ts` β€”
// would put the whole spreadsheet engine on a stranger's first, cold, probably
// mobile page load.
//
// β›” AND IT RENDERS NO EDIT AFFORDANCE OF ANY KIND. There is no cell to click, no
// menu, no "open in app". A published link is a READ of a projection, and a
// control that looks actionable on a page with no session is a promise the
// server would refuse.
//
// ⚠ Styling is co-located (`publish.css`, contract C4) because `index.css` is
// B's file this wave. COLOUR is local to that sheet, TYPE uses the product's
// `--lp-fs-*` tokens β€” the sheet's own header carries the argument, and the
// first draft got it wrong in the direction `verify_ui` caught.
// ---------------------------------------------------------------------------

import { useEffect, useState } from "react";
import { Brand } from "../shell/Brand";

import "./publish.css";

/** One column, exactly as `routes_publish._public_view` builds it. */
export interface PubColumn {
  key: string;
  label: string;
  /** The server's own word. Deliberately `string`, not a union β€” an unknown type
   *  renders as text, which is the safe direction; a union would render nothing
   *  at all for a type this page has not heard of. */
  type: string;
  options?: string[];
}

export interface PubRow {
  pid: number;
  /** ⚠ Present ONLY on a map β€” the server ships coordinates for that mode alone,
   *  because they are an address in another form. */
  lat?: number | null;
  lon?: number | null;
  [key: string]: unknown;
}

export interface PubLimit {
  subject: string;
  effect: string;
  detail: string;
  recommendation?: string;
}

export interface PubPage {
  title: string;
  mode: string;
  display: Record<string, string>;
  columns: PubColumn[];
  rows: PubRow[];
  total: number;
  limits?: PubLimit[];
}

type Phase = "loading" | "locked" | "ready" | "gone";

const NUMERIC = new Set(["int", "number", "money", "pct", "rating"]);

function cellText(value: unknown): string {
  if (value === null || value === undefined) return "";
  if (typeof value === "boolean") return value ? "Yes" : "No";
  return String(value);
}

/**
 * A plot of positions β€” equirectangular, fitted to the points, and that is the
 * whole design note.
 *
 * β›” NO TILE LAYER, NO MAP LIBRARY, NO EXTERNAL HOST. A published page is loaded
 * by somebody with no account, so every byte it fetches from a third party is a
 * request WE caused a stranger's browser to make, carrying their IP to a vendor
 * they never chose. Plotting the points the server already sent into an inline
 * SVG costs nothing and asks nobody.
 *
 * ⚠ IT DOES NOT PRETEND TO BE A MAP OF A TERRITORY β€” no coastlines, no
 * graticule, no scale bar. Drawing chrome that implies a basemap we do not have
 * would be a picture making a claim the data does not support.
 */
function MapPlot({ rows, title }: { rows: PubRow[]; title: (r: PubRow) => string }) {
  // β›” `coord` REJECTS null BEFORE `Number()` SEES IT, and that is not defensive noise β€” the
  // first version of this function did `Number(r.lat)` straight, and `Number(null)` is **0**,
  // which is finite and inside Β±90. Every row with no location plotted at the equator, off the
  // west coast of Africa, and the "nothing to plot" message could never render. Caught by this
  // component's own render test on its first run; a source grep could not have seen it, and
  // neither could a screenshot of a table that HAS coordinates.
  const coord = (v: unknown, max: number): number | null => {
    if (v === null || v === undefined || v === "") return null;
    const n = Number(v);
    return Number.isFinite(n) && Math.abs(n) <= max ? n : null;
  };
  const pts = rows
    .map((r) => ({ r, lat: coord(r.lat, 90), lon: coord(r.lon, 180) }))
    .filter((p): p is { r: PubRow; lat: number; lon: number } =>
      p.lat !== null && p.lon !== null);
  if (!pts.length) {
    // ⚠ R6's second sentence, on a page: a map with nothing on it must SAY why,
    // never render an empty rectangle that reads as a broken link.
    return (
      <p className="pubv-note">
        None of these rows carry a location yet, so there is nothing to plot.
      </p>
    );
  }
  // Fit the points, then pad, so a cluster in one city does not render as one dot.
  const lats = pts.map((p) => p.lat);
  const lons = pts.map((p) => p.lon);
  const pad = 0.12;
  const minLat = Math.min(...lats);
  const maxLat = Math.max(...lats);
  const minLon = Math.min(...lons);
  const maxLon = Math.max(...lons);
  const spanLat = Math.max(maxLat - minLat, 0.05);
  const spanLon = Math.max(maxLon - minLon, 0.05);
  const box = { w: 1000, h: 560 };
  const at = (lat: number, lon: number) => ({
    x: (((lon - minLon + spanLon * pad) / (spanLon * (1 + 2 * pad))) * box.w),
    y: ((1 - (lat - minLat + spanLat * pad) / (spanLat * (1 + 2 * pad))) * box.h),
  });
  return (
    <div className="pubv-map">
      <svg viewBox={`0 0 ${box.w} ${box.h}`} role="img" aria-label="Map of the published rows">
        <rect x="0" y="0" width={box.w} height={box.h} className="pubv-map-bg" />
        {pts.map(({ r, lat, lon }) => {
          const p = at(lat, lon);
          return (
            <g key={r.pid}>
              <circle cx={p.x} cy={p.y} r="7" className="pubv-pin" />
              <title>{title(r)}</title>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

export default function PublishedView({ token }: { token: string }) {
  const [page, setPage] = useState<PubPage | null>(null);
  const [phase, setPhase] = useState<Phase>("loading");
  const [passphrase, setPassphrase] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    let live = true;
    setPhase("loading");
    fetch(`/api/v1/published/${encodeURIComponent(token)}`)
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
      .then((data) => {
        if (!live) return;
        // The server's two shapes: `{locked:true}` and nothing else, or the page.
        if (data && data.locked) {
          setPhase("locked");
          return;
        }
        setPage(data as PubPage);
        setPhase("ready");
      })
      // ⚠ ONE dead end for every failure, mirroring the server's uniform 403. Telling a visitor
      // "that link was revoked" versus "no such link" would hand back exactly the distinction the
      // server-side refusal exists to withhold.
      .catch(() => live && setPhase("gone"));
    return () => {
      live = false;
    };
  }, [token]);

  const unlock = (event: React.FormEvent) => {
    event.preventDefault();
    if (busy) return;
    setBusy(true);
    setError("");
    fetch(`/api/v1/published/${encodeURIComponent(token)}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ passphrase }),
    })
      .then(async (r) => {
        if (r.ok) {
          setPage((await r.json()) as PubPage);
          setPhase("ready");
          // β›” The typed secret does not outlive the request that used it.
          setPassphrase("");
          return;
        }
        setError("That passphrase did not open this link.");
      })
      .catch(() => setError("That could not be checked; try again in a moment."))
      .finally(() => setBusy(false));
  };

  if (phase === "loading") {
    return (
      <div className="pubv-root pubv-boot signed-out" aria-busy="true">
        <div className="signed-out-panel" role="status" aria-label="Loading shared view">
          <Brand size={44} className="signed-out-brand" />
        </div>
      </div>
    );
  }

  if (phase === "gone") {
    return (
      <div className="pubv-root signed-out">
        <div className="pubv-card signed-out-panel">
          <Brand size={44} className="signed-out-brand" />
          <h1 className="pubv-title">This link is not available</h1>
          <p className="pubv-note">Ask for a new link.</p>
        </div>
      </div>
    );
  }

  if (phase === "locked") {
    return (
      <div className="pubv-root signed-out">
        <form className="pubv-card signed-out-panel" onSubmit={unlock}>
          <Brand size={44} className="signed-out-brand" />
          <h1 className="pubv-title">This link needs a passphrase</h1>
          <label className="pubv-label" htmlFor="pubv-pass">
            Passphrase
          </label>
          <input
            id="pubv-pass"
            className="pubv-input"
            type="password"
            autoFocus
            autoComplete="off"
            value={passphrase}
            onChange={(e) => setPassphrase(e.target.value)}
          />
          {error ? <p className="pubv-error">{error}</p> : null}
          <button className="pubv-btn" type="submit" disabled={busy || !passphrase}>
            {busy ? "Checking…" : "Open"}
          </button>
        </form>
      </div>
    );
  }

  if (!page) return null;
  return <PublishedBody page={page} />;
}

/**
 * The page itself, as a PURE function of the server's payload.
 *
 * ⭐ EXPORTED, AND SPLIT OUT FOR ONE REASON: it makes this surface RENDERABLE without a browser,
 * a server or a session. `renderToStaticMarkup` runs no effects, so a component that fetches in
 * `useEffect` can only ever paint its loading state under this repo's render harness β€” which
 * would have left the published page in the same "gated by things assertions cannot see" bucket
 * as everything else in [[ui-invisible-to-assertions]]. With the fetch above and the markup here,
 * `verify_wiring` can render the REAL component over a fixture payload and assert what a reader
 * would actually see β€” including the things that matter most and are least visible to a source
 * grep: that a hidden column's VALUE is nowhere in the emitted HTML, and that the page offers no
 * control a session-less visitor could press.
 *
 * ⚠ It takes the payload and nothing else. A prop for "is this a preview?" or a callback would
 * reintroduce exactly the state the split exists to remove.
 */
export function PublishedBody({ page }: { page: PubPage }) {
  // The first text column is what a pin, a card or a row leads with. Derived from the
  // projection the server sent, never named here β€” this page has no idea what the table is.
  const lead = page.columns.find((c) => !NUMERIC.has(c.type)) || page.columns[0];
  const titleOf = (r: PubRow) => (lead ? cellText(r[lead.key]) : `#${r.pid}`);

  const body =
    page.mode === "map" ? (
      <MapPlot rows={page.rows} title={titleOf} />
    ) : page.mode === "catalog" || page.mode === "swipe" ? (
      <ul className="pubv-cards">
        {page.rows.map((r) => (
          <li className="pubv-card-item" key={r.pid}>
            <h2 className="pubv-card-title">{titleOf(r)}</h2>
            <dl className="pubv-pairs">
              {page.columns
                .filter((c) => !lead || c.key !== lead.key)
                .map((c) => (
                  <div className="pubv-pair" key={c.key}>
                    <dt>{c.label}</dt>
                    <dd className={NUMERIC.has(c.type) ? "is-num" : undefined}>
                      {cellText(r[c.key])}
                    </dd>
                  </div>
                ))}
            </dl>
          </li>
        ))}
      </ul>
    ) : (
      // Unknown future modes fall back to a read-only table, the
      // presentation that cannot be wrong about a mode this page has not learned yet.
      <div className="pubv-tablewrap">
        <table className="pubv-table">
          <thead>
            <tr>
              {page.columns.map((c) => (
                <th key={c.key} className={NUMERIC.has(c.type) ? "is-num" : undefined}>
                  {c.label}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {page.rows.map((r) => (
              <tr key={r.pid}>
                {page.columns.map((c) => (
                  <td key={c.key} className={NUMERIC.has(c.type) ? "is-num" : undefined}>
                    {cellText(r[c.key])}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );

  return (
    <div className="pubv-root pubv-page signed-out">
      <div className="signed-out-panel signed-out-wide">
      <Brand size={44} className="signed-out-brand" />
      <header className="pubv-head">
        <h1 className="pubv-title">{page.title || "Shared view"}</h1>
        <p className="pubv-count">
          {page.total} {page.total === 1 ? "record" : "records"}
        </p>
      </header>
      {body}
      {/* ⚠ R6's second sentence, rendered. A page that serves fewer rows than the view holds
          says so, with the cause β€” a short page that stays quiet about being short is the
          silent truncation the rule is actually about. */}
      {(page.limits || []).map((l) => (
        <p className="pubv-note" key={l.subject}>
          {l.detail}
          {l.recommendation ? `; ${l.recommendation}` : ""}
        </p>
      ))}
      {page.rows.length === 0 ? (
        <p className="pubv-note">This view has no records right now.</p>
      ) : null}
      </div>
    </div>
  );
}