Skip to content

Feat/unify command palettes - #11

Merged
AllTerrainDeveloper merged 5 commits into
trunkfrom
feat/unify-command-palettes
Apr 24, 2026
Merged

AllTerrainDeveloper merged 5 commits into
trunkfrom
feat/unify-command-palettes

Conversation

@AllTerrainDeveloper

@AllTerrainDeveloper AllTerrainDeveloper commented Apr 23, 2026 •

Copy link
Copy Markdown
Collaborator

feat/iframe-command-bridge — Harvest @wordpress/commands into the shell palette

Summary

Demo.CM.mov

Replaces the "press Cmd+K twice to escape the native palette" workaround with a proper bridge: the shell palette hijacks Cmd+K inside chromeless iframes, harvests the focused window's wp.data.select('core/commands') registry, and re-publishes every command (context-scoped statics and dynamic loader hooks like "Duplicate block") as first-class entries in our own palette. Selecting one runs inside the source iframe via postMessage, or opens a new desktop window when the command is a pure navigation.

One palette. One keystroke. Contextual to the focused window. The native WP palette is never seen.

Motivation

Before this PR we had two disconnected palettes:

  1. WP's native @wordpress/commands UI — only visible while focus was inside a Gutenberg / site-editor iframe.
  2. Our AI Assistant palette — the shell-level surface the desktop UX is built around.

Cmd+K fired whichever one owned focus first, and the user had to double-tap to escalate from one to the other. Worse, every command the WP editor exposed ("toggle distraction-free", "duplicate block", pattern insertions) was stranded inside its iframe and invisible to the desktop shell.

The fix is architecturally invasive enough that we couldn't ship it as a small follow-up — it touches the chromeless bridge, the palette UI, the command registry, and adds a new cross-frame protocol. Grouping it into one PR keeps the story readable.

What changed

New cross-frame protocol

Direction Message Purpose
parent → iframe wp-desktop-commands-subscribe Start streaming this iframe's command list
parent → iframe wp-desktop-commands-unsubscribe Stop streaming
parent → iframe wp-desktop-commands-invoke Run a previously-harvested command
iframe → parent wp-desktop-commands-list Ship the current command snapshot
iframe → parent wp-desktop-bridge-ready Handshake — fixes the subscribe-before-listener race

All messages are window.location.origin-gated on both ends.

Iframe side (includes/render.php)

  • Cmd+K is captured unconditionally and forwarded to the parent. The prior "let the native palette flash, dismiss with synthetic Escape" block is gone. Defensive CSS hides any .commands-command-menu that might render via a non-keyboard path.
  • A React component is mounted into a hidden div using wp.element.createRoot. It's the only way to legally call useSelect + each loader's hook — Gutenberg loaders are React hooks and can't run outside a render. We went through a classic setState-inside-useEffect loop en route to a ref-based bucket (see "Gotchas"). Results cover tier-2 (getCommands(true)) + tier-3 (getCommandLoaders(true)). Tier-1 (global nav) is deliberately skipped — the dock already has those.
  • Static classification for navigation commands: Function.prototype.toString() + regex for location.href = '…' / .assign('…') / .replace('…'). An earlier dry-run sandbox silently failed to intercept the href setter (Location.prototype.href is non-configurable) and every nav callback actually navigated the iframe → infinite window spawning. The static scan is now the only safe path.
  • React icons are flattened to SVG via wp.element.renderToString before crossing postMessage (structured clone refuses React elements). Parent injects the SVG via innerHTML in the palette row.
  • Callback cache (__wpdCommandCallbacks): loader-returned commands don't exist in getCommands(), so invoke needs its own lookup keyed on command name, rebuilt every merge so closures stay fresh.

Parent side (src/commands/iframe-bridge.ts)

  • New IframeCommandBridge class; installed from desktop.ts.
  • On focus change: unsubscribe + evict the prior iframe:<windowId> owner, subscribe the new one.
  • On minimize of the subscribed window: evict + clear the subscription so restore re-hydrates through onFocused.
  • On close: evict.
  • Navigation commands register a run that opens a new desktop window via manager.open({ id: deriveWindowId(url), ... }) instead of navigating the current iframe.
  • Action commands register a run that posts wp-desktop-commands-invoke back to the source iframe.

Command registry (src/commands.ts)

  • New owner?: string field (already existed) + new unregisterByOwner(owner) helper for bulk eviction.
  • New eager?: boolean field: true ⇒ surfaces before the user types /. Harvested iframe commands auto-set it. Built-in commands stay slash-only.
  • New listEagerCommands() export for the palette.
  • New iconSvg?: string field for inline SVG glyphs.

Palette UX (src/ai-assistant.ts, assets/css/ai-assistant.css)

  • Empty input → eager commands only, sorted so iframe-harvested entries float to the top.
  • Typed / → slash-only commands (disjoint from eager — the two surfaces don't overlap).
  • Selection paint is now incremental (class toggle, no re-render) so arrowing through the list doesn't clobber hover state or scroll position.
  • Keyboard-nav guard class on the list container suppresses :hover styling while arrow keys drive selection; a real mousemove clears it.
  • scrollIntoView on arrow-key selection for long lists.
  • Bigger icon tiles (36×36) with larger dashicons / SVG glyphs to match the native palette's scale.
  • Vertical centering when a command has no description (CSS :has()).
  • Label as primary line, slug hidden when no description is present — the harvested command names (core/block-editor/action-duplicate) are ugly and not user-facing.

Docs

  • docs/architecture.md — new "Command palette bridge (Cmd+K, hijacked)" section: names the approach as a hack, walks through both sides, calls out caveats.
  • docs/javascript-reference.md — rewritten wp-desktop-commands-list payload (no more dry-invoke; static regex + React-mounted loader harvest), added iconSvg / eager / owner to registerCommand docs with the disjoint eager/slash behavior spelled out.

Gotchas worth knowing (for future-us)

  1. Location.prototype.href is non-configurable. An Object.defineProperty shim silently fails — no throw, no sentinel. Any code that relies on intercepting navigation via this property should use a static approach (regex on the callback's source) or assume the navigation will happen.
  2. useState-based aggregation in the React harvester loops. Loader hooks return fresh array references on every render even when contents are unchanged. setState inside useEffect → re-render → new ref → setState → Maximum update depth. Refs + content-fingerprint deps solved it.
  3. Loader commands aren't in getCommands(). Invoke must consult the harvester's own cache first.
  4. The subscribe-before-listener race is real. The iframe's message listener isn't attached until the bridge script runs (after admin_footer). The parent can send subscribe arbitrarily earlier. Fix: iframe posts wp-desktop-bridge-ready once listeners exist; parent replays subscribe if the source is the currently focused window.
  5. Minimized windows must evict. A focused-but-minimized window otherwise leaves its commands in the palette with no clear mental model of where they'd run.

Testing

  • npm run build — green, bundle grew by ~4 kB gzipped.
  • npm test — 364 / 364 passing.
  • php -l includes/render.php — clean.

Manual QA:

  • Open Posts → Add New (Gutenberg) → Cmd+K → palette opens single-press, shows block commands. Pick "Duplicate" → block actually duplicates inside the editor.
  • Open Dashboard in a new window while Add Post stays open → Cmd+K in dashboard → no Gutenberg commands (expected — dashboard has no contextual registry).
  • Refocus Add Post → Cmd+K → block commands return.
  • Minimize Add Post → Cmd+K from somewhere else → its commands are gone from the list.
  • Restore Add Post → commands come back.
  • Select a block in the editor → Cmd+K → block-specific commands (transform to, move up/down) appear; switch selection, list updates.
  • Type / → eager commands vanish, the built-in /open is the only entry.

Breaking changes

None for end users. Plugin-facing: the eager flag defaults to false, so commands registered via wp.desktop.registerCommand() are now slash-only unless they opt in. No existing caller relies on the previous "always visible on empty input" behavior — the palette only recently shipped that surface.

Follow-ups (not in this PR)

  • Stale-closure detection for loader commands invoked long after the editor re-rendered (current behavior: best-effort, may no-op).
  • Extend the same bridge pattern to core/block-editor's useCommandLoader hooks that depend on selection state beyond what we currently surface.
  • Documented example in docs/examples/ showing eager: true vs. default.

…tration

- Added IframeCommandBridge to subscribe to commands from focused iframe windows.
- Commands are re-registered as slash-commands in the shell palette, allowing for dynamic updates.
- Introduced unregisterByOwner function to evict commands when focus shifts between windows.
- Enhanced AiAssistant to eagerly display commands without requiring user input.
- Implemented keyboard navigation improvements for command selection.
- Added sorting functionality for commands to prioritize iframe commands.
- Updated types to support harvested commands from iframes.
Comment thread includes/render.php

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to refactor this and ship it into smaller and meaningful pieces as one of the next steps.

Comment thread src/ai-assistant.ts

@AllTerrainDeveloper AllTerrainDeveloper Apr 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same thing, this ai-assistant.ts is a monster. It's actually the Command Palette, not sure if a renaming is worthy, as its also acting as a AI assistant.

@epeicher epeicher left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is great @AllTerrainDeveloper! I have tested it, and it works very well 🙌 LGTM!

@AllTerrainDeveloper

Copy link
Copy Markdown
Collaborator Author

I have cleaned up the logs and a some dead code :)

@AllTerrainDeveloper
AllTerrainDeveloper merged commit e308bd3 into trunk Apr 24, 2026
3 checks passed
@AllTerrainDeveloper
AllTerrainDeveloper deleted the feat/unify-command-palettes branch April 24, 2026 10:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants