-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwp-admin-workspaces.php
More file actions
1518 lines (1420 loc) · 65.8 KB
/
Copy pathwp-admin-workspaces.php
File metadata and controls
1518 lines (1420 loc) · 65.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: WP Admin Workspaces
* Plugin URI: https://github.com/dabowman/WordPress-Admin-Workspaces
* Description: A configurable, React-based WordPress admin environment driven by workspace.json configuration files.
* Version: 0.1.0
* Requires PHP: 7.4
* Requires at least: 6.7
* Author: WP Admin Workspaces Contributors
* Author URI: https://github.com/dabowman/WordPress-Admin-Workspaces
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: wp-admin-workspaces
* Domain Path: /languages
*/
defined( 'ABSPATH' ) || exit;
// Runtime private-API dependency. `@wordpress/ui` overlay components
// transitively import `@wordpress/theme`, which calls
// __dangerousOptInToUnstableAPIsOnlyForCoreModules against the runtime
// wp.privateApis. That opt-in only succeeds if the module name is on the
// allowlist baked into the loaded `wp-private-apis` script.
//
// - WordPress < 7.0: core's allowlist EXCLUDES @wordpress/theme /
// @wordpress/ui / @wordpress/dataviews. Only the Gutenberg plugin's
// wp-private-apis override whitelists them, so Gutenberg is required —
// without it every overlay component throws at module-load and the
// workspace renders empty.
// - WordPress >= 7.0: core bundles @wordpress/theme AND ships a
// wp-private-apis allowlist that includes @wordpress/theme,
// @wordpress/ui and @wordpress/dataviews (verified against the 7.0
// release — wp-includes/js/dist/private-apis.js
// CORE_MODULES_USING_PRIVATE_APIS). The opt-in consent string is
// unchanged, so the workspace's bundled overlay components unlock against
// core's own wp.privateApis and Gutenberg is no longer required.
//
// Surface a clear notice when neither path is satisfied instead of
// letting the workspace render blank.
/**
* Whether the WordPress version supplies the private-API allowlist the workspace
* needs in core (i.e. the Gutenberg plugin is no longer required).
*
* @param string|null $version WordPress version to test. Defaults to the
* running install's version. Injectable for tests.
* @return bool True on WordPress 7.0+.
*/
function wp_admin_workspaces_core_supplies_private_apis( $version = null ) {
if ( null === $version ) {
$version = get_bloginfo( 'version' );
}
return version_compare( $version, '7.0', '>=' );
}
/**
* Whether the workspace's runtime private-API dependency is satisfied.
*
* Met when either WordPress core supplies the allowlist (7.0+) or the
* Gutenberg plugin is active (its `wp-private-apis` override whitelists the
* modules on older WordPress). Gutenberg presence is detected via the runtime
* `GUTENBERG_VERSION` constant plus the plugin (option) layer.
*
* @return bool
*/
function wp_admin_workspaces_dependencies_met() {
if ( ! function_exists( 'is_plugin_active' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$gutenberg_present =
defined( 'GUTENBERG_VERSION' ) ||
is_plugin_active( 'gutenberg/gutenberg.php' );
return wp_admin_workspaces_dependencies_met_from(
wp_admin_workspaces_core_supplies_private_apis(),
$gutenberg_present
);
}
/**
* Pure composition of the dependency gate — the OR contract over its two
* signals, factored out so every branch (including the Gutenberg fallback,
* which a live 7.0 container never reaches) is deterministically testable
* without defining `GUTENBERG_VERSION` or depending on the running WP version.
*
* @param bool $core_supplies Whether core supplies the private-API allowlist (WP 7.0+).
* @param bool $gutenberg_present Whether the Gutenberg plugin is active.
* @return bool Whether the dependency is satisfied.
*/
function wp_admin_workspaces_dependencies_met_from( $core_supplies, $gutenberg_present ) {
return (bool) ( $core_supplies || $gutenberg_present );
}
add_action( 'admin_notices', function () {
if ( ! wp_admin_workspaces_dependencies_met() ) {
echo '<div class="notice notice-error"><p>';
echo esc_html__( 'WP Admin Workspaces requires either WordPress 7.0+ or the Gutenberg plugin. The workspace uses @wordpress/ui components that depend on private APIs; WordPress 7.0 ships those in core, while earlier versions need the Gutenberg plugin to whitelist them. The workspace has stood down — classic wp-admin is being served until one of those is available.', 'wp-admin-workspaces' );
echo '</p></div>';
}
} );
// Single source of truth for the plugin version — keep in sync with the
// `Version:` header above and `package.json`. Used for asset cache-busting
// fallbacks and surfaced to support/debug tooling.
define( 'WP_ADMIN_WORKSPACES_VERSION', '0.1.0' );
define( 'WP_ADMIN_WORKSPACES_PATH', plugin_dir_path( __FILE__ ) );
define( 'WP_ADMIN_WORKSPACES_URL', plugin_dir_url( __FILE__ ) );
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-util.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-can-rest.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-prefs-rest.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-themes-rest.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-site-health-rest.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-merge.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-customizable.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-cache.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-config-validator.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/origins/class-wp-admin-workspaces-origin-core.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/origins/class-wp-admin-workspaces-origin-file.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-resolver.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-data-field-collections.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-data-view-config.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-dashboard-widgets.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-preload.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-menu-items.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-appearance-menu.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-admin-routes.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-classic-menu-bridge.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-chrome-harvest.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-modes.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/cascade/class-wp-admin-workspaces-permissions.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-data-view-rest.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-data-field-collections-rest.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-config-rest.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-abilities.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-cli.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/manifests/class-wp-admin-workspaces-manifest-validator.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/manifests/class-wp-admin-workspaces-manifest-registry.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/manifests/class-wp-admin-workspaces-manifest-resolver.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/manifests/class-wp-admin-workspaces-menu-renderers.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/tokens/class-wp-admin-workspaces-tokens.php';
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-registry.php';
// Engine-specific PHP — each engine that needs server hooks ships
// under `includes/engines/<engine-id>/`. Bootstrap files load
// unconditionally; their handlers gate themselves on the active engine
// or per-request signals (`core:desktop` only hooks the chromeless
// bridge when the request carries `wp_admin_workspaces_chromeless=1`).
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/engines/core-desktop/bootstrap.php';
/**
* V2.M1 — Public manifest registration API.
*
* Plugins call these to register an `app.json` or `engine.json`
* manifest, either as an associative array or by absolute path. The
* convention path (`apps/{name}/app.json`, `engines/{name}/engine.json`
* under the plugin root) is auto-scanned on `init` priority 8 — most
* plugins don't need to call these directly.
*
* @return string|WP_Error Manifest id on success, WP_Error on failure.
*/
function wp_admin_workspaces_register_app( $manifest_or_path ) {
return WP_Admin_Workspaces_Manifest_Registry::instance()->register_app( $manifest_or_path );
}
function wp_admin_workspaces_register_engine( $manifest_or_path ) {
return WP_Admin_Workspaces_Manifest_Registry::instance()->register_engine( $manifest_or_path );
}
/**
* Register a region template against an existing engine. Plugin
* extension point per spec §13 #4 — adds a `templates[$template_id]`
* entry to the engine's manifest at runtime so workspace.json regions can
* reference it via `template`. The engine must already be registered.
*
* @param string $engine_id Engine id to extend.
* @param string $template_id Template id (use `plugin:{slug}/{name}`).
* @param array $template Template body; must declare at least `role`.
*
* @return string|WP_Error template id on success, WP_Error on failure.
*/
function wp_admin_workspaces_register_template( $engine_id, $template_id, $template ) {
return WP_Admin_Workspaces_Manifest_Registry::instance()->register_template(
$engine_id,
$template_id,
$template
);
}
/**
* Register a plugin menu renderer (spec §13 #15).
*
* An engine names a renderer through its `engine.json` `menu-renderer`
* field; a `plugin:{slug}/{name}` id resolves to a React component a
* plugin supplies. This declares the id + the script handle that
* registers that component (`window.wpAdminWorkspaces.kernel.registerMenuRenderer`).
* The workspace enqueues the script on the admin-workspace page.
*
* The renderer component receives `{ items, currentPrimary, navConfig }`
* — the host-pruned menu tree, the active URL primary path, and the
* per-region nav config — and returns React.
*
* Timing: register the script handle (`wp_register_script`, with
* `wp-admin-workspaces` as a dependency) before the workspace page renders, then
* call this from `admin_enqueue_scripts` or earlier.
*
* @param string $renderer_id Renderer id (`plugin:{slug}/{name}`).
* @param array $args See `WP_Admin_Workspaces_Menu_Renderers::register`.
* @return string|WP_Error Renderer id on success, WP_Error on failure.
*/
function wp_admin_workspaces_register_menu_renderer( $renderer_id, $args ) {
return WP_Admin_Workspaces_Menu_Renderers::register( $renderer_id, $args );
}
/**
* Register a complete workspace programmatically (spec §13 #6). Use when
* a workspace's shape is computed at runtime (per role, per feature flag,
* etc.) rather than stored on disk under `workspaces/`.
*
* The registered workspace participates in the same cascade as file
* workspaces: site/role/user origins still merge on top.
*
* @param string $slug Unique slug.
* @param array $workspace_json Full workspace.json document.
*
* @return string|WP_Error slug on success, WP_Error on failure.
*/
function wp_admin_workspaces_register_workspace( $slug, $workspace_json ) {
return WP_Admin_Workspaces_Registry::register( $slug, $workspace_json );
}
/**
* Register a nav menu item (spec §13 #10).
*
* Plugins declare the item's `to`, `label`, `icon`, `badge`, `parent`,
* `parent_type`, and `position`, plus an optional `region` arg (defaults
* to the first `core:navigation` region in the resolved tree). No inline
* `current_user_can()` gate is needed — the `capability` arg flows
* through the workspace's 4-layer cap model.
*
* Timing: call from `init` priority 9 or earlier (`plugins_loaded` is
* fine). The cascade resolver's first run on the page render or first
* REST hit triggers `wp_admin_workspaces_data_plugin` and memoizes the
* resolved tree through `WP_Admin_Workspaces_Cache`. Registrations made
* after the resolver's first run miss the current request entirely.
*
* Cross-request invalidation: the registry serializes its current
* state into the cache key via the `wp_admin_workspaces_cache_signals`
* filter, so a registration delta between page loads (e.g. plugin
* toggles a feature flag that changes which items it registers)
* automatically picks a different cache bucket on the next hit. No
* explicit `flush()` needed for deterministic registrations.
*
* @param string $id Menu-item id (must be unique within the registry).
* @param array $args Args. See `WP_Admin_Workspaces_Menu_Items::register`.
* @return string|WP_Error Id on success, WP_Error on failure.
*/
function wp_admin_workspaces_register_menu_item( $id, $args ) {
return WP_Admin_Workspaces_Menu_Items::register( $id, $args );
}
/**
* Register an admin route (spec §13 #11).
*
* Signature: `($path, [ 'app' => …, 'config' => […], 'static_data' => […] ])`.
* `app` names the app to mount; `static_data` is folded into `config`
* (explicit `config` keys win on collision).
*
* Timing: same as `wp_admin_workspaces_register_menu_item()` — call from
* `init` priority 9 or earlier so the cascade resolver picks the route
* up on its first memoized run. Cross-request cache invalidation also
* works the same way: the registry's serialized state contributes to
* the resolver cache key via the `wp_admin_workspaces_cache_signals` filter.
*
* @param string $path Route path (`/posts`, `/posts/{id}`, `/media/*`).
* @param array $args Args. See `WP_Admin_Workspaces_Admin_Routes::register`.
* @return string|WP_Error Path on success, WP_Error on failure.
*/
function wp_admin_workspaces_register_route( $path, $args ) {
return WP_Admin_Workspaces_Admin_Routes::register( $path, $args );
}
/**
* Manifest registration on init.
*
* Two phases at priority 8 (before main workspace init at 10) so manifests
* are available when the kernel's inline-script handoff is composed:
*
* 1. Workspace-bundled core manifests — registered explicitly. App
* manifests live under `src/apps/<name>/app.json`, engine
* manifests under `src/runtime/engines/<name>/engine.json` —
* co-located with their JS source rather than at the convention
* plugin-root path. They're framework defaults, not pluggable.
*
* 2. Plugin-contributed manifests — auto-discovered at the convention
* path `<plugin>/apps/<name>/app.json` and
* `<plugin>/engines/<name>/engine.json`. Plugins can also extend
* discovery by adding paths via the
* `wp_admin_workspaces_manifest_discovery_paths` filter (useful for
* plugins that ship manifests at a non-standard location).
*/
add_action( 'init', function () {
$registry = WP_Admin_Workspaces_Manifest_Registry::instance();
// 1. Workspace-bundled core manifests. Co-located with their JS source
// rather than at the plugin-root convention path. `discover()`
// scans `<base>/apps/<name>/app.json` + `<base>/engines/<name>/engine.json`;
// `src/` covers all bundled apps, `src/runtime/` covers the engines
// (still co-located with their layout JS).
$registry->discover( WP_ADMIN_WORKSPACES_PATH . 'src/' );
$registry->discover( WP_ADMIN_WORKSPACES_PATH . 'src/runtime/' );
// 2. Convention-path discovery for the workspace plugin itself + plugins
// extending the discovery surface.
$registry->discover( WP_ADMIN_WORKSPACES_PATH );
$additional = apply_filters( 'wp_admin_workspaces_manifest_discovery_paths', array() );
foreach ( (array) $additional as $path ) {
if ( is_string( $path ) ) {
$registry->discover( $path );
}
}
}, 8 );
// Workspace-as-primary-entry hijack. When a workspace is active (see
// wp_admin_workspaces_is_active()), the workspace takes over the admin
// root (`/wp-admin/`, `index.php`, bare `admin.php`) at admin_init
// priority 0 — there is no longer a `?page=wp-admin-workspaces` menu entry.
// Classic stays reachable via the allowlist + the classic-mode cookie.
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-hijack.php';
WP_Admin_Workspaces_Hijack::init();
// Classic-mode escape hatch — cap-gated `?classic=1` cookie toggle that
// lets an admin drop into classic wp-admin (and back). Runs at admin_init
// priority -10, before the hijack.
require_once WP_ADMIN_WORKSPACES_PATH . 'includes/class-wp-admin-workspaces-classic-mode.php';
WP_Admin_Workspaces_Classic_Mode::init();
/**
* Register a classic-wp-admin Settings page (Settings → WP Admin Workspaces)
* that mirrors the workspace's `core:settings-workspace` screen. Without
* this, a user who toggles the workspace off would have no UI to turn it
* back on — they'd be stuck in classic with no entry point.
*
* Hooks `admin_menu`, which fires on non-root admin requests (the hijack
* exits before this on root entries when the workspace is active, so it's
* effectively classic-only).
*/
add_action( 'admin_menu', function () {
add_options_page(
__( 'WP Admin Workspaces', 'wp-admin-workspaces' ),
__( 'WP Admin Workspaces', 'wp-admin-workspaces' ),
'manage_options',
'wp-admin-workspaces-workspace',
'wp_admin_workspaces_render_workspace_settings_page'
);
} );
/**
* Classic-side render callback for the workspace toggle. The form posts
* to options.php with the `wp_admin_workspaces_settings` group, which is the
* same group `register_setting` uses below — the option goes through the
* registered `rest_sanitize_boolean` callback either way.
*
* The hidden 0-value field paired with the checkbox is the standard WP
* pattern for capturing an unchecked checkbox (browsers omit unchecked
* checkboxes from form submission); options.php picks the last value
* sent, so checked → 1, unchecked → 0.
*/
function wp_admin_workspaces_render_workspace_settings_page() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$enabled = (bool) get_option( 'wp_admin_workspaces_enabled', true );
?>
<div class="wrap">
<h1><?php esc_html_e( 'WP Admin Workspaces', 'wp-admin-workspaces' ); ?></h1>
<form method="post" action="options.php">
<?php settings_fields( 'wp_admin_workspaces_settings' ); ?>
<table class="form-table" role="presentation">
<tr>
<th scope="row"><?php esc_html_e( 'Workspace', 'wp-admin-workspaces' ); ?></th>
<td>
<label>
<input type="hidden" name="wp_admin_workspaces_enabled" value="0" />
<input type="checkbox" name="wp_admin_workspaces_enabled" value="1" <?php checked( $enabled ); ?> />
<?php esc_html_e( 'Activate WP Admin Workspace', 'wp-admin-workspaces' ); ?>
</label>
<p class="description"><?php esc_html_e( 'When enabled, the workspace replaces classic wp-admin at /wp-admin/. Requires a valid wp-content/workspace.json. Disable to fall back to classic.', 'wp-admin-workspaces' ); ?></p>
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
}
/**
* Enqueue workspace assets for a workspace takeover request.
*
* Runs on `admin_enqueue_scripts` during the hijack's admin-header
* render (and is harmless elsewhere because it self-gates). The
* `$hook` arg is ignored — `wp_admin_workspaces_is_active_request()` is the
* sole gate now that the workspace mounts at the admin root rather than a
* registered page.
*
* @param string $hook Admin page hook suffix (unused).
*/
function wp_admin_workspaces_enqueue_assets( $hook = '' ) {
if ( ! wp_admin_workspaces_is_active_request() ) {
return;
}
$asset_path = WP_ADMIN_WORKSPACES_PATH . 'build/index.asset.php';
if ( ! file_exists( $asset_path ) ) {
return;
}
$asset = include $asset_path;
// Filter out script dependencies that aren't registered in this
// WordPress version (e.g., wp-dataviews requires Gutenberg plugin
// or may not be registered on all admin pages).
$deps = array_filter( $asset['dependencies'], function ( $dep ) {
return wp_scripts()->query( $dep, 'registered' ) || wp_scripts()->query( $dep, 'enqueued' );
} );
wp_enqueue_script(
'wp-admin-workspaces',
WP_ADMIN_WORKSPACES_URL . 'build/index.js',
array_values( $deps ),
$asset['version'],
true
);
// JS i18n: load translations for every `__()`/`_n()`/`sprintf` string in
// the bundle (and lazily-loaded app chunks, which share the handle's
// domain). `.json` translation files live in `languages/`; regenerate the
// `.pot` with `wp i18n make-pot . languages/wp-admin-workspaces.pot`.
wp_set_script_translations(
'wp-admin-workspaces',
'wp-admin-workspaces',
WP_ADMIN_WORKSPACES_PATH . 'languages'
);
// Media modal. The shared media-library-picker `Edit` control
// (`src/apps/_shared/forms/controls/MediaPicker.js`, via
// `@wordpress/media-utils` `MediaUpload`) opens the WordPress media frame,
// which needs the `media-editor` scripts + the footer template markup that
// `wp_enqueue_media()` registers. Consumers today: settings-general's Site
// Icon picker.
//
// PERF NOTE: this is NOT a no-op when no picker is on screen — it enqueues
// the media-frame scripts (media-editor/media-views/media-models/plupload)
// and prints the backbone media-modal templates on the footer of EVERY
// workspace render, a per-page cost paid even on Dashboard/Posts where no
// picker exists. Acceptable for alpha; if cold-mount perf
// (`docs/perf-baseline.md`) becomes a concern, gate this on whether the
// active screen can host a picker rather than enqueuing unconditionally.
wp_enqueue_media();
// Plugin menu renderers (spec §13 #15). Each registered renderer's
// script enqueues here, after the main bundle, so a handle declaring
// `wp-admin-workspaces` as a dependency loads once the kernel has published
// `window.wpAdminWorkspaces.kernel.registerMenuRenderer`.
WP_Admin_Workspaces_Menu_Renderers::enqueue_assets();
$config = wp_admin_workspaces_get_active_config();
// REST preload (spec §13 #9). Cascade-resolved `preload[]` paths
// hydrate through `rest_preload_api_request` and ship as inline
// script on `wp-api-fetch` before the workspace bundle runs. Eliminates
// cold-mount round-trips for `useEntityRecord('root','user',me)`,
// `loadPostTypeEntities`, and similar resolvers.
WP_Admin_Workspaces_Preload::inject();
// Engine-driven style enqueue. Each registered engine declares a
// `styles` array in its manifest listing the CSS bundles it depends
// on (WPDS baseline tokens, DataViews stylesheet, MUI bundle, etc.).
// Only the active engine's styles enqueue — keeps non-WPDS engines
// from loading WPDS tokens (and vice versa for other DS plugins).
$active_engine_id = is_array( $config )
? ( $config['engine'] ?? null )
: null;
$active_engine_manifest = $active_engine_id ? WP_Admin_Workspaces_Manifest_Registry::instance()->get_engine( $active_engine_id ) : null;
if ( is_array( $active_engine_manifest ) && isset( $active_engine_manifest['styles'] ) && is_array( $active_engine_manifest['styles'] ) ) {
foreach ( $active_engine_manifest['styles'] as $style ) {
if ( ! isset( $style['handle'], $style['src'] ) ) {
continue;
}
$src = $style['src'];
$deps = isset( $style['deps'] ) && is_array( $style['deps'] ) ? $style['deps'] : array();
// Plugin-relative path → resolve against plugin URL. Absolute
// URLs pass through unchanged.
$resolved_src = ( strpos( $src, '//' ) === 0 || preg_match( '#^https?://#', $src ) ) ? $src : WP_ADMIN_WORKSPACES_URL . ltrim( $src, '/' );
wp_enqueue_style( $style['handle'], $resolved_src, $deps, $asset['version'] );
}
}
// Block editor styles — needed by SimpleEditorApp (BlockEditorProvider + BlockList).
wp_enqueue_style( 'wp-block-editor' );
wp_enqueue_style( 'wp-block-library' );
wp_enqueue_style( 'wp-format-library' );
wp_enqueue_style(
'wp-admin-workspaces',
WP_ADMIN_WORKSPACES_URL . 'build/index.css',
array( 'wp-components' ),
$asset['version']
);
$current_user = wp_get_current_user();
$manifest_registry = WP_Admin_Workspaces_Manifest_Registry::instance();
// Server-side visibility prune: ship only the screens + menu this user can
// reach. The full $config stays available above for engine/preload/style
// selection (user-invariant); everything user-facing below reads the
// pruned copy so the page source never carries an unreachable screen's
// permissions/legacy maps or a role-gated nav item the client can't gate.
$client_config = wp_admin_workspaces_prune_config_for_user( $config, get_current_user_id() );
wp_add_inline_script( 'wp-admin-workspaces', 'window.wpAdminWorkspaces = ' . wp_json_encode( array(
'config' => $client_config,
'siteUrl' => get_site_url(),
'homeUrl' => home_url(),
'adminUrl' => admin_url(),
'dashboardUrl' => admin_url(),
'pluginUrl' => WP_ADMIN_WORKSPACES_URL,
// Classic→workspace legacy-route map for the admin-link interceptor
// (W4). Keyed by workspace route path → { legacy_path, legacy_query,
// legacy_params }. Empty until screens / programmatic routes declare
// `legacy_path`.
'adminRoutes' => WP_Admin_Workspaces_Admin_Routes::legacy_map( $client_config ),
'restUrl' => get_rest_url(),
'nonce' => wp_create_nonce( 'wp_rest' ),
'userId' => get_current_user_id(),
'siteName' => get_bloginfo( 'name' ),
// Running PHP + WordPress versions, so list apps can flag resources
// whose declared `requires_php` / `requires_wp` exceed the environment
// (e.g. the Plugins list's PHP/WP-incompatibility warning). Mirrors
// core's `is_php_version_compatible()` / `is_wp_version_compatible()`.
'phpVersion' => PHP_VERSION,
'wpVersion' => get_bloginfo( 'version' ),
'workspaces' => wp_admin_workspaces_get_available_workspaces(),
// True when a wp-content/workspace.json override is active — it wins over
// the active-workspace option, so the workspace switcher hides + switchWorkspace()
// refuses (writing the option would be a silent no-op).
'fileActive' => class_exists( 'WP_Admin_Workspaces_Origin_File' ) && WP_Admin_Workspaces_Origin_File::exists_and_valid(),
// Opt-in surface for non-fatal JS diagnostics (e.g. chrome-hide
// injection failures) in minified builds — site admins with
// `WP_DEBUG` on get the console warnings production builds
// otherwise suppress.
'debug' => defined( 'WP_DEBUG' ) && WP_DEBUG,
'user' => array(
'displayName' => $current_user->display_name,
'avatarUrl' => get_avatar_url( $current_user->ID, array( 'size' => 32 ) ),
'profileUrl' => '#/profile',
'logoutUrl' => wp_logout_url( admin_url( '/' ) ),
),
'capabilities' => wp_admin_workspaces_resolve_capabilities( $client_config ),
// V2.M1 — manifest payload. Empty until plugins ship app.json /
// engine.json files; the kernel reads from this map alongside
// the imperative registry during the v1→v2 transition.
'manifests' => array(
'apps' => $manifest_registry->list_apps(),
'engines' => $manifest_registry->list_engines(),
),
// V2.M5 — DTCG primitives layer. Site → theme → plugin → core
// origins merged here. Empty object when no origin contributes.
// `compileStyles` consumes this when resolving non-`styles.*`
// curly-brace aliases in workspace.json `styles`. Token serialization
// is skipped entirely when the resolved styles tree references
// zero token aliases — the DTCG layer is dead weight for workspaces
// that only set seeds + slot overrides. The empty-path cast to
// stdClass keeps the JS shape stable: `wp_json_encode( array() )`
// emits `[]`, but the kernel + downstream typedef `tokens` as an
// object — `(object) array()` serializes as `{}`.
'tokens' => wp_admin_workspaces_styles_reference_tokens( $config )
? WP_Admin_Workspaces_Tokens::resolve()
: (object) array(),
// v3 — flattened engine-modes catalog. The active engine's
// `modes` block is walked for `extends` chains (depth-limited),
// then the `wp_admin_workspaces_engine_modes_{engineId}` filter runs
// so plugins can contribute additional modes. Empty object when
// no engine is resolved (degenerate; the workspace would fail to
// mount upstream of this anyway).
'engineModes' => $active_engine_manifest
? WP_Admin_Workspaces_Modes::resolve_engine_modes( $active_engine_manifest )
: WP_Admin_Workspaces_Modes::synthesize_default_catalog(),
// #128 — admin-bar runtime harvest. Plugin admin-bar nodes the
// workspace doesn't own first-class (site-hub / user-menu / +New are
// skipped), folded submenus → dropdowns. `core:toolbar-actions`
// reads this global. Empty array when no plugin registers a node.
'adminBar' => WP_Admin_Workspaces_Chrome_Harvest::harvest_admin_bar(),
// #128 — buffered global `admin_notices` HTML (admin trust, same as
// classic). `core:notices-banner` renders it alongside its
// `@wordpress/notices` source. Empty string when none fire.
// Documented limitation: only GLOBAL notices that fire on the
// workspace's own page load are captured (per-screen notices keyed on
// `$pagenow` don't fire) — see the harvest class docblock.
'adminNotices' => WP_Admin_Workspaces_Chrome_Harvest::capture_admin_notices(),
// #125 — the `flip` modifier on the `/wp/v2/media/{id}/edit` route's
// `modifiers[]` enum is WP 6.9+. On 6.7/6.8 (supported targets via the
// Gutenberg private-API fallback) a `flip` edit returns
// `rest_invalid_param` and — because validation is per-item — fails the
// whole rotate+flip+crop edit. The media app's `ImageEditor` hides the
// flip tools when this is false so flip is never emitted below 6.9.
// Crop / rotate work everywhere.
'supportsImageFlip' => version_compare( get_bloginfo( 'version' ), '6.9', '>=' ),
) ) . ';', 'before' );
wp_add_inline_style( 'wp-admin-workspaces', '
#adminmenuwrap, #adminmenuback, #wpadminbar, #wpfooter { display: none !important; }
#wpcontent { margin-left: 0 !important; }
#wpbody-content { padding-bottom: 0; }
html.wp-toolbar { padding-top: 0 !important; }
#wp-admin-workspaces { position: fixed; inset: 0; z-index: 99999; }
' );
wp_admin_workspaces_guard_jquery_hash_selectors();
}
/**
* Neutralize the jQuery/Sizzle "unrecognized expression: #/<route>" throw on
* the workspace shell page (issue #248).
*
* The hijack renders through `admin-header.php` / `admin-footer.php`, so the
* full classic-admin jQuery ecosystem co-loads on the same page as the React
* shell. The shell publishes navigation as slash-containing hash routes
* (`<a href="#/site-editor">`, `window.location.hash = '#/posts'`). A leading
* `#/` is NOT a valid jQuery/Sizzle selector: jQuery's `rquickExpr`
* (`#([\w-]+)$`) rejects it, so `$()` falls through to `Sizzle.tokenize`, which
* throws. Any co-loaded handler that feeds the URL hash — or a clicked
* anchor's `href` — into `jQuery()` (a screen-meta/help handler hit via an
* unexpected DOM path, a third-party plugin's anchor/hashchange handler, …)
* therefore throws on every shell navigation, aborting the rest of that
* handler.
*
* Rather than enumerate (and dequeue) every co-loaded thrower — fragile,
* version-dependent, and impossible to fully pin without the live stack — we
* guard at the throw site: wrap `jQuery.fn.init` so a `#/`-prefixed string
* selector resolves to an empty set instead of reaching the tokenizer. On the
* shell page `#/…` is always a workspace route and never a real element id
* (ids can't carry an unescaped `/`), so an empty match is the semantically
* correct, no-op result — identical to what a valid-but-nonmatching selector
* would return. The guard is intentionally narrow to the route prefix `#/`,
* so genuinely-malformed selectors elsewhere still surface.
*
* jQuery (always present in wp-admin) loads before this; the shim installs at
* script-load time, ahead of the DOM-ready / hashchange / click handlers that
* actually call `$( hash )`.
*/
function wp_admin_workspaces_guard_jquery_hash_selectors() {
wp_enqueue_script( 'jquery-core' );
$guard = <<<'JS'
( function ( $ ) {
if ( ! $ || ! $.fn || ! $.fn.init || $.fn.init.__wpAdminWorkspacesHashGuard ) {
return;
}
var origInit = $.fn.init;
function GuardedInit( selector, context, root ) {
if (
typeof selector === 'string' &&
selector.charCodeAt( 0 ) === 35 /* # */ &&
selector.charCodeAt( 1 ) === 47 /* / */
) {
// A workspace hash route ("#/…"), never an element id on this
// page — resolve to an empty set instead of throwing in Sizzle.
return new origInit( [], context, root );
}
return new origInit( selector, context, root );
}
GuardedInit.prototype = origInit.prototype;
GuardedInit.__wpAdminWorkspacesHashGuard = true;
$.fn.init = GuardedInit;
} )( window.jQuery );
JS;
wp_add_inline_script( 'jquery-core', $guard, 'after' );
}
add_action( 'admin_enqueue_scripts', 'wp_admin_workspaces_enqueue_assets' );
/**
* Read the active workspace.json configuration through the cascade resolver.
*
* Six origins (core / engine / plugin / site / role / user) are loaded, filtered,
* and merged into a single resolved doc. The legacy single-file loader is
* gone — every workspace file goes through the same pipeline so behavior is
* uniform whether the workspace ships with the plugin, lives in DB options,
* or is contributed by a programmatic registration.
*/
function wp_admin_workspaces_get_active_config() {
return WP_Admin_Workspaces_Resolver::resolve();
}
/**
* Whether the workspace should take over the admin.
*
* Single source of truth for the workspace-as-primary-entry hijack and
* the classic-mode escape hatch. True when EITHER:
* - a valid `wp-content/workspace.json` override file is present, OR
* - the legacy `wp_admin_workspaces_active_workspace` option was explicitly
* written (back-compat for installs that selected a workspace before the
* file-based trigger landed).
*
* A fresh install with neither returns false, so the workspace never
* mounts and classic wp-admin is served untouched.
*
* @return bool
*/
function wp_admin_workspaces_is_active() {
// Explicit OFF wins over file/legacy triggers. Settings → Workspace
// (workspace) and Settings → WP Admin Workspaces (classic) surface this as a
// checkbox; the option defaults to enabled, so a fresh install with a
// file present still flips active true.
if ( ! get_option( 'wp_admin_workspaces_enabled', true ) ) {
return false;
}
if ( class_exists( 'WP_Admin_Workspaces_Origin_File' ) && WP_Admin_Workspaces_Origin_File::exists_and_valid() ) {
return true;
}
$active_workspace = get_option( 'wp_admin_workspaces_active_workspace', null );
return is_string( $active_workspace ) && $active_workspace !== '';
}
/**
* Whether the current request is a workspace takeover (the W2 hijack
* fired / will fire). Thin wrapper over WP_Admin_Workspaces_Hijack so the
* asset-enqueue gate and other callers don't reach into the class.
*
* @return bool
*/
function wp_admin_workspaces_is_active_request() {
return class_exists( 'WP_Admin_Workspaces_Hijack' ) && WP_Admin_Workspaces_Hijack::is_active_request();
}
/**
* Sanitize + validate the wp_admin_workspaces_active_workspace option write.
*
* Returns the sanitized slug if a matching workspace file exists; returns
* the previous option value (or empty string for the first write)
* when the slug is unknown. Empty string passes through so the
* resolver's fallback chain still resolves (legacy active_config →
* default).
*/
function wp_admin_workspaces_sanitize_active_workspace( $value ) {
$sanitized = sanitize_file_name( (string) $value );
if ( $sanitized === '' ) {
return '';
}
$path = WP_ADMIN_WORKSPACES_PATH . 'workspaces/' . $sanitized . '.json';
if ( file_exists( $path ) ) {
return $sanitized;
}
if ( class_exists( 'WP_Admin_Workspaces_Registry' ) && WP_Admin_Workspaces_Registry::has( $sanitized ) ) {
return $sanitized;
}
add_settings_error(
'wp_admin_workspaces_active_workspace',
'wp_admin_workspaces_unknown_workspace_slug',
sprintf(
/* translators: %s: workspace slug */
__( 'Unknown workspace: "%s". The previous active workspace was kept.', 'wp-admin-workspaces' ),
esc_html( $sanitized )
),
'error'
);
$previous = get_option( 'wp_admin_workspaces_active_workspace', '' );
return $previous;
}
/**
* Pre-compute capability decisions for every cap declared in the resolved
* config. Walks regions[*].capability + applications[*].capability, plus
* built-in source capability floors. The runtime sees an absolute
* `{cap: bool}` map for everything that matters during initial render;
* the /wp-admin-workspaces/v1/can/{cap} endpoint covers anything plugin code
* looks up dynamically.
*
* Cost: each unique declared cap costs one `current_user_can()` call.
* A 50-app workspace with 30 unique caps = 30 cap checks per page load on
* a cold resolver-cache miss. The M2.7 resolver cache memoizes the
* entire resolved config + cap precomputation across requests, so this
* cost only fires when origin signals (option / user-meta / file-mtime)
* change. Hot path = zero cap checks.
*/
/**
* Prune screens + menu the given user can't reach BEFORE the resolved config
* is serialized to the page. Without this the full admin IA — every screen,
* each screen's `permissions` block, `legacy_path` maps, the whole menu tree —
* ships in page source to every logged-in user down to subscriber, with
* capability gating applied client-side only (and roles not evaluable on the
* client at all). Entity *data* is still REST-gated; this closes the
* structural/metadata leak and makes the server the authority for visibility,
* mirroring how wp-admin server-prunes its own menu by capability.
*
* Operates on a COPY — callers keep the full resolved doc for server-side use
* (REST screen-permission floors must still see every screen). Scope is
* screens + menu: the `regions`/`routes` escape hatches and `commands` are
* left intact (rarely role-gated; a command pointing at a pruned screen just
* resolves to no route). The `workspace.default-screen` is always kept so the
* kernel always has a landing route — its mounted app cap-gates itself.
*
* @param array $config Full resolved workspace.json doc.
* @param int $user_id Current user id.
* @return array Pruned copy.
*/
function wp_admin_workspaces_prune_config_for_user( $config, $user_id ) {
if ( ! is_array( $config ) || ! class_exists( 'WP_Admin_Workspaces_Permissions' ) ) {
return $config;
}
$user_id = (int) $user_id;
/**
* Escape hatch — return false to ship the full unpruned config (e.g. to
* debug a workspace whose screens vanish unexpectedly). Default true.
*
* @param bool $prune Whether to prune.
* @param array $config The resolved doc.
* @param int $user_id Current user id.
*/
if ( ! apply_filters( 'wp_admin_workspaces_prune_unreachable', true, $config, $user_id ) ) {
return $config;
}
$default_screen = isset( $config['workspace']['default-screen'] ) && is_string( $config['workspace']['default-screen'] )
? (string) $config['workspace']['default-screen']
: '';
// 1. Prune screens whose resolved permissions the user fails.
$removed = array();
if ( isset( $config['screens'] ) && is_array( $config['screens'] ) ) {
foreach ( $config['screens'] as $screen_id => $screen ) {
if ( ! is_array( $screen ) ) {
continue;
}
if ( (string) $screen_id === $default_screen ) {
continue;
}
$resolved = WP_Admin_Workspaces_Permissions::resolve(
$screen['permissions'] ?? null,
WP_Admin_Workspaces_Permissions::app_floor_for( $screen )
);
if ( ! WP_Admin_Workspaces_Permissions::user_passes( $user_id, $resolved ) ) {
unset( $config['screens'][ $screen_id ] );
$removed[ (string) $screen_id ] = true;
}
}
}
// 2. Prune menu nodes bound to a removed screen, or carrying their own
// failing permissions (the role-gated nav-item leak the client can't
// evaluate). Reachable children of a pruned node are hoisted, not lost.
if ( isset( $config['menu'] ) && is_array( $config['menu'] ) ) {
$config['menu'] = wp_admin_workspaces_prune_menu_for_user( $config['menu'], $removed, $user_id, 0 );
}
return $config;
}
/**
* Recursive helper for {@see wp_admin_workspaces_prune_config_for_user()}. Drops
* menu nodes bound to a removed screen id and nodes whose own `permissions`
* fail for the user.
*
* When a node is dropped it recurses into `items` first and HOISTS the
* surviving (reachable) children up to the dropped node's level rather than
* discarding the whole subtree — otherwise a reachable child nested only under
* an unreachable parent (e.g. `profile`, `read`-floor, living solely at
* `menu.users.items.profile` under the admin-only `users` node) would vanish
* from a non-admin's menu even though the screen itself survives. Mirrors
* `WP_Admin_Workspaces_Menu_Items::drop_deeper_duplicates()`.
*
* @param array $tree Menu (sub-)tree.
* @param array $removed_screens Map of removed screen id → true.
* @param int $user_id Current user id.
* @param int $depth Recursion guard.
* @return array
*/
function wp_admin_workspaces_prune_menu_for_user( $tree, $removed_screens, $user_id, $depth ) {
if ( ! is_array( $tree ) || $depth > 20 ) {
return $tree;
}
$out = array();
foreach ( $tree as $id => $item ) {
// Recurse first so reachable children can be hoisted if this node
// itself turns out to be unreachable.
$children = null;
if ( is_array( $item ) && isset( $item['items'] ) && is_array( $item['items'] ) ) {
$children = wp_admin_workspaces_prune_menu_for_user( $item['items'], $removed_screens, $user_id, $depth + 1 );
}
// Is this node itself unreachable — bound to a pruned screen, or its
// own (possibly screen-inherited) permissions fail?
$drop = isset( $removed_screens[ (string) $id ] );
if ( ! $drop && is_array( $item ) && isset( $item['permissions'] ) && is_array( $item['permissions'] ) ) {
$resolved = WP_Admin_Workspaces_Permissions::resolve( $item['permissions'], array() );
if ( ! WP_Admin_Workspaces_Permissions::user_passes( $user_id, $resolved ) ) {
$drop = true;
}
}
if ( $drop ) {
// Hoist the surviving children so a reachable item nested only
// under this unreachable node isn't lost with it.
if ( is_array( $children ) ) {
foreach ( $children as $child_id => $child_item ) {
if ( ! isset( $out[ $child_id ] ) ) {
$out[ $child_id ] = $child_item;
}
}
}
continue;
}
if ( is_array( $children ) ) {
$item['items'] = $children;
}
$out[ $id ] = $item;
}
return $out;
}
function wp_admin_workspaces_resolve_capabilities( $config ) {
$declared = array();
// Escape-hatch `regions` block (recursive). A region may declare a
// `capability`, and a nav-style app embedded in a region may declare
// per-item caps in `region.config.items`. Walk both so they reach the
// runtime cap-map.
$collect_from_regions = function ( $regions ) use ( &$declared, &$collect_from_regions ) {
if ( ! is_array( $regions ) ) {
return;
}
foreach ( $regions as $region ) {
if ( ! is_array( $region ) ) {
continue;
}
if ( isset( $region['capability'] ) && is_string( $region['capability'] ) ) {
$declared[ $region['capability'] ] = true;
}
$items = $region['config']['items'] ?? null;
if ( is_array( $items ) ) {
wp_admin_workspaces_collect_nav_item_caps( $items, $declared );
}
if ( ! empty( $region['regions'] ) && is_array( $region['regions'] ) ) {
$collect_from_regions( $region['regions'] );
}
}
};
if ( isset( $config['regions'] ) && is_array( $config['regions'] ) ) {
$collect_from_regions( $config['regions'] );
}
// Per-screen permissions block. screens[id].permissions has
// `capabilities[]` + `roles[]`; we collect the cap slugs so the
// runtime cap-map covers v3 screens the same way v2 region.capability
// strings were collected. Roles are evaluated separately (membership
// check, not a capability check).
if ( isset( $config['screens'] ) && is_array( $config['screens'] ) ) {
foreach ( $config['screens'] as $screen ) {
if ( ! is_array( $screen ) ) {
continue;
}
$caps = $screen['permissions']['capabilities'] ?? array();
if ( is_array( $caps ) ) {
foreach ( $caps as $cap ) {
if ( is_string( $cap ) && $cap !== '' ) {
$declared[ $cap ] = true;
}
}
}
}
}
// Menu items can carry their own `permissions.capabilities[]` when
// they don't inherit from a bound screen (e.g. standalone link
// items registered via `wp_admin_workspaces_register_menu_item()`). Walk
// the menu tree so those caps reach the runtime cap-map too — without
// this, `userCan()` would default-false on inline-permissioned menu
// items that have no screen binding.
if ( isset( $config['menu'] ) && is_array( $config['menu'] ) ) {
wp_admin_workspaces_collect_menu_item_caps( $config['menu'], $declared );
}
// Built-in source capability floors (mirrors registry/builtins.js
// `capabilities` arrays). Kept tight to the surface authors actually
// declare — adding every WP cap here would inflate the inline script.
foreach ( array( 'list_users', 'moderate_comments', 'manage_options', 'edit_theme_options' ) as $cap ) {
$declared[ $cap ] = true;
}
$out = array();
foreach ( array_keys( $declared ) as $cap ) {
$out[ $cap ] = current_user_can( $cap );
}
return $out;