PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 1.1.5
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v1.1.5
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 / render / assets.php

assets.php in OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin 1.1.5, at includes/render/assets.php

1,246 lines 59.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * OpenStation — Asset enqueue.
4 *
5 * Loads the desktop shell CSS + JS bundles when OpenStation is
6 * active and the request isn't chromeless / classic-overridden.
7 * Owns the entire `openstation_enqueue_assets()` body — the
8 * largest hook in the original render.php and the natural seam
9 * for "what does the shell ship to the browser today?".
10 *
11 * Extracted from `render.php` during the architecture-0.8.1 PHP
12 * slicing (phase 6).
13 *
14 * @package OpenStation
15 */
16
17 defined( 'ABSPATH' ) || exit;
18
19 /**
20 * Enqueues the OpenStation shell assets (CSS + JS) when OpenStation is active.
21 *
22 * Only loads the full desktop shell scripts and styles when the user has
23 * OpenStation enabled and the request is not a chromeless iframe load.
24 */
25 function openstation_enqueue_assets() {
26 if ( ! is_admin() ) {
27 return;
28 }
29
30 // Auto-enqueue the iframe bridge anywhere a openstation user
31 // might land. The bundle self-bails when not inside an iframe
32 // (`window.parent === window`), so it's a no-op on the parent
33 // shell — but cheap insurance against the failure mode the
34 // developer hit: an internal admin navigation drops the
35 // `?openstation_chromeless=1` flag, the chromeless inline bridge doesn't
36 // run, and `wp.os.iframe` silently disappears. With this
37 // auto-enqueue, the API is universally present for any same-
38 // origin admin page a openstation user opens — chromeless or
39 // accidentally classic.
40 if ( openstation_is_enabled() ) {
41 wp_enqueue_script( 'os-iframe-bridge' );
42
43 // Block Editor cross-window drop receiver. Listens for
44 // `os-drop` postMessages from the parent shell and
45 // inserts the matching block. Only enqueue inside the
46 // post-edit Block Editor screens — every other admin page
47 // would be paying for a bundle it never uses.
48 //
49 // `site-editor.php` (full-site editor) deliberately omitted:
50 // the FSE doesn't expose `wp.data.dispatch('core/block-editor')`
51 // until the user opens a template in the canvas iframe, so
52 // drops arriving before that point would silently time out
53 // after the receiver's 5 s `waitForEditor()` poll. Re-enable
54 // once we have a reliable readiness signal in that context.
55 global $hook_suffix;
56 if ( 'post.php' === $hook_suffix || 'post-new.php' === $hook_suffix ) {
57 wp_enqueue_script( 'os-gutenberg-drop-receiver' );
58 }
59 }
60
61 // Chromeless requests (iframes) need chromeless styles and overrides.
62 if ( openstation_is_chromeless_request() ) {
63 wp_enqueue_style( 'openstation' );
64 wp_enqueue_style( 'os-chromeless' );
65
66 /**
67 * Fires when chromeless styles are enqueued inside a OpenStation iframe.
68 *
69 * Plugin and theme authors can hook here to enqueue their own CSS
70 * overrides for legacy pages rendered in chromeless mode. Use the
71 * `.os-chromeless` body class to scope your rules.
72 */
73 do_action( 'openstation_chromeless_styles' );
74 return;
75 }
76
77 if ( ! openstation_is_shell_request() ) {
78 return;
79 }
80
81 // CSS. Only the sheets that paint surfaces present at boot — the
82 // shell chrome, the dock, desktop tiles and pinned notes. Sheets
83 // for on-demand surfaces (Preferences panel, AI assistant, bug
84 // report) ship as `deferredStyles` in the config blob below and
85 // inject on first open; a native window's sheet rides its
86 // registration's `styles` companion list the same way.
87 wp_enqueue_style( 'openstation' );
88 wp_enqueue_style( 'os-windows' );
89 wp_enqueue_style( 'os-window-overview' );
90 wp_enqueue_style( 'os-dock' );
91 wp_enqueue_style( 'os-dock-peek' );
92 wp_enqueue_style( 'os-notch' );
93 wp_enqueue_style( 'os-shortcuts' );
94 wp_enqueue_style( 'os-openstation-layout' );
95 wp_enqueue_style( 'os-files' );
96 wp_enqueue_style( 'os-notes' );
97
98 // Solo mode — a single window freed into a native OS window by the
99 // desktop host. Same shell, everything but that one window hidden.
100 $solo_window = openstation_solo_window_id();
101 if ( '' !== $solo_window ) {
102 wp_enqueue_style( 'os-solo' );
103
104 /*
105 * Hide every window that is not the one this surface was booted
106 * to paint — from the first frame, before any of them exist.
107 *
108 * Solo mode promises one window. Anything that opens a second
109 * (a game launched from a freed Games hub, a plugin calling
110 * `openWindow`) would otherwise land on top of the first, and
111 * solo's CSS stretches every window to fill the viewport, so it
112 * covers what the user was using.
113 *
114 * This has to be CSS rather than JavaScript, and it has to be
115 * inline. A JS rule can only run once the window exists, which
116 * is a frame too late — the user sees the newcomer flash before
117 * it is dealt with. A static stylesheet cannot express it
118 * either, because the selector depends on which window this is.
119 * So the rule is emitted with the id baked in, and no window but
120 * that one is ever painted.
121 *
122 * `visibility` rather than `display`: a hidden-but-laid-out
123 * window still has a size, which canvas-based windows need in
124 * order to initialise without dividing by zero on the way to
125 * being closed.
126 *
127 * The id is `sanitize_key()`-clean (see `openstation_solo_window_id()`),
128 * so it is safe in a selector; it is escaped again here because
129 * the distance between those two facts is exactly where this
130 * kind of bug lives.
131 */
132 wp_add_inline_style(
133 'os-solo',
134 sprintf(
135 'body.os-solo .os-window:not(#wp-window-%1$s){visibility:hidden !important;pointer-events:none !important;}',
136 esc_attr( $solo_window )
137 )
138 );
139 }
140
141 // The rebrand announcement paints on one visit per user and never
142 // again, so its stylesheet is only worth sending to the users who
143 // are actually going to see it. Computed once here and reused for
144 // the `rebrandNotice` config key below, which reads the same answer.
145 $show_rebrand_notice = openstation_should_show_rebrand_notice();
146 if ( $show_rebrand_notice ) {
147 wp_enqueue_style( 'os-announce' );
148 }
149
150 // JS.
151 wp_enqueue_script( 'openstation' );
152
153 // `wp_enqueue_command_palette_assets()` (WP 6.9+) enqueues the
154 // `wp-commands` store package, the `wp-core-commands` script that
155 // registers the WordPress-wide baseline (Add new post, Manage
156 // plugins, Switch theme, Browse patterns, …) AND — critically —
157 // the inline `wp.coreCommands.initializeCommandPalette( … )` call
158 // that actually populates the `core/commands` data store with the
159 // admin-menu commands. Without that inline init, the script loads
160 // but the store stays empty and `src/commands/shell-harvester.ts`
161 // finds nothing to publish.
162 //
163 // WP normally only calls this on screens that opt in to the native
164 // palette; the shell needs it on every admin URL it might wrap.
165 // `function_exists` guard for pre-6.9 sites — the harvester gracefully
166 // no-ops when the store is missing.
167 // See `openstation_defer_core_command_palette()` below for why
168 // Core's own boot-time enqueue is unhooked on shell pages.
169 //
170 // The Core command-palette runtime is NOT enqueued here any more.
171 // Its dependency chain is the whole Gutenberg runtime (~800 KB
172 // gzipped across forty-odd bundles), paid on every boot for a ⌘K
173 // palette most sessions never open. It now ships as an ordered
174 // manifest in the config blob (`commandPalette`, built by
175 // `openstation_build_command_palette_assets_payload()`), and
176 // `src/commands/palette-assets.ts` replays it the first time the
177 // palette is invoked. The shell harvester keeps its idle-time
178 // `install()` — a graceful no-op until the store exists — and
179 // re-installs on `os-command-palette-ready`.
180 $command_palette = openstation_build_command_palette_assets_payload();
181
182 if ( function_exists( 'wp_enqueue_command_palette_assets' ) ) {
183 // Expose the same menu-commands array WP serializes into
184 // `wp.coreCommands.initializeCommandPalette(...)` on a window
185 // slot the shell harvester can read. Built in PHP from `$menu`
186 // / `$submenu`, then injected as a `before` inline on our own
187 // bundle — that runs synchronously before `desktop.min.js`
188 // boots the shell harvester, so the lookup is guaranteed
189 // populated by the time `src/commands/shell-harvester.ts`
190 // classifies any command. Decoupled from WP's command-palette
191 // mount timing (which fires from a core-registered hook we
192 // can't reorder) — and, since the palette bundles went lazy,
193 // from whether they have loaded at all.
194 $menu_map = openstation_build_command_menu_map();
195 wp_add_inline_script(
196 'openstation',
197 'window.__openStationMenuCommands = ' . wp_json_encode( $menu_map ) . ';',
198 'before'
199 );
200 }
201
202 // Pass configuration to JavaScript.
203 global $title, $parent_file, $menu;
204
205 $menu_icon = 'dashicons-admin-generic';
206 if ( ! empty( $parent_file ) && ! empty( $menu ) ) {
207 foreach ( $menu as $item ) {
208 if ( ! empty( $item[2] ) && $item[2] === $parent_file && ! empty( $item[6] ) ) {
209 $menu_icon = $item[6];
210 break;
211 }
212 }
213 }
214
215 // Build dock items from the admin menu. Core pages are ordered
216 // first (Dashboard, Posts, Plugins, Users, Settings, …), then
217 // plugin-contributed top-level routes. `openstation_dock_placement`
218 // is the per-item filter escape hatch for hiding. Shared with the
219 // REST menu endpoint so live refreshes (post plugin-activation)
220 // produce the same ordering as the boot payload.
221 $menu_payload = openstation_build_menu_payload();
222 $dock_items = $menu_payload['dockItems'];
223 $native_windows = isset( $menu_payload['nativeWindows'] )
224 ? $menu_payload['nativeWindows']
225 : array();
226
227 // The BOOT page prints every registry window's template as a real
228 // `<template>` tag (`openstation_render_native_window_templates()`,
229 // admin_footer @ 20 — before footer scripts, so the tags are in
230 // the DOM before the shell boots and `ensureTemplate()` adopts
231 // them by id). The payload's `templateHtml` copy exists for the
232 // MID-SESSION path — a bridge or probe payload delivering a
233 // window whose plugin activated after the page rendered — so on
234 // the boot config it is ~27 KB of the same markup twice. Strip it
235 // here, and only here: the bridge and probe payloads keep theirs.
236 foreach ( $native_windows as &$native_window_row ) {
237 if ( is_array( $native_window_row ) ) {
238 $native_window_row['templateHtml'] = '';
239 }
240 }
241 unset( $native_window_row );
242 $native_window_script_data = isset( $menu_payload['nativeWindowScriptData'] )
243 ? $menu_payload['nativeWindowScriptData']
244 : array();
245 $server_widgets = isset( $menu_payload['serverWidgets'] )
246 ? $menu_payload['serverWidgets']
247 : array();
248 $server_wallpapers = isset( $menu_payload['serverWallpapers'] )
249 ? $menu_payload['serverWallpapers']
250 : array();
251 $server_command_scripts = isset( $menu_payload['serverCommandScripts'] )
252 ? $menu_payload['serverCommandScripts']
253 : array();
254 $server_commands = isset( $menu_payload['serverCommands'] )
255 ? $menu_payload['serverCommands']
256 : array();
257 $server_settings_tab_scripts = isset( $menu_payload['serverSettingsTabScripts'] )
258 ? $menu_payload['serverSettingsTabScripts']
259 : array();
260 $server_settings_tabs = isset( $menu_payload['serverSettingsTabs'] )
261 ? $menu_payload['serverSettingsTabs']
262 : array();
263 $server_dock_rail_renderer_scripts = isset( $menu_payload['serverDockRailRendererScripts'] )
264 ? $menu_payload['serverDockRailRendererScripts']
265 : array();
266 $server_titlebar_button_scripts = isset( $menu_payload['serverTitleBarButtonScripts'] )
267 ? $menu_payload['serverTitleBarButtonScripts']
268 : array();
269 $server_window_action_scripts = isset( $menu_payload['serverWindowActionScripts'] )
270 ? $menu_payload['serverWindowActionScripts']
271 : array();
272 $server_window_theme_scripts = isset( $menu_payload['serverWindowThemeScripts'] )
273 ? $menu_payload['serverWindowThemeScripts']
274 : array();
275 $server_window_themes = isset( $menu_payload['serverWindowThemes'] )
276 ? $menu_payload['serverWindowThemes']
277 : array();
278 $server_window_control_scripts = isset( $menu_payload['serverWindowControlScripts'] )
279 ? $menu_payload['serverWindowControlScripts']
280 : array();
281 $server_window_controls = isset( $menu_payload['serverWindowControls'] )
282 ? $menu_payload['serverWindowControls']
283 : array();
284 $server_window_slot_scripts = isset( $menu_payload['serverWindowSlotScripts'] )
285 ? $menu_payload['serverWindowSlotScripts']
286 : array();
287 $server_window_slots = isset( $menu_payload['serverWindowSlots'] )
288 ? $menu_payload['serverWindowSlots']
289 : array();
290 $server_window_chrome_scripts = isset( $menu_payload['serverWindowChromeScripts'] )
291 ? $menu_payload['serverWindowChromeScripts']
292 : array();
293 $server_window_chromes = isset( $menu_payload['serverWindowChromes'] )
294 ? $menu_payload['serverWindowChromes']
295 : array();
296 $server_window_notices = isset( $menu_payload['serverWindowNotices'] )
297 ? $menu_payload['serverWindowNotices']
298 : array();
299 $server_games = isset( $menu_payload['serverGames'] )
300 ? $menu_payload['serverGames']
301 : array();
302 // Boot-time copy of the desktop-theme library. Without it the
303 // shell's registry seeds EMPTY, and the consequences are subtle
304 // rather than obvious: PHP has already applied the user's theme
305 // server-side (stylesheet + shell attribute), but the client
306 // can't resolve the slug to an entry, so it believes nothing is
307 // active. Themed ICONS never paint, and switching back to the
308 // system default no-ops the first time — `applyDesktopTheme()`
309 // dedupes on an `activeId` that was never set.
310 $server_desktop_themes = isset( $menu_payload['serverDesktopThemes'] )
311 ? $menu_payload['serverDesktopThemes']
312 : array();
313
314 // Slim the theme library for BOOT: `cssText` and `tokens` are
315 // each ~20 KB per theme, and neither is read at boot — the ACTIVE
316 // theme's stylesheet is server-delivered (see
317 // `openstation_enqueue_desktop_theme_style()`, whose stamp
318 // `bootAlreadyApplied()` detects), and an inactive theme's CSS
319 // only matters at the moment the user picks it in the Preferences
320 // picker — which fetches the full entries from
321 // `GET desktop-mode/v1/desktop-themes` (`ensureFullDesktopThemes()`
322 // client-side). `cssDeferred` marks the gap so the shell can tell
323 // a slimmed entry from a theme that genuinely ships no CSS.
324 // Bridge and probe payloads keep full entries.
325 foreach ( $server_desktop_themes as &$desktop_theme_row ) {
326 if ( is_array( $desktop_theme_row ) ) {
327 $desktop_theme_row['cssText'] = '';
328 $desktop_theme_row['tokens'] = new stdClass();
329 $desktop_theme_row['cssDeferred'] = true;
330 }
331 }
332 unset( $desktop_theme_row );
333 $desktop_icons = isset( $menu_payload['desktopIcons'] )
334 ? $menu_payload['desktopIcons']
335 : array();
336
337 // Files-on-the-Desktop payload (Phase 0+1). Plugin-registered
338 // file types and openers ship as metadata only; the JS side
339 // holds the executable handlers and resolves on double-click.
340 $server_file_types = function_exists( 'openstation_build_file_types_payload' )
341 ? openstation_build_file_types_payload()
342 : array();
343 $server_file_openers = function_exists( 'openstation_build_file_openers_payload' )
344 ? openstation_build_file_openers_payload()
345 : array();
346 $user_file_associations = function_exists( 'openstation_get_user_file_associations' )
347 ? openstation_get_user_file_associations( get_current_user_id() )
348 : array();
349 $server_wallpaper_menu_items = function_exists( 'openstation_build_wallpaper_menu_items' )
350 ? openstation_build_wallpaper_menu_items()
351 : array();
352
353 /*
354 * OS-file drop config — what the browser drop manager will
355 * accept when the user drags a file from their native desktop
356 * onto any surface inside OpenStation (wallpaper, a folder,
357 * a window, or a chromeless iframe). The allowed-mimes list is
358 * the user-scoped `get_allowed_mime_types()` (already capability
359 * gated by WordPress); the size cap is `wp_max_upload_size()`.
360 *
361 * Both are filterable so plugins can narrow or widen the set —
362 * e.g. a media-only plugin can restrict drops to images, or a
363 * docs plugin can opt PDFs in for a specific role.
364 */
365 $drop_allowed_mimes_map = current_user_can( 'upload_files' )
366 ? get_allowed_mime_types( get_current_user_id() )
367 : array();
368 /**
369 * Filter the allowed-mime map used by the OS-file drop manager.
370 *
371 * @param array<string,string> $mimes_map `ext => mime-type` map (same shape `get_allowed_mime_types()` returns).
372 * @param int $user_id The current user id.
373 */
374 $drop_allowed_mimes_map = apply_filters( 'openstation_drop_allowed_mimes', $drop_allowed_mimes_map, get_current_user_id() );
375 $drop_allowed_mimes_map = is_array( $drop_allowed_mimes_map ) ? $drop_allowed_mimes_map : array();
376 $drop_allowed_mimes = array_values( array_unique( array_values( $drop_allowed_mimes_map ) ) );
377
378 $drop_max_size = (int) wp_max_upload_size();
379 /**
380 * Filter the per-file size cap (in bytes) used by the OS-file
381 * drop manager. Returning `0` disables the client-side cap —
382 * the server still enforces its own.
383 *
384 * @param int $max_size Default `wp_max_upload_size()`.
385 * @param int $user_id The current user id.
386 */
387 $drop_max_size = (int) apply_filters( 'openstation_drop_max_size', $drop_max_size, get_current_user_id() );
388
389 /**
390 * Filter the master OS-file drop enable gate. Lets plugins
391 * disable the drop manager by role / capability beyond the
392 * default `upload_files` check (e.g. only for admins, or
393 * only on specific multisite blogs).
394 *
395 * @param bool $enabled Default — `current_user_can( 'upload_files' )`.
396 * @param int $user_id The current user id.
397 */
398 $drop_enabled = (bool) apply_filters(
399 'openstation_drop_enabled',
400 current_user_can( 'upload_files' ),
401 get_current_user_id()
402 );
403
404 $drop_config = array(
405 'enabled' => $drop_enabled,
406 'allowedMimes' => $drop_allowed_mimes,
407 'extToMime' => $drop_allowed_mimes_map,
408 'maxSize' => $drop_max_size,
409 );
410
411 // Lazy-bundle URL builder. Each lazy-loaded bundle (AI Assistant,
412 // OS Settings panel, shell-overlays, window-system)
413 // is `<script>`-injected by the main bundle on demand — they don't
414 // go through `wp_register_script`, so they don't pick up WordPress's
415 // usual `?ver=<filemtime>` cache-buster. Without one, the browser
416 // happily serves a stale cached copy across plugin updates that
417 // don't bump `OPENSTATION_VERSION`, and the main bundle's loader
418 // fires a `<script>`-loaded event for a file that's missing the
419 // fresh `window.openStation*` factory the new code expects.
420 //
421 // Mirror the `$built_version( … )` helper in `includes/assets.php`:
422 // prefer the on-disk mtime of the actual file, fall back to the
423 // plugin version when the file is missing (dev environments where
424 // the bundle hasn't been built yet).
425 $suffix = openstation_asset_suffix();
426 $lazy_bundle_url = static function ( $base ) use ( $suffix ) {
427 $path = OPENSTATION_DIR . 'assets/js/' . $base . $suffix . '.js';
428 $ver = file_exists( $path )
429 ? (string) filemtime( $path )
430 : OPENSTATION_VERSION;
431 return esc_url_raw(
432 OPENSTATION_URL . 'assets/js/' . $base . $suffix . '.js?ver=' . $ver
433 );
434 };
435
436 // The page the shell opens first. On the shell screen it is the
437 // validated `target` query arg (else the session's focused window,
438 // the default window, the Dashboard); on a solo boot it is the
439 // request's own URL. Either way the frozen portal flags are gone
440 // from it, so the derived window id matches what the dock would
441 // produce for the same page — otherwise auto-opening the entry
442 // window and clicking the same dock icon would create a duplicate.
443 $boot_target = openstation_shell_boot_target();
444 $current_page = $boot_target['url'];
445 $from_portal = $boot_target['fromPortal'];
446 $from_portal_intent = $boot_target['fromPortalIntent'];
447
448 // On the shell screen `$title` and `$parent_file` describe the
449 // screen ("OpenStation", no menu), not the page about to open. The
450 // dock entry for that page is the identity the entry window folds
451 // into, so its title and icon are the right first paint; the iframe
452 // reports its own title once it lands either way.
453 $current_title = wp_strip_all_tags( (string) $title );
454 if ( openstation_is_shell_screen_request() ) {
455 $boot_meta = openstation_shell_boot_target_meta( $current_page, $dock_items );
456 $current_title = wp_strip_all_tags( $boot_meta['title'] );
457 if ( '' !== $boot_meta['icon'] ) {
458 $menu_icon = $boot_meta['icon'];
459 }
460 }
461
462 /**
463 * Filters the desktop shell configuration passed to JavaScript.
464 *
465 * @param array $config {
466 * Desktop shell configuration.
467 *
468 * @type string $currentPage The current admin page URL.
469 * @type string $currentTitle The current page title.
470 * @type string $currentIcon Dashicon class for the current page.
471 * @type string $adminUrl The base admin URL.
472 * @type string $colorScheme The active admin color scheme.
473 * @type array $dockItems Dock items derived from the admin menu. Core WordPress pages (Dashboard, Posts, Plugins, Users, Settings, CPTs…) are ordered first; plugin-contributed top-level routes (admin.php?page=*) follow. Items hidden via `openstation_dock_placement` are omitted.
474 * @type array $nativeWindows Server-declared native windows (via `openstation_register_window`). Shell registers + syncs tiles based on this list — activation/deactivation is a diff without shell reload.
475 * @type array $serverWidgets Server-declared right-column widgets (via `openstation_register_widget`). Shell syncs the widget registry + dynamically loads plugin scripts so widgets appear in the picker without a shell reload.
476 * @type array $serverWallpapers Server-declared wallpapers (via `openstation_register_wallpaper`). Same lifecycle — shell loads the plugin's JS, reads the full `WallpaperDef` from `window.openStationWallpapers[id]`, and registers / unregisters as plugins activate / deactivate.
477 * @type array $serverCommandScripts Script handles opted-in via `openstation_register_command_script`. Shell injects each URL on activation so commands registered by `wp.os.registerCommand` appear in the palette live. Deactivation unregisters any commands whose `owner` matches the departing handle.
478 * @type array $serverCommands Server-declared command metadata (via `openstation_register_command`). Advisory today — reserved for future pre-registration shims.
479 * @type array $serverSettingsTabScripts Script handles opted-in via `openstation_register_settings_tab_script`. Shell injects each URL on activation so tabs registered by `wp.os.registerSettingsTab` appear in the OS Settings window live. Deactivation unregisters tabs attributable to the departing handle.
480 * @type array $serverSettingsTabs Server-declared settings-tab metadata (via `openstation_register_settings_tab`). Enables live unregistration on plugin deactivation without requiring JS to set `owner`.
481 * @type array $desktopIcons Server-declared desktop icons (via `openstation_register_icon`). Rendered on the wallpaper as clickable shortcut tiles.
482 * @type array $accentColors Swatch list for the OS Settings accent picker. Filterable via `openstation_accent_colors`.
483 * @type array $toastTypes Toast-notification type map. Filterable via `openstation_toast_types`.
484 * @type string $defaultWallpaper Wallpaper slug applied on first boot. Filterable via `openstation_default_wallpaper`.
485 * @type array $session Saved session (windows, focused, updated).
486 * @type string $sessionUrl REST endpoint for saving the session.
487 * @type string $mediaUrl REST endpoint for media uploads (wp/v2/media).
488 * @type string $restUrl REST API root from rest_url(), safe for pretty and plain permalink installs.
489 * @type string $defaultWindowUrl REST endpoint for saving the default-window preference.
490 * @type array $defaultWindow { enabled: bool, url: string } — current default-window preference.
491 * @type bool $canUpload Whether the user holds the `upload_files` capability.
492 * @type string $pluginUrl Plugin base URL (no trailing slash). Used by the shell to locate vendor assets and by plugins to build asset URLs.
493 * @type string $pluginVersion Plugin semver string. Surfaced in the OS Settings → About tab; plugins can read it to gate features by version.
494 * @type string $aboutFeedUrl Authenticated admin-AJAX URL that returns the cached OpenStation journal feed for the About tab.
495 * @type string $restNonce Nonce for the session REST endpoint.
496 * @type string $soloWindow Window id when the shell was asked to paint exactly one window (`?openstation_solo=<id>`); '' otherwise. No dock, taskbar, wallpaper or desk, and no session restore.
497 * @type string $portalUrl Canonical `/openstation/` URL.
498 * @type bool $fromPortal Whether the shell was reached via the portal.
499 * @type bool $fromPortalIntent Whether the portal redirect resolved from an explicit `?target=…` (user navigation intent) rather than the session's focused window or the default-window fallback. Distinguishes a bare `/openstation/` visit from a portal-redirected admin-bar click so the shell can honour the URL the user actually asked for.
500 * @type array $seenIntros Slugs of one-time announcements the user has dismissed (e.g. `['openstation-rebrand']`).
501 * @type string $seenIntrosUrl REST endpoint for the seen-intros surface — POST `/seen` to mark, DELETE the base to reset.
502 * @type bool $rebrandNotice Whether to offer this user the one-off announcement explaining the rename from Desktop Mode to OpenStation. True only when migration 5 flagged this user as a Desktop Mode user from before the rename AND they haven't dismissed the `openstation-rebrand` intro. Only ever present in the shell config, so the announcement never reaches the classic admin.
503 * }
504 */
505 $config = apply_filters(
506 'openstation_shell_config',
507 array(
508 'currentPage' => esc_url( $current_page ),
509 'currentTitle' => $current_title,
510 'currentIcon' => sanitize_html_class( $menu_icon ),
511 'adminUrl' => esc_url( admin_url() ),
512 'homeUrl' => esc_url( home_url( '/' ) ),
513 // Decoded: the shell assigns this to `window.location`,
514 // where `&amp;` would make `_wpnonce` arrive as
515 // `amp;_wpnonce` and fail the nonce check.
516 'logoutUrl' => esc_url_raw(
517 html_entity_decode( wp_logout_url(), ENT_QUOTES, 'UTF-8' )
518 ),
519 'colorScheme' => sanitize_html_class( get_user_option( 'admin_color' ), 'fresh' ),
520 'dockItems' => $dock_items,
521 // Baseline menu fingerprint. The shell seeds its last-known
522 // signature from this so the first off-allowlist menu change
523 // (vs. this boot state) is caught without a wasted probe. GH#325.
524 'menuSig' => isset( $menu_payload['menuSig'] ) ? (string) $menu_payload['menuSig'] : '',
525 'nativeWindows' => $native_windows,
526 // Handle-keyed script data the entries above reference —
527 // one copy per bundle, not one per window. See
528 // `openstation_collect_native_windows_payload()`.
529 'nativeWindowScriptData' => $native_window_script_data,
530 'serverWidgets' => $server_widgets,
531 'serverWallpapers' => $server_wallpapers,
532 'serverCommandScripts' => $server_command_scripts,
533 'serverCommands' => $server_commands,
534 'serverSettingsTabScripts' => $server_settings_tab_scripts,
535 'serverSettingsTabs' => $server_settings_tabs,
536 'serverDockRailRendererScripts' => $server_dock_rail_renderer_scripts,
537 'serverTitleBarButtonScripts' => $server_titlebar_button_scripts,
538 'serverWindowActionScripts' => $server_window_action_scripts,
539 'serverWindowThemeScripts' => $server_window_theme_scripts,
540 'serverWindowThemes' => $server_window_themes,
541 'serverWindowControlScripts' => $server_window_control_scripts,
542 'serverWindowControls' => $server_window_controls,
543 'serverWindowSlotScripts' => $server_window_slot_scripts,
544 'serverWindowSlots' => $server_window_slots,
545 'serverWindowChromeScripts' => $server_window_chrome_scripts,
546 'serverWindowChromes' => $server_window_chromes,
547 'serverWindowNotices' => $server_window_notices,
548 // Boot-time copy of the payload's `serverGames` — the same
549 // list the live-refresh path applies. Without it the games
550 // registry only fills after the first chromeless
551 // full-payload refresh and the Games hub boots empty.
552 'serverGames' => $server_games,
553 'serverDesktopThemes' => $server_desktop_themes,
554 'desktopIcons' => $desktop_icons,
555 'serverFileTypes' => $server_file_types,
556 'serverFileOpeners' => $server_file_openers,
557 'userFileAssociations' => $user_file_associations,
558 'filesUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/files' ) ),
559 // Pinned-notes REST base (`includes/notes/rest.php`). The
560 // notes layer boots only when this is present.
561 'notesUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/notes' ) ),
562 // Gates the "Convert to post" note affordance — the convert
563 // route (and its dock drop target) only make sense for users
564 // who can author posts.
565 'canCreatePosts' => current_user_can( 'edit_posts' ),
566 'serverWallpaperMenuItems' => $server_wallpaper_menu_items,
567 'accentColors' => openstation_get_accent_colors(),
568 'toastTypes' => openstation_get_toast_types(),
569 'coreUpdate' => openstation_get_core_update(),
570 'coreNotices' => openstation_get_core_notices(),
571 'pluginNotices' => openstation_get_plugin_notices(),
572 'defaultWallpaper' => openstation_get_default_wallpaper(),
573 'session' => openstation_get_session( get_current_user_id() ),
574 'sessionUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/session' ) ),
575 'restUrl' => esc_url_raw( rest_url() ),
576 'mediaUrl' => esc_url_raw( rest_url( 'wp/v2/media' ) ),
577 'dropConfig' => $drop_config,
578 'defaultWindowUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/default-window' ) ),
579 'defaultWindow' => openstation_get_default_window( get_current_user_id() ),
580 'canUpload' => current_user_can( 'upload_files' ),
581 'pluginUrl' => esc_url_raw( untrailingslashit( OPENSTATION_URL ) ),
582 'pluginVersion' => OPENSTATION_VERSION,
583 'aboutFeedUrl' => esc_url_raw(
584 add_query_arg(
585 array(
586 'action' => 'openstation_about_feed',
587 'nonce' => wp_create_nonce( 'openstation_about_feed' ),
588 ),
589 admin_url( 'admin-ajax.php' )
590 )
591 ),
592 'iframeBridgeUrl' => $lazy_bundle_url( 'iframe-bridge' ),
593 // URL of the AI Assistant lazy bundle. The main bundle
594 // ships a stub matching the public `wp.os.ai` API; the
595 // stub `<script>`-injects this URL the first time the user
596 // opens the assistant. Picking `.js` vs `.min.js` here keeps
597 // the SCRIPT_DEBUG gate server-side, matching iframeBridgeUrl.
598 'aiAssistantBundleUrl' => $lazy_bundle_url( 'ai-assistant' ),
599 // URL of the OS Settings panel lazy bundle. Injected by
600 // the main bundle's `OsSettings.renderPanel()` stub on
601 // the user's first Settings open. Holds every section
602 // renderer + the `<os-*>` components only the panel
603 // uses, so nothing about Settings ships in
604 // `desktop.min.js` for users who never open it.
605 'osSettingsPanelBundleUrl' => $lazy_bundle_url( 'os-settings-panel' ),
606 // URL of the shell-overlays lazy bundle. Pre-loaded by
607 // the main bundle after first paint so action-triggered
608 // overlays (toast, confirm dialog, context menus) feel
609 // instant the first time they fire.
610 'shellOverlaysBundleUrl' => $lazy_bundle_url( 'shell-overlays' ),
611 // The shell-bundle diet: features whose right moment is a
612 // user gesture (or a presence signal) ride their own
613 // bundles instead of the boot-critical `desktop[.min].js`.
614 // Each sentinel in the shell loads its bundle at that
615 // moment — see the entry file each bundle names.
616 'fileDropBundleUrl' => $lazy_bundle_url( 'file-drop' ),
617 'filesOverlaysBundleUrl' => $lazy_bundle_url( 'files-overlays' ),
618 'notesBundleUrl' => $lazy_bundle_url( 'notes' ),
619 'dockConstellationBundleUrl' => $lazy_bundle_url( 'dock-constellation' ),
620 'windowLinkVisualsBundleUrl' => $lazy_bundle_url( 'window-link-visuals' ),
621 // Presence hint for the notes sentinel: a desktop with no
622 // notes skips the notes bundle AND the boot-time list
623 // request. Two id-only existence probes at most.
624 'hasNotes' => function_exists( 'openstation_notes_user_has_any' )
625 ? openstation_notes_user_has_any()
626 : false,
627 // URL of the full `<os-*>` component kit. The shell
628 // never loads this — its own bundles import the
629 // components they render. It exists for
630 // `wp.os.loadComponents()`, i.e. for plugin code that
631 // CANNOT import: a plugin shipped as a zip has no path
632 // to this repo at build time, so before this URL its
633 // only routes to a `<os-switch>` were to bundle a second
634 // copy or hand-roll one. Shipping the URL costs one
635 // string and keeps the SCRIPT_DEBUG choice server-side.
636 'componentsBundleUrl' => $lazy_bundle_url( 'os-components' ),
637 // Mio — the desk companion. `mio` carries the
638 // appearance + physics (see `openstation_mio_config()`);
639 // `mioBundleUrl` is the lazy PixiJS bundle the shell
640 // controller injects the first time a user switches the
641 // Mio on from its dock tile. Shipping the URL
642 // unconditionally costs one short string and keeps the
643 // SCRIPT_DEBUG choice server-side, matching every other
644 // lazy bundle here.
645 //
646 // Both keys ship whether or not the user has Mio on,
647 // and that is the whole of its cost to a shell that doesn't:
648 // ~470 bytes gzipped of config, plus a URL. No script, no
649 // style, no PixiJS. The config has to be here rather than
650 // fetched on first toggle, or the `openstation_mio_config`
651 // filter would silently not apply until the next reload.
652 'mio' => openstation_mio_config(),
653 'mioBundleUrl' => $lazy_bundle_url( 'mio' ),
654 // URL of the lazy window-system bundle (Stage 11).
655 // Holds the `Window` class and its DOM / pointer / tab /
656 // chrome helpers — the single largest module split out of
657 // the main bundle. Loaded on first `windowManager.open()`
658 // / `openNew()` call (both async); pre-loaded
659 // by the shell after first paint when no session is being
660 // restored and no `openCurrentPage` will fire.
661 'windowSystemBundleUrl' => $lazy_bundle_url( 'window-system' ),
662 // URL of the item-visibility-menu lazy bundle — the
663 // right-click "hide from dock / desktop" menu. Injected by
664 // the main bundle's loader shim on the first right-click.
665 'itemVisibilityMenuBundleUrl' => $lazy_bundle_url( 'item-visibility-menu' ),
666 // URL of the release-card lazy bundle — the vinyl core-
667 // update announcement. Injected by `maybeShowUpdate()` only
668 // when a core update is actually pending.
669 'releaseCardBundleUrl' => $lazy_bundle_url( 'release-card' ),
670 'restNonce' => wp_create_nonce( 'wp_rest' ),
671 // Non-empty when the shell was asked to paint exactly one
672 // window and nothing else. See `OPENSTATION_SOLO_FLAG`.
673 'soloWindow' => openstation_solo_window_id(),
674 'osSettings' => openstation_get_os_settings( get_current_user_id() ),
675 'osSettingsUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/os-settings' ) ),
676 'seenIntros' => openstation_get_seen_intros( get_current_user_id() ),
677 'seenIntrosUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/intros' ) ),
678 // True only for a user migration 5 flagged as a Desktop Mode
679 // user from before the rename, who hasn't dismissed the
680 // announcement yet. Same value that gated `os-announce`
681 // above; the dialog cannot paint without that stylesheet, so
682 // the two must not diverge.
683 'rebrandNotice' => $show_rebrand_notice,
684 'aiSearchUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/ai/search' ) ),
685 // AI assistant availability + per-user toggle. Drives whether the
686 // Cmd+K palette and admin-bar icon appear, and the setup placeholder.
687 'aiAssistant' => function_exists( 'openstation_ai_assistant_config' )
688 ? openstation_ai_assistant_config()
689 : null,
690 // Lets the Features tab re-check provider availability without a
691 // reload after a connector is configured in Settings → Connectors.
692 'aiStatusUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/ai/status' ) ),
693 'extendedOptions' => current_user_can( 'manage_options' ) ? openstation_get_extended_options() : null,
694 'extendedOptionsUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/extended-options' ) ),
695 // Site-wide games kill switch (Extended options). Exposed to
696 // every user — the shell skips the challenges Heartbeat
697 // channel when the framework is off.
698 'gamesEnabled' => openstation_games_enabled(),
699 // Comments-window AI moderation toggle — surfaced at the
700 // shell level so the OS Settings → Features tab can render
701 // the toggle without depending on the Comments window
702 // being registered for this user. URL is the same
703 // endpoint the comments-window config exposes; state is
704 // `null` for non-admins (the UI hides the row entirely).
705 'commentsAiUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/comments/ai-settings' ) ),
706 // Non-null only for admins on a site where the Core AI stack is
707 // present. Comment scoring routes through the AI Client (WP 7.0+),
708 // so on older WordPress the whole row is hidden — same as the
709 // assistant toggle — rather than shown disabled pointing at a
710 // Settings → Connectors screen that doesn't exist there.
711 'commentsAi' => (
712 current_user_can( 'manage_options' )
713 && function_exists( 'openstation_ai_is_available' )
714 && openstation_ai_is_available()
715 )
716 ? array(
717 'enabled' => function_exists( 'openstation_comments_ai_is_enabled' )
718 ? openstation_comments_ai_is_enabled()
719 : false,
720 'providerConfigured' => function_exists( 'openstation_comments_ai_provider_configured' )
721 ? openstation_comments_ai_provider_configured()
722 : false,
723 )
724 : null,
725 'currentUserIsAdmin' => current_user_can( 'manage_options' ),
726 'portalUrl' => esc_url( openstation_portal_url() ),
727 'fromPortal' => $from_portal,
728 'fromPortalIntent' => $from_portal_intent,
729 'pwa' => array(
730 'manifestUrl' => esc_url_raw( openstation_pwa_manifest_url() ),
731 'swUrl' => esc_url_raw( openstation_pwa_sw_url() ),
732 // Extensionless retry target for hosts whose nginx 404s
733 // virtual .js paths before WordPress runs (WordPress.com).
734 'swFallbackUrl' => esc_url_raw( openstation_pwa_sw_fallback_url() ),
735 // The worker's per-user flags, computed HERE rather than
736 // baked into the served `sw.js`.
737 //
738 // A service worker is origin-wide but these are per-user
739 // preferences, so putting them in the script bytes made
740 // the body differ between an anonymous and a logged-in
741 // request — and any in-scope logged-out navigation then
742 // installed a "new" worker and tripped the shell's
743 // `controllerchange` reload. The bytes are identical for
744 // everyone now; the shell posts these to the worker at
745 // boot.
746 //
747 // Computed server-side, not read from the settings
748 // snapshot client-side, because
749 // `openstation_pwa_admin_asset_cache_enabled()` applies
750 // the `openstation_pwa_admin_asset_cache` filter — an
751 // operator's site-wide veto has to keep working.
752 'swConfig' => array(
753 'adminAssetCache' => (bool) openstation_pwa_admin_asset_cache_enabled(),
754 'windowPrewarm' => ! empty( openstation_get_os_settings( get_current_user_id() )['windowPrewarmEnabled'] ),
755 ),
756 'stateUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/pwa-state' ) ),
757 'state' => openstation_pwa_get_user_state( get_current_user_id() ),
758 // Mirrors the manifest's `name` field — used by the
759 // install pill so the button reads "Install <site>"
760 // rather than "Install <current page>" (which would
761 // be misleading: we install the whole site as an
762 // app, not the dashboard window the user happens to
763 // be viewing).
764 'appName' => get_bloginfo( 'name' ),
765 // Operators set the `openstation_pwa_force_replace_sw`
766 // filter to `true` when another root-scope service
767 // worker on the origin is blocking openstation
768 // installability (foreign-SW guard in
769 // `src/pwa/sw-register.ts`). Default `false` preserves
770 // the polite behaviour where we yield to existing PWAs.
771 'forceReplaceSw' => openstation_pwa_force_replace_sw(),
772 ),
773 // Ordered Core command-palette asset manifest, replayed on
774 // first palette invocation. `null` on pre-6.9 sites.
775 'commandPalette' => $command_palette,
776 // Stylesheets for shell surfaces that render on demand —
777 // the Preferences panel, the AI assistant, the bug-report
778 // window. None of them is a server-registered native
779 // window (they are built client-side by the shell
780 // bundle), so the `styles` companion mechanism can't
781 // carry their CSS; instead the shell injects each sheet
782 // the first time its surface opens, via
783 // `ensureDeferredStyle()` in `src/deferred-styles.ts`.
784 // Same resolved shape a native window's `styleUrl` /
785 // `styleInline` travels in.
786 // Which of the `deferredStyles` entries a game needs.
787 // `launchGame()` injects these before the window paints.
788 'gameStyleHandles' => function_exists( 'openstation_games_style_handles' )
789 ? openstation_games_style_handles()
790 : array(),
791 'deferredStyles' => openstation_build_deferred_styles(
792 array_merge(
793 array(
794 'os-settings',
795 'desktop-mode-ai-assistant',
796 'desktop-mode-bug-report',
797 // WP Explorer's sheet. It rides that window as a
798 // companion style, but the desktop FOLDER window
799 // paints its preview pane with the same
800 // `os-my-wordpress__*` classes and — being a
801 // native window opened straight from JS — carries
802 // no companion styles of its own. Without this,
803 // the pane rendered unstyled until WP Explorer
804 // had been opened once in the session.
805 'desktop-mode-my-wordpress',
806 ),
807 // The Games sheets. They also ride the hub window as
808 // companion styles, but a game is reachable without
809 // the hub — the challenge toast, solo mode, and
810 // `wp.os.games.launch()` all land in `launchGame()`
811 // with no hub window in the tab. Listing them here
812 // costs a URL each in the boot config and no CSS
813 // until `launchGame()` asks.
814 function_exists( 'openstation_games_style_handles' )
815 ? openstation_games_style_handles()
816 : array()
817 )
818 ),
819 )
820 );
821
822 wp_localize_script( 'openstation', 'openStationConfig', $config );
823
824 /**
825 * Fires when OpenStation assets are enqueued.
826 */
827 do_action( 'openstation_mode_init' );
828 }
829 add_action( 'admin_enqueue_scripts', 'openstation_enqueue_assets' );
830
831 /**
832 * Keep Core's boot-time command-palette enqueue off shell pages.
833 *
834 * WordPress 7.0 hooks `wp_enqueue_command_palette_assets()` on
835 * `admin_enqueue_scripts` by default, which puts the palette's whole
836 * dependency chain — the Gutenberg runtime, ~800 KB gzipped — on
837 * every admin page. On a SHELL page that is pure dead weight: the
838 * shell suppresses Core's palette unconditionally (the ⌘K keystroke
839 * and the admin-bar icon both route to the shell's own palette), so
840 * the runtime it powers can never be shown. Unhooking here lets the
841 * deferred manifest (`openstation_build_command_palette_assets_payload()`)
842 * capture the chain instead, and the shell loads it on the first
843 * palette invocation.
844 *
845 * Deliberately scoped: classic-mode requests keep Core's default,
846 * because a classic page is Core's own UI where Core's palette is the
847 * right one.
848 *
849 * Windows are handled separately by
850 * {@see openstation_chromeless_should_trim_command_palette()} in
851 * `includes/render/chromeless-trim.php` — same idea, but it has to
852 * drop the whole palette *family* rather than just unhook Core's
853 * callback, and it exempts block-editor screens. Unhooking alone is
854 * not enough there: a third-party palette extension that declares
855 * `wp-commands` keeps the entire chain queued as its dependency.
856 *
857 * Priority 0, ahead of Core's default 10, so the removal lands
858 * before the callback fires. On WP 6.9 (function exists, no default
859 * hook) the `remove_action()` is a harmless no-op.
860 */
861 function openstation_defer_core_command_palette() {
862 if ( ! openstation_is_shell_request() ) {
863 return;
864 }
865 remove_action( 'admin_enqueue_scripts', 'wp_enqueue_command_palette_assets' );
866 }
867 add_action( 'admin_enqueue_scripts', 'openstation_defer_core_command_palette', 0 );
868
869 /**
870 * Emits `<link rel="preload">` hints for the shell's critical-path
871 * assets so the browser starts fetching them as soon as it parses
872 * the document `<head>`.
873 *
874 * Without this, the browser doesn't discover the main `desktop.min.js`
875 * bundle URL until it parses the footer `<script>` tag — typically
876 * ~1 RTT after the rest of the page has started loading. For a 464 KB
877 * bundle on a midrange phone that's a measurable FCP delay; on a
878 * slow connection it dominates first paint entirely.
879 *
880 * Hooked at `admin_print_styles @ 1` so the preload tags land in
881 * `<head>` BEFORE the regular `<link rel="stylesheet">` tags (which
882 * default to priority 10) and well before the footer `<script>`
883 * tag. The `wp_resource_hints` filter is frontend-only (`wp_head`-
884 * driven) and isn't invoked in admin context, so we emit our own
885 * tags.
886 *
887 * Four targets by default, split across two relationship types:
888 * - `desktop[.min].js` (preload) — the shell bundle (biggest win),
889 * consumed by the footer `<script>` on this very load.
890 * - `desktop.css` (preload) — shell base CSS, needed for first
891 * paint. Its registered handle is `filemtime`-stamped so the
892 * stylesheet URL matches this hint exactly (a `?ver=` mismatch makes
893 * the browser treat the preload as unused).
894 * - `window-system[.min].js` (prefetch) — lazy bundle `<script>`-
895 * injected by the main bundle on the first `open()`.
896 * - `shell-overlays[.min].js` (prefetch) — lazy bundle injected on the
897 * first toast / dialog / context-menu.
898 *
899 * The lazy bundles use `prefetch` rather than `preload`: they're loaded
900 * later (often beyond the ~3s window Chrome allows a `preload` before it
901 * warns "preloaded but not used in time"), so `prefetch` keeps the early
902 * low-priority cache fill without the must-use-now contract.
903 *
904 * Plugins can extend the hint list via the `openstation_preload_hints`
905 * filter — e.g. a settings tab whose bundle the user opens on every
906 * visit can opt its own URL into the preload phase.
907 *
908 * Same-origin resources only — no `crossorigin` attribute. CDN hosts
909 * that serve `wp-content/plugins/` from a different origin should
910 * supply absolute URLs through the filter; in that case the consumer
911 * is responsible for the `crossorigin` semantics.
912 */
913 function openstation_print_preload_hints() {
914 if ( ! openstation_is_shell_request() ) {
915 return;
916 }
917
918 $suffix = openstation_asset_suffix();
919
920 $build_url = static function ( $relative ) {
921 $path = OPENSTATION_DIR . $relative;
922 $ver = file_exists( $path ) ? (string) filemtime( $path ) : OPENSTATION_VERSION;
923 return OPENSTATION_URL . $relative . '?ver=' . $ver;
924 };
925
926 $hints = array(
927 // Critical path — consumed on this very page load (the footer
928 // `<script>` and the shell stylesheet), so `preload` is correct.
929 array(
930 'href' => $build_url( 'assets/js/desktop' . $suffix . '.js' ),
931 'as' => 'script',
932 'rel' => 'preload',
933 ),
934 array(
935 'href' => $build_url( 'assets/css/desktop.css' ),
936 'as' => 'style',
937 'rel' => 'preload',
938 ),
939 // Lazy bundles — `<script>`-injected by the main bundle after
940 // first paint (window-system on the first `open()`, shell-overlays
941 // on the first toast / dialog / context-menu). They are frequently
942 // NOT requested within the ~3s window Chrome allows a `preload`,
943 // which produced "resource was preloaded but not used in time"
944 // warnings. `prefetch` is the right hint: same early, low-priority
945 // fetch into the cache, but no must-use-now contract — so the
946 // injected `<script src>` is served from cache with no warning.
947 array(
948 'href' => $build_url( 'assets/js/window-system' . $suffix . '.js' ),
949 'as' => 'script',
950 'rel' => 'prefetch',
951 ),
952 array(
953 'href' => $build_url( 'assets/js/shell-overlays' . $suffix . '.js' ),
954 'as' => 'script',
955 'rel' => 'prefetch',
956 ),
957 );
958
959 /**
960 * Filters the list of resource preload hints emitted in `<head>`.
961 *
962 * Each entry is a `{ 'href' => string, 'as' => string,
963 * 'rel' => 'preload'|'prefetch' }` array rendered as
964 * `<link rel="<rel>" as="<as>" href="<href>">`. `rel` is optional and
965 * defaults to `preload`; any value other than `prefetch` is coerced
966 * back to `preload`. Unrecognized entries are silently skipped — keep
967 * the contract permissive so a misconfigured plugin can't tank first
968 * paint.
969 *
970 * @param array $hints Default hints (main bundle + base CSS as
971 * `preload`; window-system + shell-overlays as
972 * `prefetch`).
973 */
974 $hints = apply_filters( 'openstation_preload_hints', $hints );
975
976 if ( ! is_array( $hints ) ) {
977 return;
978 }
979
980 foreach ( $hints as $hint ) {
981 if ( ! is_array( $hint ) ) {
982 continue;
983 }
984 $href = isset( $hint['href'] ) ? (string) $hint['href'] : '';
985 $as = isset( $hint['as'] ) ? (string) $hint['as'] : '';
986 if ( '' === $href || '' === $as ) {
987 continue;
988 }
989 // `preload` (critical, used on this load) vs `prefetch` (lazy,
990 // used on a later interaction). Anything else falls back to
991 // `preload` so a typo can't emit an invalid relationship.
992 $rel = isset( $hint['rel'] ) ? (string) $hint['rel'] : 'preload';
993 if ( 'prefetch' !== $rel ) {
994 $rel = 'preload';
995 }
996 printf(
997 '<link rel="%s" as="%s" href="%s" />' . "\n",
998 esc_attr( $rel ),
999 esc_attr( $as ),
1000 esc_url( $href )
1001 );
1002 }
1003 }
1004 add_action( 'admin_print_styles', 'openstation_print_preload_hints', 1 );
1005
1006 /**
1007 * Defers loading of non-critical openstation stylesheets so they
1008 * don't block first paint.
1009 *
1010 * Three stylesheets in the default enqueue list are only needed
1011 * after a user interaction — `dock-peek` (mouseover a dock tile),
1012 * `ai-assistant` (Cmd+K palette), `bug-report` (Report-a-bug
1013 * window). With the normal `<link rel="stylesheet">` tag they sit
1014 * on the critical path and the browser blocks first paint waiting
1015 * for them, even though nothing on screen needs them yet.
1016 *
1017 * The well-known mitigation is the `media="print" onload="…"`
1018 * pattern:
1019 *
1020 * <link rel="stylesheet" media="print"
1021 * onload="this.media='all'; this.onload=null" href="…">
1022 * <noscript><link rel="stylesheet" href="…"></noscript>
1023 *
1024 * `media="print"` makes the browser treat the sheet as
1025 * non-applicable to the current display, so it downloads with
1026 * low priority and doesn't block render. The `onload` handler
1027 * swaps `media` to the original value once the bytes arrive
1028 * (within ms of page load), making the styles take effect long
1029 * before the user clicks anything that needs them. The
1030 * `<noscript>` fallback restores critical-path behavior for JS-off
1031 * browsers, so accessibility isn't degraded.
1032 *
1033 * Filterable via `openstation_deferred_styles` so plugins can opt
1034 * their own non-critical stylesheets in (or pull a built-in out).
1035 * Chromeless iframes are skipped — their CSS pipeline is separate.
1036 *
1037 * @param string $html The original <link> tag HTML.
1038 * @param string $handle The stylesheet handle WP is printing.
1039 * @param string $href The full URL of the stylesheet.
1040 * @param string $media The media attribute value WP resolved.
1041 * @return string Possibly-rewritten tag.
1042 */
1043 function openstation_defer_non_critical_styles( $html, $handle, $href, $media ) {
1044 // Cheap gates first — `style_loader_tag` fires once per enqueued
1045 // stylesheet on EVERY admin page (frontend doesn't go through
1046 // this filter, but admin does, including pages where OpenStation
1047 // is disabled). The deferred handles only ship when OpenStation
1048 // is active, so the in_array check below would always miss on
1049 // classic-only admin pages — but the `apply_filters` call still
1050 // builds an array and walks subscribers per stylesheet. Short-
1051 // circuit on the cheap helper checks (`is_admin` / enabled /
1052 // chromeless) so non-openstation users pay nothing.
1053 if ( ! openstation_is_enabled() ) {
1054 return $html;
1055 }
1056 if ( openstation_is_chromeless_request() ) {
1057 return $html;
1058 }
1059
1060 /**
1061 * Filters the list of stylesheet handles that should be loaded
1062 * deferred via the media-print-onload pattern. Plugins can add
1063 * their own non-critical stylesheets here, or pull a built-in
1064 * out (e.g. a plugin that surfaces the AI assistant on every
1065 * page might want to keep its CSS critical-path).
1066 *
1067 * @param string[] $handles Default deferred handles.
1068 */
1069 $deferred = apply_filters(
1070 'openstation_deferred_styles',
1071 array(
1072 'os-dock-peek',
1073 'os-openstation-layout',
1074 'desktop-mode-ai-assistant',
1075 'desktop-mode-bug-report',
1076 'os-window-overview',
1077 'os-settings',
1078 )
1079 );
1080
1081 if ( ! in_array( $handle, (array) $deferred, true ) ) {
1082 return $html;
1083 }
1084
1085 $resolved_media = $media ? $media : 'all';
1086 $id = $handle . '-css';
1087
1088 // Two contexts, two escapers for the same `$resolved_media` value:
1089 //
1090 // - `%3$s` lands inside a JS string literal inside the HTML
1091 // `onload="…"` attribute (`this.media='%3$s'`). `esc_attr`
1092 // escapes `"` and `&` but NOT single quotes, so a media
1093 // value containing `'` would break out of the JS string.
1094 // `esc_js` is the correct escaper for "string literal inside
1095 // an event-handler attribute" — escapes single quotes, double
1096 // quotes, backslashes, newlines. Today `$resolved_media`
1097 // comes from `wp_enqueue_style()`'s `$media` parameter (always
1098 // a CSS media type / query produced by WordPress core), so
1099 // this is pure defense-in-depth, but the cost is one extra
1100 // function call.
1101 //
1102 // - `%4$s` lands inside an HTML attribute in the `<noscript>`
1103 // fallback (`media='%4$s'`). That's standard `esc_attr`.
1104 //
1105 // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- This filter rewrites a tag WordPress is in the process of emitting for an already-registered+enqueued stylesheet handle; the linter doesn't trace the `style_loader_tag` filter context, so the raw <link rel="stylesheet"> output is a false-positive.
1106 $markup = sprintf(
1107 '<link rel=\'stylesheet\' id=\'%1$s\' href=\'%2$s\' media=\'print\' onload="this.media=\'%3$s\'; this.onload=null;" />' . "\n" .
1108 '<noscript><link rel=\'stylesheet\' id=\'%1$s-noscript\' href=\'%2$s\' media=\'%4$s\' /></noscript>' . "\n",
1109 esc_attr( $id ),
1110 esc_url( $href ),
1111 esc_js( $resolved_media ),
1112 esc_attr( $resolved_media )
1113 );
1114 // phpcs:enable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
1115
1116 return $markup;
1117 }
1118 add_filter( 'style_loader_tag', 'openstation_defer_non_critical_styles', 10, 4 );
1119
1120 /**
1121 * Build the admin-menu command map (name → URL) and expose it on
1122 * `window.__openStationMenuCommands`. The shell command harvester
1123 * (`src/commands/shell-harvester.ts`) reads this slot to resolve URLs
1124 * for "Go to: …" commands whose JS callbacks
1125 * (`document.location = menuCommand.url`) close over a variable URL
1126 * we can't extract from source. Without this map those commands
1127 * either get skipped (no URL recoverable) or — if the location
1128 * shadow misses — navigate the SHELL out of OpenStation.
1129 *
1130 * Mirrors what WordPress core's `wp_enqueue_command_palette_assets()`
1131 * builds for `wp.coreCommands.initializeCommandPalette(...)`. We
1132 * duplicate the logic here (instead of monkey-patching the JS init
1133 * which is timing-sensitive — WP registers its hook during core load,
1134 * so it always emits its inline before any plugin-added inline on the
1135 * same handle) and ship the result through `wp_add_inline_script` on
1136 * our own bundle handle. That decouples us entirely from WP's command-
1137 * palette mount timing.
1138 *
1139 * @global array $menu
1140 * @global array $submenu
1141 * @return array<int, array{label:string, url:string, name:string}>
1142 */
1143 function openstation_build_command_menu_map() {
1144 global $menu, $submenu, $_parent_pages;
1145 if ( ! is_array( $menu ) ) {
1146 return array();
1147 }
1148 $out = array();
1149
1150 $extract_root_text = static function ( $label ) {
1151 if ( '' === $label || ! is_string( $label ) ) {
1152 return '';
1153 }
1154 if ( class_exists( 'WP_HTML_Tag_Processor' ) ) {
1155 $processor = new WP_HTML_Tag_Processor( $label );
1156 $text = '';
1157 $depth = 0;
1158 while ( $processor->next_token() ) {
1159 $token_type = $processor->get_token_type();
1160 if ( '#text' === $token_type && 0 === $depth ) {
1161 $text .= $processor->get_modifiable_text();
1162 }
1163 if ( '#tag' === $token_type ) {
1164 if ( $processor->is_tag_closer() ) {
1165 if ( $depth > 0 ) {
1166 --$depth;
1167 }
1168 continue;
1169 }
1170 $name = $processor->get_tag();
1171 if ( $name && ! ( class_exists( 'WP_HTML_Processor' ) && WP_HTML_Processor::is_void( $name ) ) ) {
1172 ++$depth;
1173 }
1174 }
1175 }
1176 return trim( $text );
1177 }
1178 return trim( wp_strip_all_tags( $label ) );
1179 };
1180
1181 foreach ( $menu as $menu_item ) {
1182 if ( empty( $menu_item[0] ) || ! is_string( $menu_item[0] ) ) {
1183 continue;
1184 }
1185 if ( ! empty( $menu_item[1] ) && ! current_user_can( $menu_item[1] ) ) {
1186 continue;
1187 }
1188 $menu_label = $extract_root_text( $menu_item[0] );
1189 $menu_slug = $menu_item[2];
1190 $menu_url = '';
1191 // Registered plugin pages win over the direct-file test: a
1192 // legacy file-path slug ('wp-sweep/admin.php') matches the
1193 // `.php` regex yet must route through menu_page_url(). The
1194 // exception is URL-style slugs referencing a real admin file
1195 // (ACF's 'edit.php?post_type=acf-field-group' — also a
1196 // registered page) — those stay direct links, matching
1197 // classic admin's menu-header.php.
1198 if ( ( ! isset( $_parent_pages[ $menu_slug ] ) || openstation_is_admin_file_slug( $menu_slug ) ) && ( preg_match( '/\.php($|\?)/', $menu_slug ) || wp_http_validate_url( $menu_slug ) ) ) {
1199 $menu_url = $menu_slug;
1200 } elseif ( ! empty( menu_page_url( $menu_slug, false ) ) ) {
1201 $menu_url = menu_page_url( $menu_slug, false );
1202 }
1203 if ( '' !== $menu_url ) {
1204 $out[] = array(
1205 'label' => $menu_label,
1206 'url' => $menu_url,
1207 'name' => $menu_slug,
1208 );
1209 }
1210 if ( ! empty( $submenu ) && is_array( $submenu ) && array_key_exists( $menu_slug, $submenu ) ) {
1211 foreach ( $submenu[ $menu_slug ] as $submenu_item ) {
1212 if ( empty( $submenu_item[0] ) ) {
1213 continue;
1214 }
1215 if ( ! empty( $submenu_item[1] ) && ! current_user_can( $submenu_item[1] ) ) {
1216 continue;
1217 }
1218 $submenu_label = $extract_root_text( $submenu_item[0] );
1219 $submenu_slug = $submenu_item[2];
1220 $submenu_url = '';
1221 // Same registered-page vs admin-file rule as the
1222 // top-level loop.
1223 if ( ( ! isset( $_parent_pages[ $submenu_slug ] ) || openstation_is_admin_file_slug( $submenu_slug ) ) && ( preg_match( '/\.php($|\?)/', $submenu_slug ) || wp_http_validate_url( $submenu_slug ) ) ) {
1224 $submenu_url = $submenu_slug;
1225 } elseif ( ! empty( menu_page_url( $submenu_slug, false ) ) ) {
1226 $submenu_url = menu_page_url( $submenu_slug, false );
1227 }
1228 if ( '' === $submenu_url ) {
1229 continue;
1230 }
1231 $out[] = array(
1232 'label' => sprintf(
1233 /* translators: 1: parent menu label, 2: submenu label */
1234 __( '%1$s > %2$s', 'desktop-mode' ),
1235 $menu_label,
1236 $submenu_label
1237 ),
1238 'url' => $submenu_url,
1239 'name' => $menu_slug . '-' . $submenu_item[2],
1240 );
1241 }
1242 }
1243 }
1244 return $out;
1245 }
1246