The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(plugins): pause and suspend plugin frames when they leave the screen
Mauricec4a2a9157816
diff --git a/client/src/components/Plugins/PluginFrame.test.tsx b/client/src/components/Plugins/PluginFrame.test.tsxindex 151484793..dbf7d1eb1 100644--- a/client/src/components/Plugins/PluginFrame.test.tsx+++ b/client/src/components/Plugins/PluginFrame.test.tsx@@ -939,3 +939,58 @@ describe('PluginFrame', () => {});});});++// FE-PLUGINS-FRAME-062 to 063: visibility lifecycle + phone off-screen suspend.+// A heavy plugin that keeps working off screen bogs down the shared WebView on a+// phone (reported via TestFlight), so the frame tells the plugin when it is hidden+// and, for a phone dashboard widget, unmounts the iframe entirely while off screen.+describe('PluginFrame visibility and mobile suspend', () => {+ let ios: Array<{ cb: IntersectionObserverCallback }>;+ let realIO: unknown;+ let realMM: typeof window.matchMedia;+ beforeEach(() => {+ ios = [];+ realIO = (window as unknown as { IntersectionObserver: unknown }).IntersectionObserver;+ realMM = window.matchMedia;+ class IO {+ cb: IntersectionObserverCallback;+ constructor(cb: IntersectionObserverCallback) { this.cb = cb; ios.push({ cb }); }+ observe() {} unobserve() {} disconnect() {} takeRecords() { return []; }+ }+ (window as unknown as { IntersectionObserver: unknown }).IntersectionObserver = IO as unknown;+ });+ afterEach(() => {+ (window as unknown as { IntersectionObserver: unknown }).IntersectionObserver = realIO;+ window.matchMedia = realMM;+ cleanup();+ });+ const asPhone = () => {+ window.matchMedia = ((q: string) => ({+ matches: true, media: q, onchange: null,+ addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {}, dispatchEvent() { return false; },+ })) as unknown as typeof window.matchMedia;+ };+ const fire = (intersecting: boolean) =>+ act(() => { ios[ios.length - 1].cb([{ isIntersecting: intersecting } as IntersectionObserverEntry], {} as IntersectionObserver); });++ it('FE-PLUGINS-FRAME-062: tells the plugin when it leaves the screen', () => {+ 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) => posted.push(m as Record<string, unknown>);+ fire(false);+ expect(posted.find((m) => m.type === 'trek:visibility')).toMatchObject({ visible: false });+ fire(true);+ expect(posted.filter((m) => m.type === 'trek:visibility').pop()).toMatchObject({ visible: true });+ });++ it('FE-PLUGINS-FRAME-063: suspends a phone dashboard widget off screen and brings it back', () => {+ asPhone();+ const { container } = render(<PluginFrame pluginId="demo" surface="dashboard-widget" />);+ expect(container.querySelector('iframe')).toBeTruthy();+ fire(false);+ expect(container.querySelector('iframe')).toBeNull();+ fire(true);+ expect(container.querySelector('iframe')).toBeTruthy();+ });+});diff --git a/client/src/components/Plugins/PluginFrame.tsx b/client/src/components/Plugins/PluginFrame.tsxindex 21f514780..f3410a089 100644--- a/client/src/components/Plugins/PluginFrame.tsx+++ b/client/src/components/Plugins/PluginFrame.tsx@@ -320,6 +320,16 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, dconst tripCurrency = useTripStore((s) => s.trip?.currency)const displayCurrency = (settings.default_currency || tripCurrency || 'EUR').toUpperCase()const [height, setHeight] = useState<number | null>(null)+ // Lifecycle: tell a plugin when it is off the screen or the app is backgrounded,+ // so a heavy one can pause its timers, polling and animation instead of burning+ // the shared main thread (worst on a phone, where the whole app janks). And on a+ // phone a dashboard-widget plugin scrolled well out of view is suspended outright+ // — its iframe is unmounted and a placeholder keeps its height — so an offscreen+ // widget costs nothing and comes back on its own when it scrolls into view.+ const wrapRef = useRef<HTMLDivElement | null>(null)+ const visibleRef = useRef(true)+ const [suspended, setSuspended] = useState(false)+ const suspendable = isPhone && surface === 'dashboard-widget'// A host-rendered ConfirmDialog on the plugin's behalf: sandboxed frames have no// allow-modals and can't overlay the host, so destructive plugin actions get the// same native confirm every TREK feature uses. One at a time; extras are refused.@@ -670,6 +680,56 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d}}, [pluginId])+ // Watch whether the frame is on screen (and the tab/app in the foreground) and+ // forward it to the plugin as `trek:visibility`; on a phone, a dashboard widget+ // that leaves the screen (with a margin so a partial scroll never tears it down)+ // is suspended, which unmounts the heavy iframe entirely.+ useEffect(() => {+ // A phone widget keeps the wrapper mounted across a suspend and is observed+ // there; everything else is observed on the iframe itself, which never unmounts.+ const el = suspendable ? wrapRef.current : frameRef.current+ if (!el || typeof IntersectionObserver === 'undefined') return+ let onscreen = true+ const emit = () => {+ const visible = onscreen && !document.hidden+ if (visible !== visibleRef.current) {+ visibleRef.current = visible+ postFrame({ type: 'trek:visibility', visible })+ }+ }+ const io = new IntersectionObserver(+ (entries) => {+ onscreen = entries[entries.length - 1]?.isIntersecting ?? true+ emit()+ if (suspendable) setSuspended(!onscreen)+ },+ { rootMargin: suspendable ? '250px 0px' : '0px', threshold: 0 }+ )+ io.observe(el)+ const onVis = () => emit()+ document.addEventListener('visibilitychange', onVis)+ return () => {+ io.disconnect()+ document.removeEventListener('visibilitychange', onVis)+ }+ }, [pluginId, postFrame, suspendable])++ // Coming back from a suspend remounts a fresh iframe (same pluginId key), so the+ // load counter has to start over or the remount reads as a self-navigation and+ // never gets the context; going into one stops the geolocation watch of the frame+ // that is about to be unmounted.+ useEffect(() => {+ if (suspended) {+ if (geoWatchRef.current != null) {+ navigator.geolocation.clearWatch(geoWatchRef.current)+ geoWatchRef.current = null+ }+ } else {+ loadsRef.current = 0+ visibleRef.current = true+ }+ }, [suspended])+const answerConfirm = (confirmed: boolean) => {const req = confirmReqRef.currentif (req) postFrame({ type: 'trek:confirm:result', requestId: req.requestId, confirmed })@@ -682,36 +742,53 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, dconst pluginLabel = title || pluginIdconst confirmTitle = confirmReq?.title ? `${pluginLabel} — ${confirmReq.title}` : pluginLabel+ const pluginFrame = (+ <iframe+ key={pluginId}+ ref={frameRef}+ src={`/plugin-frame/${pluginId}/${path}`}+ // Deliver the context as soon as the document is parsed (the plugin sets up its+ // message listener during parse), closing the trek:ready race so the theme is+ // right on first paint. A 2nd load is a self-navigation — don't bridge to it.+ onLoad={() => {+ setLoadFailed(false)+ loadsRef.current += 1+ if (loadsRef.current === 1) {+ postFrame(buildContext())+ // A widget that loaded off screen (or a backgrounded app) learns so at once,+ // so it never starts its work just to be told to stop a frame later.+ if (!visibleRef.current) postFrame({ type: 'trek:visibility', visible: false })+ }+ // A self-navigated frame is no longer bridged, so its watch is only+ // burning battery for positions nobody receives.+ else if (geoWatchRef.current != null) { navigator.geolocation.clearWatch(geoWatchRef.current); geoWatchRef.current = null }+ }}+ onError={() => setLoadFailed(true)}+ sandbox="allow-scripts allow-forms"+ allowFullScreen+ allow="fullscreen"+ referrerPolicy="no-referrer"+ loading="lazy"+ title={title || pluginId}+ className={className}+ style={{ width: '100%', height: suspendable ? '100%' : fill ? '100%' : height ?? '100%', border: 0, display: loadFailed ? 'none' : undefined }}+ />+ )+return (// Third-party code: a throw in here must cost the plugin, not the page.<ErrorBoundary boundaryId="plugin-frame" label={pluginLabel} resetKeys={[pluginId]}><>- <iframe- key={pluginId}- ref={frameRef}- src={`/plugin-frame/${pluginId}/${path}`}- // Deliver the context as soon as the document is parsed (the plugin sets up its- // message listener during parse), closing the trek:ready race so the theme is- // right on first paint. A 2nd load is a self-navigation — don't bridge to it.- onLoad={() => {- setLoadFailed(false)- loadsRef.current += 1- if (loadsRef.current === 1) postFrame(buildContext())- // A self-navigated frame is no longer bridged, so its watch is only- // burning battery for positions nobody receives.- else if (geoWatchRef.current != null) { navigator.geolocation.clearWatch(geoWatchRef.current); geoWatchRef.current = null }- }}- onError={() => setLoadFailed(true)}- sandbox="allow-scripts allow-forms"- allowFullScreen- allow="fullscreen"- referrerPolicy="no-referrer"- loading="lazy"- title={title || pluginId}- className={className}- style={{ width: '100%', height: fill ? '100%' : height ?? '100%', border: 0, display: loadFailed ? 'none' : undefined }}- />- {loadFailed && (+ {suspendable ? (+ // Phone dashboard widget: the wrapper holds the widget's measured height so+ // the list does not jump when the iframe is unmounted off screen.+ <div ref={wrapRef} style={{ width: '100%', height: height ?? 160 }}>+ {!suspended && pluginFrame}+ </div>+ ) : (+ pluginFrame+ )}+ {loadFailed && !suspended && (<divrole="alert"className="flex items-center justify-center rounded-xl border border-edge bg-surface-2 p-6 text-caption text-content-2"diff --git a/plugin-sdk/package.json b/plugin-sdk/package.jsonindex c867bfa96..f0379e9aa 100644--- a/plugin-sdk/package.json+++ b/plugin-sdk/package.json@@ -1,6 +1,6 @@{"name": "trek-plugin-sdk",- "version": "1.9.0",+ "version": "1.9.1","description": "SDK for building TREK plugins: types, definePlugin, a mock host, manifest validation, and the create-trek-plugin / trek-plugin CLIs.","type": "module","license": "MIT",diff --git a/plugin-sdk/src/ui/kit.ts b/plugin-sdk/src/ui/kit.tsindex 25b74a422..4a4718a93 100644--- a/plugin-sdk/src/ui/kit.ts+++ b/plugin-sdk/src/ui/kit.ts@@ -475,6 +475,8 @@ export const TREK_THEME_JS = `(function () {var docEl = document.documentElement;var ctxHandlers = [];var evtHandlers = [];+ var visHandlers = [];+ var visible = true;var lastCtx = null;var pending = {};var pendingConfirms = {};@@ -555,6 +557,14 @@ export const TREK_THEME_JS = `(function () {for (var w = 0; w < geoWatchers.length; w++) { try { geoWatchers[w](m.position || null, m.error || null); } catch (e) {} }} else if (m.type === 'trek:event') {for (var j = 0; j < evtHandlers.length; j++) { try { evtHandlers[j](m.event, m.tripId); } catch (e) {} }+ } else if (m.type === 'trek:visibility') {+ // The host tells us when this frame leaves the screen or the app goes to the+ // background. Pause your timers, polling and animation here: a widget that keeps+ // working off screen bogs down the shared WebView on a phone. data-hidden lets the+ // kit CSS pause its own animations; onVisibility gets the plugin's own work.+ visible = m.visible !== false;+ setFlag('data-hidden', !visible);+ for (var v = 0; v < visHandlers.length; v++) { try { visHandlers[v](visible); } catch (e) {} }}});@@ -635,6 +645,14 @@ export const TREK_THEME_JS = `(function () {if (lastCtx) { try { cb(lastCtx); } catch (e) {} }return function () { var i = ctxHandlers.indexOf(cb); if (i >= 0) { ctxHandlers.splice(i, 1); } };},+ // Whether the frame is on screen and the app is in the foreground, and a hook for+ // the changes. Use it to pause heavy work while hidden; isVisible() seeds the first+ // run. Returns an unsubscribe.+ isVisible: function () { return visible; },+ onVisibility: function (cb) {+ visHandlers.push(cb);+ return function () { var i = visHandlers.indexOf(cb); if (i >= 0) { visHandlers.splice(i, 1); } };+ },notify: function (level, message, duration) { send({ type: 'trek:notify', level: level, message: message, duration: duration }); },navigate: function (to) { send({ type: 'trek:navigate', to: to }); },openExternal: function (url) { send({ type: 'trek:openExternal', url: url }); },