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

1,094 lines 40.8 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 'columns' => true,
522 'rows' => true,
523 'sortable' => true,
524 'expandable' => true,
525 'preset' => true,
526 'label' => true,
527 'description' => true,
528 'orientation' => true,
529 'level' => true,
530 'collapsed' => true,
531 // `<os-form>` props + the `full-width` row span flag
532 // honoured by the form's slotted-child layout rule.
533 'submit-label' => true,
534 'reset-label' => true,
535 'busy' => true,
536 'error' => true,
537 'min-column' => true,
538 'show-reset' => true,
539 'reveal' => true,
540 'full-width' => true,
541 )
542 );
543
544 // Built-in HTML elements the templates rely on.
545 $extra = array(
546 'form' => $form_attrs,
547 'fieldset' => $form_attrs,
548 'legend' => $global_attrs,
549 'label' => $form_attrs,
550 'input' => $form_attrs,
551 'select' => $form_attrs,
552 'option' => $form_attrs,
553 'optgroup' => $form_attrs,
554 'textarea' => $form_attrs,
555 'button' => $form_attrs,
556 'output' => $form_attrs,
557 'datalist' => $global_attrs,
558 'progress' => $form_attrs,
559 'meter' => $form_attrs,
560 'details' => $global_attrs,
561 'summary' => $global_attrs,
562 'dialog' => $global_attrs,
563 'header' => $global_attrs,
564 'footer' => $global_attrs,
565 'main' => $global_attrs,
566 'nav' => $global_attrs,
567 'section' => $global_attrs,
568 'article' => $global_attrs,
569 'aside' => $global_attrs,
570 'figure' => $global_attrs,
571 'figcaption' => $global_attrs,
572 'time' => array_merge( $global_attrs, array( 'datetime' => true ) ),
573 'mark' => $global_attrs,
574 'small' => $global_attrs,
575 'svg' => array_merge(
576 $global_attrs,
577 array(
578 'viewbox' => true,
579 'width' => true,
580 'height' => true,
581 'fill' => true,
582 'stroke' => true,
583 'xmlns' => true,
584 )
585 ),
586 'path' => array(
587 'd' => true,
588 'fill' => true,
589 'stroke' => true,
590 'stroke-width' => true,
591 'stroke-linecap' => true,
592 'stroke-linejoin' => true,
593 'class' => true,
594 ),
595 'g' => array(
596 'class' => true,
597 'transform' => true,
598 'fill' => true,
599 ),
600 'circle' => array(
601 'cx' => true,
602 'cy' => true,
603 'r' => true,
604 'fill' => true,
605 'stroke' => true,
606 'class' => true,
607 ),
608 'rect' => array(
609 'x' => true,
610 'y' => true,
611 'width' => true,
612 'height' => true,
613 'rx' => true,
614 'ry' => true,
615 'fill' => true,
616 'stroke' => true,
617 'class' => true,
618 ),
619 'line' => array(
620 'x1' => true,
621 'y1' => true,
622 'x2' => true,
623 'y2' => true,
624 'stroke' => true,
625 'stroke-width' => true,
626 'class' => true,
627 ),
628 'polyline' => array(
629 'points' => true,
630 'fill' => true,
631 'stroke' => true,
632 'class' => true,
633 ),
634 'polygon' => array(
635 'points' => true,
636 'fill' => true,
637 'stroke' => true,
638 'class' => true,
639 ),
640 'use' => array(
641 'href' => true,
642 'class' => true,
643 ),
644 );
645
646 // `<os-*>` web components — every shipped tag plus a permissive
647 // open door for new ones added by plugin templates.
648 $wpd_tags = array(
649 'os-stack',
650 'os-cluster',
651 'os-grid',
652 'os-spacer',
653 'os-divider',
654 'os-tabs',
655 'os-tab',
656 'os-tabpanel',
657 'os-segmented',
658 'os-segment',
659 'os-button',
660 'os-icon-button',
661 'os-button-group',
662 'os-text-field',
663 'os-textarea',
664 'os-search-field',
665 'os-select',
666 'os-option',
667 'os-checkbox',
668 'os-checkbox-label',
669 'os-radio',
670 'os-radio-group',
671 'os-form',
672 'os-switch',
673 'os-slider',
674 'os-table',
675 'os-table-column',
676 'os-table-row',
677 'os-table-cell',
678 'os-card',
679 'os-list',
680 'os-list-item',
681 'os-badge',
682 'os-pill',
683 'os-tag',
684 'os-chip',
685 'os-spinner',
686 'os-skeleton',
687 'os-empty-state',
688 'os-tooltip',
689 'os-popover',
690 'os-menu',
691 'os-menu-item',
692 'os-modal',
693 'os-drawer',
694 'os-toast',
695 'os-icon',
696 'os-avatar',
697 'os-heading',
698 'os-text',
699 'os-link',
700 'os-banner',
701 'os-alert',
702 'os-callout',
703 'os-form-row',
704 'os-form-section',
705 'os-help-text',
706 'os-toolbar',
707 'os-toolbar-group',
708 );
709 foreach ( $wpd_tags as $tag ) {
710 $extra[ $tag ] = $wpd_attrs;
711 }
712
713 $allowed = array_merge( $base, $extra );
714
715 // Promote the framework's global attrs (`slot`, `part`,
716 // `full-width`, `data-*`, common ARIA, …) to EVERY allowed tag —
717 // otherwise plain wrappers like `<div slot="header">` lose
718 // their `slot` attribute on the way through kses and get
719 // projected into the default slot instead of the named one.
720 // Caught by inspection when the Add User form's header
721 // rendered as a fields-grid cell instead of a banner above
722 // the fields. `array_merge( + )` with a kses-true value
723 // (boolean `true`) is harmless for tags whose entries are
724 // just `true` rather than an attrs map — array_merge skips
725 // non-array values.
726 foreach ( $allowed as $tag => $attrs ) {
727 if ( is_array( $attrs ) ) {
728 $allowed[ $tag ] = array_merge( $attrs, $global_attrs );
729 }
730 }
731
732 /**
733 * Filters the kses allowlist used when escaping native-window
734 * `<template>` payloads.
735 *
736 * Plugins registering their own native windows can extend the
737 * list with custom tags or attributes if their templates need
738 * markup not covered here.
739 *
740 * @param array $allowed wp_kses-shaped allowlist.
741 */
742 return (array) apply_filters( 'openstation_native_window_allowed_html', $allowed );
743 }
744
745 /**
746 * Run `wp_kses` on a native-window template body with the framework
747 * allowlist, **auto-extending the allowlist with every `<os-*>` tag
748 * the template actually uses.**
749 *
750 * The pain this fixes: each shipped `<os-*>` component had to be
751 * manually added to the `$wpd_tags` list above, and the failure mode
752 * of forgetting it was silent — kses would strip the tag, the
753 * template would render as a sea of unparented children, and you'd
754 * spend an afternoon working out why "the form has no buttons."
755 *
756 * Plugin authors registering a new component now only need to
757 * `defineComponent('os-foo', OsFoo)` on the JS side and use
758 * `<os-foo>` in their template — this helper finds the tag at
759 * render time, tags it onto the allowlist with the standard
760 * permissive attrs, and runs kses with the extended list.
761 *
762 * Every callsite in the framework that previously did the
763 * `wp_kses( $html, openstation_native_window_allowed_html() )`
764 * dance can call this instead and get tag-discovery for free.
765 *
766 * @param string $html Template HTML to sanitize.
767 * @return string Sanitized HTML.
768 */
769 function openstation_kses_native_window_template( $html ) {
770 $allowed = openstation_native_window_allowed_html();
771
772 if ( preg_match_all( '/<(os-[a-z][a-z0-9-]*)\b/i', (string) $html, $matches ) ) {
773 $unique = array_unique( array_map( 'strtolower', $matches[1] ) );
774 $wpd_attrs = isset( $allowed['os-button'] )
775 ? $allowed['os-button']
776 : array();
777 foreach ( $unique as $tag ) {
778 if ( ! isset( $allowed[ $tag ] ) ) {
779 $allowed[ $tag ] = $wpd_attrs;
780 }
781 }
782 }
783
784 return wp_kses( (string) $html, $allowed );
785 }
786
787 /**
788 * Render a native window's template HTML to a string, wrapping
789 * with tabs when the window has at least one additional tab
790 * registered. Shared by `openstation_render_native_window_templates()`
791 * (which emits the live `<template>` element) and
792 * `openstation_build_native_windows_payload()` (which captures the same
793 * string for the shell config so mid-session activation can inject
794 * the template without a reload).
795 *
796 * Single-tab windows (no additional tabs registered) render the
797 * same flat body they always did — backwards-compatible with
798 * every existing caller.
799 *
800 * @param array $entry Window registry entry.
801 * @return string Template body HTML (no outer `<template>` tag).
802 */
803 function openstation_build_native_window_template_html( $entry ) {
804 if ( ! is_array( $entry ) || ! is_callable( $entry['template'] ) ) {
805 return '';
806 }
807
808 $tabs = openstation_get_native_window_tabs( $entry['id'] );
809 $has_extras = count( $tabs ) > 1;
810
811 // Fast path — single-pane window, no wrapping.
812 if ( ! $has_extras ) {
813 ob_start();
814 call_user_func( $entry['template'] );
815 return (string) ob_get_clean();
816 }
817
818 // Multi-tab window — wrap in <os-stack> + one <os-tabpanel> per
819 // tab. The default active tab is the main one (the window's own
820 // template).
821 //
822 // The tab STRIP is deliberately absent from this markup. It is
823 // built by the shell in the window chrome, under the title bar,
824 // from the same tab metadata this function walks (the payload
825 // carries it as `tabs`). One tab strip per window, in one place,
826 // whether the window is an admin page in an iframe or a native
827 // window like this one.
828 //
829 // Plugin authors declare tab-change side effects by listening for
830 // `os-window-tab-change` on the window element; see
831 // docs/migration-window-tabs.md.
832 //
833 // The wrap's padding is plugin-controllable two ways:
834 // 1. `main_tab_padding` arg on `openstation_register_window` —
835 // a per-window override. `0` opts into edge-to-edge
836 // content.
837 // 2. `openstation_native_window_tab_wrap_padding` filter for
838 // late-bound overrides (e.g. a theme that wants every
839 // tabbed window to adopt a narrower inset).
840 // Default stays 16px so existing plugins don't shift.
841 $default_padding = isset( $entry['main_tab_padding'] )
842 && '' !== (string) $entry['main_tab_padding']
843 ? (int) $entry['main_tab_padding']
844 : 16;
845 /**
846 * Filters the padding (in px) applied to the auto-generated
847 * tab wrap around a native window's template body. The shell
848 * emits the wrap as `<os-stack padding="N">`; the CSS-as-
849 * attribute pipeline at the client translates that to
850 * `style.padding`.
851 *
852 * Return `0` for edge-to-edge content. Negative values are
853 * clamped to 0.
854 *
855 * @param int $padding Default padding in px.
856 * @param string $window_id The native window id.
857 */
858 $padding = (int) apply_filters(
859 'openstation_native_window_tab_wrap_padding',
860 $default_padding,
861 (string) $entry['id']
862 );
863 if ( $padding < 0 ) {
864 $padding = 0;
865 }
866
867 $buffer = sprintf(
868 '<os-stack gap="12" padding="%d">',
869 $padding
870 );
871
872 // Stamp `hidden` on every non-active panel directly in the
873 // emitted HTML. The shell takes over panel visibility as soon as
874 // it declares the strip, but that happens after the template is
875 // in the body — setting the attribute server-side makes first
876 // paint correct rather than flashing every pane at once.
877 foreach ( $tabs as $tab ) {
878 if ( ! is_callable( $tab['template'] ) ) {
879 continue;
880 }
881 $is_active = OPENSTATION_NATIVE_WINDOW_MAIN_TAB === $tab['value'];
882 $buffer .= sprintf(
883 '<os-tabpanel for="%s"%s>',
884 esc_attr( $tab['value'] ),
885 $is_active ? '' : ' hidden'
886 );
887 ob_start();
888 call_user_func( $tab['template'] );
889 $buffer .= (string) ob_get_clean();
890 $buffer .= '</os-tabpanel>';
891 }
892
893 $buffer .= '</os-stack>';
894 return $buffer;
895 }
896
897 /**
898 * Run a native window's registered `config` through the
899 * `openstation_native_window_config` filter, normalized to an array.
900 *
901 * Called at BOTH serialization points — the eager inline-script
902 * attach in `openstation_enqueue_native_window_scripts()` and the
903 * lazy `scriptL10n` synthesis in
904 * `openstation_build_native_windows_payload()` — so the filter sees
905 * every copy of the blob that can reach a browser.
906 *
907 * @param array $entry Registry entry (needs `id`; `config` optional).
908 * @return array Filtered config. Empty array when nothing to ship.
909 */
910 function openstation_filter_native_window_config( $entry ) {
911 $config = isset( $entry['config'] ) && is_array( $entry['config'] )
912 ? $entry['config']
913 : array();
914
915 /**
916 * Filter a native window's config blob at emit time.
917 *
918 * The registry snapshots `config` when `openstation_register_window()`
919 * runs — usually `init`. This filter runs when the blob is
920 * serialized for the browser (enqueue time on the eager path,
921 * payload-build time on the lazy path), so values that depend on
922 * hooks registered later in the bootstrap can be refreshed without
923 * moving the whole registration. The WP Explorer uses it to
924 * re-collect `previewActions` so plugins may add
925 * `openstation_my_wordpress_preview_actions` callbacks any time
926 * during a normal bootstrap, not just before `init` 99.
927 *
928 * Runs per request, after the current user is determined —
929 * capability-gated values are safe to compute here.
930 *
931 * **Status: Experimental**
932 *
933 * @param array $config Config blob as registered (empty array
934 * when the window registered none).
935 * @param string $window_id Native window id.
936 */
937 $config = apply_filters( 'openstation_native_window_config', $config, (string) $entry['id'] );
938
939 return is_array( $config ) ? $config : array();
940 }
941
942 /**
943 * Attach every registered native window's script data, and enqueue
944 * the handful of bundles that asked to load at boot.
945 *
946 * **A native window's bundle is not enqueued here.** It loads the
947 * first time the window opens: the shell reads the render callback
948 * off `window.openStationNativeWindows[ <id> ]` at open time, so a
949 * bundle printed at boot is weight on every admin page the window is
950 * never opened from — and between WP Explorer, Posts, Plugins,
951 * Comments, the Recycle Bin, Content Graph, Games and the agent
952 * runner that came to well over a megabyte before a single window
953 * had been clicked. `preload_script` is the opt-out for a bundle
954 * with a genuine boot-time job.
955 *
956 * What still happens for EVERY window is the data attach: the
957 * localize blob and the `config` inline. Those hang off the
958 * REGISTERED handle whether or not it is enqueued, which is exactly
959 * how the lazy path gets them — `openstation_resolve_script_payload()`
960 * harvests both into the payload for the shell to replay around the
961 * script tag it injects. Hence priority 5: `openstation_enqueue_assets()`
962 * builds that payload at 10, and data attached after it would ship a
963 * bundle with no config.
964 */
965 function openstation_enqueue_native_window_scripts() {
966 if ( ! openstation_is_enabled() || openstation_is_chromeless_request() || openstation_is_classic_request() ) {
967 return;
968 }
969 $registry = openstation_native_window_registry();
970 if ( ! is_array( $registry ) ) {
971 return;
972 }
973 foreach ( $registry as $entry ) {
974 $preload = ! empty( $entry['preload_script'] );
975
976 // Per-tab scripts stay eager. The shell has no lazy path for
977 // them — a tab's script is not part of the window's own
978 // bundle chain — so deferring here would simply break the
979 // tab. The main tab uses the window's own `script`.
980 $tabs = openstation_get_native_window_tabs( $entry['id'] );
981 foreach ( $tabs as $tab ) {
982 if ( $tab['is_main'] || empty( $tab['script'] ) ) {
983 continue;
984 }
985 wp_enqueue_script( $tab['script'] );
986 }
987
988 if ( empty( $entry['script'] ) ) {
989 continue;
990 }
991 if ( $preload ) {
992 wp_enqueue_script( $entry['script'] );
993 foreach ( (array) $entry['scripts'] as $companion ) {
994 wp_enqueue_script( $companion );
995 }
996 // Preload means "everything at boot" — companion styles
997 // ride along so the window paints styled on a preloaded
998 // first open, same as its scripts are already parsed.
999 if ( ! empty( $entry['styles'] ) ) {
1000 foreach ( (array) $entry['styles'] as $companion_style ) {
1001 wp_enqueue_style( $companion_style );
1002 }
1003 }
1004 }
1005 // Localize the config the JS side reads to register itself.
1006 wp_localize_script(
1007 $entry['script'],
1008 'openStationNativeWindow_' . str_replace( '-', '_', $entry['id'] ),
1009 array(
1010 'id' => $entry['id'],
1011 'title' => $entry['title'],
1012 'icon' => $entry['icon'],
1013 'width' => $entry['width'],
1014 'height' => $entry['height'],
1015 'minWidth' => $entry['min_width'],
1016 'minHeight' => $entry['min_height'],
1017 'placement' => $entry['placement'],
1018 'autofocus' => $entry['autofocus'],
1019 'templateId' => 'os-native-window-' . $entry['id'],
1020 'tabs' => array_map(
1021 static function ( $tab ) {
1022 return array(
1023 'value' => $tab['value'],
1024 'label' => $tab['label'],
1025 'isMain' => $tab['is_main'],
1026 );
1027 },
1028 $tabs
1029 ),
1030 )
1031 );
1032
1033 // Bundle-bound `config`, for the eager print path only.
1034 // `openstation_build_native_windows_payload()` synthesizes the
1035 // same assignment into the payload's `scriptL10n`, which is
1036 // what delivers it on the lazy path — and it has to, because
1037 // that payload is also built inside chromeless iframes, where
1038 // this function returns early. Attaching here unconditionally
1039 // would mean a shell page shipped the identical assignment
1040 // twice: once as `before`, once as `l10n`. The bundle reads it
1041 // via `wp.os.getWindowConfig( id )` or directly at
1042 // `window.openStationWindowConfig[ id ]`.
1043 $config = openstation_filter_native_window_config( $entry );
1044 if ( $preload && ! empty( $config ) ) {
1045 wp_add_inline_script(
1046 $entry['script'],
1047 sprintf(
1048 'window.openStationWindowConfig=window.openStationWindowConfig||{};window.openStationWindowConfig[%s]=%s;',
1049 wp_json_encode( $entry['id'] ),
1050 wp_json_encode( $config )
1051 ),
1052 'before'
1053 );
1054 }
1055 }
1056 }
1057 add_action( 'admin_enqueue_scripts', 'openstation_enqueue_native_window_scripts', 5 );
1058
1059 /**
1060 * Emit a `<template>` tag for every registered native window on
1061 * `admin_footer` when the shell is active. The JS side resolves
1062 * these via `document.getElementById( `os-native-window-${id}` )`
1063 * and clones them into each opened window's body.
1064 */
1065 function openstation_render_native_window_templates() {
1066 if ( ! openstation_is_enabled() || openstation_is_chromeless_request() || openstation_is_classic_request() ) {
1067 return;
1068 }
1069 $registry = openstation_native_window_registry();
1070 if ( ! is_array( $registry ) ) {
1071 return;
1072 }
1073 foreach ( $registry as $entry ) {
1074 if ( ! is_callable( $entry['template'] ) ) {
1075 continue;
1076 }
1077 $html = openstation_build_native_window_template_html( $entry );
1078 if ( '' === $html ) {
1079 continue;
1080 }
1081 printf(
1082 '<template id="os-native-window-%s">',
1083 esc_attr( $entry['id'] )
1084 );
1085 // `openstation_kses_native_window_template()` auto-extends
1086 // the allowlist with any `<os-*>` tag the template carries
1087 // — so plugin authors never have to remember to register
1088 // their custom component tags in the kses list.
1089 echo openstation_kses_native_window_template( $html ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- helper kses-escapes.
1090 echo '</template>';
1091 }
1092 }
1093 add_action( 'admin_footer', 'openstation_render_native_window_templates', 20 );
1094