cfo-os / web /src /publish /PublishedView.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
6c9f944 verified
Raw History Blame Contribute Delete
13.8 kB
// ---------------------------------------------------------------------------
// 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 "./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" aria-busy="true" />;
}
if (phase === "gone") {
return (
<div className="pubv-root">
<div className="pubv-card">
<h1 className="pubv-title">This link is not available</h1>
<p className="pubv-note">
It may have been revoked, or the view it pointed at may have changed. Ask whoever
shared it for a new link.
</p>
</div>
</div>
);
}
if (phase === "locked") {
return (
<div className="pubv-root">
<form className="pubv-card" onSubmit={unlock}>
<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>
) : (
// timeseries / form / anything the server offers next. A read-only table is 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">
<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>
);
}