#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Portal ProcessorFlow: proportional particle emission + Storybook playground (#7105)
EthanHealy01bda9cebc5cfc
diff --git a/frontend/editor/src/core/ui/StatusBadge.css b/frontend/editor/src/core/ui/StatusBadge.cssindex 9115eb6099..62f6fb0f3a 100644--- a/frontend/editor/src/core/ui/StatusBadge.css+++ b/frontend/editor/src/core/ui/StatusBadge.css@@ -55,9 +55,8 @@background: var(--color-bg-muted);border-color: var(--color-border-light);}-/* Accent tones only pick the accent; the base rule builds the fill + border.- The `-dark` variants are theme-adaptive (darker in light, brighter in dark),- so the text stays legible on the pale fill in both themes. */+/* Tones only pick the accent; the base rule builds the fill + border. `-dark`+ is theme-adaptive, so text stays legible on the pale fill in both themes. */.sui-status--success {--sui-status-c: var(--color-green-dark);}diff --git a/frontend/editor/src/portal/api/processorFlow.ts b/frontend/editor/src/portal/api/processorFlow.tsindex 30a9b468a6..35adc9c89f 100644--- a/frontend/editor/src/portal/api/processorFlow.ts+++ b/frontend/editor/src/portal/api/processorFlow.ts@@ -1,18 +1,5 @@-/**- * Processor-flow assembler for the home visualiser.- *- * Fans in the three real portal surfaces — sources (`/api/v1/sources`), policies- * (`/api/v1/policies`) and their runs (`/api/v1/policies/runs`) — and derives the- * left→middle→right shape the {@link ProcessorFlow} component renders:- *- * sources → policies → outcomes- *- * Everything here is real backend data. Per-run source attribution does not- * exist (a `PolicyRunView` carries `policyId` but no source id), so the flow- * animation is illustrative; the node counts are not — each source's `docs24h`,- * each policy's trailing-24h run count, and the success/failure split all come- * straight from the API.- */+/** Assembles the home visualiser's sources → policies → outcomes from the real+ * sources/policies/runs APIs. Counts are real; the flow motion is illustrative. */import { apiClient } from "@portal/api/http";import { fetchSources } from "@portal/api/sources";@@ -30,27 +17,19 @@ export interface FlowSource {docs24h: number;}-/**- * A connector type shown in the sources column but not yet a real source type —- * a "coming soon" affordance only. `labelKey` is an i18n key.- */+/** A "coming soon" connector shown in the sources column but not a real source+ * type yet. `labelKey` is an i18n key. */export interface FlowComingSoonSource {key: string;labelKey: string;}-/**- * Row display state, mirroring the Policies page:- * - `active` — configured + enabled; shows its live 24h run count- * - `off` — available but not set up; offers a "Set up" CTA- * - `locked` — a coming-soon category that doesn't exist yet- */+/** Row state (mirrors the Policies page): `active` = configured+enabled with a+ * 24h count, `off` = available (offers "Set up"), `locked` = coming-soon. */export type FlowPolicyState = "active" | "off" | "locked";-/**- * One row in the middle policies column — the full policy catalogue, in the- * same order the Policies page shows, including the coming-soon categories.- */+/** One policies-column row — the full catalogue in Policies-page order,+ * including the coming-soon categories. */export interface FlowPolicy {/** Category id (also the lane key for the flow animation + its icon). */key: string;@@ -92,11 +71,8 @@ const COMING_SOON_SOURCES: FlowComingSoonSource[] = [},];-/**- * The full policy catalogue, in the Policies-page order, including the- * coming-soon categories (rendered as locked). `active` rows carry their- * trailing-24h run count.- */+/** Full catalogue in Policies-page order (coming-soon → locked); `active` rows+ * carry their trailing-24h run count. */function buildPolicies(wirePolicies: WirePolicy[],runs: PolicyRunView[],diff --git a/frontend/editor/src/portal/components/ProcessorFlow.css b/frontend/editor/src/portal/components/ProcessorFlow.cssindex 5aa7f6198f..7e020d0253 100644--- a/frontend/editor/src/portal/components/ProcessorFlow.css+++ b/frontend/editor/src/portal/components/ProcessorFlow.css@@ -1,6 +1,5 @@-/* Processor-flow visualiser — sources → policies → outcomes. The flow is an- SVG overlay measured from the HTML cards: bézier wires underneath, and a- rAF-driven particle layer on top (see ProcessorFlow.tsx). */+/* Processor-flow visualiser: SVG overlay (bézier wires + rAF particle layer)+ measured from the HTML cards. See ProcessorFlow.tsx. */.portal-pf {--pf-accent: var(--color-green);diff --git a/frontend/editor/src/portal/components/ProcessorFlow.stories.tsx b/frontend/editor/src/portal/components/ProcessorFlow.stories.tsxindex e573751ac6..0622b31e55 100644--- a/frontend/editor/src/portal/components/ProcessorFlow.stories.tsx+++ b/frontend/editor/src/portal/components/ProcessorFlow.stories.tsx@@ -1,17 +1,14 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { http, HttpResponse } from "msw";import { ProcessorFlow } from "@portal/components/ProcessorFlow";+import type {+ FlowOutcome,+ FlowPolicy,+ ProcessorFlow as ProcessorFlowModel,+} from "@portal/api/processorFlow";-/**- * The home processor visualiser. Data is served by the global portal MSW- * handlers (seeded sources + one active Security policy + its runs), so the- * middle column shows Security "active" and Classification with a "Set up" CTA,- * and the outcomes reflect the seeded 24h success/failure split.- *- * NB: the flow particles animate via requestAnimationFrame, which browsers- * pause while the tab/preview is hidden — open the story in a focused tab to- * see the dots move.- */+/** Home processor visualiser, backed by the global portal MSW handlers.+ * Particles animate via rAF (paused for hidden tabs — view in a focused tab). */const meta: Meta<typeof ProcessorFlow> = {title: "Portal/Components/ProcessorFlow",component: ProcessorFlow,@@ -24,11 +21,8 @@ type Story = StoryObj<typeof ProcessorFlow>;/** Live machine: Security configured + real throughput → the flow runs. */export const Default: Story = {};-/**- * Nothing set up and no activity — the empty state from the design. In- * production the flow stays still here; the DEV_KEEP_FLOWING dev flag forces it- * on with synthetic rates so the animation is visible while iterating.- */+/** Nothing set up and no activity — the empty state. The flow stays still here+ * in production (DEV_KEEP_FLOWING can force it on while iterating). */export const IdleEmpty: Story = {parameters: {msw: {@@ -58,3 +52,128 @@ export const IdleEmpty: Story = {},},};++/* ── Playground ───────────────────────────────────────────────────────────── */++interface PlaygroundArgs {+ /** Editor input volume (docs / 24h). */+ editorRate: number;+ /** "Claims intake" input volume (docs / 24h). */+ claimsRate: number;+ /** "Contracts drop" input volume (docs / 24h). */+ contractsRate: number;+ /** Delivered (success) outcomes over 24h. */+ delivered: number;+ /** Failed outcomes over 24h — drives the red-dot ratio. */+ failed: number;+ /** Whether the Classification policy is active (a second particle lane). */+ classificationActive: boolean;+}++const CATEGORY_LABEL = (id: string) => `portal.policies.categories.${id}.label`;++/** Build a flow model from the playground controls. */+function buildModel(a: PlaygroundArgs): ProcessorFlowModel {+ const sources = [+ { id: "editor", name: "Editor", type: "editor", docs24h: a.editorRate },+ {+ id: "claims",+ name: "Claims intake",+ type: "folder",+ docs24h: a.claimsRate,+ },+ {+ id: "contracts",+ name: "Contracts drop",+ type: "folder",+ docs24h: a.contractsRate,+ },+ ];+ const policies: FlowPolicy[] = [+ {+ key: "ingestion",+ labelKey: CATEGORY_LABEL("ingestion"),+ state: "locked",+ configured: false,+ runs24h: 0,+ },+ {+ key: "security",+ labelKey: CATEGORY_LABEL("security"),+ state: "active",+ configured: true,+ runs24h: Math.round(a.delivered * 0.6),+ },+ {+ key: "classification",+ labelKey: CATEGORY_LABEL("classification"),+ state: a.classificationActive ? "active" : "off",+ configured: a.classificationActive,+ runs24h: a.classificationActive ? Math.round(a.delivered * 0.4) : 0,+ },+ {+ key: "compliance",+ labelKey: CATEGORY_LABEL("compliance"),+ state: "locked",+ configured: false,+ runs24h: 0,+ },+ {+ key: "routing",+ labelKey: CATEGORY_LABEL("routing"),+ state: "locked",+ configured: false,+ runs24h: 0,+ },+ {+ key: "retention",+ labelKey: CATEGORY_LABEL("retention"),+ state: "locked",+ configured: false,+ runs24h: 0,+ },+ ];+ const outcomes: FlowOutcome[] = [+ {+ key: "success",+ labelKey: "portal.processorFlow.outcomes.success",+ count24h: a.delivered,+ },+ {+ key: "failed",+ labelKey: "portal.processorFlow.outcomes.failed",+ count24h: a.failed,+ },+ ];+ const comingSoonSources = [+ {+ key: "apiMcp",+ labelKey: "portal.processorFlow.sources.comingSoon.apiMcp",+ },+ { key: "cloud", labelKey: "portal.processorFlow.sources.comingSoon.cloud" },+ { key: "email", labelKey: "portal.processorFlow.sources.comingSoon.email" },+ ];+ return { sources, comingSoonSources, policies, outcomes };+}++/** Tune each input rate and the delivered/failed split live to watch emission+ * speed, per-source scaling, the 250ms ceiling, and the ratio (focused tab). */+export const Playground: StoryObj<PlaygroundArgs> = {+ args: {+ editorRate: 400,+ claimsRate: 800,+ contractsRate: 150,+ delivered: 90,+ failed: 10,+ classificationActive: true,+ },+ argTypes: {+ editorRate: { control: { type: "range", min: 0, max: 2000, step: 10 } },+ claimsRate: { control: { type: "range", min: 0, max: 2000, step: 10 } },+ contractsRate: { control: { type: "range", min: 0, max: 2000, step: 10 } },+ delivered: { control: { type: "number", min: 0 } },+ failed: { control: { type: "number", min: 0 } },+ classificationActive: { control: "boolean" },+ },+ render: (args) => <ProcessorFlow dataOverride={buildModel(args)} />,+};diff --git a/frontend/editor/src/portal/components/ProcessorFlow.tsx b/frontend/editor/src/portal/components/ProcessorFlow.tsxindex 4b4a832ad3..af9e318ba4 100644--- a/frontend/editor/src/portal/components/ProcessorFlow.tsx+++ b/frontend/editor/src/portal/components/ProcessorFlow.tsx@@ -25,25 +25,21 @@ import { FlowOutcomes } from "@portal/components/processor-flow/FlowOutcomes";import { FlowSankey } from "@portal/components/processor-flow/FlowSankey";import "@portal/components/ProcessorFlow.css";-/**- * Animated processor visualiser for the home surface: connected sources on the- * left flow through the standing policies in the middle to their audit outcomes- * on the right. Two lenses — a live particle flow and a Sankey summary.- *- * This module wires the data + gating together; the moving parts live under- * `processor-flow/`: geometry ({@link useFlowGeometry}), the rAF particle loop- * ({@link useFlowParticles}), the three columns, and the Sankey. The flow only- * runs when something is set up AND there's activity; an idle machine stays- * still (unless {@link DEV_KEEP_FLOWING} forces it while iterating).- */-export function ProcessorFlow() {+/** Home processor visualiser: sources → policies → outcomes, as a live particle+ * flow or a Sankey. Data + gating here; moving parts live under `processor-flow/`. */+interface ProcessorFlowProps {+ /** Testing seam: render this model directly instead of fetching. Never set in+ * the app — used by the Playground story to drive rates/counts from controls. */+ dataOverride?: ProcessorFlowModel;+}++export function ProcessorFlow({ dataOverride }: ProcessorFlowProps = {}) {const { t } = useTranslation();const { setActiveView } = useView();const navigate = useNavigate();- const { data, loading } = useAsync<ProcessorFlowModel>(- () => fetchProcessorFlow(),- [],- );+ const fetched = useAsync<ProcessorFlowModel>(() => fetchProcessorFlow(), []);+ const data = dataOverride ?? fetched.data;+ const loading = dataOverride ? false : fetched.loading;const [lens, setLens] = useState<Lens>("flow");const isLoading = loading && data === null;diff --git a/frontend/editor/src/portal/components/processor-flow/FlowSankey.tsx b/frontend/editor/src/portal/components/processor-flow/FlowSankey.tsxindex 1d90705c2c..43170a21a4 100644--- a/frontend/editor/src/portal/components/processor-flow/FlowSankey.tsx+++ b/frontend/editor/src/portal/components/processor-flow/FlowSankey.tsx@@ -18,11 +18,8 @@ interface FlowSankeyProps {policies: FlowPolicy[];}-/**- * Sankey lens: sources → policies waist → outcomes, ribbon width ∝ 24h volume.- * The waist splits into one segment per active policy. Shows a friendly empty- * state when nothing has flowed yet.- */+/** Sankey lens: sources → policies waist → outcomes, ribbon width ∝ 24h volume;+ * the waist splits per active policy. Empty state when nothing has flowed. */export function FlowSankey({ sources, outcomes, policies }: FlowSankeyProps) {const { t } = useTranslation();const activePolicies = policies.filter((p) => p.state === "active");diff --git a/frontend/editor/src/portal/components/processor-flow/flowTypes.ts b/frontend/editor/src/portal/components/processor-flow/flowTypes.tsindex 217d35760f..f8f0edd578 100644--- a/frontend/editor/src/portal/components/processor-flow/flowTypes.ts+++ b/frontend/editor/src/portal/components/processor-flow/flowTypes.ts@@ -3,18 +3,17 @@ import type { FlowOutcomeKey } from "@portal/api/processorFlow";/** Which lens the visualiser is showing. */export type Lens = "flow" | "sankey";-/**- * DEV ONLY: force the flow animation on even when nothing is set up / no- * activity has taken place, using synthetic rates. Off by design — an idle- * machine shows no animated dots; flip to true only to preview the motion- * while iterating on an empty workspace.- */+/** DEV ONLY: force the flow on (synthetic rates) even when idle. Off by design;+ * flip to true only to preview the motion on an empty workspace. */export const DEV_KEEP_FLOWING = false;export const EDITOR_TYPE = "editor";-/** Emission tuning: particles/sec for a source ≈ rate / 86400 × SPEED. */-export const SPEED = 300;+/** Emission tuning: dots/sec ≈ rate / EMIT_DIVISOR (2× volume ≈ 2× dots), capped+ * at MAX_EMIT_PER_SEC (250ms) and bounded to ≤EMIT_SPREAD_CAP× across sources. */+export const EMIT_DIVISOR = 200;+export const MAX_EMIT_PER_SEC = 4;+export const EMIT_SPREAD_CAP = 5;/** Synthetic per-source rate used only while DEV_KEEP_FLOWING forces the flow. */export const DEV_SYNTH_RATE = 320;/** Hard cap on live particles (matches the reference). */diff --git a/frontend/editor/src/portal/components/processor-flow/useFlowGeometry.tsx b/frontend/editor/src/portal/components/processor-flow/useFlowGeometry.tsxindex 1e43ebc161..6e0179dadb 100644--- a/frontend/editor/src/portal/components/processor-flow/useFlowGeometry.tsx+++ b/frontend/editor/src/portal/components/processor-flow/useFlowGeometry.tsx@@ -11,16 +11,8 @@ import {type Rect,} from "@portal/components/processor-flow/flowTypes";-/**- * Owns the measured-geometry seam for the flow visualiser: refs for the source,- * outcome and core cards (plus the per-policy lane lines), a `measure()` that- * projects their edges into a wrapper-relative {@link Geo}, and the SVG wires- * drawn between them. The particle loop reads the same `geoRef` live.- *- * Callers spread the returned refs onto the cards and render `wires` inside the- * underlay `<svg>`; geometry re-measures on every layout + on resize, and the- * wires re-render only when the measured signature actually changes.- */+/** Measures card edges into a wrapper-relative {@link Geo} and builds the SVG+ * wires; returns the refs + wires. The particle loop reads the same `geoRef`. */export function useFlowGeometry() {const wrapRef = useRef<HTMLDivElement>(null);const srcRefs = useRef<(HTMLElement | null)[]>([]);diff --git a/frontend/editor/src/portal/components/processor-flow/useFlowParticles.ts b/frontend/editor/src/portal/components/processor-flow/useFlowParticles.tsindex 0d19ab5295..7efbee40e2 100644--- a/frontend/editor/src/portal/components/processor-flow/useFlowParticles.ts+++ b/frontend/editor/src/portal/components/processor-flow/useFlowParticles.ts@@ -4,10 +4,12 @@ import {cbez,coreEntryY,smooth,+ EMIT_DIVISOR,+ EMIT_SPREAD_CAP,+ MAX_EMIT_PER_SEC,MAX_PARTICLES,MIN_EMIT_GAP,OUTCOME_FILL,- SPEED,type Geo,type Lens,type Particle,@@ -28,17 +30,8 @@ interface FlowParticlesOptions {outcomeKeys: FlowOutcomeKey[];}-/**- * Drives the rAF particle loop: emits dots per source on a jittered schedule- * (min-gap floored), routes each to an outcome via a weighted round-robin so- * the split matches the counts, threads it through a policy lane (blinking that- * row's LED), and recolours it to the outcome on arrival. Reads geometry live- * from `geoRef`, so it tracks card movement without restarting.- *- * Returns the `<g>` ref the caller mounts inside the particle overlay `<svg>`.- * The loop only runs on the flow lens, when `animate` is set, and outside- * reduced-motion; browsers pause rAF for hidden tabs (desirable).- */+/** rAF particle loop: emits jittered dots per source, routes each to an outcome by+ * weighted round-robin through a policy lane. Returns the overlay `<g>` ref. */export function useFlowParticles({geoRef,animate,@@ -76,25 +69,30 @@ export function useFlowParticles({let raf = 0;const glowTimers: Record<string, ReturnType<typeof setTimeout>> = {};- // Per-source emission schedule. Mean interval keeps each source's share of- // the flow proportional to its rate; the scheduled model (vs. a steady- // accumulator) is what lets us jitter departures and floor the gap.- const meanInterval = rates.map((r) => {- const perSec = (r / 86400) * SPEED;- return perSec > 0 ? 1000 / perSec : Infinity;- });+ // Per-source dots/sec: ~linear with volume, capped at MAX_EMIT_PER_SEC.+ // Scheduled (not accumulated) so we can jitter departures and floor the gap.+ const rawPerSec = rates.map((r) =>+ r > 0 ? Math.min(MAX_EMIT_PER_SEC, r / EMIT_DIVISOR) : 0,+ );+ // Bound the spread: the busiest source emits at most EMIT_SPREAD_CAP× the+ // quietest, so a dominant source can't starve the others.+ const busiest = Math.max(0, ...rawPerSec);+ const floorPerSec = busiest / EMIT_SPREAD_CAP;+ const meanInterval = rawPerSec.map((p) =>+ p > 0 ? 1000 / Math.max(p, floorPerSec) : Infinity,+ );// Stagger the first emission so sources don't all fire together at t=0.const nextEmit = meanInterval.map((mi) =>Number.isFinite(mi) ? last + Math.random() * mi : Infinity,);- // Random departure within [0.5×, 1.5×] the mean, but never closer than the- // minimum gap — a random flow with no two dots out at once per source.+ // Random departure within [0.4×, 1.7×] the mean, but never closer than the+ // minimum gap — a scattered flow with no two dots out at once per source.const scheduleNext = (i: number, now: number): number =>- now + Math.max(MIN_EMIT_GAP, meanInterval[i] * (0.5 + Math.random()));+ now ++ Math.max(MIN_EMIT_GAP, meanInterval[i] * (0.4 + Math.random() * 1.3));- // Weighted round-robin so the outcome split visibly matches the counts- // (e.g. 3 failed / 30 delivered → ~1 in 11 dots to Failed), interleaved- // rather than clustered like independent random draws.+ // Weighted round-robin so the outcome split matches the counts, evenly+ // interleaved (e.g. 3 failed / 30 delivered → ~1 in 11 dots to Failed).const outAcc = weights.map(() => 0);const pickOut = (): number => {if (!weights.length) return 0;@@ -151,9 +149,10 @@ export function useFlowParticles({lane: pickLane(),phase: 0,t: 0,- d0: 900 + Math.random() * 300,- d1: 760,- d2: 780 + Math.random() * 200,+ // Faster travel than before (~2× quicker) so the flow reads lively.+ d0: 460 + Math.random() * 220,+ d1: 380,+ d2: 400 + Math.random() * 200,pulsed: false,});nextEmit[i] = scheduleNext(i, now);@@ -203,14 +202,17 @@ export function useFlowParticles({yy = entY + (exitY - entY) * f1;} else if (f1 < 0.25) {yy = entY + (ly1 - entY) * smooth(f1 / 0.25);- } else if (f1 < 0.75) {- yy = ly1;+ } else {+ // Pulse once on reaching the lane — even if a slow frame overshoots+ // the 0.25–0.75 window straight into the glide-out segment.if (!p.pulsed) {p.pulsed = true;pulseLane(g, p.lane);}- } else {- yy = ly1 + (exitY - ly1) * smooth((f1 - 0.75) / 0.25);+ yy =+ f1 < 0.75+ ? ly1+ : ly1 + (exitY - ly1) * smooth((f1 - 0.75) / 0.25);}pos = { x: g.core.l + (g.core.r - g.core.l) * f1, y: yy };if (f1 >= 1) {diff --git a/frontend/editor/src/portal/mocks/policies.ts b/frontend/editor/src/portal/mocks/policies.tsindex 1a3cfa2259..85f3ccd6e7 100644--- a/frontend/editor/src/portal/mocks/policies.ts+++ b/frontend/editor/src/portal/mocks/policies.ts@@ -1,8 +1,5 @@-/**- * Policies fixtures. The canonical TS model and the static catalogue- * definitions live in api/policies.ts (the backend contract); this module- * only builds seed data for the MSW handlers and tests.- */+/** Policies seed data for the MSW handlers and tests. The canonical model and+ * catalogue live in api/policies.ts (the backend contract). */import type {PolicyRunView,@@ -92,13 +89,11 @@ const NOW = Date.now();const M = 60000;const D = 86400000;-/** Seed `PolicyRunView` records that drive the activity feed + stats.- * 40 delivered + 3 failed within the trailing 24h so the home visualiser shows- * a lively flow; a tail of older completed runs keeps the lifetime stats real.- * Runs are split across the two active policies so the Sankey waist divides. */+/** Seed runs: 40 delivered + 3 failed in the last 24h (split across the two+ * active policies), plus a tail of older completed runs for lifetime stats. */export function seedPolicyRuns(): PolicyRunView[] {- // Split the throughput across the two active policies (security / classification)- // so both show a 24h count and the Sankey waist splits into two segments.+ // Split throughput across security / classification so both show a 24h count+ // and the Sankey waist splits into two segments.const policyFor = (i: number, total: number) =>i < Math.round(total * 0.6)? "pol_security_default"diff --git a/frontend/editor/src/portal/views/Sources.css b/frontend/editor/src/portal/views/Sources.cssindex 90d30c4175..c0e7a56bd9 100644--- a/frontend/editor/src/portal/views/Sources.css+++ b/frontend/editor/src/portal/views/Sources.css@@ -379,9 +379,8 @@}}-/* The shared Button lays its children out in a flex-row label; force the type- tile back to a centred icon-over-label column so the SVG sits above the name- with real spacing (not jammed against it). */+/* Override the shared Button's flex-row label to a centred icon-over-label+ column so the SVG sits above the name with real spacing. */.portal-sources__type-card .mantine-Button-label {display: flex;flex-direction: column;