Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ Everything in our registry has a `nanoforge.manifest.json` and a name `@scope/na
- Lint wants `SvelteSet`/`SvelteMap` for mutable collections. For a throwaway copy, disable `svelte/prefer-svelte-reactivity` on that line.
- **Docks (IntelliJ tool windows):** six slots (`bottom` is the bottom row's left part, `bottomRight` its right part). Their panels are icons in the left and right stripes (`ToolStripe.svelte`), and a docked stack shows only the active panel's header. Clicking the icon of a shown panel **hides its slot**: in e2e, use `showPanel`/`panelTab` (`e2e/helpers.ts`), never a bare click on a panel's tab. Floats keep a tab strip. A dock's icon shows before its plugin activates: built-in widget icons live in the kit (`icons.ts`).
- **Kit z-order:** dock 10 < float 100 < tour 1500 < dialog 2000 < menu 2500 < toast 3000. Menus, selects and tooltips must open above dialogs.
- **Menus:** checked menu entries are plain `menuitem`s with a check icon (no `menuitemcheckbox` role).
- **Menus:** an entry with `checked` set (true or false) is a toggle: a `menuitemcheckbox` with `aria-checked` and a check icon when on (`MenuEntries.svelte`, also used by `context-menu.svelte`). With `radio: true` it is one choice of several (`menuitemradio`: setting scopes, game resolutions). In e2e, find them by those roles, not `menuitem`. A manifest menu item's `checked` clause can read a setting with `config.<setting key>`, so its state shows before the plugin activates; the command still needs an `onCommand:` activation to work then.
- **Actions and shortcuts:**
- An _action_ is a command with its arguments (`actionId`). The palette and the keymap page list `listActions`: titled commands, plus menu entries that give arguments.
- A command that needs arguments sets `palette: false` (in `commands.register` or in the manifest), or it shows in the palette and does nothing.
Expand Down
8 changes: 7 additions & 1 deletion apps/editor/e2e/console.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,15 @@ test('console: groups, levels, search, repeats, values and file links', async ({

await page.getByRole('button', { name: 'Sources' }).click();
await page.getByRole('menuitem', { name: 'Plugins' }).click();
await page.getByRole('menuitem', { name: '@acme/hello' }).click();
const source = page.getByRole('menuitemcheckbox', { name: '@acme/hello' });
await expect(source).toHaveAttribute('aria-checked', 'true');
await source.click();
await expect(hello).toHaveCount(0);
await page.getByRole('button', { name: 'Sources' }).click();
await page.getByRole('menuitem', { name: 'Plugins' }).click();
await expect(source).toHaveAttribute('aria-checked', 'false');
await page.keyboard.press('Escape');
await page.getByRole('button', { name: 'Sources' }).click();
await page.getByRole('menuitem', { name: 'Show every source' }).click();
await expect(hello.filter({ hasText: 'Hello state' })).toHaveCount(1);

Expand Down
78 changes: 78 additions & 0 deletions apps/editor/e2e/menu-toggle.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { openProject, resetLayout, saved } from './helpers';
import { type Page, expect, test } from './test';

const files = (page: Page) => page.getByRole('tree', { name: 'Project files' });
/** The View menu trigger, whatever its role (a button, or a menubar item). */
const view = (page: Page) =>
page
.locator('[aria-label="Main menu"] [aria-haspopup="menu"]')
.filter({ hasText: /^View$/ })
.click();
const hiddenFiles = (page: Page) =>
page.getByRole('menuitemcheckbox', { name: 'Show hidden files' });

const open = async (page: Page) => {
await openProject(page, 'pong');
await page.waitForURL(/\/project\//);
await expect(files(page).getByRole('treeitem', { name: 'apps', exact: true })).toBeVisible();
};

test('view menu toggles show their on or off state', async ({ page }) => {
await open(page);
const dotFolder = files(page).getByRole('treeitem', { name: /^\.nanoforge/ });
await expect(dotFolder).toHaveCount(0);

await view(page);
await expect(page.getByRole('menuitemcheckbox', { name: 'Dark theme' })).toHaveAttribute(
'aria-checked',
'true',
);
await expect(hiddenFiles(page)).toHaveAttribute('aria-checked', 'false');
await hiddenFiles(page).click();
await expect(dotFolder).toBeVisible();

await view(page);
await expect(hiddenFiles(page)).toHaveAttribute('aria-checked', 'true');
await hiddenFiles(page).click();
await expect(dotFolder).toHaveCount(0);
await saved(page);
});

test('shows hidden files as on before the Files panel loads, and toggles from the keyboard', async ({
page,
}) => {
await open(page);
try {
await view(page);
await hiddenFiles(page).click();
await page.getByRole('button', { name: 'Hide Files' }).click();
await saved(page);
await page.reload();
await expect(page.getByRole('navigation', { name: /tool windows$/ }).first()).toBeVisible();
await expect(files(page)).toHaveCount(0);

await view(page);
const toggle = hiddenFiles(page);
await expect(toggle).toHaveAttribute('aria-checked', 'true');
for (let step = 0; step < 20; step++) {
if (await toggle.evaluate((element) => element === document.activeElement)) break;
await page.keyboard.press('ArrowDown');
}
await expect(toggle).toBeFocused();
await page.keyboard.press('Space');
await view(page);
await expect(hiddenFiles(page)).toHaveAttribute('aria-checked', 'false');
await page.keyboard.press('Escape');
} finally {
/** Puts back what a failure may leave: hidden files shown, the Files slot hidden. */
await page.keyboard.press('Escape');
await view(page);
if ((await hiddenFiles(page).getAttribute('aria-checked')) === 'true') {
await hiddenFiles(page).click();
} else {
await page.keyboard.press('Escape');
}
await resetLayout(page);
await saved(page);
}
});
6 changes: 3 additions & 3 deletions apps/editor/e2e/settings-ui.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ test('finds a setting, applies or cancels a change', async ({ page }) => {
await expect(dialog(page).locator('[data-key]')).toHaveCount(1);
const toggle = setting(page, MAXIMIZE).getByRole('switch', { name: 'Maximize on play' });
await setting(page, MAXIMIZE).getByRole('button', { name: 'Scope of Maximize on play' }).click();
await page.getByRole('menuitem', { name: 'This machine' }).click();
await page.getByRole('menuitemradio', { name: 'This machine' }).click();

await toggle.click();
await expect(toggle).toHaveAttribute('aria-checked', 'true');
Expand All @@ -51,7 +51,7 @@ test('finds a setting, applies or cancels a change', async ({ page }) => {
await expect(toggle).toHaveAttribute('aria-checked', 'false');

await setting(page, MAXIMIZE).getByRole('button', { name: 'Scope of Maximize on play' }).click();
await page.getByRole('menuitem', { name: 'This machine' }).click();
await page.getByRole('menuitemradio', { name: 'This machine' }).click();
await toggle.click();
await dialog(page).getByRole('button', { name: 'Apply' }).click();
await expect(dialog(page).getByRole('button', { name: 'Apply' })).toBeDisabled();
Expand All @@ -70,7 +70,7 @@ test('writes a setting to another scope, inspects and resets it', async ({ page
await dialog(page).getByRole('treeitem', { name: 'Game view' }).click();
const row = setting(page, MAXIMIZE);
await row.getByRole('button', { name: 'Scope of Maximize on play' }).click();
await page.getByRole('menuitem', { name: 'Project', exact: true }).click();
await page.getByRole('menuitemradio', { name: 'Project', exact: true }).click();
await row.getByRole('switch', { name: 'Maximize on play' }).click();
await dialog(page).getByRole('button', { name: 'Apply' }).click();
await expect.poll(() => projectValue(MAXIMIZE)).toBe(true);
Expand Down
2 changes: 1 addition & 1 deletion apps/editor/e2e/viewport.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ test.describe('while playing', () => {
await view(page, 'Stats').click();
await play(page);
await page.getByRole('button', { name: 'Resolution' }).click();
await page.getByRole('menuitem', { name: /1280 × 720/ }).click();
await page.getByRole('menuitemradio', { name: /1280 × 720/ }).click();
const frame = page.getByRole('application', { name: 'Running game' });
await expect.poll(async () => (await frame.boundingBox())?.width).toBe(1280);
await page.getByRole('button', { name: 'Zoom out' }).click();
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/editor/layout.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,4 @@ With _Settings › Editor › Game view › Maximize on play_, the docks and str

## Theme

The editor follows the light or dark mode of your system (_Match the system_) until you choose a theme. Switch with _View › Toggle light/dark theme_, or choose one in _Settings › Editor › Appearance_. Plugins can add themes: see [Settings](settings#appearance).
The editor follows the light or dark mode of your system (_Match the system_) until you choose a theme. Switch with _View › Dark theme_ (checked while a dark theme is on), or choose one in _Settings › Editor › Appearance_. Plugins can add themes: see [Settings](settings#appearance).
3 changes: 3 additions & 0 deletions docs/docs/plugins/manifest.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ The code gives the widget its view with the `WIDGET_VIEWS` extension point. See
| `submenu`, `title` | Instead of a command: opens the submenu with that id. |
| `group` | Entries are separated by group (default `main`), then sorted by `order`. |
| `when` | Shown only while true. |
| `checked` | A [when clause](#when-clauses) that makes the entry a toggle: a check box item, checked while it is true. `config.<setting key>` reads a setting. |
| `args` | Arguments passed to the command. |

### `keybindings`
Expand Down Expand Up @@ -230,5 +231,7 @@ Operators: `!`, `&&`, `||`, `==`, `!=`, `=~` (regular expression), `in`, and par
| `fileKind`, `fileExtname`, `fileReadOnly`, `fileSelectionCount` | in file context menus |
| `fileFolder`, `appType` | in file templates |
| `ecsEntity`, `ecsComponent:<class>` | in entity actions of the Hierarchy |
| `themeKind` | `light` or `dark`, the kind of the current theme |
| `config.<setting key>` | the value of a setting, in a menu item's `checked` only (`config.@nanoforge/file-manager.showHidden`) |

A plugin sets its own keys with `context.contextKeys.set(key, value)`.
38 changes: 30 additions & 8 deletions packages/ui/src/components/MenuEntries.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@
const { items }: { items: readonly MenuEntry[] } = $props();
</script>

{#snippet body(entry: MenuEntry & { kind: 'item' }, icon: string | undefined)}
<span class="nf-menu-check" aria-hidden={entry.checked === undefined ? undefined : 'true'}>
{#if icon}<Icon name={icon} size={14} />{/if}
</span>
<span class="nf-menu-label">{entry.label}</span>
{#if entry.shortcut}<kbd class="nf-menu-shortcut">{entry.shortcut}</kbd>{/if}
{/snippet}

{#each items as entry, index (index)}
{#if entry.kind === 'separator'}
<DropdownMenu.Separator class="nf-menu-separator" />
Expand All @@ -22,20 +30,34 @@
<MenuEntries items={entry.items} />
</DropdownMenu.SubContent>
</DropdownMenu.Sub>
{:else if entry.checked !== undefined && entry.radio}
<DropdownMenu.Item
class="nf-menu-item"
disabled={entry.disabled ?? false}
onSelect={entry.onSelect}
>
{#snippet child({ props })}
<div {...props} role="menuitemradio" aria-checked={entry.checked}>
{@render body(entry, entry.checked ? 'check' : undefined)}
</div>
{/snippet}
</DropdownMenu.Item>
{:else if entry.checked !== undefined}
<DropdownMenu.CheckboxItem
class="nf-menu-item"
checked={entry.checked}
disabled={entry.disabled ?? false}
onSelect={entry.onSelect}
>
{@render body(entry, entry.checked ? 'check' : undefined)}
</DropdownMenu.CheckboxItem>
{:else}
<DropdownMenu.Item
class="nf-menu-item"
disabled={entry.disabled ?? false}
onSelect={entry.onSelect}
>
<span class="nf-menu-check">
{#if entry.checked}<Icon name="check" size={14} />{:else if entry.icon}<Icon
name={entry.icon}
size={14}
/>{/if}
</span>
<span class="nf-menu-label">{entry.label}</span>
{#if entry.shortcut}<kbd class="nf-menu-shortcut">{entry.shortcut}</kbd>{/if}
{@render body(entry, entry.icon)}
</DropdownMenu.Item>
{/if}
{/each}
47 changes: 2 additions & 45 deletions packages/ui/src/components/context-menu.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { ContextMenu as BitsContextMenu } from 'bits-ui';
import type { Snippet } from 'svelte';

import Icon from './icon.svelte';
import MenuEntries from './MenuEntries.svelte';
import type { MenuEntry } from './menu-entry.type';

interface Props {
Expand All @@ -21,50 +21,7 @@
</BitsContextMenu.Trigger>
<BitsContextMenu.Portal>
<BitsContextMenu.Content class="nf-popover nf-menu">
{#each entries as entry, index (index)}
{#if entry.kind === 'separator'}
<BitsContextMenu.Separator class="nf-menu-separator" />
{:else if entry.kind === 'submenu'}
<BitsContextMenu.Sub>
<BitsContextMenu.SubTrigger class="nf-menu-item" disabled={entry.disabled ?? false}>
<span class="nf-menu-check"></span>
<span class="nf-menu-label">{entry.label}</span>
<Icon name="chevron-right" size={14} />
</BitsContextMenu.SubTrigger>
<BitsContextMenu.SubContent class="nf-popover nf-menu">
{#each entry.items as child, childIndex (childIndex)}
{#if child.kind === 'item'}
<BitsContextMenu.Item
class="nf-menu-item"
disabled={child.disabled ?? false}
onSelect={child.onSelect}
>
<span class="nf-menu-check"></span>
<span class="nf-menu-label">{child.label}</span>
</BitsContextMenu.Item>
{:else if child.kind === 'separator'}
<BitsContextMenu.Separator class="nf-menu-separator" />
{/if}
{/each}
</BitsContextMenu.SubContent>
</BitsContextMenu.Sub>
{:else}
<BitsContextMenu.Item
class="nf-menu-item"
disabled={entry.disabled ?? false}
onSelect={entry.onSelect}
>
<span class="nf-menu-check">
{#if entry.checked}<Icon name="check" size={14} />{:else if entry.icon}<Icon
name={entry.icon}
size={14}
/>{/if}
</span>
<span class="nf-menu-label">{entry.label}</span>
{#if entry.shortcut}<kbd class="nf-menu-shortcut">{entry.shortcut}</kbd>{/if}
</BitsContextMenu.Item>
{/if}
{/each}
<MenuEntries items={entries} />
</BitsContextMenu.Content>
</BitsContextMenu.Portal>
</BitsContextMenu.Root>
3 changes: 3 additions & 0 deletions packages/ui/src/components/menu-entry.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ export type MenuEntry =
readonly shortcut?: string;
readonly icon?: string;
readonly disabled?: boolean;
/** Set on a toggle: a `menuitemcheckbox` with a check icon when true. */
readonly checked?: boolean;
/** With `checked`: one choice among its neighbours (`menuitemradio`), not a toggle. */
readonly radio?: boolean;
readonly onSelect: () => void;
}
| { readonly kind: 'separator' }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ export const MenuItemSchema = z.object({
group: z.string().default('main'),
order: z.number().default(0),
when: z.string().optional(),
/**
* A `when` clause that makes the item a toggle, checked while it holds. `config.<setting key>`
* reads a setting, e.g. `config.@nanoforge/file-manager.showHidden`.
*/
checked: z.string().optional(),
args: z.array(z.unknown()).default([]),
});
export type MenuItem = z.output<typeof MenuItemSchema>;
Expand Down
29 changes: 28 additions & 1 deletion packages/ui/src/workbench/menu/resolve-menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import {
type ContextKeyService,
type ExtensionRegistry,
type Logger,
parseWhen,
} from '@nanoforge-dev/editor-kernel';
import type { SettingsService } from '@nanoforge-dev/editor-settings';

import type { MenuEntry } from '../../components/menu-entry.type';
import { MENU_ITEMS, type MenuItem } from '../extension-point/menu.extension-point';
Expand All @@ -17,6 +19,8 @@ export interface MenuContext {
readonly contextKeys: ContextKeyService;
readonly keybindings?: KeybindingService;
readonly logger?: Logger;
/** Read by `config.<setting key>` in a `checked` clause. */
readonly settings?: SettingsService;
}

/** Title of a command: its runtime registration, else its manifest metadata, else its id. */
Expand All @@ -26,9 +30,31 @@ export const commandTitle = (context: MenuContext, command: string): string =>
?.title ??
command;

const SETTING_KEY = 'config.';
/** Clauses already warned about: a bad one warns once, not on every menu opening. */
const warned = new Set<string>();

/**
* A toggle's state. `config.<setting key>` reads the setting, so the state shows before its
* plugin activates. A clause that fails leaves the entry unchecked, not the menu broken.
*/
const isChecked = (context: MenuContext, when: string): boolean => {
try {
return parseWhen(when).evaluate((key) =>
key.startsWith(SETTING_KEY) && context.settings
? context.settings.get(key.slice(SETTING_KEY.length))
: context.contextKeys.get(key),
);
} catch (error) {
if (!warned.has(when)) context.logger?.warn(`Menu checked clause "${when}" failed`, error);
warned.add(when);
return false;
}
};

/**
* Menu entries of a menu id: contributed items passing their `when`, grouped (separators
* between groups) and sorted by order.
* between groups) and sorted by order. An item with `checked` is a toggle, checked while it holds.
*/
export const resolveMenu = (context: MenuContext, menu: string, depth = 0): MenuEntry[] => {
if (depth > 5) return [];
Expand Down Expand Up @@ -61,6 +87,7 @@ export const resolveMenu = (context: MenuContext, menu: string, depth = 0): Menu
label: item.title ?? commandTitle(context, command),
...(item.icon && { icon: item.icon }),
...(key && { shortcut: formatKeybinding(key) }),
...(item.checked !== undefined && { checked: isChecked(context, item.checked) }),
disabled: context.commands.has(command) && !context.commands.isEnabled(command),
onSelect: () => {
context.commands
Expand Down
12 changes: 11 additions & 1 deletion packages/ui/src/workbench/setup/setup-shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
type PluginHost,
type StaticContributionHandler,
derived,
observe,
} from '@nanoforge-dev/editor-kernel';
import { CoreSettings, type SettingsService } from '@nanoforge-dev/editor-settings';

Expand Down Expand Up @@ -162,8 +163,17 @@ export const setupShell = (options: ShellOptions): Shell => {
contribute(MENU_ITEMS, [
{ menu: 'edit', command: 'history.undo', group: 'history', order: 0, args: [] },
{ menu: 'edit', command: 'history.redo', group: 'history', order: 1, args: [] },
{ menu: 'view', command: 'appearance.toggleTheme', group: 'z-appearance', order: 0, args: [] },
{
menu: 'view',
command: 'appearance.toggleTheme',
title: 'Dark theme',
checked: "themeKind == 'dark'",
group: 'z-appearance',
order: 0,
args: [],
},
]);
store.add(observe(themes.current, (theme) => contextKeys.set('themeKind', theme.kind)));

store.add(
commands.register({
Expand Down
Loading
Loading