t1k:cocos:playable:layout
| Field | Value |
|---|---|
| Module | playable |
| Version | 4.33.13 |
| Effort | high |
| Tools | — |
Keywords: aspect ratio, layout, responsive, safe area, UI
How to invoke
Section titled “How to invoke”/t1k:cocos:playable:layoutResponsiveLayoutService
Section titled “ResponsiveLayoutService”Cocos Component singleton that detects device aspect ratio on load and on every canvas resize, categorizes it into NARROW/STANDARD/WIDE, fires ScreenResizedSignal via SignalBus, and provides helpers for adaptive node positioning and scaling. Attach to a persistent node in the scene (e.g. Canvas root). See also: t1k-cocos-playable-signalbus.
Import paths:
db://assets/packages/@playablelabs/game-foundation/layout
Details
Section titled “Details”- API reference: categories, signal, properties, methods (
references/api-reference.md) - Usage examples: signal subscription, adjustForAspectRatio, scaleToFit, getSafeArea (
references/usage-examples.md) - Fit policy: runtime picker re-run on every resize, wide landscape window, host-frame size, bar colour, cover backdrops, HUD width budget, build orientation (
references/fit-policy.md) - Safe area is 2D only, Widget align modes, DPR above the engine’s 2 clamp,
UIScreenResolutionre-entrancy (references/safe-area-and-dpr.md)
Integration Points
Section titled “Integration Points”ScreenResizedSignalfires once ononLoadimmediately after detection — subscribe beforeonLoadcompletes if you need the initial value, or readservice.categorydirectly instart().- Plays well with the parameter system: subscribe to
ScreenResizedSignalinParameterControllerto re-apply layout-sensitive parameter values when the device rotates or the browser is resized. getSafeArea()is safe to call unconditionally, but is NOT always zero on web: it reads--safe-top/bottom/left/rightCSS vars (built HTML maps them toenv(safe-area-inset-*)), non-zero on notched phones and in host-page previews that set them (e.g. a dashboard iPhone mockup). See Gotchas.- Only one
ResponsiveLayoutServiceinstance is allowed; a secondonLoadcall destroys the newer component.
Common Mistakes
Section titled “Common Mistakes”- Reading
ResponsiveLayoutService.instancebefore the component’sonLoadhas run — returns null. Always guard with a null check or access instart()/ after a frame delay. - Calling
adjustForAspectRatiowithout subscribing toScreenResizedSignal— positions only set once and will not update if browser is resized. - Using
scaleToFiton a node whoseUITransform.contentSizeis zero — method early-returns silently. SetcontentSizeexplicitly. - ES2017 target: do not use optional chaining (
?.) or nullish coalescing (??) in game code.
Hard rules
Section titled “Hard rules”- Cocos
Widgetaligns relative to parent at layout time — animating the parent breaks the widget unlessalignFlagsare reapplied per frame (orWidget.targetis locked). - Never scale a panel down to make it fit; re-lay it. A 1000x1000 panel set to scale ~0.6 so it sits above a nav bar renders its body text at 5-7 px on a phone. Resize the panel (or its container) and re-flow the children, and keep every panel’s cumulative scale >= 0.9; the effective text size is
authored font px x cumulative node scale, so a scaled-down parent shrinks every label under it. A uniform scale is for a pop-in tween or a card authored at another size, never for fitting a screen. Gate:t1k-cocos-playable-ui-from-imagescripts/check-ui-geometry.cjsfails a labelled panel scaled below 0.9 and any label under its px floor. Evidence: ForceMasterPort owner decision (extra panels at ~0.6 changed to near full screen; item-card text 7.7-10.2 px at 0.65 scale, then PanelRoot enlarged to render near 0.9). - A scale tween on an edge-aligned
WidgetinALWAYSmode DRIFTS the node across the screen — distinct from the parent-animation case above: the widget is correctly aligned at rest, and the tween itself is what moves it.ALWAYSmode recomputes alignment ascontentSize * node.scale(widget-manager.ts:112horizontal,:175vertical), and the Widget re-aligns on its own node’sTRANSFORM_CHANGEDevent which a scale write fires (widget.ts:892). Workarounds: animate position instead of scale; use centre alignment (isAlignHorizontalCenter/isAlignVerticalCenter— a centredanchorPointalone is NOT enough, see the next gotcha); or switch toONCE/ON_WINDOW_RESIZEmode for the tween duration (#780). See references/widget-always-mode-drift.md for the exact re-alignment formula, measured real-game numbers, an additional fix option, and how this differs fromt1k-cocos-playable-juice’sONCE/ON_WINDOW_RESIZEstaging-time variant. - Safe-area inset on iOS in-app webview is not always reported — provide a manual fallback inset of 24px top, 12px bottom.
cc.SafeAreacannot move a 3D/world-space node, and a preview inset does not prove a device; never port a fixed “notch offset” (safe-area-and-dpr.md (references/safe-area-and-dpr.md) §1). - The project’s fit flags are a boot default — install one runtime picker that re-applies the policy on every
window-resize, and read the host frame, notscreen.windowSize, while a pillarbox is on (fit-policy.md (references/fit-policy.md)). - Self-resizing layout Components need a re-entrancy guard on
SIZE_CHANGED— a Component that both listens to its OWN node’sNode.EventType.SIZE_CHANGEDand sets that same node’s size inside the handler is inherently self-triggering. It only appears stable because Cocos does not re-emitSIZE_CHANGEDwhen a size is set to its current value (the handler converges to a fixed point). The moment you chain ANY additional size mutation into that handler — e.g. anAspectRatioSizeFitter.apply()that runsUITransform.setContentSize, or resizing referenced fitters — each pass changes a size again,SIZE_CHANGEDre-fires, and because Cocos emits it synchronously the handler re-enters itself on the stack (not the event queue), producingRangeError: Maximum call stack size exceeded. Fix — guard the handler with a boolean flag in try/finally:Every re-entrant emission during the pass hits the guard and returns; after the pass the flag clears with nothing queued. Also: an aspect-ratio /private isResizing = false;private resizeToFullScreen(): void {if (this.isResizing) return;this.isResizing = true;try {// set sizes + trigger child fitters} finally {this.isResizing = false;}}contentSizefitter and a full-screen cover resizer must NOT share a node — they compete for that node’scontentSize(last writer in the pass wins). Keep fitters on CHILD nodes so they read the sized parent and size only themselves.UIScreenResolutionis the canonical instance, and its degenerate-frame test must rejectNaN/Infinity, not only<= 0(safe-area-and-dpr.md (references/safe-area-and-dpr.md) §4). (Observed 2026-07-02: Cocos 3.8.7 editor crash — aUIScreenResolutioncomponent chainingAspectRatioSizeFitter.apply()inside its ownSIZE_CHANGEDhandler.) - A layout cache key must include the Widget target box, not just the window. The window does not change when
SafeAreadoes. Key on window/visible-size metrics PLUS each Widget target’swidth,height,anchorX,anchorY,x,y, and re-base the pose driver when the key changes. - Test insets without a phone: before the view is shown, run
document.documentElement.style.setProperty('--safe-top','47px'); document.documentElement.style.setProperty('--safe-bottom','34px')in the preview or built HTML, then measure. Zero-inset previews hide this whole bug class. - A modal is only modal where its dimmer is. A Backdrop/Blocker authored at the design size (fixed position, no
cc.Widget) misses the top and bottom strips on a window taller than the design: the HUD shows undimmed above and below the card AND still takes taps. Author it with a four-edgecc.Widget(or as a child of a stretched root) and gate the top and bottom edge against the canvas, not against the card. Evidence:AirportEmpire 4811a97(4 popups, 11 prefabs). Input side of the same rule:t1k-cocos-playable-gameflowreferences/popup-input-and-stack.md§ 1. - Visibility is sibling index, and one viewport proves nothing. A later sibling paints over an earlier one and takes its tap with no error; a HUD laid out for one width stacks its rails on another. Gate it numerically at several widths: references/hud-overlap-matrix.md.
- A node that is present, sized, wired and invisible is, in order, a
_layeroutside the UI camera’s mask, an anchor the owning component re-positions, or a parent alpha cascade:t1k-cocos-base-editor-mcp-truthreferences/invisible-node-checklist.md.