PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 1.1.2
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v1.1.2
1.1.10 1.1.9 1.1.8 1.1.7 1.1.6 1.1.5 1.1.4 1.1.3 1.1.2 1.1.1 1.1.0 1.0.1 1.0.0 0.9.8 0.9.7 0.9.6 0.9.4 0.9.5 0.9.3 0.9.2 0.9.1 0.9.0 0.8.9 0.8.8 0.8.7 All 34 releases
desktop-mode / includes / registries / native-windows.php

native-windows.php in OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin 1.1.2, at includes/registries/native-windows.php

1,055 lines 38.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * OpenStation — Native windows registry.
4 *
5 * The largest of the five components.php registries — owns:
6 *
7 * - `openstation_register_window()` — plugin-author API
8 * - `openstation_native_window_registry()` — internal store
9 * - `openstation_native_window_allowed_html()` — wp_kses
10 * allowlist for `<template>` payloads
11 * - `openstation_build_native_window_template_html()` —
12 * wraps the registered template callback in tabs markup
13 * when the window has multiple registered tabs
14 * - `openstation_enqueue_native_window_scripts()` — enqueue
15 * hook that ships every registered window's script handle
16 * - `openstation_render_native_window_templates()` — renders
17 * the `<template>` elements the shell clones
18 *
19 * Extracted from `components.php` during the architecture-0.8.1
20 * PHP slicing (phase 6). The window-tabs registry that builds on
21 * top of this lives in `includes/registries/window-tabs.php`.
22 *
23 * @package OpenStation
24 */
25
26 defined( 'ABSPATH' ) || exit;
27
28 /**
29 * Register a PHP-owned native desktop window with one call.
30 *
31 * Under the hood this:
32 *
33 * 1. Captures the $args and stores them on a module-level
34 * registry so the relevant admin_footer + enqueue hooks fire
35 * only for the current user's openstation shell.
36 * 2. On `admin_footer` (shell-side only), emits
37 * `<template id="os-native-window-<id>">` wrapping the
38 * output of the `template` callback. Each registered window
39 * gets its own template element.
40 * 3. On `admin_enqueue_scripts` (shell-side), enqueues the
41 * caller's `script` handle if one was provided. The script
42 * registers a render callback at
43 * `window.openStationNativeWindows[<id>]`. On every window open
44 * the shell clones the registered template into the body and
45 * then invokes the callback — render is enhancement: query
46 * the body for mount points your template declared, light
47 * them up. Without a `script` the cloned template IS the
48 * window; declarative-only plugins need zero JS.
49 * 4. Passes a localized config blob to the script
50 * (`openStationNativeWindow_<id>`) carrying the window's
51 * `id`, `title`, `icon`, dimensions, and `placement`. The
52 * script then calls `wp.os.registerSystemTile()` +
53 * `wp.os.registerWindow()` to wire up the dock tile
54 * and the open-on-click behaviour.
55 *
56 * Plugins write the template callback + the render callback on
57 * the JS side; everything else is shell plumbing. Capability gate
58 * honours WP admin conventions: any `capabilities` entries must
59 * ALL match for the window to register.
60 *
61 * Note on scope: the shell doesn't auto-open windows server-side
62 * — `registerWindow` declares availability, not presence. Users
63 * click the registered tile (or your plugin calls
64 * `wp.os.windowManager.open()` programmatically) to surface
65 * the window.
66 *
67 * @param string $id Doubles as window id + dock-tile id. Must
68 * be a kebab-case-ish slug.
69 * @param array $args {
70 * Window registration options.
71 *
72 * @type string $title Window + tooltip title. Required.
73 * @type string $icon Dashicons class or URL. Required.
74 * @type callable $template Echoes the window body markup.
75 * Wrapped on `admin_footer` in a
76 * `<template id="os-native-window-
77 * <id>">`; cloned into the window
78 * body on every open. The render
79 * callback runs against the cloned
80 * body, so mount points declared in
81 * the template are guaranteed to be
82 * present.
83 * @type string $script Registered script handle that
84 * owns the JS render callback.
85 * Optional — omit for a purely
86 * declarative window whose body is
87 * exactly the cloned template.
88 * Loaded the first time the window
89 * opens, not at boot — see
90 * `$preload_script`.
91 * @type string[] $scripts Companion script handles loaded
92 * immediately before `$script`, in
93 * the order given. For a bundle that
94 * extends the window from outside it
95 * — subscribing to the window's own
96 * actions, contributing a section —
97 * and therefore has to be in the tab
98 * before the window's render callback
99 * paints. Declaring it here is what
100 * keeps it off the boot critical
101 * path: it travels with the window
102 * it extends. Default empty.
103 * @type bool $preload_script Load `$script` (and `$scripts`) at
104 * shell boot instead of on first
105 * open. Default false — a window's
106 * bundle is dead weight until the
107 * window opens, and the documented
108 * contract for it is "publish a
109 * render callback on
110 * `window.openStationNativeWindows[
111 * <id> ]`", which the shell reads at
112 * open time. Opt in only when the
113 * bundle ALSO has a boot-time job
114 * that must run whether or not the
115 * user ever opens the window — a
116 * dock badge poller, a public API it
117 * installs on `wp.os`. Prefer
118 * splitting that job into an
119 * always-loaded bundle over paying
120 * the whole window's weight on every
121 * admin page.
122 * @type int $width Initial width (px). Default 520.
123 * @type int $height Initial height (px). Default 400.
124 * @type int $min_width Minimum width (px). Default 280.
125 * @type int $min_height Minimum height (px). Default 220.
126 * @type string $placement 'dock' | 'none'. Default 'dock'.
127 * 'none' skips the tile (plugin
128 * opens the window programmatically).
129 * A PROPOSED default only: the user's
130 * OpenStation Preferences → Navigation
131 * pick wins, and so does a right-click
132 * "Keep in dock".
133 * @type string $nav_kind 'app' | 'control'. Default 'app'.
134 * What the window IS, which decides
135 * where its launcher defaults to (apps
136 * to the desktop, controls to the
137 * dock) and which dock zone it sits
138 * in. Plugins want 'app'; 'control'
139 * is for OpenStation's own
140 * affordances.
141 * @type int $dock_order Sort key among system tiles,
142 * ascending; ties keep registration
143 * order. Default 0, which places the
144 * tile ahead of the shell's own
145 * trailing cluster (Mio 10, Overview
146 * 20, System 30, Exit 35, Trash 40).
147 * Needed because registration order
148 * is not something a plugin controls:
149 * tiles land when their lazy script
150 * resolves.
151 * @type bool $placeable Whether the dock tile gets a row in
152 * OpenStation Preferences → Apps &
153 * Plugins, so the user can move it to
154 * the wallpaper or hide it. Defaults
155 * to the dock either way. Default
156 * false, because most tiles are
157 * load-bearing. Opt in for a window
158 * the user can reasonably do without.
159 * Only offer this on a window that
160 * registers no desktop icon: the icon
161 * already owns a row of its own.
162 * @type string[] $capabilities User capabilities that gate the
163 * registration. ANY miss returns
164 * `WP_Error openstation_capability_denied`.
165 * @type bool|string $autofocus Passed verbatim to
166 * `NativeWindowDef.autofocus`.
167 * @type string $main_tab_label Label for the "main" tab that
168 * displays the window's own
169 * `template` output. Only rendered
170 * when at least one additional
171 * tab is registered via
172 * {@see openstation_register_window_tab()}.
173 * Defaults to the window's `title`.
174 * @type int $main_tab_padding Padding (in px) applied to the
175 * auto-generated tab-wrap around
176 * the window body. Only applies
177 * when additional tabs are
178 * registered. Default 16. Pass 0
179 * for edge-to-edge content.
180 * Filterable at runtime via
181 * `openstation_native_window_tab_wrap_padding`.
182 * @type array $config Arbitrary serializable data to ship
183 * to the bundle alongside the script
184 * tag. Read in JS via
185 * `wp.os.getWindowConfig( $id )`
186 * (or directly at
187 * `window.openStationWindowConfig[ $id ]`).
188 * Recommended over `wp_localize_script`
189 * for native-window scripts because
190 * the lazy-load path bypasses
191 * `wp_print_scripts` — passing config
192 * through this arg guarantees delivery
193 * on both eager AND lazy paths
194 * (mid-session activation). Use this
195 * for REST URLs, nonces, capability
196 * flags, anything session-bound. Empty
197 * array (default) ships nothing.
198 * }
199 * @return true|WP_Error `true` on success; `WP_Error` when any
200 * required arg is missing/invalid or a
201 * declared capability is unmet.
202 */
203 function openstation_register_window( $id, $args = array() ) {
204 $id = sanitize_key( (string) $id );
205 if ( '' === $id ) {
206 return openstation_registration_error(
207 'openstation_missing_id',
208 __( 'Native window id is required and must be a valid slug.', 'desktop-mode' )
209 );
210 }
211
212 $defaults = array(
213 'title' => '',
214 'icon' => 'dashicons-admin-generic',
215 'template' => null,
216 'script' => '',
217 'scripts' => array(),
218 'preload_script' => false,
219 // Optional WP style handle (registered with `wp_register_style()`).
220 // Resolved at payload-build time so the shell can lazy-inject a
221 // `<link rel="stylesheet">` when a peer plugin is activated
222 // mid-session — without this, the parent shell page already
223 // finished `wp_print_styles` and the plugin's CSS is missing
224 // until F5.
225 'style' => '',
226 'width' => 520,
227 'height' => 400,
228 'min_width' => 280,
229 'min_height' => 220,
230 'placement' => 'dock',
231 'nav_kind' => 'app',
232 'dock_order' => 0,
233 'placeable' => false,
234 'capabilities' => array(),
235 'autofocus' => false,
236 'main_tab_label' => '',
237 'main_tab_padding' => '',
238 'config' => array(),
239 );
240 $args = wp_parse_args( $args, $defaults );
241
242 // Capability gate — ALL listed caps must match. Fail closed.
243 foreach ( (array) $args['capabilities'] as $cap ) {
244 if ( ! current_user_can( (string) $cap ) ) {
245 return openstation_registration_error(
246 'openstation_capability_denied',
247 sprintf(
248 /* translators: %s: capability slug. */
249 __( 'Current user lacks the %s capability required to register this native window.', 'desktop-mode' ),
250 (string) $cap
251 ),
252 array(
253 'capability' => (string) $cap,
254 'id' => $id,
255 )
256 );
257 }
258 }
259
260 // Required fields.
261 if ( '' === (string) $args['title'] ) {
262 return openstation_registration_error(
263 'openstation_missing_title',
264 __( 'Native window registration requires a non-empty `title`.', 'desktop-mode' ),
265 array( 'id' => $id )
266 );
267 }
268 if ( ! is_callable( $args['template'] ) ) {
269 return openstation_registration_error(
270 'openstation_invalid_template',
271 __( 'Native window registration requires a callable `template` that echoes the template body.', 'desktop-mode' ),
272 array( 'id' => $id )
273 );
274 }
275
276 $placement = in_array( $args['placement'], array( 'dock', 'none' ), true )
277 ? $args['placement']
278 : 'dock';
279
280 // What the window IS, which is what decides where its launcher
281 // goes by default and which dock zone it sits in. `'app'` for an
282 // installed app (the default, and what every plugin wants);
283 // `'control'` for an OpenStation affordance — the Trash is the
284 // only shipped one.
285 $nav_kind = in_array( $args['nav_kind'], array( 'app', 'control' ), true )
286 ? $args['nav_kind']
287 : 'app';
288
289 $entry = array(
290 'id' => $id,
291 'title' => (string) $args['title'],
292 'icon' => (string) $args['icon'],
293 'template' => $args['template'],
294 'script' => (string) $args['script'],
295 // Companion handles, deduped and stripped of empties so the
296 // payload builder can resolve the list without re-checking.
297 'scripts' => array_values(
298 array_unique(
299 array_filter(
300 array_map( 'strval', (array) $args['scripts'] ),
301 static function ( $handle ) {
302 return '' !== $handle;
303 }
304 )
305 )
306 ),
307 'preload_script' => (bool) $args['preload_script'],
308 'style' => (string) $args['style'],
309 'width' => (int) $args['width'],
310 'height' => (int) $args['height'],
311 'min_width' => (int) $args['min_width'],
312 'min_height' => (int) $args['min_height'],
313 'placement' => $placement,
314 'nav_kind' => $nav_kind,
315 // Sort key among system tiles, ascending. `0` (the default)
316 // puts a plugin's tile ahead of the shell's own trailing
317 // cluster — Mio 10, Overview 20, System 30 — which is where a
318 // launcher belongs. Trash uses 40 to sit at the very end.
319 'dock_order' => (int) $args['dock_order'],
320 'placeable' => (bool) $args['placeable'],
321 'autofocus' => $args['autofocus'],
322 'main_tab_label' => (string) $args['main_tab_label'],
323 // Stored as-is (string or int). `openstation_build_native_window_template_html`
324 // coerces to int and falls back to 16 when absent.
325 'main_tab_padding' => $args['main_tab_padding'],
326 // Bundle-bound config delivered through the same path as
327 // `wp_localize_script` `extra['data']` — see the `config` doc
328 // in this function's `$args` block and `openstation_resolve_script_payload()`
329 // for how it lands on the wire.
330 'config' => is_array( $args['config'] ) ? $args['config'] : array(),
331 );
332 openstation_native_window_registry( $id, $entry );
333
334 /**
335 * Fires after a native desktop window is successfully registered.
336 *
337 * Lets plugins react to registrations made by other plugins —
338 * e.g. a widget that auto-opens when a given window registers,
339 * or analytics tracking of which windows the current install
340 * exposes. Does NOT fire when `openstation_register_window()`
341 * returns a `WP_Error`.
342 *
343 * @param string $id The window id.
344 * @param array $entry The stored registry entry (id, title,
345 * icon, template callback, script handle,
346 * size defaults, placement, autofocus).
347 */
348 do_action( 'openstation_native_window_registered', $id, $entry );
349
350 return true;
351 }
352
353 /**
354 * Internal module-level registry for native windows registered
355 * via {@see openstation_register_window()}. Passing a second
356 * argument stores the entry; passing only the id returns the
357 * stored value (or null). Kept small and side-effect-free so
358 * tests can introspect.
359 *
360 * @internal
361 *
362 * @param string $id Window id.
363 * @param array|null $entry Entry to store, or null to just read.
364 * @return array|null Either the stored entry or the full registry
365 * (when id is empty).
366 */
367 function openstation_native_window_registry( $id = '', $entry = null ) {
368 static $store = array();
369
370 if ( '' === (string) $id ) {
371 return $store;
372 }
373 if ( null !== $entry ) {
374 $store[ $id ] = $entry;
375 }
376 return isset( $store[ $id ] ) ? $store[ $id ] : null;
377 }
378
379
380 /**
381 * Returns the `wp_kses`-shaped allowlist used to escape native-window
382 * `<template>` payloads (and the recycle-bin template) before they're
383 * emitted into the page.
384 *
385 * Templates are inert until JS clones them out of the `<template>`
386 * tag — but Plugin Check still requires escape-on-output. The list
387 * extends `wp_kses_allowed_html( 'post' )` with form controls,
388 * `<os-*>` web components, and dashicon spans, plus permissive
389 * `data-*`, common ARIA, and component-specific attributes. Plugins
390 * registering their own native windows can extend the list via the
391 * `openstation_native_window_allowed_html` filter below.
392 *
393 * @return array<string,array<string,bool>>
394 */
395 function openstation_native_window_allowed_html() {
396 $base = wp_kses_allowed_html( 'post' );
397
398 $global_attrs = array(
399 'id' => true,
400 'class' => true,
401 'style' => true,
402 'title' => true,
403 'role' => true,
404 'tabindex' => true,
405 'hidden' => true,
406 'slot' => true,
407 'part' => true,
408 'lang' => true,
409 'dir' => true,
410 'draggable' => true,
411 'contenteditable' => true,
412 'data-*' => true,
413 // `wp_kses` only treats the `data-*` wildcard specially. ARIA
414 // attributes must be admitted by their exact names or they are
415 // silently stripped from native-window templates.
416 'aria-label' => true,
417 'aria-labelledby' => true,
418 'aria-current' => true,
419 'aria-hidden' => true,
420 // `full-width` is a layout-level flag honoured by
421 // `<os-form>` (and any future os-* container that opts in
422 // to row-spanning slotted children). Lives in the global
423 // allowlist so a plain `<div full-width>` wrapper isn't
424 // stripped by kses on its way through the template.
425 'full-width' => true,
426 );
427
428 $form_attrs = array_merge(
429 $global_attrs,
430 array(
431 'name' => true,
432 'value' => true,
433 'placeholder' => true,
434 'required' => true,
435 'disabled' => true,
436 'readonly' => true,
437 'checked' => true,
438 'selected' => true,
439 'min' => true,
440 'max' => true,
441 'step' => true,
442 'minlength' => true,
443 'maxlength' => true,
444 'pattern' => true,
445 'autocomplete' => true,
446 'autofocus' => true,
447 'multiple' => true,
448 'rows' => true,
449 'cols' => true,
450 'wrap' => true,
451 'size' => true,
452 'for' => true,
453 'form' => true,
454 'type' => true,
455 'accept' => true,
456 'list' => true,
457 'src' => true,
458 'href' => true,
459 'target' => true,
460 'rel' => true,
461 'open' => true,
462 'variant' => true,
463 )
464 );
465
466 $wpd_attrs = array_merge(
467 $form_attrs,
468 array(
469 'gap' => true,
470 'padding' => true,
471 'align' => true,
472 'justify' => true,
473 'direction' => true,
474 'wrap' => true,
475 'inset' => true,
476 'icon' => true,
477 'tone' => true,
478 'size' => true,
479 'shape' => true,
480 'badge' => true,
481 'selectable' => true,
482 'sticky-header' => true,
483 'sticky-columns' => true,
484 'hover' => true,
485 'striped' => true,
486 'bordered' => true,
487 'compact' => true,
488 'loading' => true,
489 'loading-rows' => true,
490 'columns' => true,
491 'rows' => true,
492 'sortable' => true,
493 'expandable' => true,
494 'preset' => true,
495 'label' => true,
496 'description' => true,
497 'orientation' => true,
498 'level' => true,
499 'collapsed' => true,
500 // `<os-form>` props + the `full-width` row span flag
501 // honoured by the form's slotted-child layout rule.
502 'submit-label' => true,
503 'reset-label' => true,
504 'busy' => true,
505 'error' => true,
506 'min-column' => true,
507 'show-reset' => true,
508 'reveal' => true,
509 'full-width' => true,
510 )
511 );
512
513 // Built-in HTML elements the templates rely on.
514 $extra = array(
515 'form' => $form_attrs,
516 'fieldset' => $form_attrs,
517 'legend' => $global_attrs,
518 'label' => $form_attrs,
519 'input' => $form_attrs,
520 'select' => $form_attrs,
521 'option' => $form_attrs,
522 'optgroup' => $form_attrs,
523 'textarea' => $form_attrs,
524 'button' => $form_attrs,
525 'output' => $form_attrs,
526 'datalist' => $global_attrs,
527 'progress' => $form_attrs,
528 'meter' => $form_attrs,
529 'details' => $global_attrs,
530 'summary' => $global_attrs,
531 'dialog' => $global_attrs,
532 'header' => $global_attrs,
533 'footer' => $global_attrs,
534 'main' => $global_attrs,
535 'nav' => $global_attrs,
536 'section' => $global_attrs,
537 'article' => $global_attrs,
538 'aside' => $global_attrs,
539 'figure' => $global_attrs,
540 'figcaption' => $global_attrs,
541 'time' => array_merge( $global_attrs, array( 'datetime' => true ) ),
542 'mark' => $global_attrs,
543 'small' => $global_attrs,
544 'svg' => array_merge(
545 $global_attrs,
546 array(
547 'viewbox' => true,
548 'width' => true,
549 'height' => true,
550 'fill' => true,
551 'stroke' => true,
552 'xmlns' => true,
553 )
554 ),
555 'path' => array(
556 'd' => true,
557 'fill' => true,
558 'stroke' => true,
559 'stroke-width' => true,
560 'stroke-linecap' => true,
561 'stroke-linejoin' => true,
562 'class' => true,
563 ),
564 'g' => array(
565 'class' => true,
566 'transform' => true,
567 'fill' => true,
568 ),
569 'circle' => array(
570 'cx' => true,
571 'cy' => true,
572 'r' => true,
573 'fill' => true,
574 'stroke' => true,
575 'class' => true,
576 ),
577 'rect' => array(
578 'x' => true,
579 'y' => true,
580 'width' => true,
581 'height' => true,
582 'rx' => true,
583 'ry' => true,
584 'fill' => true,
585 'stroke' => true,
586 'class' => true,
587 ),
588 'line' => array(
589 'x1' => true,
590 'y1' => true,
591 'x2' => true,
592 'y2' => true,
593 'stroke' => true,
594 'stroke-width' => true,
595 'class' => true,
596 ),
597 'polyline' => array(
598 'points' => true,
599 'fill' => true,
600 'stroke' => true,
601 'class' => true,
602 ),
603 'polygon' => array(
604 'points' => true,
605 'fill' => true,
606 'stroke' => true,
607 'class' => true,
608 ),
609 'use' => array(
610 'href' => true,
611 'class' => true,
612 ),
613 );
614
615 // `<os-*>` web components — every shipped tag plus a permissive
616 // open door for new ones added by plugin templates.
617 $wpd_tags = array(
618 'os-stack',
619 'os-cluster',
620 'os-grid',
621 'os-spacer',
622 'os-divider',
623 'os-tabs',
624 'os-tab',
625 'os-tabpanel',
626 'os-segmented',
627 'os-segment',
628 'os-button',
629 'os-icon-button',
630 'os-button-group',
631 'os-text-field',
632 'os-textarea',
633 'os-search-field',
634 'os-select',
635 'os-option',
636 'os-checkbox',
637 'os-checkbox-label',
638 'os-radio',
639 'os-radio-group',
640 'os-form',
641 'os-switch',
642 'os-slider',
643 'os-table',
644 'os-table-column',
645 'os-table-row',
646 'os-table-cell',
647 'os-card',
648 'os-list',
649 'os-list-item',
650 'os-badge',
651 'os-pill',
652 'os-tag',
653 'os-chip',
654 'os-spinner',
655 'os-skeleton',
656 'os-empty-state',
657 'os-tooltip',
658 'os-popover',
659 'os-menu',
660 'os-menu-item',
661 'os-modal',
662 'os-drawer',
663 'os-toast',
664 'os-icon',
665 'os-avatar',
666 'os-heading',
667 'os-text',
668 'os-link',
669 'os-banner',
670 'os-alert',
671 'os-callout',
672 'os-form-row',
673 'os-form-section',
674 'os-help-text',
675 'os-toolbar',
676 'os-toolbar-group',
677 );
678 foreach ( $wpd_tags as $tag ) {
679 $extra[ $tag ] = $wpd_attrs;
680 }
681
682 $allowed = array_merge( $base, $extra );
683
684 // Promote the framework's global attrs (`slot`, `part`,
685 // `full-width`, `data-*`, common ARIA, …) to EVERY allowed tag —
686 // otherwise plain wrappers like `<div slot="header">` lose
687 // their `slot` attribute on the way through kses and get
688 // projected into the default slot instead of the named one.
689 // Caught by inspection when the Add User form's header
690 // rendered as a fields-grid cell instead of a banner above
691 // the fields. `array_merge( + )` with a kses-true value
692 // (boolean `true`) is harmless for tags whose entries are
693 // just `true` rather than an attrs map — array_merge skips
694 // non-array values.
695 foreach ( $allowed as $tag => $attrs ) {
696 if ( is_array( $attrs ) ) {
697 $allowed[ $tag ] = array_merge( $attrs, $global_attrs );
698 }
699 }
700
701 /**
702 * Filters the kses allowlist used when escaping native-window
703 * `<template>` payloads.
704 *
705 * Plugins registering their own native windows can extend the
706 * list with custom tags or attributes if their templates need
707 * markup not covered here.
708 *
709 * @param array $allowed wp_kses-shaped allowlist.
710 */
711 return (array) apply_filters( 'openstation_native_window_allowed_html', $allowed );
712 }
713
714 /**
715 * Run `wp_kses` on a native-window template body with the framework
716 * allowlist, **auto-extending the allowlist with every `<os-*>` tag
717 * the template actually uses.**
718 *
719 * The pain this fixes: each shipped `<os-*>` component had to be
720 * manually added to the `$wpd_tags` list above, and the failure mode
721 * of forgetting it was silent — kses would strip the tag, the
722 * template would render as a sea of unparented children, and you'd
723 * spend an afternoon working out why "the form has no buttons."
724 *
725 * Plugin authors registering a new component now only need to
726 * `defineComponent('os-foo', OsFoo)` on the JS side and use
727 * `<os-foo>` in their template — this helper finds the tag at
728 * render time, tags it onto the allowlist with the standard
729 * permissive attrs, and runs kses with the extended list.
730 *
731 * Every callsite in the framework that previously did the
732 * `wp_kses( $html, openstation_native_window_allowed_html() )`
733 * dance can call this instead and get tag-discovery for free.
734 *
735 * @param string $html Template HTML to sanitize.
736 * @return string Sanitized HTML.
737 */
738 function openstation_kses_native_window_template( $html ) {
739 $allowed = openstation_native_window_allowed_html();
740
741 if ( preg_match_all( '/<(os-[a-z][a-z0-9-]*)\b/i', (string) $html, $matches ) ) {
742 $unique = array_unique( array_map( 'strtolower', $matches[1] ) );
743 $wpd_attrs = isset( $allowed['os-button'] )
744 ? $allowed['os-button']
745 : array();
746 foreach ( $unique as $tag ) {
747 if ( ! isset( $allowed[ $tag ] ) ) {
748 $allowed[ $tag ] = $wpd_attrs;
749 }
750 }
751 }
752
753 return wp_kses( (string) $html, $allowed );
754 }
755
756 /**
757 * Render a native window's template HTML to a string, wrapping
758 * with tabs when the window has at least one additional tab
759 * registered. Shared by `openstation_render_native_window_templates()`
760 * (which emits the live `<template>` element) and
761 * `openstation_build_native_windows_payload()` (which captures the same
762 * string for the shell config so mid-session activation can inject
763 * the template without a reload).
764 *
765 * Single-tab windows (no additional tabs registered) render the
766 * same flat body they always did — backwards-compatible with
767 * every existing caller.
768 *
769 * @param array $entry Window registry entry.
770 * @return string Template body HTML (no outer `<template>` tag).
771 */
772 function openstation_build_native_window_template_html( $entry ) {
773 if ( ! is_array( $entry ) || ! is_callable( $entry['template'] ) ) {
774 return '';
775 }
776
777 $tabs = openstation_get_native_window_tabs( $entry['id'] );
778 $has_extras = count( $tabs ) > 1;
779
780 // Fast path — single-pane window, no wrapping.
781 if ( ! $has_extras ) {
782 ob_start();
783 call_user_func( $entry['template'] );
784 return (string) ob_get_clean();
785 }
786
787 // Multi-tab window — wrap in <os-stack> + one <os-tabpanel> per
788 // tab. The default active tab is the main one (the window's own
789 // template).
790 //
791 // The tab STRIP is deliberately absent from this markup. It is
792 // built by the shell in the window chrome, under the title bar,
793 // from the same tab metadata this function walks (the payload
794 // carries it as `tabs`). One tab strip per window, in one place,
795 // whether the window is an admin page in an iframe or a native
796 // window like this one.
797 //
798 // Plugin authors declare tab-change side effects by listening for
799 // `os-window-tab-change` on the window element; see
800 // docs/migration-window-tabs.md.
801 //
802 // The wrap's padding is plugin-controllable two ways:
803 // 1. `main_tab_padding` arg on `openstation_register_window` —
804 // a per-window override. `0` opts into edge-to-edge
805 // content.
806 // 2. `openstation_native_window_tab_wrap_padding` filter for
807 // late-bound overrides (e.g. a theme that wants every
808 // tabbed window to adopt a narrower inset).
809 // Default stays 16px so existing plugins don't shift.
810 $default_padding = isset( $entry['main_tab_padding'] )
811 && '' !== (string) $entry['main_tab_padding']
812 ? (int) $entry['main_tab_padding']
813 : 16;
814 /**
815 * Filters the padding (in px) applied to the auto-generated
816 * tab wrap around a native window's template body. The shell
817 * emits the wrap as `<os-stack padding="N">`; the CSS-as-
818 * attribute pipeline at the client translates that to
819 * `style.padding`.
820 *
821 * Return `0` for edge-to-edge content. Negative values are
822 * clamped to 0.
823 *
824 * @param int $padding Default padding in px.
825 * @param string $window_id The native window id.
826 */
827 $padding = (int) apply_filters(
828 'openstation_native_window_tab_wrap_padding',
829 $default_padding,
830 (string) $entry['id']
831 );
832 if ( $padding < 0 ) {
833 $padding = 0;
834 }
835
836 $buffer = sprintf(
837 '<os-stack gap="12" padding="%d">',
838 $padding
839 );
840
841 // Stamp `hidden` on every non-active panel directly in the
842 // emitted HTML. The shell takes over panel visibility as soon as
843 // it declares the strip, but that happens after the template is
844 // in the body — setting the attribute server-side makes first
845 // paint correct rather than flashing every pane at once.
846 foreach ( $tabs as $tab ) {
847 if ( ! is_callable( $tab['template'] ) ) {
848 continue;
849 }
850 $is_active = OPENSTATION_NATIVE_WINDOW_MAIN_TAB === $tab['value'];
851 $buffer .= sprintf(
852 '<os-tabpanel for="%s"%s>',
853 esc_attr( $tab['value'] ),
854 $is_active ? '' : ' hidden'
855 );
856 ob_start();
857 call_user_func( $tab['template'] );
858 $buffer .= (string) ob_get_clean();
859 $buffer .= '</os-tabpanel>';
860 }
861
862 $buffer .= '</os-stack>';
863 return $buffer;
864 }
865
866 /**
867 * Run a native window's registered `config` through the
868 * `openstation_native_window_config` filter, normalized to an array.
869 *
870 * Called at BOTH serialization points — the eager inline-script
871 * attach in `openstation_enqueue_native_window_scripts()` and the
872 * lazy `scriptL10n` synthesis in
873 * `openstation_build_native_windows_payload()` — so the filter sees
874 * every copy of the blob that can reach a browser.
875 *
876 * @param array $entry Registry entry (needs `id`; `config` optional).
877 * @return array Filtered config. Empty array when nothing to ship.
878 */
879 function openstation_filter_native_window_config( $entry ) {
880 $config = isset( $entry['config'] ) && is_array( $entry['config'] )
881 ? $entry['config']
882 : array();
883
884 /**
885 * Filter a native window's config blob at emit time.
886 *
887 * The registry snapshots `config` when `openstation_register_window()`
888 * runs — usually `init`. This filter runs when the blob is
889 * serialized for the browser (enqueue time on the eager path,
890 * payload-build time on the lazy path), so values that depend on
891 * hooks registered later in the bootstrap can be refreshed without
892 * moving the whole registration. The WP Explorer uses it to
893 * re-collect `previewActions` so plugins may add
894 * `openstation_my_wordpress_preview_actions` callbacks any time
895 * during a normal bootstrap, not just before `init` 99.
896 *
897 * Runs per request, after the current user is determined —
898 * capability-gated values are safe to compute here.
899 *
900 * **Status: Experimental**
901 *
902 * @param array $config Config blob as registered (empty array
903 * when the window registered none).
904 * @param string $window_id Native window id.
905 */
906 $config = apply_filters( 'openstation_native_window_config', $config, (string) $entry['id'] );
907
908 return is_array( $config ) ? $config : array();
909 }
910
911 /**
912 * Attach every registered native window's script data, and enqueue
913 * the handful of bundles that asked to load at boot.
914 *
915 * **A native window's bundle is not enqueued here.** It loads the
916 * first time the window opens: the shell reads the render callback
917 * off `window.openStationNativeWindows[ <id> ]` at open time, so a
918 * bundle printed at boot is weight on every admin page the window is
919 * never opened from — and between WP Explorer, Posts, Plugins,
920 * Comments, the Recycle Bin, Content Graph, Games and the agent
921 * runner that came to well over a megabyte before a single window
922 * had been clicked. `preload_script` is the opt-out for a bundle
923 * with a genuine boot-time job.
924 *
925 * What still happens for EVERY window is the data attach: the
926 * localize blob and the `config` inline. Those hang off the
927 * REGISTERED handle whether or not it is enqueued, which is exactly
928 * how the lazy path gets them — `openstation_resolve_script_payload()`
929 * harvests both into the payload for the shell to replay around the
930 * script tag it injects. Hence priority 5: `openstation_enqueue_assets()`
931 * builds that payload at 10, and data attached after it would ship a
932 * bundle with no config.
933 */
934 function openstation_enqueue_native_window_scripts() {
935 if ( ! openstation_is_enabled() || openstation_is_chromeless_request() || openstation_is_classic_request() ) {
936 return;
937 }
938 $registry = openstation_native_window_registry();
939 if ( ! is_array( $registry ) ) {
940 return;
941 }
942 foreach ( $registry as $entry ) {
943 $preload = ! empty( $entry['preload_script'] );
944
945 // Per-tab scripts stay eager. The shell has no lazy path for
946 // them — a tab's script is not part of the window's own
947 // bundle chain — so deferring here would simply break the
948 // tab. The main tab uses the window's own `script`.
949 $tabs = openstation_get_native_window_tabs( $entry['id'] );
950 foreach ( $tabs as $tab ) {
951 if ( $tab['is_main'] || empty( $tab['script'] ) ) {
952 continue;
953 }
954 wp_enqueue_script( $tab['script'] );
955 }
956
957 if ( empty( $entry['script'] ) ) {
958 continue;
959 }
960 if ( $preload ) {
961 wp_enqueue_script( $entry['script'] );
962 foreach ( (array) $entry['scripts'] as $companion ) {
963 wp_enqueue_script( $companion );
964 }
965 }
966 // Localize the config the JS side reads to register itself.
967 wp_localize_script(
968 $entry['script'],
969 'openStationNativeWindow_' . str_replace( '-', '_', $entry['id'] ),
970 array(
971 'id' => $entry['id'],
972 'title' => $entry['title'],
973 'icon' => $entry['icon'],
974 'width' => $entry['width'],
975 'height' => $entry['height'],
976 'minWidth' => $entry['min_width'],
977 'minHeight' => $entry['min_height'],
978 'placement' => $entry['placement'],
979 'autofocus' => $entry['autofocus'],
980 'templateId' => 'os-native-window-' . $entry['id'],
981 'tabs' => array_map(
982 static function ( $tab ) {
983 return array(
984 'value' => $tab['value'],
985 'label' => $tab['label'],
986 'isMain' => $tab['is_main'],
987 );
988 },
989 $tabs
990 ),
991 )
992 );
993
994 // Bundle-bound `config`, for the eager print path only.
995 // `openstation_build_native_windows_payload()` synthesizes the
996 // same assignment into the payload's `scriptL10n`, which is
997 // what delivers it on the lazy path — and it has to, because
998 // that payload is also built inside chromeless iframes, where
999 // this function returns early. Attaching here unconditionally
1000 // would mean a shell page shipped the identical assignment
1001 // twice: once as `before`, once as `l10n`. The bundle reads it
1002 // via `wp.os.getWindowConfig( id )` or directly at
1003 // `window.openStationWindowConfig[ id ]`.
1004 $config = openstation_filter_native_window_config( $entry );
1005 if ( $preload && ! empty( $config ) ) {
1006 wp_add_inline_script(
1007 $entry['script'],
1008 sprintf(
1009 'window.openStationWindowConfig=window.openStationWindowConfig||{};window.openStationWindowConfig[%s]=%s;',
1010 wp_json_encode( $entry['id'] ),
1011 wp_json_encode( $config )
1012 ),
1013 'before'
1014 );
1015 }
1016 }
1017 }
1018 add_action( 'admin_enqueue_scripts', 'openstation_enqueue_native_window_scripts', 5 );
1019
1020 /**
1021 * Emit a `<template>` tag for every registered native window on
1022 * `admin_footer` when the shell is active. The JS side resolves
1023 * these via `document.getElementById( `os-native-window-${id}` )`
1024 * and clones them into each opened window's body.
1025 */
1026 function openstation_render_native_window_templates() {
1027 if ( ! openstation_is_enabled() || openstation_is_chromeless_request() || openstation_is_classic_request() ) {
1028 return;
1029 }
1030 $registry = openstation_native_window_registry();
1031 if ( ! is_array( $registry ) ) {
1032 return;
1033 }
1034 foreach ( $registry as $entry ) {
1035 if ( ! is_callable( $entry['template'] ) ) {
1036 continue;
1037 }
1038 $html = openstation_build_native_window_template_html( $entry );
1039 if ( '' === $html ) {
1040 continue;
1041 }
1042 printf(
1043 '<template id="os-native-window-%s">',
1044 esc_attr( $entry['id'] )
1045 );
1046 // `openstation_kses_native_window_template()` auto-extends
1047 // the allowlist with any `<os-*>` tag the template carries
1048 // — so plugin authors never have to remember to register
1049 // their custom component tags in the kses list.
1050 echo openstation_kses_native_window_template( $html ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- helper kses-escapes.
1051 echo '</template>';
1052 }
1053 }
1054 add_action( 'admin_footer', 'openstation_render_native_window_templates', 20 );
1055