feat(plugins): give plugins the surface, insets and mobile palette they need (#1886)

* Tell a plugin where it is mounted

A plugin sits in one of six host surfaces and cannot see which: a trip tab and
the plugin page fill their container and scroll themselves, a dashboard widget
and the settings frame report their height, a detail slot is a narrow column in
someone else's panel. The contracts differ, and on a filling surface the height
report is discarded, so a plugin cannot even discover the difference by trying.

trek:context now carries viewport: the surface by name, phone or desktop, the
fill flag, and the insets the host already keeps clear. The insets describe
space that is held free, not padding to add — the mobile trip tab is the only
surface with chrome floating over it, and the numbers come from the same
variables the native tabs use so the two cannot drift.

* Seat the plugin tab like a native one

The mobile plugin tab kept clearance at the bottom and none at the top, so the
plugin's first row sat under the status bar and behind the floating back button.
The bottom value was a copied 84 that ignored the safe area on the devices that
have one, and the padding sat on the container rather than in the scroller.

Both clearances now come from the variables TabScroller uses, so the tab cannot
drift away from the native ones. The frame also states its surface, and pins
color-scheme for the reason both settings mounts already pin it: Chromium paints
a white canvas behind a transparent frame otherwise.

The tab also had no name anywhere on screen. It is not in the dock, so nothing
lit up there either, and the header had a branch for every other tab. It gets
the same treatment, built from the tab entry the planner already assembles.

* Keep the widget card intact on the phone

The card is built from the dashboard's glass vocabulary, which is scoped to
.trek-dash. The phone dashboard is a different route and mounts these widgets
outside that subtree, so background, border, shadow and blur all resolved empty
and the widget stood on the gradient as a bare title over an iframe. Each value
now falls back to the mobile token the surrounding cards are made of.

* Give the design kit a mobile layer

The kit was written for the desktop and stayed there: a filled card with a drop
shadow where the mobile design is translucent and border-led, inputs at 13px
which make iOS Safari zoom on focus and never zoom back, feedback on :hover
which never fires on a touchscreen, and one media query in the whole stylesheet.

It reads the new viewport field now and sets data-form-factor, data-surface and
data-fill on the document, plus the insets as variables. Everything mobile hangs
off data-form-factor="phone", so nothing changes on the desktop: the card loses
its shadow and takes the mobile surface tokens, targets grow to 44px, inputs to
16px, and pressing something scales it instead of waiting for a hover that will
not come. A filling surface anchors the body and scrolls an inner element,
because its height report is discarded by the host.

Plus the pieces a v4 screen is actually made of, so an author does not have to
reverse-engineer them: eyebrow, count pill, section header, status dot, round
icon button, field, segmented control. Each falls back to a global token where
the mobile family is absent, so they work on both.

* Document what a plugin needs on a phone

The guide had nothing on the subject: no mention of the second token family, of
who scrolls, of what sizes to expect, or that the kit brings almost nothing
responsive. It also promised more than it delivered, claiming the palette was
complete and that applying it matches the host "exactly" — fonts are named, not
shipped, so that was never true.

The new section covers the six surfaces and which of them fill versus report a
height, what insets mean (space already held free, not padding to add), the
mobile palette with the branch-on-absence pattern, and the four rules that
decide whether it feels native. It also says plainly that the dev preview cannot
show a phone width yet.
This commit is contained in:
Maurice
2026-08-11 16:51:02 +02:00
committed by GitHub
parent d1e3d8a75a
commit 6fe89588c2
17 changed files with 433 additions and 30 deletions
@@ -342,7 +342,7 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12 }}>
{dayDetailPlugins.map((p) => (
<div key={p.id} className="bg-surface-hover" style={{ borderRadius: 10, overflow: 'hidden' }}>
<PluginFrame pluginId={p.id} tripId={String(tripId)} dayId={String(day.id)} title={p.name} />
<PluginFrame pluginId={p.id} tripId={String(tripId)} dayId={String(day.id)} title={p.name} surface="detail-slot" />
</div>
))}
</div>
@@ -451,7 +451,7 @@ export default function PlaceInspector({
const tid = (place as { trip_id?: number | string }).trip_id
return (
<div key={p.id} className="bg-surface-hover" style={{ borderRadius: 10, overflow: 'hidden' }}>
<PluginFrame pluginId={p.id} tripId={tid != null ? String(tid) : null} placeId={String(place.id)} title={p.name} />
<PluginFrame pluginId={p.id} tripId={tid != null ? String(tid) : null} placeId={String(place.id)} title={p.name} surface="detail-slot" />
</div>
)
})}
@@ -443,7 +443,7 @@ function ReservationCard({ r, tripId, onEdit, onDelete, files = [], onNavigateTo
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '0 14px 14px' }}>
{detailPlugins.map(p => (
<div key={p.id} className="bg-surface-hover" style={{ borderRadius: 10, overflow: 'hidden' }}>
<PluginFrame pluginId={p.id} tripId={String(tripId)} reservationId={String(r.id)} title={p.name} />
<PluginFrame pluginId={p.id} tripId={String(tripId)} reservationId={String(r.id)} title={p.name} surface="detail-slot" />
</div>
))}
</div>
@@ -623,7 +623,7 @@ function TransitJourneyCard({ r, days, onOpen, onDelete, canEdit, tripId, contri
<div onClick={e => e.stopPropagation()} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{detailPlugins.map(p => (
<div key={p.id} className="bg-surface-hover" style={{ borderRadius: 10, overflow: 'hidden' }}>
<PluginFrame pluginId={p.id} tripId={String(tripId)} reservationId={String(r.id)} title={p.name} />
<PluginFrame pluginId={p.id} tripId={String(tripId)} reservationId={String(r.id)} title={p.name} surface="detail-slot" />
</div>
))}
</div>
@@ -115,7 +115,7 @@ export function PluginActions({ items, tripId, className }: { items: ViewContrib
<button onClick={() => setFrame(null)} className="text-content-muted hover:text-content"><X size={16} /></button>
</div>
<div className="flex-1 min-h-0">
<PluginFrame pluginId={frame.pluginId} tripId={tripId != null ? String(tripId) : null} title={frame.label} fill />
<PluginFrame pluginId={frame.pluginId} tripId={tripId != null ? String(tripId) : null} title={frame.label} fill surface="action-frame" />
</div>
</div>
</div>
@@ -109,6 +109,58 @@ describe('PluginFrame', () => {
await waitFor(() => expect(posted.some((m) => (m as { type?: string }).type === 'trek:response')).toBe(true));
});
it('FE-PLUGINS-FRAME-005a: the context says which surface the frame sits in and what shape it takes', () => {
// Without this a plugin cannot tell a full-height tab from a widget that
// reports its own height — and on a filling surface the height report is
// dropped, so it never finds out by trying.
const { container } = render(<PluginFrame pluginId="demo" surface="trip-tab" fill />);
const iframe = container.querySelector('iframe')!;
const posted: Array<Record<string, unknown>> = [];
(iframe.contentWindow as unknown as { postMessage: (m: unknown) => void }).postMessage = (m: unknown) => posted.push(m as Record<string, unknown>);
fromFrame(iframe, { type: 'trek:context:request' });
const ctx = posted.find((m) => m.type === 'trek:context') as Record<string, unknown> | undefined;
expect(ctx!.viewport).toMatchObject({ surface: 'trip-tab', fill: true, formFactor: 'desktop' });
expect((ctx!.viewport as { insets: unknown }).insets).toEqual({ top: 0, bottom: 0 });
});
it('FE-PLUGINS-FRAME-005b: a widget reports its own height, and says so', () => {
const { container } = render(<PluginFrame pluginId="demo" surface="dashboard-widget" />);
const iframe = container.querySelector('iframe')!;
const posted: Array<Record<string, unknown>> = [];
(iframe.contentWindow as unknown as { postMessage: (m: unknown) => void }).postMessage = (m: unknown) => posted.push(m as Record<string, unknown>);
fromFrame(iframe, { type: 'trek:context:request' });
const ctx = posted.find((m) => m.type === 'trek:context') as Record<string, unknown> | undefined;
expect(ctx!.viewport).toMatchObject({ surface: 'dashboard-widget', fill: false });
});
it('FE-PLUGINS-FRAME-005c: the mobile palette is read off the mobile shell, not the document element', () => {
// The --m-* family is scoped to .m-root. Reading it at documentElement — where
// every other token lives — yields nothing, which is why it never reached a
// plugin before.
const shell = document.createElement('div');
shell.className = 'm-root';
shell.style.setProperty('--m-card', 'rgba(255,255,255,.55)');
shell.style.setProperty('--m-ink', '#101013');
document.body.appendChild(shell);
try {
const { container } = render(<PluginFrame pluginId="demo" surface="trip-tab" fill />);
const iframe = container.querySelector('iframe')!;
const posted: Array<Record<string, unknown>> = [];
(iframe.contentWindow as unknown as { postMessage: (m: unknown) => void }).postMessage = (m: unknown) => posted.push(m as Record<string, unknown>);
fromFrame(iframe, { type: 'trek:context:request' });
const ctx = posted.find((m) => m.type === 'trek:context') as Record<string, unknown> | undefined;
expect(ctx!.tokens).toMatchObject({ '--m-card': 'rgba(255,255,255,.55)', '--m-ink': '#101013' });
} finally {
shell.remove();
}
});
it('FE-PLUGINS-FRAME-005: context carries theme tokens, formats and non-secret display identity', () => {
const { container } = render(<PluginFrame pluginId="demo" />);
const iframe = container.querySelector('iframe')!;
+93 -2
View File
@@ -10,6 +10,7 @@ import { useToast } from '../shared/Toast'
import ConfirmDialog from '../shared/ConfirmDialog'
import { pluginsApi } from '../../api/client'
import { addListener, removeListener } from '../../api/websocket'
import { useIsPhone } from '../../mobile/useIsPhone'
// The design-token contract handed to plugins (#4 richer context): non-secret CSS
// values, resolved for the CURRENT theme, so a plugin can match TREK exactly (and
@@ -21,6 +22,31 @@ import { addListener, removeListener } from '../../api/websocket'
// (--glass-*/--r-*/--sh-*) is intentionally NOT read here: it is scoped to the
// dashboard subtree, so it resolves EMPTY at documentElement — the SDK design kit
// bakes those values instead (they don't vary with the accent, only light/dark).
/**
* The mobile palette (client/src/mobile/mobile.css) is a SECOND, unrelated token
* family, and it is scoped to `.m-root` rather than to the document element. That
* scope is the reason it cannot simply join the list below: `readThemeTokens`
* measures at documentElement, where every one of these resolves empty — the same
* trap the comment above describes for `--glass-*`. They are read off the mobile
* shell instead, when one is mounted.
*
* A plugin sitting inside the mobile shell needs these to match its surroundings;
* the global palette above describes the desktop chrome and looks foreign there.
*/
const MOBILE_TOKEN_VARS = [
// ink + ground
'--m-ink', '--m-muted', '--m-faint', '--m-bg', '--m-scr',
// glass surfaces the mobile design is built from
'--m-glass', '--m-gbr', '--m-card', '--m-cbr', '--m-inner', '--m-inbr',
'--m-sheet', '--m-sheetop', '--m-shbr',
// action + accents
'--m-act', '--m-actfg', '--m-dim', '--m-ic', '--m-rowbr', '--m-avbr', '--m-knob',
// status canon (theme independent, but a plugin should not restate it)
'--m-st-confirmed', '--m-st-pending', '--m-st-info', '--m-st-danger', '--m-st-neutral',
// chrome metrics
'--m-safe-top',
]
const TOKEN_VARS = [
// surfaces
'--bg-primary', '--bg-secondary', '--bg-tertiary', '--bg-elevated',
@@ -39,6 +65,9 @@ const TOKEN_VARS = [
// radii, type, misc
'--radius-sm', '--radius-md', '--radius-lg', '--radius-xl',
'--font-system', '--font-subtext', '--overlay', '--ease-out-quint',
// How much a host surface keeps clear at the bottom. Global, unlike the rest of
// the mobile metrics, and useful on both form factors.
'--bottom-nav-h',
]
function readThemeTokens(): Record<string, string> {
const cs = getComputedStyle(document.documentElement)
@@ -47,9 +76,54 @@ function readThemeTokens(): Record<string, string> {
const val = cs.getPropertyValue(v).trim()
if (val) out[v] = val
}
// Measured on the mobile shell, because that is where the mobile palette is
// declared. Absent on desktop, and then these keys are simply absent too — a
// plugin checks for them rather than assuming both families are present.
const mobileRoot = document.querySelector('.m-root')
if (mobileRoot) {
const mcs = getComputedStyle(mobileRoot)
for (const v of MOBILE_TOKEN_VARS) {
const val = mcs.getPropertyValue(v).trim()
if (val) out[v] = val
}
}
return out
}
/** Where a frame is mounted. Part of the plugin contract, so the names are stable. */
export type PluginSurface =
| 'trip-tab' // a plugin's own tab inside a trip (fills, scrolls itself)
| 'plugin-page' // /plugins/:id (fills, scrolls itself)
| 'dashboard-widget'// a card on the dashboard (reports its height)
| 'user-settings' // the plugin's settings.html (reports its height)
| 'detail-slot' // inside a place/day/reservation panel (reports its height)
| 'action-frame' // the modal a table action opens (fills)
/**
* What the host already keeps clear around this frame, in CSS pixels.
*
* This describes space the plugin does NOT have to account for; it is not a
* request to add padding. The mobile trip tab is the only surface with floating
* chrome above and below it, and the numbers come from the same variables the
* native tabs use, so the two can never drift apart.
*/
function readInsets(surface: PluginSurface | undefined, phone: boolean): { top: number; bottom: number } {
if (!phone || surface !== 'trip-tab') return { top: 0, bottom: 0 }
const mobileRoot = document.querySelector('.m-root')
if (!mobileRoot) return { top: 0, bottom: 0 }
const cs = getComputedStyle(mobileRoot)
const px = (value: string, fallback: number) => {
const n = Number.parseFloat(value)
return Number.isFinite(n) ? n : fallback
}
// Mirrors TabScroller: the controls end 58px below the safe-top anchor, and the
// dock plus its breathing room is what --bottom-nav-h already expresses.
return {
top: px(cs.getPropertyValue('--m-safe-top'), 12) + 58,
bottom: px(cs.getPropertyValue('--bottom-nav-h'), 84) + 22,
}
}
/**
* The host's current appearance state, mirrored from the attributes applyAppearance
* writes on <html>, so a plugin can honour the same accessibility/appearance choices
@@ -97,6 +171,13 @@ interface PluginFrameProps {
* below — right for dashboard widgets, wrong for a page.
*/
fill?: boolean
/**
* Which host surface this frame is mounted in. Handed to the plugin verbatim,
* because the contract differs per surface and a plugin cannot see where it
* sits: a page fills and scrolls itself, a widget reports its height and gets
* it honoured, a detail slot is a narrow column inside someone else's panel.
*/
surface?: PluginSurface
className?: string
title?: string
/**
@@ -208,7 +289,8 @@ function createPluginSessionStorageKeys(
}
}
export default function PluginFrame({ pluginId, tripId = null, placeId = null, dayId = null, reservationId = null, fill = false, className, title, path = 'index.html' }: PluginFrameProps) {
export default function PluginFrame({ pluginId, tripId = null, placeId = null, dayId = null, reservationId = null, fill = false, surface, className, title, path = 'index.html' }: PluginFrameProps) {
const isPhone = useIsPhone()
const frameRef = useRef<HTMLIFrameElement | null>(null)
// A sandboxed frame may navigate ITSELF (connect-src can't stop that), and its
// window identity keeps matching our iframe afterwards. Track loads and refuse
@@ -282,6 +364,15 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
// mirror the same look and accessibility choices as the host.
user: userName != null ? { name: userName, avatar: userAvatar, isAdmin } : null,
appearance: readAppearance(),
// Where this frame sits and what shape it is expected to take. Without it a
// plugin cannot tell a full-height tab from a widget that reports its own
// height, and a height report is silently dropped on a filling surface.
viewport: {
surface: surface ?? null,
formFactor: isPhone ? 'phone' : 'desktop',
fill,
insets: readInsets(surface, isPhone),
},
formats: {
locale,
currency: displayCurrency,
@@ -292,7 +383,7 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
blurBookingCodes: Boolean(settings.blur_booking_codes),
},
tokens: readThemeTokens(),
}), [tripId, placeId, dayId, reservationId, userId, locale, userName, userAvatar, isAdmin, settings])
}), [tripId, placeId, dayId, reservationId, userId, locale, userName, userAvatar, isAdmin, settings, surface, fill, isPhone])
useEffect(() => {
const frame = frameRef.current
@@ -18,13 +18,19 @@ export default function PluginWidgets({ plugins, tripId = null }: { plugins: Act
{plugins.map((p) => (
<div
key={p.id}
// The glass vocabulary (--glass-*, --r-xl, --ink-3) is scoped to
// .trek-dash. The phone dashboard is a different route and mounts these
// widgets outside that subtree, so every one of those resolved empty and
// the card lost its background, border, shadow and blur — a bare title
// over the gradient. Each now falls back to a mobile token, which is
// what the surrounding cards on that screen are made of.
style={{
background: 'var(--glass-bg)',
border: '1px solid var(--glass-border)',
background: 'var(--glass-bg, var(--m-card))',
border: '1px solid var(--glass-border, var(--m-cbr))',
borderRadius: 'var(--r-xl, 20px)',
boxShadow: 'var(--glass-shadow), var(--glass-highlight)',
backdropFilter: 'var(--glass-blur)',
WebkitBackdropFilter: 'var(--glass-blur)',
boxShadow: 'var(--glass-shadow, 0 16px 44px -20px rgba(0,0,0,.28)), var(--glass-highlight, 0 0 0 0 transparent)',
backdropFilter: 'var(--glass-blur, blur(30px) saturate(1.8))',
WebkitBackdropFilter: 'var(--glass-blur, blur(30px) saturate(1.8))',
overflow: 'hidden',
}}
>
@@ -32,7 +38,7 @@ export default function PluginWidgets({ plugins, tripId = null }: { plugins: Act
style={{
display: 'flex', alignItems: 'center', gap: 8, padding: '16px 20px 8px',
fontSize: 13, fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.14em',
color: 'var(--ink-3)',
color: 'var(--ink-3, var(--m-faint))',
}}
>
<PluginIcon name={p.icon} size={14} style={{ flexShrink: 0 }} />
@@ -40,7 +46,7 @@ export default function PluginWidgets({ plugins, tripId = null }: { plugins: Act
</div>
{/* min-height is just a pre-resize floor; trek:resize drives the real height. */}
<div style={{ minHeight: 60 }}>
<PluginFrame pluginId={p.id} tripId={tripId} title={p.name} />
<PluginFrame pluginId={p.id} tripId={tripId} title={p.name} surface="dashboard-widget" />
</div>
</div>
))}
@@ -242,7 +242,7 @@ function PluginSettingsUiCard({ id, name, icon }: { id: string; name: string; ic
white canvas behind the transparent frame (same trap .hero-overlay-frame
guards against), which glares in dark mode. */}
<div className="min-h-[120px]">
<PluginFrame pluginId={id} path="settings.html" title={name} className="[color-scheme:light]" />
<PluginFrame pluginId={id} path="settings.html" title={name} surface="user-settings" className="[color-scheme:light]" />
</div>
</div>
)