PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 1.1.4
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v1.1.4
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.4, at includes/registries/native-windows.php

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