Skip to content

t1k:cocos:playable:layout

FieldValue
Moduleplayable
Version4.33.13
Efforthigh
Tools—

Keywords: aspect ratio, layout, responsive, safe area, UI

/t1k:cocos:playable:layout

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
  • 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, UIScreenResolution re-entrancy (references/safe-area-and-dpr.md)
  • ScreenResizedSignal fires once on onLoad immediately after detection — subscribe before onLoad completes if you need the initial value, or read service.category directly in start().
  • Plays well with the parameter system: subscribe to ScreenResizedSignal in ParameterController to 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/right CSS vars (built HTML maps them to env(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 ResponsiveLayoutService instance is allowed; a second onLoad call destroys the newer component.
  • Reading ResponsiveLayoutService.instance before the component’s onLoad has run — returns null. Always guard with a null check or access in start() / after a frame delay.
  • Calling adjustForAspectRatio without subscribing to ScreenResizedSignal — positions only set once and will not update if browser is resized.
  • Using scaleToFit on a node whose UITransform.contentSize is zero — method early-returns silently. Set contentSize explicitly.
  • ES2017 target: do not use optional chaining (?.) or nullish coalescing (??) in game code.
  • Cocos Widget aligns relative to parent at layout time — animating the parent breaks the widget unless alignFlags are reapplied per frame (or Widget.target is 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-image scripts/check-ui-geometry.cjs fails 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 Widget in ALWAYS mode 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. ALWAYS mode recomputes alignment as contentSize * node.scale (widget-manager.ts:112 horizontal, :175 vertical), and the Widget re-aligns on its own node’s TRANSFORM_CHANGED event which a scale write fires (widget.ts:892). Workarounds: animate position instead of scale; use centre alignment (isAlignHorizontalCenter / isAlignVerticalCenter — a centred anchorPoint alone is NOT enough, see the next gotcha); or switch to ONCE / ON_WINDOW_RESIZE mode 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 from t1k-cocos-playable-juice’s ONCE/ON_WINDOW_RESIZE staging-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.SafeArea cannot 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, not screen.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’s Node.EventType.SIZE_CHANGED and sets that same node’s size inside the handler is inherently self-triggering. It only appears stable because Cocos does not re-emit SIZE_CHANGED when 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. an AspectRatioSizeFitter.apply() that runs UITransform.setContentSize, or resizing referenced fitters — each pass changes a size again, SIZE_CHANGED re-fires, and because Cocos emits it synchronously the handler re-enters itself on the stack (not the event queue), producing RangeError: Maximum call stack size exceeded. Fix — guard the handler with a boolean flag in try/finally:
    private isResizing = false;
    private resizeToFullScreen(): void {
    if (this.isResizing) return;
    this.isResizing = true;
    try {
    // set sizes + trigger child fitters
    } finally {
    this.isResizing = false;
    }
    }
    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 / contentSize fitter and a full-screen cover resizer must NOT share a node — they compete for that node’s contentSize (last writer in the pass wins). Keep fitters on CHILD nodes so they read the sized parent and size only themselves. UIScreenResolution is the canonical instance, and its degenerate-frame test must reject NaN/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 — a UIScreenResolution component chaining AspectRatioSizeFitter.apply() inside its own SIZE_CHANGED handler.)
  • A layout cache key must include the Widget target box, not just the window. The window does not change when SafeArea does. Key on window/visible-size metrics PLUS each Widget target’s width,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-edge cc.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-gameflow references/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 _layer outside the UI camera’s mask, an anchor the owning component re-positions, or a parent alpha cascade: t1k-cocos-base-editor-mcp-truth references/invisible-node-checklist.md.