PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 0.9.8
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v0.9.8
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 0.9.8, at includes/render/assets.php

965 lines 45.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Desktop Mode — Asset enqueue.
4 *
5 * Loads the desktop shell CSS + JS bundles when desktop mode is
6 * active and the request isn't chromeless / classic-overridden.
7 * Owns the entire `desktop_mode_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 Desktop_Mode
15 */
16
17 defined( 'ABSPATH' ) || exit;
18
19 /**
20 * Enqueues the desktop mode shell assets (CSS + JS) when desktop mode is active.
21 *
22 * Only loads the full desktop shell scripts and styles when the user has
23 * desktop mode enabled and the request is not a chromeless iframe load.
24 */
25 function desktop_mode_enqueue_assets() {
26 if ( ! is_admin() ) {
27 return;
28 }
29
30 // Auto-enqueue the iframe bridge anywhere a desktop-mode 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 // `?desktop_mode_chromeless=1` flag, the chromeless inline bridge doesn't
36 // run, and `wp.desktop.iframe` silently disappears. With this
37 // auto-enqueue, the API is universally present for any same-
38 // origin admin page a desktop-mode user opens — chromeless or
39 // accidentally classic.
40 if ( desktop_mode_is_enabled() ) {
41 wp_enqueue_script( 'desktop-mode-iframe-bridge' );
42
43 // Block Editor cross-window drop receiver. Listens for
44 // `desktop-mode-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( 'desktop-mode-gutenberg-drop-receiver' );
58 }
59 }
60
61 // Chromeless requests (iframes) need chromeless styles and overrides.
62 if ( desktop_mode_is_chromeless_request() ) {
63 wp_enqueue_style( 'desktop-mode' );
64 wp_enqueue_style( 'desktop-mode-chromeless' );
65
66 /**
67 * Fires when chromeless styles are enqueued inside a desktop mode 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 * `.desktop-mode-chromeless` body class to scope your rules.
72 */
73 do_action( 'desktop_mode_chromeless_styles' );
74 return;
75 }
76
77 if ( ! desktop_mode_is_enabled() || desktop_mode_is_classic_request() ) {
78 return;
79 }
80
81 // CSS.
82 wp_enqueue_style( 'desktop-mode' );
83 wp_enqueue_style( 'desktop-mode-windows' );
84 wp_enqueue_style( 'desktop-mode-window-overview' );
85 wp_enqueue_style( 'desktop-mode-os-settings' );
86 wp_enqueue_style( 'desktop-mode-dock' );
87 wp_enqueue_style( 'desktop-mode-dock-peek' );
88 wp_enqueue_style( 'desktop-mode-ai-assistant' );
89 wp_enqueue_style( 'desktop-mode-bug-report' );
90 wp_enqueue_style( 'desktop-mode-files' );
91 wp_enqueue_style( 'desktop-mode-notes' );
92
93 // JS.
94 wp_enqueue_script( 'desktop-mode' );
95
96 // `wp_enqueue_command_palette_assets()` (WP 6.9+) enqueues the
97 // `wp-commands` store package, the `wp-core-commands` script that
98 // registers the WordPress-wide baseline (Add new post, Manage
99 // plugins, Switch theme, Browse patterns, …) AND — critically —
100 // the inline `wp.coreCommands.initializeCommandPalette( … )` call
101 // that actually populates the `core/commands` data store with the
102 // admin-menu commands. Without that inline init, the script loads
103 // but the store stays empty and `src/commands/shell-harvester.ts`
104 // finds nothing to publish.
105 //
106 // WP normally only calls this on screens that opt in to the native
107 // palette; the shell needs it on every admin URL it might wrap.
108 // `function_exists` guard for pre-6.9 sites — the harvester gracefully
109 // no-ops when the store is missing.
110 if ( function_exists( 'wp_enqueue_command_palette_assets' ) ) {
111 // `wp_enqueue_command_palette_assets()` calls
112 // `array_key_exists( $menu_slug, $submenu )` without guarding
113 // the global, so an unset `$submenu` (test contexts, edge-case
114 // admin requests where the menu wasn't built yet) blows up
115 // with a TypeError. Initialize defensively before calling.
116 global $menu, $submenu;
117 if ( ! isset( $submenu ) || ! is_array( $submenu ) ) {
118 $submenu = array();
119 }
120 if ( ! isset( $menu ) || ! is_array( $menu ) ) {
121 $menu = array();
122 }
123 wp_enqueue_command_palette_assets();
124
125 // Expose the same menu-commands array WP serializes into
126 // `wp.coreCommands.initializeCommandPalette(...)` on a window
127 // slot the shell harvester can read. Built in PHP from `$menu`
128 // / `$submenu` here (we already guarded that they're arrays
129 // above), then injected as a `before` inline on our own bundle
130 // — that runs synchronously before `desktop.min.js` boots the
131 // shell harvester, so the lookup is guaranteed populated by
132 // the time `src/commands/shell-harvester.ts` classifies any
133 // command. Decoupled from WP's command-palette mount timing
134 // (which fires from a core-registered hook we can't reorder).
135 $menu_map = desktop_mode_build_command_menu_map();
136 wp_add_inline_script(
137 'desktop-mode',
138 'window.__desktopModeMenuCommands = ' . wp_json_encode( $menu_map ) . ';',
139 'before'
140 );
141 }
142
143 // Pass configuration to JavaScript.
144 global $title, $pagenow, $parent_file, $menu;
145
146 $menu_icon = 'dashicons-admin-generic';
147 if ( ! empty( $parent_file ) && ! empty( $menu ) ) {
148 foreach ( $menu as $item ) {
149 if ( ! empty( $item[2] ) && $item[2] === $parent_file && ! empty( $item[6] ) ) {
150 $menu_icon = $item[6];
151 break;
152 }
153 }
154 }
155
156 // Build dock items from the admin menu. Core pages are ordered
157 // first (Dashboard, Posts, Plugins, Users, Settings, …), then
158 // plugin-contributed top-level routes. `desktop_mode_dock_placement`
159 // is the per-item filter escape hatch for hiding. Shared with the
160 // REST menu endpoint so live refreshes (post plugin-activation)
161 // produce the same ordering as the boot payload.
162 $menu_payload = desktop_mode_build_menu_payload();
163 $dock_items = $menu_payload['dockItems'];
164 $native_windows = isset( $menu_payload['nativeWindows'] )
165 ? $menu_payload['nativeWindows']
166 : array();
167 $server_widgets = isset( $menu_payload['serverWidgets'] )
168 ? $menu_payload['serverWidgets']
169 : array();
170 $server_wallpapers = isset( $menu_payload['serverWallpapers'] )
171 ? $menu_payload['serverWallpapers']
172 : array();
173 $server_command_scripts = isset( $menu_payload['serverCommandScripts'] )
174 ? $menu_payload['serverCommandScripts']
175 : array();
176 $server_commands = isset( $menu_payload['serverCommands'] )
177 ? $menu_payload['serverCommands']
178 : array();
179 $server_settings_tab_scripts = isset( $menu_payload['serverSettingsTabScripts'] )
180 ? $menu_payload['serverSettingsTabScripts']
181 : array();
182 $server_settings_tabs = isset( $menu_payload['serverSettingsTabs'] )
183 ? $menu_payload['serverSettingsTabs']
184 : array();
185 $server_dock_rail_renderer_scripts = isset( $menu_payload['serverDockRailRendererScripts'] )
186 ? $menu_payload['serverDockRailRendererScripts']
187 : array();
188 $server_titlebar_button_scripts = isset( $menu_payload['serverTitleBarButtonScripts'] )
189 ? $menu_payload['serverTitleBarButtonScripts']
190 : array();
191 $server_window_theme_scripts = isset( $menu_payload['serverWindowThemeScripts'] )
192 ? $menu_payload['serverWindowThemeScripts']
193 : array();
194 $server_window_themes = isset( $menu_payload['serverWindowThemes'] )
195 ? $menu_payload['serverWindowThemes']
196 : array();
197 $server_window_control_scripts = isset( $menu_payload['serverWindowControlScripts'] )
198 ? $menu_payload['serverWindowControlScripts']
199 : array();
200 $server_window_controls = isset( $menu_payload['serverWindowControls'] )
201 ? $menu_payload['serverWindowControls']
202 : array();
203 $server_window_slot_scripts = isset( $menu_payload['serverWindowSlotScripts'] )
204 ? $menu_payload['serverWindowSlotScripts']
205 : array();
206 $server_window_slots = isset( $menu_payload['serverWindowSlots'] )
207 ? $menu_payload['serverWindowSlots']
208 : array();
209 $server_window_chrome_scripts = isset( $menu_payload['serverWindowChromeScripts'] )
210 ? $menu_payload['serverWindowChromeScripts']
211 : array();
212 $server_window_chromes = isset( $menu_payload['serverWindowChromes'] )
213 ? $menu_payload['serverWindowChromes']
214 : array();
215 $server_window_notices = isset( $menu_payload['serverWindowNotices'] )
216 ? $menu_payload['serverWindowNotices']
217 : array();
218 $server_games = isset( $menu_payload['serverGames'] )
219 ? $menu_payload['serverGames']
220 : array();
221 // Boot-time copy of the desktop-theme library. Without it the
222 // shell's registry seeds EMPTY, and the consequences are subtle
223 // rather than obvious: PHP has already applied the user's theme
224 // server-side (stylesheet + shell attribute), but the client
225 // can't resolve the slug to an entry, so it believes nothing is
226 // active. Themed ICONS never paint, and switching back to the
227 // system default no-ops the first time — `applyDesktopTheme()`
228 // dedupes on an `activeId` that was never set.
229 $server_desktop_themes = isset( $menu_payload['serverDesktopThemes'] )
230 ? $menu_payload['serverDesktopThemes']
231 : array();
232 $desktop_icons = isset( $menu_payload['desktopIcons'] )
233 ? $menu_payload['desktopIcons']
234 : array();
235
236 // Files-on-the-Desktop payload (Phase 0+1). Plugin-registered
237 // file types and openers ship as metadata only; the JS side
238 // holds the executable handlers and resolves on double-click.
239 $server_file_types = function_exists( 'desktop_mode_build_file_types_payload' )
240 ? desktop_mode_build_file_types_payload()
241 : array();
242 $server_file_openers = function_exists( 'desktop_mode_build_file_openers_payload' )
243 ? desktop_mode_build_file_openers_payload()
244 : array();
245 $user_file_associations = function_exists( 'desktop_mode_get_user_file_associations' )
246 ? desktop_mode_get_user_file_associations( get_current_user_id() )
247 : array();
248 $server_wallpaper_menu_items = function_exists( 'desktop_mode_build_wallpaper_menu_items' )
249 ? desktop_mode_build_wallpaper_menu_items()
250 : array();
251
252 /*
253 * OS-file drop config — what the browser drop manager will
254 * accept when the user drags a file from their native desktop
255 * onto any surface inside Desktop Mode (wallpaper, a folder,
256 * a window, or a chromeless iframe). The allowed-mimes list is
257 * the user-scoped `get_allowed_mime_types()` (already capability
258 * gated by WordPress); the size cap is `wp_max_upload_size()`.
259 *
260 * Both are filterable so plugins can narrow or widen the set —
261 * e.g. a media-only plugin can restrict drops to images, or a
262 * docs plugin can opt PDFs in for a specific role.
263 */
264 $drop_allowed_mimes_map = current_user_can( 'upload_files' )
265 ? get_allowed_mime_types( get_current_user_id() )
266 : array();
267 /**
268 * Filter the allowed-mime map used by the OS-file drop manager.
269 *
270 * @param array<string,string> $mimes_map `ext => mime-type` map (same shape `get_allowed_mime_types()` returns).
271 * @param int $user_id The current user id.
272 */
273 $drop_allowed_mimes_map = apply_filters( 'desktop_mode_drop_allowed_mimes', $drop_allowed_mimes_map, get_current_user_id() );
274 $drop_allowed_mimes_map = is_array( $drop_allowed_mimes_map ) ? $drop_allowed_mimes_map : array();
275 $drop_allowed_mimes = array_values( array_unique( array_values( $drop_allowed_mimes_map ) ) );
276
277 $drop_max_size = (int) wp_max_upload_size();
278 /**
279 * Filter the per-file size cap (in bytes) used by the OS-file
280 * drop manager. Returning `0` disables the client-side cap —
281 * the server still enforces its own.
282 *
283 * @param int $max_size Default `wp_max_upload_size()`.
284 * @param int $user_id The current user id.
285 */
286 $drop_max_size = (int) apply_filters( 'desktop_mode_drop_max_size', $drop_max_size, get_current_user_id() );
287
288 /**
289 * Filter the master OS-file drop enable gate. Lets plugins
290 * disable the drop manager by role / capability beyond the
291 * default `upload_files` check (e.g. only for admins, or
292 * only on specific multisite blogs).
293 *
294 * @param bool $enabled Default — `current_user_can( 'upload_files' )`.
295 * @param int $user_id The current user id.
296 */
297 $drop_enabled = (bool) apply_filters(
298 'desktop_mode_drop_enabled',
299 current_user_can( 'upload_files' ),
300 get_current_user_id()
301 );
302
303 $drop_config = array(
304 'enabled' => $drop_enabled,
305 'allowedMimes' => $drop_allowed_mimes,
306 'extToMime' => $drop_allowed_mimes_map,
307 'maxSize' => $drop_max_size,
308 );
309
310 // Lazy-bundle URL builder. Each lazy-loaded bundle (AI Assistant,
311 // About-scene, OS Settings panel, shell-overlays, window-system)
312 // is `<script>`-injected by the main bundle on demand — they don't
313 // go through `wp_register_script`, so they don't pick up WordPress's
314 // usual `?ver=<filemtime>` cache-buster. Without one, the browser
315 // happily serves a stale cached copy across plugin updates that
316 // don't bump `DESKTOP_MODE_VERSION`, and the main bundle's loader
317 // fires a `<script>`-loaded event for a file that's missing the
318 // fresh `window.desktopMode*` factory the new code expects.
319 //
320 // Mirror the `$built_version( … )` helper in `includes/assets.php`:
321 // prefer the on-disk mtime of the actual file, fall back to the
322 // plugin version when the file is missing (dev environments where
323 // the bundle hasn't been built yet).
324 $suffix = desktop_mode_asset_suffix();
325 $lazy_bundle_url = static function ( $base ) use ( $suffix ) {
326 $path = DESKTOP_MODE_DIR . 'assets/js/' . $base . $suffix . '.js';
327 $ver = file_exists( $path )
328 ? (string) filemtime( $path )
329 : DESKTOP_MODE_VERSION;
330 return esc_url_raw(
331 DESKTOP_MODE_URL . 'assets/js/' . $base . $suffix . '.js?ver=' . $ver
332 );
333 };
334
335 // Build the current page URL from $pagenow + $_GET. Strip the portal
336 // markers so the derived window ID matches what the dock would produce
337 // for the same page — otherwise auto-opening the entry window and
338 // clicking the same dock icon would create a duplicate.
339 $current_query = $_GET; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
340 unset( $current_query[ DESKTOP_MODE_PORTAL_FLAG ], $current_query[ DESKTOP_MODE_PORTAL_INTENT_FLAG ] );
341 $current_page = admin_url( $pagenow ) . ( ! empty( $current_query ) ? '?' . http_build_query( $current_query ) : '' );
342
343 $from_portal = ! empty( $_GET[ DESKTOP_MODE_PORTAL_FLAG ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
344 $from_portal_intent = ! empty( $_GET[ DESKTOP_MODE_PORTAL_INTENT_FLAG ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
345
346 /**
347 * Filters the desktop shell configuration passed to JavaScript.
348 *
349 * @param array $config {
350 * Desktop shell configuration.
351 *
352 * @type string $currentPage The current admin page URL.
353 * @type string $currentTitle The current page title.
354 * @type string $currentIcon Dashicon class for the current page.
355 * @type string $adminUrl The base admin URL.
356 * @type string $colorScheme The active admin color scheme.
357 * @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 `desktop_mode_dock_placement` are omitted.
358 * @type array $nativeWindows Server-declared native windows (via `desktop_mode_register_window`). Shell registers + syncs tiles based on this list — activation/deactivation is a diff without shell reload.
359 * @type array $serverWidgets Server-declared right-column widgets (via `desktop_mode_register_widget`). Shell syncs the widget registry + dynamically loads plugin scripts so widgets appear in the picker without a shell reload.
360 * @type array $serverWallpapers Server-declared wallpapers (via `desktop_mode_register_wallpaper`). Same lifecycle — shell loads the plugin's JS, reads the full `WallpaperDef` from `window.desktopModeWallpapers[id]`, and registers / unregisters as plugins activate / deactivate.
361 * @type array $serverCommandScripts Script handles opted-in via `desktop_mode_register_command_script`. Shell injects each URL on activation so commands registered by `wp.desktop.registerCommand` appear in the palette live. Deactivation unregisters any commands whose `owner` matches the departing handle.
362 * @type array $serverCommands Server-declared command metadata (via `desktop_mode_register_command`). Advisory today — reserved for future pre-registration shims.
363 * @type array $serverSettingsTabScripts Script handles opted-in via `desktop_mode_register_settings_tab_script`. Shell injects each URL on activation so tabs registered by `wp.desktop.registerSettingsTab` appear in the OS Settings window live. Deactivation unregisters tabs attributable to the departing handle.
364 * @type array $serverSettingsTabs Server-declared settings-tab metadata (via `desktop_mode_register_settings_tab`). Enables live unregistration on plugin deactivation without requiring JS to set `owner`.
365 * @type array $desktopIcons Server-declared desktop icons (via `desktop_mode_register_icon`). Rendered on the wallpaper as clickable shortcut tiles.
366 * @type array $accentColors Swatch list for the OS Settings accent picker. Filterable via `desktop_mode_accent_colors`.
367 * @type array $toastTypes Toast-notification type map. Filterable via `desktop_mode_toast_types`.
368 * @type string $defaultWallpaper Wallpaper slug applied on first boot. Filterable via `desktop_mode_default_wallpaper`.
369 * @type array $session Saved session (windows, focused, updated).
370 * @type string $sessionUrl REST endpoint for saving the session.
371 * @type string $mediaUrl REST endpoint for media uploads (wp/v2/media).
372 * @type string $restUrl REST API root from rest_url(), safe for pretty and plain permalink installs.
373 * @type string $defaultWindowUrl REST endpoint for saving the default-window preference.
374 * @type array $defaultWindow { enabled: bool, url: string } — current default-window preference.
375 * @type bool $canUpload Whether the user holds the `upload_files` capability.
376 * @type string $pluginUrl Plugin base URL (no trailing slash). Used by the shell to locate vendor assets and by plugins to build asset URLs.
377 * @type string $pluginVersion Plugin semver string. Surfaced in the OS Settings → About tab; plugins can read it to gate features by version.
378 * @type string $restNonce Nonce for the session REST endpoint.
379 * @type string $portalUrl Canonical `/desktop-mode/` URL.
380 * @type bool $fromPortal Whether the shell was reached via the portal.
381 * @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 `/desktop-mode/` visit from a portal-redirected admin-bar click so the shell can honour the URL the user actually asked for.
382 * @type array $seenIntros Slugs of one-time intro dialogs the user has dismissed (e.g. `['posts']`). Native windows gate their first-open intro on this list.
383 * @type string $seenIntrosUrl REST endpoint for the seen-intros surface — POST `/seen` to mark, DELETE the base to reset.
384 * @type array $stickyNotes { available: bool } — whether the Gutenberg Guidelines experiment (the `wp_guideline` CPT + `wp_guideline_type` taxonomy) is registered. The shell skips booting the sticky-notes layer when false, avoiding the REST probes that 404 without the experiment. See `desktop_mode_sticky_notes_is_available()`.
385 * }
386 */
387 $config = apply_filters(
388 'desktop_mode_shell_config',
389 array(
390 'currentPage' => esc_url( $current_page ),
391 'currentTitle' => wp_strip_all_tags( $title ),
392 'currentIcon' => sanitize_html_class( $menu_icon ),
393 'adminUrl' => esc_url( admin_url() ),
394 'colorScheme' => sanitize_html_class( get_user_option( 'admin_color' ), 'fresh' ),
395 'dockItems' => $dock_items,
396 // Baseline menu fingerprint. The shell seeds its last-known
397 // signature from this so the first off-allowlist menu change
398 // (vs. this boot state) is caught without a wasted probe. GH#325.
399 'menuSig' => isset( $menu_payload['menuSig'] ) ? (string) $menu_payload['menuSig'] : '',
400 'nativeWindows' => $native_windows,
401 'serverWidgets' => $server_widgets,
402 'serverWallpapers' => $server_wallpapers,
403 'serverCommandScripts' => $server_command_scripts,
404 'serverCommands' => $server_commands,
405 'serverSettingsTabScripts' => $server_settings_tab_scripts,
406 'serverSettingsTabs' => $server_settings_tabs,
407 'serverDockRailRendererScripts' => $server_dock_rail_renderer_scripts,
408 'serverTitleBarButtonScripts' => $server_titlebar_button_scripts,
409 'serverWindowThemeScripts' => $server_window_theme_scripts,
410 'serverWindowThemes' => $server_window_themes,
411 'serverWindowControlScripts' => $server_window_control_scripts,
412 'serverWindowControls' => $server_window_controls,
413 'serverWindowSlotScripts' => $server_window_slot_scripts,
414 'serverWindowSlots' => $server_window_slots,
415 'serverWindowChromeScripts' => $server_window_chrome_scripts,
416 'serverWindowChromes' => $server_window_chromes,
417 'serverWindowNotices' => $server_window_notices,
418 // Boot-time copy of the payload's `serverGames` — the same
419 // list the live-refresh path applies. Without it the games
420 // registry only fills after the first chromeless
421 // full-payload refresh and the Games hub boots empty.
422 'serverGames' => $server_games,
423 'serverDesktopThemes' => $server_desktop_themes,
424 'desktopIcons' => $desktop_icons,
425 'serverFileTypes' => $server_file_types,
426 'serverFileOpeners' => $server_file_openers,
427 'userFileAssociations' => $user_file_associations,
428 'filesUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/files' ) ),
429 // Pinned-notes REST base (`includes/notes/rest.php`). The
430 // notes layer boots only when this is present.
431 'notesUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/notes' ) ),
432 // Gates the "Convert to post" note affordance — the convert
433 // route (and its dock drop target) only make sense for users
434 // who can author posts.
435 'canCreatePosts' => current_user_can( 'edit_posts' ),
436 'serverWallpaperMenuItems' => $server_wallpaper_menu_items,
437 'accentColors' => desktop_mode_get_accent_colors(),
438 'toastTypes' => desktop_mode_get_toast_types(),
439 'coreUpdate' => desktop_mode_get_core_update(),
440 'coreNotices' => desktop_mode_get_core_notices(),
441 'pluginNotices' => desktop_mode_get_plugin_notices(),
442 'defaultWallpaper' => desktop_mode_get_default_wallpaper(),
443 'session' => desktop_mode_get_session( get_current_user_id() ),
444 'sessionUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/session' ) ),
445 'restUrl' => esc_url_raw( rest_url() ),
446 'mediaUrl' => esc_url_raw( rest_url( 'wp/v2/media' ) ),
447 'dropConfig' => $drop_config,
448 'defaultWindowUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/default-window' ) ),
449 'defaultWindow' => desktop_mode_get_default_window( get_current_user_id() ),
450 'canUpload' => current_user_can( 'upload_files' ),
451 'pluginUrl' => esc_url_raw( untrailingslashit( DESKTOP_MODE_URL ) ),
452 'pluginVersion' => DESKTOP_MODE_VERSION,
453 'iframeBridgeUrl' => $lazy_bundle_url( 'iframe-bridge' ),
454 // URL of the AI Assistant lazy bundle. The main bundle
455 // ships a stub matching the public `wp.desktop.ai` API; the
456 // stub `<script>`-injects this URL the first time the user
457 // opens the assistant. Picking `.js` vs `.min.js` here keeps
458 // the SCRIPT_DEBUG gate server-side, matching iframeBridgeUrl.
459 'aiAssistantBundleUrl' => $lazy_bundle_url( 'ai-assistant' ),
460 // URL of the About-scene lazy bundle. The OS Settings →
461 // About tab loads this on first mount; ~25 kB PixiJS
462 // particle scene that would otherwise ship in the main
463 // bundle for every shell load.
464 'aboutSceneBundleUrl' => $lazy_bundle_url( 'about-scene' ),
465 // URL of the OS Settings panel lazy bundle. Injected by
466 // the main bundle's `OsSettings.renderPanel()` stub on
467 // the user's first Settings open. Holds every section
468 // renderer + the `<wpd-*>` components only the panel
469 // uses, so nothing about Settings ships in
470 // `desktop.min.js` for users who never open it.
471 'osSettingsPanelBundleUrl' => $lazy_bundle_url( 'os-settings-panel' ),
472 // URL of the shell-overlays lazy bundle. Pre-loaded by
473 // the main bundle after first paint so action-triggered
474 // overlays (toast, confirm dialog, context menus) feel
475 // instant the first time they fire.
476 'shellOverlaysBundleUrl' => $lazy_bundle_url( 'shell-overlays' ),
477 // URL of the lazy window-system bundle (Stage 11).
478 // Holds the `Window` class and its DOM / pointer / tab /
479 // chrome helpers — the single largest module split out of
480 // the main bundle. Loaded on first `windowManager.open()`
481 // / `openNew()` call (both async); pre-loaded
482 // by the shell after first paint when no session is being
483 // restored and no `openCurrentPage` will fire.
484 'windowSystemBundleUrl' => $lazy_bundle_url( 'window-system' ),
485 // URL of the item-visibility-menu lazy bundle — the
486 // right-click "hide from dock / desktop" menu. Injected by
487 // the main bundle's loader shim on the first right-click.
488 'itemVisibilityMenuBundleUrl' => $lazy_bundle_url( 'item-visibility-menu' ),
489 // URL of the release-card lazy bundle — the vinyl core-
490 // update announcement. Injected by `maybeShowUpdate()` only
491 // when a core update is actually pending.
492 'releaseCardBundleUrl' => $lazy_bundle_url( 'release-card' ),
493 'restNonce' => wp_create_nonce( 'wp_rest' ),
494 'osSettings' => desktop_mode_get_os_settings( get_current_user_id() ),
495 'osSettingsUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/os-settings' ) ),
496 'seenIntros' => desktop_mode_get_seen_intros( get_current_user_id() ),
497 'seenIntrosUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/intros' ) ),
498 // Sticky notes ride on Gutenberg's Guidelines experiment
499 // (the `wp_guideline` CPT + `wp_guideline_type` taxonomy).
500 // When that experiment isn't active the `wp/v2/guidelines`
501 // + `wp/v2/wp_guideline_type` probes 404 — harmless but
502 // noisy — so the shell skips booting the layer entirely.
503 'stickyNotes' => array(
504 'available' => desktop_mode_sticky_notes_is_available(),
505 ),
506 'aiSearchUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/ai/search' ) ),
507 'aiSearchStreamUrl' => esc_url_raw( add_query_arg( 'action', 'desktop_mode_ai_search_stream', admin_url( 'admin-ajax.php' ) ) ),
508 // AI assistant availability + per-user toggle. Drives whether the
509 // Cmd+K palette and admin-bar icon appear, and the setup placeholder.
510 'aiAssistant' => function_exists( 'desktop_mode_ai_assistant_config' )
511 ? desktop_mode_ai_assistant_config()
512 : null,
513 // Lets the Features tab re-check provider availability without a
514 // reload after a connector is configured in Settings → Connectors.
515 'aiStatusUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/ai/status' ) ),
516 'extendedOptions' => current_user_can( 'manage_options' ) ? desktop_mode_get_extended_options() : null,
517 'extendedOptionsUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/extended-options' ) ),
518 // Site-wide games kill switch (Extended options). Exposed to
519 // every user — the shell skips the challenges Heartbeat
520 // channel when the framework is off.
521 'gamesEnabled' => desktop_mode_games_enabled(),
522 // Comments-window AI moderation toggle — surfaced at the
523 // shell level so the OS Settings → Features tab can render
524 // the toggle without depending on the Comments window
525 // being registered for this user. URL is the same
526 // endpoint the comments-window config exposes; state is
527 // `null` for non-admins (the UI hides the row entirely).
528 'commentsAiUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/comments/ai-settings' ) ),
529 // Non-null only for admins on a site where the Core AI stack is
530 // present. Comment scoring routes through the AI Client (WP 7.0+),
531 // so on older WordPress the whole row is hidden — same as the
532 // assistant toggle — rather than shown disabled pointing at a
533 // Settings → Connectors screen that doesn't exist there.
534 'commentsAi' => (
535 current_user_can( 'manage_options' )
536 && function_exists( 'desktop_mode_ai_is_available' )
537 && desktop_mode_ai_is_available()
538 )
539 ? array(
540 'enabled' => function_exists( 'desktop_mode_comments_ai_is_enabled' )
541 ? desktop_mode_comments_ai_is_enabled()
542 : false,
543 'providerConfigured' => function_exists( 'desktop_mode_comments_ai_provider_configured' )
544 ? desktop_mode_comments_ai_provider_configured()
545 : false,
546 )
547 : null,
548 'currentUserIsAdmin' => current_user_can( 'manage_options' ),
549 'portalUrl' => esc_url( desktop_mode_portal_url() ),
550 'fromPortal' => $from_portal,
551 'fromPortalIntent' => $from_portal_intent,
552 'pwa' => array(
553 'manifestUrl' => esc_url_raw( desktop_mode_pwa_manifest_url() ),
554 'swUrl' => esc_url_raw( desktop_mode_pwa_sw_url() ),
555 'stateUrl' => esc_url_raw( rest_url( 'desktop-mode/v1/pwa-state' ) ),
556 'state' => desktop_mode_pwa_get_user_state( get_current_user_id() ),
557 // Mirrors the manifest's `name` field — used by the
558 // install pill so the button reads "Install <site>"
559 // rather than "Install <current page>" (which would
560 // be misleading: we install the whole site as an
561 // app, not the dashboard window the user happens to
562 // be viewing).
563 'appName' => get_bloginfo( 'name' ),
564 // Operators set the `desktop_mode_pwa_force_replace_sw`
565 // filter to `true` when another root-scope service
566 // worker on the origin is blocking desktop-mode
567 // installability (foreign-SW guard in
568 // `src/pwa/sw-register.ts`). Default `false` preserves
569 // the polite behaviour where we yield to existing PWAs.
570 'forceReplaceSw' => desktop_mode_pwa_force_replace_sw(),
571 ),
572 )
573 );
574
575 wp_localize_script( 'desktop-mode', 'desktopModeConfig', $config );
576
577 /**
578 * Fires when desktop mode assets are enqueued.
579 */
580 do_action( 'desktop_mode_mode_init' );
581 }
582 add_action( 'admin_enqueue_scripts', 'desktop_mode_enqueue_assets' );
583
584 /**
585 * Emits `<link rel="preload">` hints for the shell's critical-path
586 * assets so the browser starts fetching them as soon as it parses
587 * the document `<head>`.
588 *
589 * Without this, the browser doesn't discover the main `desktop.min.js`
590 * bundle URL until it parses the footer `<script>` tag — typically
591 * ~1 RTT after the rest of the page has started loading. For a 464 KB
592 * bundle on a midrange phone that's a measurable FCP delay; on a
593 * slow connection it dominates first paint entirely.
594 *
595 * Hooked at `admin_print_styles @ 1` so the preload tags land in
596 * `<head>` BEFORE the regular `<link rel="stylesheet">` tags (which
597 * default to priority 10) and well before the footer `<script>`
598 * tag. The `wp_resource_hints` filter is frontend-only (`wp_head`-
599 * driven) and isn't invoked in admin context, so we emit our own
600 * tags.
601 *
602 * Four targets by default, split across two relationship types:
603 * - `desktop[.min].js` (preload) — the shell bundle (biggest win),
604 * consumed by the footer `<script>` on this very load.
605 * - `desktop.css` (preload) — shell base CSS, needed for first
606 * paint. Its registered handle is `filemtime`-stamped so the
607 * stylesheet URL matches this hint exactly (a `?ver=` mismatch makes
608 * the browser treat the preload as unused).
609 * - `window-system[.min].js` (prefetch) — lazy bundle `<script>`-
610 * injected by the main bundle on the first `open()`.
611 * - `shell-overlays[.min].js` (prefetch) — lazy bundle injected on the
612 * first toast / dialog / context-menu.
613 *
614 * The lazy bundles use `prefetch` rather than `preload`: they're loaded
615 * later (often beyond the ~3s window Chrome allows a `preload` before it
616 * warns "preloaded but not used in time"), so `prefetch` keeps the early
617 * low-priority cache fill without the must-use-now contract.
618 *
619 * Plugins can extend the hint list via the `desktop_mode_preload_hints`
620 * filter — e.g. a settings tab whose bundle the user opens on every
621 * visit can opt its own URL into the preload phase.
622 *
623 * Same-origin resources only — no `crossorigin` attribute. CDN hosts
624 * that serve `wp-content/plugins/` from a different origin should
625 * supply absolute URLs through the filter; in that case the consumer
626 * is responsible for the `crossorigin` semantics.
627 */
628 function desktop_mode_print_preload_hints() {
629 if (
630 ! is_admin()
631 || ! desktop_mode_is_enabled()
632 || desktop_mode_is_chromeless_request()
633 || desktop_mode_is_classic_request()
634 ) {
635 return;
636 }
637
638 $suffix = desktop_mode_asset_suffix();
639
640 $build_url = static function ( $relative ) {
641 $path = DESKTOP_MODE_DIR . $relative;
642 $ver = file_exists( $path ) ? (string) filemtime( $path ) : DESKTOP_MODE_VERSION;
643 return DESKTOP_MODE_URL . $relative . '?ver=' . $ver;
644 };
645
646 $hints = array(
647 // Critical path — consumed on this very page load (the footer
648 // `<script>` and the shell stylesheet), so `preload` is correct.
649 array(
650 'href' => $build_url( 'assets/js/desktop' . $suffix . '.js' ),
651 'as' => 'script',
652 'rel' => 'preload',
653 ),
654 array(
655 'href' => $build_url( 'assets/css/desktop.css' ),
656 'as' => 'style',
657 'rel' => 'preload',
658 ),
659 // Lazy bundles — `<script>`-injected by the main bundle after
660 // first paint (window-system on the first `open()`, shell-overlays
661 // on the first toast / dialog / context-menu). They are frequently
662 // NOT requested within the ~3s window Chrome allows a `preload`,
663 // which produced "resource was preloaded but not used in time"
664 // warnings. `prefetch` is the right hint: same early, low-priority
665 // fetch into the cache, but no must-use-now contract — so the
666 // injected `<script src>` is served from cache with no warning.
667 array(
668 'href' => $build_url( 'assets/js/window-system' . $suffix . '.js' ),
669 'as' => 'script',
670 'rel' => 'prefetch',
671 ),
672 array(
673 'href' => $build_url( 'assets/js/shell-overlays' . $suffix . '.js' ),
674 'as' => 'script',
675 'rel' => 'prefetch',
676 ),
677 );
678
679 /**
680 * Filters the list of resource preload hints emitted in `<head>`.
681 *
682 * Each entry is a `{ 'href' => string, 'as' => string,
683 * 'rel' => 'preload'|'prefetch' }` array rendered as
684 * `<link rel="<rel>" as="<as>" href="<href>">`. `rel` is optional and
685 * defaults to `preload`; any value other than `prefetch` is coerced
686 * back to `preload`. Unrecognized entries are silently skipped — keep
687 * the contract permissive so a misconfigured plugin can't tank first
688 * paint.
689 *
690 * @param array $hints Default hints (main bundle + base CSS as
691 * `preload`; window-system + shell-overlays as
692 * `prefetch`).
693 */
694 $hints = apply_filters( 'desktop_mode_preload_hints', $hints );
695
696 if ( ! is_array( $hints ) ) {
697 return;
698 }
699
700 foreach ( $hints as $hint ) {
701 if ( ! is_array( $hint ) ) {
702 continue;
703 }
704 $href = isset( $hint['href'] ) ? (string) $hint['href'] : '';
705 $as = isset( $hint['as'] ) ? (string) $hint['as'] : '';
706 if ( '' === $href || '' === $as ) {
707 continue;
708 }
709 // `preload` (critical, used on this load) vs `prefetch` (lazy,
710 // used on a later interaction). Anything else falls back to
711 // `preload` so a typo can't emit an invalid relationship.
712 $rel = isset( $hint['rel'] ) ? (string) $hint['rel'] : 'preload';
713 if ( 'prefetch' !== $rel ) {
714 $rel = 'preload';
715 }
716 printf(
717 '<link rel="%s" as="%s" href="%s" />' . "\n",
718 esc_attr( $rel ),
719 esc_attr( $as ),
720 esc_url( $href )
721 );
722 }
723 }
724 add_action( 'admin_print_styles', 'desktop_mode_print_preload_hints', 1 );
725
726 /**
727 * Defers loading of non-critical desktop-mode stylesheets so they
728 * don't block first paint.
729 *
730 * Three stylesheets in the default enqueue list are only needed
731 * after a user interaction — `dock-peek` (mouseover a dock tile),
732 * `ai-assistant` (Cmd+K palette), `bug-report` (Report-a-bug
733 * window). With the normal `<link rel="stylesheet">` tag they sit
734 * on the critical path and the browser blocks first paint waiting
735 * for them, even though nothing on screen needs them yet.
736 *
737 * The well-known mitigation is the `media="print" onload="…"`
738 * pattern:
739 *
740 * <link rel="stylesheet" media="print"
741 * onload="this.media='all'; this.onload=null" href="…">
742 * <noscript><link rel="stylesheet" href="…"></noscript>
743 *
744 * `media="print"` makes the browser treat the sheet as
745 * non-applicable to the current display, so it downloads with
746 * low priority and doesn't block render. The `onload` handler
747 * swaps `media` to the original value once the bytes arrive
748 * (within ms of page load), making the styles take effect long
749 * before the user clicks anything that needs them. The
750 * `<noscript>` fallback restores critical-path behavior for JS-off
751 * browsers, so accessibility isn't degraded.
752 *
753 * Filterable via `desktop_mode_deferred_styles` so plugins can opt
754 * their own non-critical stylesheets in (or pull a built-in out).
755 * Chromeless iframes are skipped — their CSS pipeline is separate.
756 *
757 * @param string $html The original <link> tag HTML.
758 * @param string $handle The stylesheet handle WP is printing.
759 * @param string $href The full URL of the stylesheet.
760 * @param string $media The media attribute value WP resolved.
761 * @return string Possibly-rewritten tag.
762 */
763 function desktop_mode_defer_non_critical_styles( $html, $handle, $href, $media ) {
764 // Cheap gates first — `style_loader_tag` fires once per enqueued
765 // stylesheet on EVERY admin page (frontend doesn't go through
766 // this filter, but admin does, including pages where desktop mode
767 // is disabled). The deferred handles only ship when desktop mode
768 // is active, so the in_array check below would always miss on
769 // classic-only admin pages — but the `apply_filters` call still
770 // builds an array and walks subscribers per stylesheet. Short-
771 // circuit on the cheap helper checks (`is_admin` / enabled /
772 // chromeless) so non-desktop-mode users pay nothing.
773 if ( ! desktop_mode_is_enabled() ) {
774 return $html;
775 }
776 if ( desktop_mode_is_chromeless_request() ) {
777 return $html;
778 }
779
780 /**
781 * Filters the list of stylesheet handles that should be loaded
782 * deferred via the media-print-onload pattern. Plugins can add
783 * their own non-critical stylesheets here, or pull a built-in
784 * out (e.g. a plugin that surfaces the AI assistant on every
785 * page might want to keep its CSS critical-path).
786 *
787 * @param string[] $handles Default deferred handles.
788 */
789 $deferred = apply_filters(
790 'desktop_mode_deferred_styles',
791 array(
792 'desktop-mode-dock-peek',
793 'desktop-mode-ai-assistant',
794 'desktop-mode-bug-report',
795 'desktop-mode-window-overview',
796 'desktop-mode-os-settings',
797 )
798 );
799
800 if ( ! in_array( $handle, (array) $deferred, true ) ) {
801 return $html;
802 }
803
804 $resolved_media = $media ? $media : 'all';
805 $id = $handle . '-css';
806
807 // Two contexts, two escapers for the same `$resolved_media` value:
808 //
809 // - `%3$s` lands inside a JS string literal inside the HTML
810 // `onload="…"` attribute (`this.media='%3$s'`). `esc_attr`
811 // escapes `"` and `&` but NOT single quotes, so a media
812 // value containing `'` would break out of the JS string.
813 // `esc_js` is the correct escaper for "string literal inside
814 // an event-handler attribute" — escapes single quotes, double
815 // quotes, backslashes, newlines. Today `$resolved_media`
816 // comes from `wp_enqueue_style()`'s `$media` parameter (always
817 // a CSS media type / query produced by WordPress core), so
818 // this is pure defense-in-depth, but the cost is one extra
819 // function call.
820 //
821 // - `%4$s` lands inside an HTML attribute in the `<noscript>`
822 // fallback (`media='%4$s'`). That's standard `esc_attr`.
823 //
824 // 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.
825 $markup = sprintf(
826 '<link rel=\'stylesheet\' id=\'%1$s\' href=\'%2$s\' media=\'print\' onload="this.media=\'%3$s\'; this.onload=null;" />' . "\n" .
827 '<noscript><link rel=\'stylesheet\' id=\'%1$s-noscript\' href=\'%2$s\' media=\'%4$s\' /></noscript>' . "\n",
828 esc_attr( $id ),
829 esc_url( $href ),
830 esc_js( $resolved_media ),
831 esc_attr( $resolved_media )
832 );
833 // phpcs:enable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
834
835 return $markup;
836 }
837 add_filter( 'style_loader_tag', 'desktop_mode_defer_non_critical_styles', 10, 4 );
838
839 /**
840 * Build the admin-menu command map (name → URL) and expose it on
841 * `window.__desktopModeMenuCommands`. The shell command harvester
842 * (`src/commands/shell-harvester.ts`) reads this slot to resolve URLs
843 * for "Go to: …" commands whose JS callbacks
844 * (`document.location = menuCommand.url`) close over a variable URL
845 * we can't extract from source. Without this map those commands
846 * either get skipped (no URL recoverable) or — if the location
847 * shadow misses — navigate the SHELL out of desktop mode.
848 *
849 * Mirrors what WordPress core's `wp_enqueue_command_palette_assets()`
850 * builds for `wp.coreCommands.initializeCommandPalette(...)`. We
851 * duplicate the logic here (instead of monkey-patching the JS init
852 * which is timing-sensitive — WP registers its hook during core load,
853 * so it always emits its inline before any plugin-added inline on the
854 * same handle) and ship the result through `wp_add_inline_script` on
855 * our own bundle handle. That decouples us entirely from WP's command-
856 * palette mount timing.
857 *
858 * @global array $menu
859 * @global array $submenu
860 * @return array<int, array{label:string, url:string, name:string}>
861 */
862 function desktop_mode_build_command_menu_map() {
863 global $menu, $submenu, $_parent_pages;
864 if ( ! is_array( $menu ) ) {
865 return array();
866 }
867 $out = array();
868
869 $extract_root_text = static function ( $label ) {
870 if ( '' === $label || ! is_string( $label ) ) {
871 return '';
872 }
873 if ( class_exists( 'WP_HTML_Tag_Processor' ) ) {
874 $processor = new WP_HTML_Tag_Processor( $label );
875 $text = '';
876 $depth = 0;
877 while ( $processor->next_token() ) {
878 $token_type = $processor->get_token_type();
879 if ( '#text' === $token_type && 0 === $depth ) {
880 $text .= $processor->get_modifiable_text();
881 }
882 if ( '#tag' === $token_type ) {
883 if ( $processor->is_tag_closer() ) {
884 if ( $depth > 0 ) {
885 --$depth;
886 }
887 continue;
888 }
889 $name = $processor->get_tag();
890 if ( $name && ! ( class_exists( 'WP_HTML_Processor' ) && WP_HTML_Processor::is_void( $name ) ) ) {
891 ++$depth;
892 }
893 }
894 }
895 return trim( $text );
896 }
897 return trim( wp_strip_all_tags( $label ) );
898 };
899
900 foreach ( $menu as $menu_item ) {
901 if ( empty( $menu_item[0] ) || ! is_string( $menu_item[0] ) ) {
902 continue;
903 }
904 if ( ! empty( $menu_item[1] ) && ! current_user_can( $menu_item[1] ) ) {
905 continue;
906 }
907 $menu_label = $extract_root_text( $menu_item[0] );
908 $menu_slug = $menu_item[2];
909 $menu_url = '';
910 // Registered plugin pages win over the direct-file test: a
911 // legacy file-path slug ('wp-sweep/admin.php') matches the
912 // `.php` regex yet must route through menu_page_url(). The
913 // exception is URL-style slugs referencing a real admin file
914 // (ACF's 'edit.php?post_type=acf-field-group' — also a
915 // registered page) — those stay direct links, matching
916 // classic admin's menu-header.php.
917 if ( ( ! isset( $_parent_pages[ $menu_slug ] ) || desktop_mode_is_admin_file_slug( $menu_slug ) ) && ( preg_match( '/\.php($|\?)/', $menu_slug ) || wp_http_validate_url( $menu_slug ) ) ) {
918 $menu_url = $menu_slug;
919 } elseif ( ! empty( menu_page_url( $menu_slug, false ) ) ) {
920 $menu_url = menu_page_url( $menu_slug, false );
921 }
922 if ( '' !== $menu_url ) {
923 $out[] = array(
924 'label' => $menu_label,
925 'url' => $menu_url,
926 'name' => $menu_slug,
927 );
928 }
929 if ( ! empty( $submenu ) && is_array( $submenu ) && array_key_exists( $menu_slug, $submenu ) ) {
930 foreach ( $submenu[ $menu_slug ] as $submenu_item ) {
931 if ( empty( $submenu_item[0] ) ) {
932 continue;
933 }
934 if ( ! empty( $submenu_item[1] ) && ! current_user_can( $submenu_item[1] ) ) {
935 continue;
936 }
937 $submenu_label = $extract_root_text( $submenu_item[0] );
938 $submenu_slug = $submenu_item[2];
939 $submenu_url = '';
940 // Same registered-page vs admin-file rule as the
941 // top-level loop.
942 if ( ( ! isset( $_parent_pages[ $submenu_slug ] ) || desktop_mode_is_admin_file_slug( $submenu_slug ) ) && ( preg_match( '/\.php($|\?)/', $submenu_slug ) || wp_http_validate_url( $submenu_slug ) ) ) {
943 $submenu_url = $submenu_slug;
944 } elseif ( ! empty( menu_page_url( $submenu_slug, false ) ) ) {
945 $submenu_url = menu_page_url( $submenu_slug, false );
946 }
947 if ( '' === $submenu_url ) {
948 continue;
949 }
950 $out[] = array(
951 'label' => sprintf(
952 /* translators: 1: parent menu label, 2: submenu label */
953 __( '%1$s > %2$s', 'desktop-mode' ),
954 $menu_label,
955 $submenu_label
956 ),
957 'url' => $submenu_url,
958 'name' => $menu_slug . '-' . $submenu_item[2],
959 );
960 }
961 }
962 }
963 return $out;
964 }
965