Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Hotkeys/add option to add handlers same scope id+hotkey and fix soup hotkey bugs (#1006)

Caleb Taylor3aa07632736d
diff --git a/js/app/packages/app/component/SoupContext.tsx b/js/app/packages/app/component/SoupContext.tsx
index 4582ae4cde..0410ed9d97 100644
--- a/js/app/packages/app/component/SoupContext.tsx
+++ b/js/app/packages/app/component/SoupContext.tsx
@@ -4,8 +4,8 @@ import { toast } from '@core/component/Toast/Toast';
import { HotkeyTags } from '@core/hotkey/constants';
import { activeScope, hotkeyScopeTree } from '@core/hotkey/state';
import { TOKENS } from '@core/hotkey/tokens';
-import type { ValidHotkey } from '@core/hotkey/types';
-import { getActiveCommandByToken, runCommand } from '@core/hotkey/utils';
+import { HOTKEY_PRIORITY_LOW, type ValidHotkey } from '@core/hotkey/types';
+import { getHotkeyCommand, runCommand } from '@core/hotkey/utils';
import { isModality } from '@core/mobile/inputModality';
import { DEFAULT_VIEWS, type DefaultView, type ViewId } from '@core/types/view';
import { getActualTarget } from '@core/util/getActualTarget';
@@ -329,7 +329,7 @@ export function createNavigationEntityListShortcut({
actionRegistry,
parentContextSignal: [getParentContext],
childContextSignal: [getChildContext],
- activeContextSignal: [, setActiveContext],
+ activeContextSignal: [activeContext, setActiveContext],
} = soupContext;
const viewData = createMemo(() => viewsData[selectedView()]);
const viewIds = createMemo<ViewId[]>(() => Object.keys(viewsData));
@@ -1314,7 +1314,7 @@ export function createNavigationEntityListShortcut({
});
registerEntityHotkey({
- hotkey: ['h'],
+ hotkey: ['h', 'arrowleft'],
scopeId: splitHotkeyScope,
description: 'Navigate to parent context',
hotkeyToken: TOKENS.unifiedList.navigation.parent,
@@ -1322,20 +1322,16 @@ export function createNavigationEntityListShortcut({
const parentContext = getParentContext();
if (!parentContext) {
- const [preview] = previewState;
- if (!preview()) {
- const command = getActiveCommandByToken(TOKENS.split.goHome);
- if (command) {
- runCommand(command);
- }
- }
- return true;
+ return false;
}
- setActiveContext(parentContext);
const parentDomRef = parentContext.domRef();
+ if (parentContext === activeContext()) {
+ return true;
+ }
if (parentDomRef) {
+ setActiveContext(parentContext);
parentDomRef.focus();
return true;
}
@@ -1345,22 +1341,32 @@ export function createNavigationEntityListShortcut({
canExecuteKeyDownHandler: () => {
return isViewingList();
},
+ registrationType: 'add',
+ handlerPriority: HOTKEY_PRIORITY_LOW,
hide: true,
});
registerEntityHotkey({
- hotkey: ['l'],
+ hotkey: ['l', 'arrowright'],
scopeId: splitHotkeyScope,
description: 'Navigate to child context',
hotkeyToken: TOKENS.unifiedList.navigation.child,
keyDownHandler: () => {
const childContext = getChildContext();
if (!childContext) return false;
- setActiveContext(childContext);
const childDomRef = childContext.domRef();
+ if (!childDomRef) {
+ return false;
+ }
+
+ if (childContext === activeContext()) {
+ return false;
+ }
+
if (childDomRef) {
+ setActiveContext(childContext);
childDomRef.setAttribute('data-allow-focus-in-preview', '');
childDomRef.focus();
return true;
@@ -1370,6 +1376,8 @@ export function createNavigationEntityListShortcut({
canExecuteKeyDownHandler: () => {
return isViewingList() && getChildContext() !== undefined;
},
+ registrationType: 'add',
+ handlerPriority: HOTKEY_PRIORITY_LOW,
hide: true,
});
@@ -1466,7 +1474,9 @@ export function createNavigationEntityListShortcut({
return true;
},
displayPriority: 4,
+ registrationType: 'add',
});
+
registerEntityHotkey({
hotkey: ['cmd+enter'],
scopeId: splitHotkeyScope,
@@ -1500,9 +1510,8 @@ export function createNavigationEntityListShortcut({
return;
const scopeId = closestBlockScope.dataset.hotkeyScope;
if (!scopeId) return undefined;
- const splitNode = hotkeyScopeTree.get(scopeId);
- if (!splitNode) return undefined;
- return splitNode.hotkeyCommands.get('enter');
+
+ return getHotkeyCommand(scopeId, 'enter');
};
const command = getEnterCommand();
if (command) {
@@ -1721,6 +1730,8 @@ function registerEntityHotkey(
hotkeyToken: undefined,
tags: undefined,
condition: undefined,
+ registrationType: undefined,
+ handlerPriority: undefined,
keyDownHandler: (event) => {
globalKeyboardEvent = event;
queueMicrotask(() => {
@@ -1752,10 +1763,10 @@ function registerEntityHotkey(
const splitScope = activeSoupContext?.domRef();
if (!splitScope || !(splitScope instanceof HTMLElement)) return;
const scopeId = splitScope.dataset.hotkeyScope;
- if (!scopeId) return undefined;
- const splitNode = hotkeyScopeTree.get(scopeId);
- if (!splitNode) return undefined;
- return splitNode.hotkeyCommands.get(
+ if (!scopeId || !opts.hotkey) return undefined;
+
+ return getHotkeyCommand(
+ scopeId,
// @ts-expect-error
opts.hotkey[0]
);
diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsx
index 9b72711a9c..ef3f0b0998 100644
--- a/js/app/packages/app/component/UnifiedListView.tsx
+++ b/js/app/packages/app/component/UnifiedListView.tsx
@@ -1490,6 +1490,18 @@ export function UnifiedListView(props: UnifiedListViewProps) {
}
});
+ createEffect(
+ on(splitContext.isPanelActive, () => {
+ if (splitContext.isPanelActive()) {
+ if (activeSoupContext() !== soupContext) return;
+ const domEl = activeSoupContext()?.domRef();
+ setTimeout(() => {
+ domEl?.focus();
+ });
+ }
+ })
+ );
+
return (
<>
<Show when={!props.hideToolbar}>
diff --git a/js/app/packages/app/component/split-layout/registerSplitHotkeys.ts b/js/app/packages/app/component/split-layout/registerSplitHotkeys.ts
index 87a77f4f51..43c43864b0 100644
--- a/js/app/packages/app/component/split-layout/registerSplitHotkeys.ts
+++ b/js/app/packages/app/component/split-layout/registerSplitHotkeys.ts
@@ -85,6 +85,7 @@ export function registerSplitHotkeys(args: {
});
return true;
},
+ registrationType: 'add',
hotkeyToken: TOKENS.split.goHome,
displayPriority: 8,
});
@@ -158,6 +159,7 @@ export function registerSplitHotkeys(args: {
focusAdjacentSplit('right');
return true;
},
+ registrationType: 'add',
});
registerHotkey({
@@ -170,6 +172,7 @@ export function registerSplitHotkeys(args: {
focusAdjacentSplit('left');
return true;
},
+ registrationType: 'add',
});
return {};
diff --git a/js/app/packages/core/hotkey/getCommands.ts b/js/app/packages/core/hotkey/getCommands.ts
index 716bcd6468..5ab0be70a9 100644
--- a/js/app/packages/core/hotkey/getCommands.ts
+++ b/js/app/packages/core/hotkey/getCommands.ts
@@ -43,10 +43,14 @@ export function getActiveCommandsFromScope(
const commands: CommandWithInfo[] = [];
let scopeLevel = 0;
while (currentScopeNode) {
- const scopeCommands = Array.from([
- ...(currentScopeNode?.hotkeyCommands.values() ?? []),
+ // Flatten the arrays of commands from hotkeyCommands (each hotkey can have multiple handlers)
+ const allHotkeyCommands = Array.from(
+ currentScopeNode?.hotkeyCommands.values() ?? []
+ ).flat();
+ const scopeCommands = [
+ ...allHotkeyCommands,
...(currentScopeNode?.unkeyedCommands ?? []),
- ])
+ ]
.filter(filterCommands(displayOptions))
.map((command) => {
const hotkeys = command.hotkeys ?? [];
diff --git a/js/app/packages/core/hotkey/hotkeys.ts b/js/app/packages/core/hotkey/hotkeys.ts
index dff55071f4..2d25aabab8 100644
--- a/js/app/packages/core/hotkey/hotkeys.ts
+++ b/js/app/packages/core/hotkey/hotkeys.ts
@@ -22,6 +22,7 @@ import {
setPressedKeys,
} from './state';
import {
+ HOTKEY_PRIORITY_DEFAULT,
type HotkeyCommand,
type HotkeyRegistrationOptions,
isBaseKeyboardValue,
@@ -114,6 +115,8 @@ export function registerHotkey(
runWithInputFocused,
hotkeyToken,
displayPriority,
+ handlerPriority,
+ registrationType = 'override',
hide,
icon,
tags,
@@ -189,24 +192,28 @@ export function registerHotkey(
activateCommandScopeId: commandScopeId,
runWithInputFocused: runWithInputFocused ?? false,
displayPriority: displayPriority ?? 0,
+ handlerPriority: handlerPriority ?? HOTKEY_PRIORITY_DEFAULT,
hide,
icon,
tags,
shouldReturnFocusOnClose,
};
- // Check for existing hotkeys in the scope
- hotkeys?.forEach((h) => {
- if (scopeNode.hotkeyCommands.has(h)) {
- logger.log(
- `Hotkey ${h} already registered in scope ${scopeId}. Previous hotkey is being overwritten.`,
- {
- level: 'warn',
- error: new Error('Hotkey already registered in scope'),
- }
- );
- }
- });
+ // Check for existing hotkeys in the scope and warn if overriding
+ if (registrationType === 'override') {
+ hotkeys?.forEach((h) => {
+ const existingHandlers = scopeNode.hotkeyCommands.get(h);
+ if (existingHandlers && existingHandlers.length > 0) {
+ logger.log(
+ `Hotkey ${h} already registered in scope ${scopeId}. Previous hotkey is being overwritten.`,
+ {
+ level: 'warn',
+ error: new Error('Hotkey already registered in scope'),
+ }
+ );
+ }
+ });
+ }
if (hotkeyToken) {
setHotkeyTokenMap((prev) => {
@@ -221,7 +228,14 @@ export function registerHotkey(
// Register each hotkey with the same command
if (hotkeys) {
hotkeys.forEach((h) => {
- scopeNode.hotkeyCommands.set(h, command);
+ // Add to existing handlers array
+ const existingHandlers = scopeNode.hotkeyCommands.get(h) || [];
+ if (registrationType === 'add') {
+ scopeNode.hotkeyCommands.set(h, [...existingHandlers, command]);
+ } else {
+ // Override: replace with single-element array
+ scopeNode.hotkeyCommands.set(h, [command]);
+ }
});
} else {
scopeNode.unkeyedCommands.push(command);
@@ -236,9 +250,8 @@ export function registerHotkey(
setHotkeyTokenMap((prev) => {
const newMap = new Map(prev);
const existingCommands = newMap.get(hotkeyToken) || [];
- const newCommands = existingCommands.filter(
- (c) => c.scopeId !== scopeId
- );
+ // Filter out this specific command instance
+ const newCommands = existingCommands.filter((c) => c !== command);
if (newCommands.length > 0) {
newMap.set(hotkeyToken, newCommands);
} else {
@@ -248,11 +261,19 @@ export function registerHotkey(
});
}
- // Remove hotkeys from scope
+ // Remove this specific command from scope's hotkey handlers
const scope = hotkeyScopeTree.get(scopeId);
if (scope && hotkeys) {
hotkeys.forEach((h) => {
- scope.hotkeyCommands.delete(h);
+ const existingHandlers = scope.hotkeyCommands.get(h);
+ if (existingHandlers) {
+ const newHandlers = existingHandlers.filter((c) => c !== command);
+ if (newHandlers.length > 0) {
+ scope.hotkeyCommands.set(h, newHandlers);
+ } else {
+ scope.hotkeyCommands.delete(h);
+ }
+ }
});
}
@@ -524,16 +545,36 @@ export function useHotKeyRoot() {
let commandScopeActivated = false;
while (scopeNode) {
- const command = scopeNode.hotkeyCommands.get(pressedKeysString);
- if (command && (command.runWithInputFocused || !isEditableFocused)) {
- const result = runCommand(
- command,
- e,
- pressedKeysString,
- scopeNode.scopeId
+ const commands = scopeNode.hotkeyCommands.get(pressedKeysString);
+ if (commands && commands.length > 0) {
+ // Sort commands by handlerPriority (higher priority first)
+ const sortedCommands = [...commands].sort(
+ (a, b) => (b.handlerPriority ?? 0) - (a.handlerPriority ?? 0)
);
- commandCaptured = result.commandCaptured;
- commandScopeActivated = result.commandScopeActivated;
+
+ // Run handlers in priority order
+ for (const command of sortedCommands) {
+ if (command.runWithInputFocused || !isEditableFocused) {
+ const result = runCommand(
+ command,
+ e,
+ pressedKeysString,
+ scopeNode.scopeId
+ );
+
+ if (result.commandCaptured) {
+ commandCaptured = result.commandCaptured;
+ }
+ if (result.commandScopeActivated) {
+ commandScopeActivated = true;
+ }
+
+ // stops running handlers up the scope and laterally
+ if (result.stopPropagation) {
+ break;
+ }
+ }
+ }
}
if (
diff --git a/js/app/packages/core/hotkey/types.ts b/js/app/packages/core/hotkey/types.ts
index d73f7ff183..d998513a8b 100644
--- a/js/app/packages/core/hotkey/types.ts
+++ b/js/app/packages/core/hotkey/types.ts
@@ -1,6 +1,22 @@
import type { Component, JSX } from 'solid-js';
import type { HotkeyToken } from './tokens';
+export const HOTKEY_PRIORITY_DEFAULT = 0;
+export const HOTKEY_PRIORITY_LOW = 1;
+export const HOTKEY_PRIORITY_NORMAL = 2;
+export const HOTKEY_PRIORITY_HIGH = 3;
+export const HOTKEY_PRIORITY_CRITICAL = 4;
+
+const HOTKEY_TYPE = [
+ HOTKEY_PRIORITY_DEFAULT,
+ HOTKEY_PRIORITY_LOW,
+ HOTKEY_PRIORITY_NORMAL,
+ HOTKEY_PRIORITY_HIGH,
+ HOTKEY_PRIORITY_CRITICAL,
+] as const;
+
+type HotkeyPriority = (typeof HOTKEY_TYPE)[number];
+
export interface HotkeyCommand {
// Used to identify the hotkey in UI elements. Needs to be unique to a particular scope.
hotkeyToken?: HotkeyToken;
@@ -14,7 +30,7 @@ export interface HotkeyCommand {
description: string | (() => string);
// If true, the keyDownHandler will be run even if the input is focused.
runWithInputFocused: boolean;
- // If the keyDownHandler returns true, we won't look for other commands with same hotkey.
+ // If the keyDownHandler returns true, we won't look for other commands with same hotkey in parent scopes or lateral handlers.
keyDownHandler?: (e?: KeyboardEvent) => boolean;
// Optional keyUpHandler: if the keys of this hotkey are satisfied in a particular scope, the keyUpHandler will be triggered when the key is released, even if focus is lost.
keyUpHandler?: (e: KeyboardEvent) => void;
@@ -22,6 +38,8 @@ export interface HotkeyCommand {
activateCommandScopeId?: string;
// The priority of the command for ordering hotkey display lists. Note: registerHotkey only accepts number 1-10, but here we allow any number, so that we can sort as needed.
displayPriority?: number;
+ // Priority for ordering handler execution. Higher priority handlers run first. Defaults to 0.
+ handlerPriority?: HotkeyPriority;
// If true, hotkey command can be hidden from the UI. It will still run, but will not be displayed.
hide?: boolean | (() => boolean);
// Optional icon to display in the command palette.
@@ -70,7 +88,7 @@ export interface HotkeyRegistrationOptions {
/**
* Function called when hotkey is pressed.
- * If it returns true, the event will prevent default and stop propagation.
+ * If it returns true, the event will prevent default and stop propagation to parent scopes and registered handlers to same scope.
*/
keyDownHandler: (e?: KeyboardEvent) => boolean;
@@ -100,6 +118,21 @@ export interface HotkeyRegistrationOptions {
* 1: Minimal priority.
*/
displayPriority?: CommandDisplayPriority;
+
+ /**
+ * Priority for ordering handler execution when multiple handlers are registered for the same hotkey.
+ * Higher priority handlers run first. Defaults to 0.
+ */
+ handlerPriority?: HotkeyPriority;
+
+ /**
+ * Controls how this handler is added when a handler for the same hotkey already exists.
+ * - 'override': Replace existing handler (default behavior)
+ * - 'add': Add this handler to the list of handlers for this hotkey
+ * @default 'override'
+ */
+ registrationType?: 'add' | 'override';
+
/**
* If true, hotkey command can be hidden from the UI. It will still run, but may not be displayed.
* Can be either a boolean or a function that returns a boolean for reactive behavior.
@@ -131,8 +164,8 @@ export type ScopeNodeBase = {
description?: string;
parentScopeId?: string;
childScopeIds: string[];
- // Map of hotkey -> commands
- hotkeyCommands: Map<ValidHotkey, HotkeyCommand>;
+ // Map of hotkey -> array of commands (multiple handlers can be registered for the same hotkey)
+ hotkeyCommands: Map<ValidHotkey, HotkeyCommand[]>;
// A list of commands that don't have hotkeys.
unkeyedCommands: HotkeyCommand[];
// If true, this scope is detached from the DOM tree, it's parent is global.
diff --git a/js/app/packages/core/hotkey/utils.ts b/js/app/packages/core/hotkey/utils.ts
index a13ab6dc8a..e3f0236a70 100644
--- a/js/app/packages/core/hotkey/utils.ts
+++ b/js/app/packages/core/hotkey/utils.ts
@@ -27,6 +27,75 @@ import type {
ValidHotkey,
} from './types';
+type GetHotkeyCommandOptions = {
+ /**
+ * The property to sort by. Defaults to 'handlerPriority'.
+ */
+ sortBy?: 'displayPriority' | 'handlerPriority';
+ /**
+ * Sort direction. Defaults to 'desc' (higher values first).
+ */
+ sortDirection?: 'asc' | 'desc';
+};
+
+/**
+ * Get hotkey commands from a scope, sorted by the specified property.
+ *
+ * @param scopeOrId - Either a ScopeNode or a scope ID string
+ * @param hotkey - The hotkey to look up
+ * @param options - Sorting options
+ * @returns Array of commands sorted by the specified property, or empty array if not found
+ *
+ * @example
+ * // Get commands sorted by handlerPriority (default)
+ * const commands = getHotkeyCommands(scopeNode, 'h');
+ *
+ * // Get the highest priority command
+ * const topCommand = getHotkeyCommands(scopeNode, 'h')[0];
+ *
+ * // Sort by displayPriority instead
+ * const commands = getHotkeyCommands(scopeNode, 'h', { sortBy: 'displayPriority' });
+ */
+export function getHotkeyCommands(
+ scopeOrId: ScopeNode | string,
+ hotkey: ValidHotkey,
+ options: GetHotkeyCommandOptions = {}
+): HotkeyCommand[] {
+ const { sortBy = 'handlerPriority', sortDirection = 'desc' } = options;
+
+ const scopeNode =
+ typeof scopeOrId === 'string' ? hotkeyScopeTree.get(scopeOrId) : scopeOrId;
+
+ if (!scopeNode) return [];
+
+ const commands = scopeNode.hotkeyCommands.get(hotkey);
+ if (!commands || commands.length === 0) return [];
+
+ // Sort by the specified property
+ return [...commands].sort((a, b) => {
+ const aVal = a[sortBy] ?? 0;
+ const bVal = b[sortBy] ?? 0;
+ return sortDirection === 'desc' ? bVal - aVal : aVal - bVal;
+ });
+}
+
+/**
+ * Get the first (highest priority by default) hotkey command from a scope.
+ * Convenience wrapper around getHotkeyCommands.
+ *
+ * @param scopeOrId - Either a ScopeNode or a scope ID string
+ * @param hotkey - The hotkey to look up
+ * @param options - Sorting options
+ * @returns The first command after sorting, or undefined if not found
+ */
+export function getHotkeyCommand(
+ scopeOrId: ScopeNode | string,
+ hotkey: ValidHotkey,
+ options: GetHotkeyCommandOptions = {}
+): HotkeyCommand | undefined {
+ return getHotkeyCommands(scopeOrId, hotkey, options)[0];
+}
+
let scopeCounter = 0;
export function getScopeId(prefix: string = 'scope'): string {
const scopeId = `${prefix}_${scopeCounter++}`;
@@ -245,8 +314,10 @@ export function getActiveCommandByToken(
while (currentAncestor) {
const activationKey = currentCommandScope.activationKeys?.at(0);
if (activationKey) {
- const activationCommand =
- originalParentScope.hotkeyCommands.get(activationKey);
+ const activationCommand = getHotkeyCommand(
+ originalParentScope,
+ activationKey
+ );
if (activationCommand) {
reverseActivationCommands.push(activationCommand);
} else break;
@@ -309,7 +380,7 @@ export function getPrettyHotkeyStringByToken(token: HotkeyToken) {
* @param e - The keyboard event.
* @param pressedKeysString - The string of pressed keys.
* @param scopeId - The id of the scope that the command is from.
- * @returns An object with the command captured and the command scope activated.
+ * @returns An object with the command captured, command scope activated, and propagation control flags.
*/
export function runCommand(
command: HotkeyCommand,
@@ -321,6 +392,7 @@ export function runCommand(
let commandCaptured: HotkeyCommand | undefined;
let commandScopeActivated = false;
+ let stopPropagation = false;
if (!command.condition || command.condition()) {
if (command.activateCommandScopeId) {
@@ -346,6 +418,8 @@ export function runCommand(
}
const captured = command.keyDownHandler?.(e);
+ stopPropagation = captured ?? stopPropagation;
+
if (captured) {
setPressedKeys(new Set<string>());
setLastExecutedCommand(command);
@@ -378,8 +452,9 @@ export function runCommand(
}
return {
- commandCaptured: commandCaptured,
- commandScopeActivated: commandScopeActivated,
+ commandCaptured,
+ commandScopeActivated,
+ stopPropagation,
};
}