Skip to content

Commit 35389a8

Browse files
KamilSztandurclaude
andcommitted
Live examples: one surface per view, views pooled and never removed
Two islands drawing in the same frame could paint one of them at the other's height: the engine's default rasterizer shares one offscreen surface between views and resizes it per draw, and draws are asynchronous (flutter/flutter#185034, open; also in 3.38 and in Skwasm). Reproduced with the async demo's spinner running while the hero grew its validation errors — the hero was cut at the async demo's height. With canvasKitForceMultiSurfaceRasterizer every view has its own surface and the race is gone. A surface costs two WebGL contexts that the engine never gives back on removeView, and browsers revoke the oldest live context past about sixteen — the flicker-and-blank islands seen earlier. So the runtimes (runtime.ts, landing.js) now keep a pool of four views and never remove one: an island that goes away parks its view off screen, the next island takes a parked view and points it at its own example through __advancedFormsIslandsSetExample (main.dart), and a reader scrolling back to a parked example gets it back as they left it. Verified in headless Chrome: contexts plateau at 11 across 18 navigations with zero "Too many active WebGL contexts" warnings, the hero renders fully 6/6 under the concurrent-draw test, and a re-aimed view renders pixel-identical to a fresh load of the same example. Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent 6e29281 commit 35389a8

6 files changed

Lines changed: 231 additions & 87 deletions

File tree

‎docs_app/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ debug asset server sends no CORS headers, unlike the release one.
129129
| `flutter/` | The Flutter package the snippets are compiled into |
130130
| `components/advanced-forms-example.tsx` | The MDX component; `components/example-frame.tsx` is the window around it |
131131
| `components/flutter-island.tsx` | Attaches and detaches one view |
132+
| `flutter/web/flutter_bootstrap.js` | Engine config: multi-view, one surface per view (see the comment there) |
132133
| `public/flutter-examples/` | Build output, gitignored |
133134

134135
## Design

‎docs_app/components/flutter-island.tsx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ interface FlutterIslandProps {
2525
*
2626
* Attaches when it comes near the viewport and stays attached afterwards, so
2727
* scrolling past an example and back does not wipe what the reader typed. The
28-
* shared runtime evicts the least useful view if a page has more islands than
29-
* the browser will give rendering surfaces for.
28+
* shared runtime hands out views from a small pool and evicts the least useful
29+
* one if a page has more islands than the pool holds.
3030
*/
3131
export function FlutterIsland({ exampleId, preview, height, onStatusChange }: FlutterIslandProps) {
3232
const hostRef = useRef<HTMLDivElement>(null)
@@ -82,7 +82,7 @@ export function FlutterIsland({ exampleId, preview, height, onStatusChange }: Fl
8282
setStatus("attaching")
8383

8484
attachIsland({
85-
host,
85+
container: host,
8686
exampleId,
8787
viewConstraints: height === undefined ? autoHeightConstraints : undefined,
8888
isVisible: () => visibleRef.current,

‎docs_app/flutter/lib/main.dart‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* AI-Provenance:
33
* model: Claude Opus 5
44
* harness: Cursor
5+
* edited-by: Claude Fable 5.1 (Claude Code)
56
*/
67
import 'dart:js_interop';
78
import 'dart:ui_web' as ui_web;
@@ -16,24 +17,53 @@ extension type _IslandOptions._(JSObject _) implements JSObject {
1617
external String? get exampleId;
1718
}
1819

20+
/// `window.__advancedFormsIslandsSetExample(viewId, exampleId)`: the host
21+
/// page's way to point an existing view at another example.
22+
///
23+
/// The page keeps a small pool of views and never removes one — the engine
24+
/// does not give a removed view's WebGL contexts back, and browsers revoke
25+
/// the oldest live context once about sixteen exist. A view that scrolls out
26+
/// of use is parked and later re-aimed at whatever example needs a view next.
27+
@JS('__advancedFormsIslandsSetExample')
28+
external set _setExample(JSFunction function);
29+
30+
/// The example each view shows, by view id. Created on first build with the
31+
/// example the host passed to `addView`; changed by [_setExample].
32+
final _examples = <int, ValueNotifier<String?>>{};
33+
1934
void main() {
2035
// The docs page owns the address bar. Without this a Navigator inside an
2136
// island can rewrite the URL of the page hosting it, and multi-view routing
2237
// is not supported anyway (flutter/flutter#139174).
2338
ui_web.urlStrategy = null;
2439

40+
_setExample = (JSNumber viewId, JSString? exampleId) {
41+
_examples
42+
.putIfAbsent(viewId.toDartInt, () => ValueNotifier<String?>(null))
43+
.value =
44+
exampleId?.toDart;
45+
}.toJS;
46+
2547
// `runApp` needs an implicit view, which does not exist in multi-view mode.
2648
// `runWidget` renders only into views the host has explicitly added.
2749
runWidget(
2850
MultiViewApp(
2951
viewBuilder: (context) {
3052
final viewId = View.of(context).viewId;
31-
final options = ui_web.views.getInitialData(viewId) as _IslandOptions?;
32-
final exampleId = options?.exampleId;
53+
final example = _examples.putIfAbsent(viewId, () {
54+
final options =
55+
ui_web.views.getInitialData(viewId) as _IslandOptions?;
56+
return ValueNotifier(options?.exampleId);
57+
});
3358

34-
return IslandShell(
35-
exampleId: exampleId,
36-
builder: exampleId == null ? null : examples[exampleId],
59+
return ValueListenableBuilder(
60+
valueListenable: example,
61+
builder: (context, exampleId, _) => IslandShell(
62+
// A new key per example: switching resets the example's state.
63+
key: ValueKey(exampleId),
64+
exampleId: exampleId,
65+
builder: exampleId == null ? null : examples[exampleId],
66+
),
3767
);
3868
},
3969
),

‎docs_app/flutter/web/flutter_bootstrap.js‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,17 @@
2626
const config = {
2727
renderer: "canvaskit",
2828
multiViewEnabled: true,
29-
// One shared surface for every view, the engine's default. The
30-
// multi-surface rasterizer gives each view its own WebGL context and the
31-
// engine keeps allocating them across view add/remove cycles, until the
32-
// browser starts revoking the oldest ones: the islands flicker and then
33-
// go blank ("Too many active WebGL contexts"). The size race the shared
34-
// rasterizer has when several views first render in the same frame
35-
// (flutter/flutter#185034) is avoided by attaching one island at a time,
36-
// in runtime.ts.
29+
// One surface per view. The engine's default shares one offscreen surface
30+
// between all views and resizes it for each draw; draws are asynchronous,
31+
// so when two islands render in the same frame one of them is painted at
32+
// the other's height and its lower part vanishes (flutter/flutter#185034,
33+
// open; the same race is in 3.38 and in Skwasm). With a surface per view
34+
// there is nothing to share. The price is two WebGL contexts per view,
35+
// which the engine never gives back after removeView — and browsers cap
36+
// live contexts at about 16, then revoke the oldest, live or not — so the
37+
// runtimes (runtime.ts, landing.js) keep a small pool of views and never
38+
// remove one.
39+
canvasKitForceMultiSurfaceRasterizer: true,
3740
// One CanvasKit for every browser. `auto` would try the Chromium-only
3841
// build first, which the bundle no longer ships, costing a 404 per load.
3942
canvasKitVariant: "full",

‎docs_app/lib/flutter-examples/runtime.ts‎

Lines changed: 114 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* AI-Provenance:
33
* model: Claude Opus 5
44
* harness: Cursor
5+
* edited-by: Claude Fable 5.1 (Claude Code)
56
*/
67
"use client"
78

@@ -10,19 +11,30 @@
1011
*
1112
* Multiple Flutter *engines* on one page are not supported and never will be —
1213
* they fight over globals on `window`. Multi-view embedding is the supported
13-
* shape: a single engine that renders into any number of host elements, added
14-
* and removed at runtime. This module owns that engine and hands out views.
14+
* shape: a single engine that renders into any number of host elements. This
15+
* module owns that engine and hands out views from a small pool.
16+
*
17+
* The pool, rather than adding and removing views as islands come and go:
18+
* every view owns two WebGL contexts (see flutter/web/flutter_bootstrap.js),
19+
* the engine does not give them back on `removeView`, and browsers revoke the
20+
* oldest live context once about sixteen exist — an island still on screen
21+
* then flickers and goes blank. So a view is created at most `poolSize` times
22+
* per page load and never removed: an island that unmounts parks its view off
23+
* screen, and the next island that needs one takes a parked view and points it
24+
* at its own example (`__advancedFormsIslandsSetExample`, see main.dart). A
25+
* reader who scrolls back to an example still parked gets it back as they left
26+
* it. landing/web/landing.js mirrors this file; keep the two in step.
1527
*/
1628

1729
/** Where `flutter build web -o` puts the bundle, relative to the site root. */
1830
const bundleBase = "/flutter-examples/"
1931

2032
/**
21-
* Each view gets its own rendering surface, and therefore its own WebGL
22-
* context; browsers stop handing those out somewhere around 16. Capping well
23-
* below that leaves room for everything else on the page.
33+
* Views alive at once, and so the most islands that can run on one page.
34+
* Two WebGL contexts each, plus the engine's own few, stays well under the
35+
* browser cap of about sixteen.
2436
*/
25-
const maxAttachedViews = 4
37+
const poolSize = 4
2638

2739
interface ViewConstraints {
2840
minWidth?: number
@@ -40,6 +52,8 @@ declare global {
4052
interface Window {
4153
__advancedFormsIslands?: Promise<FlutterApp>
4254
__advancedFormsIslandsConfig?: { assetBase?: string }
55+
/** Installed by the Flutter side (main.dart) once the engine runs. */
56+
__advancedFormsIslandsSetExample?: (viewId: number, exampleId: string | null) => void
4357
}
4458
}
4559

@@ -71,84 +85,144 @@ function loadEngine(): Promise<FlutterApp> {
7185
}
7286

7387
export interface IslandRequest {
74-
host: HTMLElement
88+
/** Where the view goes. The runtime appends its own host element to it. */
89+
container: HTMLElement
7590
exampleId: string
7691
/** Omit for a fixed-height island: the engine then measures the host. */
7792
viewConstraints?: ViewConstraints
7893
/** Whether this island is on or near the screen, asked when making room. */
7994
isVisible: () => boolean
80-
/** Called when the view is torn down to make room for another island. */
95+
/** Called when the view is taken away to serve another island. */
8196
onEvicted: () => void
8297
}
8398

8499
export interface AttachedIsland {
85100
detach(): void
86101
}
87102

88-
interface Entry {
103+
/** One pooled view: created once, re-aimed and re-parented for its whole life. */
104+
interface PooledView {
89105
viewId: number
90-
request: IslandRequest
91-
detached: boolean
106+
/** The element the engine renders into; moves between containers and the lot. */
107+
host: HTMLDivElement
108+
/** Auto-height views and fixed-height views have different constraints, set at creation. */
109+
auto: boolean
110+
exampleId: string
111+
/** The island using the view right now, if any. */
112+
request?: IslandRequest
113+
/** When the view was last parked; the least recently used one is re-aimed first. */
114+
parkedAt: number
92115
}
93116

94-
/** Attached views, oldest first. */
95-
const attached: Entry[] = []
117+
const pool: PooledView[] = []
96118

97119
let queue: Promise<unknown> = Promise.resolve()
98120

99121
const nextFrame = () => new Promise<void>(resolve => requestAnimationFrame(() => resolve()))
100122

101-
function detach(entry: Entry, evicted = false) {
102-
if (entry.detached) return
103-
entry.detached = true
123+
/**
124+
* Where parked views live: off screen but laid out, so the engine keeps a
125+
* sensible width and never sees a zero-sized view.
126+
*/
127+
let parkingLot: HTMLDivElement | undefined
128+
129+
function park(view: PooledView) {
130+
if (!parkingLot) {
131+
parkingLot = document.createElement("div")
132+
parkingLot.setAttribute("aria-hidden", "true")
133+
parkingLot.style.cssText =
134+
"position:fixed;top:0;left:-200vw;width:640px;height:0;overflow:visible;visibility:hidden;pointer-events:none"
135+
document.body.append(parkingLot)
136+
}
137+
view.request = undefined
138+
view.parkedAt = performance.now()
139+
parkingLot.append(view.host)
140+
}
104141

105-
const index = attached.indexOf(entry)
106-
if (index !== -1) attached.splice(index, 1)
142+
function place(view: PooledView, request: IslandRequest) {
143+
view.request = request
144+
request.container.append(view.host)
145+
}
107146

108-
void loadEngine().then(app => app.removeView(entry.viewId))
109-
if (evicted) entry.request.onEvicted()
147+
function detach(view: PooledView, evicted = false) {
148+
if (!view.request) return
149+
const { onEvicted } = view.request
150+
park(view)
151+
if (evicted) onEvicted()
110152
}
111153

112-
/** Drops off-screen views before adding one, preferring to keep what is visible. */
113-
function makeRoom() {
114-
while (attached.length >= maxAttachedViews) {
115-
detach(attached.find(entry => !entry.request.isVisible()) ?? attached[0], true)
116-
}
154+
function makeHost() {
155+
const host = document.createElement("div")
156+
host.style.cssText = "display:block;width:100%;height:100%"
157+
return host
158+
}
159+
160+
/** The view to re-aim when the pool is full: parked and least recently used, else the least visible. */
161+
function reclaim(auto: boolean): PooledView | undefined {
162+
const candidates = pool.filter(view => view.auto === auto)
163+
const parked = candidates.filter(view => !view.request).sort((a, b) => a.parkedAt - b.parkedAt)
164+
if (parked.length > 0) return parked[0]
165+
const victim = candidates.find(view => !view.request?.isVisible()) ?? candidates[0]
166+
if (victim) detach(victim, true)
167+
return victim
117168
}
118169

119170
/**
120-
* Adds one view, serialized against every other island on the page.
171+
* Gives one island a view, serialized against every other island on the page.
121172
*
122173
* The serialization is deliberate: views that first lay out in the same frame
123174
* can end up sharing a size (flutter/flutter#185034), so each one is given a
124-
* couple of frames to settle before the next is added.
175+
* couple of frames to settle before the next is touched.
125176
*/
126177
export function attachIsland(request: IslandRequest): Promise<AttachedIsland> {
178+
const auto = request.viewConstraints !== undefined
179+
127180
const attach = async (): Promise<AttachedIsland> => {
128181
const app = await loadEngine()
129-
makeRoom()
130-
131-
const entry: Entry = {
132-
viewId: app.addView({
133-
hostElement: request.host,
134-
initialData: { exampleId: request.exampleId },
135-
viewConstraints: request.viewConstraints,
136-
}),
137-
request,
138-
detached: false,
182+
183+
// A parked view still showing this very example: the reader gets it back
184+
// exactly as they left it.
185+
let view = pool.find(
186+
candidate => !candidate.request && candidate.auto === auto && candidate.exampleId === request.exampleId,
187+
)
188+
189+
if (!view && pool.length < poolSize) {
190+
const host = makeHost()
191+
request.container.append(host)
192+
view = {
193+
viewId: app.addView({
194+
hostElement: host,
195+
initialData: { exampleId: request.exampleId },
196+
viewConstraints: request.viewConstraints,
197+
}),
198+
host,
199+
auto,
200+
exampleId: request.exampleId,
201+
parkedAt: 0,
202+
}
203+
pool.push(view)
139204
}
140-
attached.push(entry)
205+
206+
if (!view) {
207+
view = reclaim(auto)
208+
if (!view) throw new Error("No Flutter view available for this island.")
209+
view.exampleId = request.exampleId
210+
window.__advancedFormsIslandsSetExample?.(view.viewId, request.exampleId)
211+
}
212+
213+
place(view, request)
141214

142215
await nextFrame()
143216
await nextFrame()
144217

145-
return { detach: () => detach(entry) }
218+
const placed = view
219+
return { detach: () => detach(placed) }
146220
}
147221

148222
const result = queue.then(attach, attach)
149223
queue = result.catch(() => undefined)
150224
return result
151225
}
152226

153-
/** Vertical constraints that let the island size itself to its content. */
227+
/** The constraints for an island whose height follows its content. */
154228
export const autoHeightConstraints: ViewConstraints = { minHeight: 0, maxHeight: Infinity }

0 commit comments

Comments
 (0)