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.

feat: Visor and WhichKey (#273)

Peter Chinmaneb7a2981d541
diff --git a/js/app/packages/app/component/EntityNavigationIndicator.tsx b/js/app/packages/app/component/EntityNavigationIndicator.tsx
index eb08c40f58..41cf768b62 100644
--- a/js/app/packages/app/component/EntityNavigationIndicator.tsx
+++ b/js/app/packages/app/component/EntityNavigationIndicator.tsx
@@ -1,8 +1,7 @@
import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
import { IconButton } from '@core/component/IconButton';
-import { runCommand } from '@core/hotkey/hotkeys';
-import { activeScope, hotkeyScopeTree } from '@core/hotkey/state';
import { TOKENS } from '@core/hotkey/tokens';
+import { getActiveCommandByToken, runCommand } from '@core/hotkey/utils';
import CaretDown from '@icon/regular/caret-down.svg';
import CaretUp from '@icon/regular/caret-up.svg';
import { Show } from 'solid-js';
@@ -21,23 +20,6 @@ const EntityNavigationIndicator = () => {
const selectedEntityIndex = () =>
entities()?.findIndex((item) => item.id === selectedEntity()?.id) ?? -1;
- const getNavigationCommand = (key: 'j' | 'k') => {
- const currentActiveScope = activeScope();
- if (!currentActiveScope) return undefined;
- let activeScopeNode = hotkeyScopeTree.get(currentActiveScope);
- if (!activeScopeNode) return undefined;
- if (activeScopeNode?.type !== 'dom') return;
- const dom = activeScopeNode.element;
- const closestSplitScope = dom.closest('[data-hotkey-scope^="split"]');
- if (!closestSplitScope || !(closestSplitScope instanceof HTMLElement))
- return;
- const scopeId = closestSplitScope.dataset.hotkeyScope;
- if (!scopeId) return undefined;
- const splitNode = hotkeyScopeTree.get(scopeId);
- if (!splitNode) return undefined;
- return splitNode.hotkeyCommands.get(key);
- };
-
return (
<Show
when={
@@ -64,7 +46,7 @@ const EntityNavigationIndicator = () => {
disabled={selectedEntityIndex() >= entities()!.length - 1}
theme="current"
onDeepClick={() => {
- const command = getNavigationCommand('j');
+ const command = getActiveCommandByToken(TOKENS.entity.select.end);
if (!command) return;
runCommand(command);
}}
@@ -79,7 +61,9 @@ const EntityNavigationIndicator = () => {
disabled={selectedEntityIndex() === 0}
theme="current"
onDeepClick={() => {
- const command = getNavigationCommand('k');
+ const command = getActiveCommandByToken(
+ TOKENS.entity.select.start
+ );
if (!command) return;
runCommand(command);
}}
diff --git a/js/app/packages/app/component/GlobalHotkeys.tsx b/js/app/packages/app/component/GlobalHotkeys.tsx
index 764f0cb57d..f9758c8305 100644
--- a/js/app/packages/app/component/GlobalHotkeys.tsx
+++ b/js/app/packages/app/component/GlobalHotkeys.tsx
@@ -1,13 +1,8 @@
import { useOpenInstructionsMd } from '@core/component/AI/util/instructions';
-import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';
import { useSettingsState } from '@core/constant/SettingsState';
import { TOKENS } from '@core/hotkey/tokens';
import type { ValidHotkey } from '@core/hotkey/types';
-import {
- isRightPanelOpen,
- useBigChat,
- useToggleRightPanel,
-} from '@core/signal/layout';
+import { useBigChat } from '@core/signal/layout';
import { AiInstructionsIcon } from '@service-storage/instructionsMd';
import { registerHotkey } from 'core/hotkey/hotkeys';
import { createMemo } from 'solid-js';
@@ -24,23 +19,23 @@ import {
toggleGutterSize,
} from '../../block-theme/signals/themeSignals';
import { applyTheme } from '../../block-theme/utils/themeUtils';
+import { globalSplitManager } from '../signal/splitLayout';
import { playSound } from '../util/sound';
import {
konsoleOpen,
resetKonsoleMode,
- setKonsoleMode,
toggleKonsoleVisibility,
} from './command/state';
import { CREATABLE_BLOCKS, setCreateMenuOpen } from './Launcher';
-import { fireMacroJump } from './MacroJump';
-import {
- quickCreateMenuOpenSignal,
- selectedQuickCreateTypeSignal,
-} from './QuickCreateMenu';
+import { useSplitLayout } from './split-layout/layout';
+import { fireVisor, resetVisor } from './Visor';
+import { openWhichKey, setOpenWhichKey } from './WhichKey';
export default function GlobalShortcuts() {
- const [bigChatOpen, setBigChatOpen] = useBigChat();
- const toggleRightPanel = useToggleRightPanel();
+ const [_, setBigChatOpen] = useBigChat();
+
+ const canFit = () =>
+ globalSplitManager()?.resizeContext()?.canFit({ minSize: 400 }) ?? true;
const { toggleSettings } = useSettingsState();
const handleCommandMenu = () => {
@@ -54,12 +49,6 @@ export default function GlobalShortcuts() {
return;
};
- const handleSearchMenu = () => {
- setKonsoleMode('FULL_TEXT_SEARCH');
- toggleKonsoleVisibility();
- return;
- };
-
const createCommandScope = registerHotkey({
hotkeyToken: TOKENS.global.createCommand,
hotkey: 'c',
@@ -99,99 +88,10 @@ export default function GlobalShortcuts() {
});
}
- const quickCreateScope = registerHotkey({
- hotkeyToken: TOKENS.global.quickCreateCommand,
- hotkey: 'q',
- scopeId: 'global',
- description: 'Quick send',
- keyDownHandler: () => {
- return true;
- },
- activateCommandScope: true,
- displayPriority: 4,
- });
-
- const [_selectedQuickCreateType, setSelectedQuickCreateType] =
- selectedQuickCreateTypeSignal;
- const [_quickCreateMenuOpen, setQuickCreateMenuOpen] =
- quickCreateMenuOpenSignal;
-
- registerHotkey({
- hotkeyToken: TOKENS.global.quickCreate.note,
- hotkey: 'n',
- scopeId: quickCreateScope.commandScopeId,
- description: 'Create note',
- keyDownHandler: () => {
- setSelectedQuickCreateType('note');
- setQuickCreateMenuOpen(true);
- return true;
- },
- displayPriority: 10,
- runWithInputFocused: true,
- });
-
- registerHotkey({
- hotkeyToken: TOKENS.global.quickCreate.email,
- hotkey: 'e',
- scopeId: quickCreateScope.commandScopeId,
- description: 'Create email',
- keyDownHandler: () => {
- setSelectedQuickCreateType('email');
- setQuickCreateMenuOpen(true);
- return true;
- },
- displayPriority: 10,
- runWithInputFocused: true,
- });
-
- registerHotkey({
- hotkeyToken: TOKENS.global.quickCreate.message,
- hotkey: 'm',
- scopeId: quickCreateScope.commandScopeId,
- description: 'Create message',
- keyDownHandler: () => {
- setSelectedQuickCreateType('message');
- setQuickCreateMenuOpen(true);
- return true;
- },
- displayPriority: 10,
- runWithInputFocused: true,
- });
-
- registerHotkey({
- hotkeyToken: TOKENS.global.macroJump,
- hotkey: 'cmd+m',
- scopeId: 'global',
- description: 'Macro jump',
- runWithInputFocused: true,
- keyDownHandler: () => {
- fireMacroJump();
- return true;
- },
- });
-
- registerHotkey({
- hotkeyToken: TOKENS.global.toggleRightPanel,
- hotkey: 'cmd+/',
- scopeId: 'global',
- description: () => {
- return isRightPanelOpen() ? 'Close AI panel' : 'Open AI panel';
- },
- keyDownHandler: () => {
- toggleRightPanel();
- return true;
- },
- condition: () => {
- return !bigChatOpen();
- },
- runWithInputFocused: true,
- });
-
registerHotkey({
hotkeyToken: TOKENS.global.commandMenu,
hotkey: 'cmd+k',
scopeId: 'global',
- // condition: () => !konsoleOpen(),
description: () => {
return konsoleOpen() ? 'Close command menu' : 'Open command menu';
},
@@ -199,8 +99,8 @@ export default function GlobalShortcuts() {
handleCommandMenu();
return true;
},
- displayPriority: 1,
- hide: true,
+ displayPriority: 10,
+ hide: konsoleOpen,
runWithInputFocused: true,
});
@@ -216,6 +116,20 @@ export default function GlobalShortcuts() {
runWithInputFocused: true,
});
+ const { insertSplit } = useSplitLayout();
+ registerHotkey({
+ hotkeyToken: TOKENS.global.createNewSplit,
+ hotkey: 'cmd+\\',
+ scopeId: 'global',
+ description: 'Create new split',
+ condition: canFit,
+ keyDownHandler: () => {
+ insertSplit({ type: 'component', id: 'unified-list' });
+ return true;
+ },
+ runWithInputFocused: true,
+ });
+
registerHotkey({
hotkeyToken: TOKENS.global.toggleSettings,
hotkey: 'cmd+;',
@@ -241,21 +155,6 @@ export default function GlobalShortcuts() {
runWithInputFocused: true,
});
- if (ENABLE_SEARCH_SERVICE) {
- registerHotkey({
- hotkeyToken: TOKENS.global.searchMenu,
- hotkey: 'cmd+p',
- scopeId: 'global',
- description: 'Full text search',
- keyDownHandler: () => {
- handleSearchMenu();
- return true;
- },
- runWithInputFocused: true,
- displayPriority: 9,
- });
- }
-
const setThemeScope = registerHotkey({
scopeId: 'global',
description: 'Change theme',
@@ -346,6 +245,25 @@ export default function GlobalShortcuts() {
runWithInputFocused: true,
});
+ registerHotkey({
+ hotkeyToken: TOKENS.global.toggleVisor,
+ scopeId: 'global',
+ hotkey: ['escape'],
+ description: 'Toggle visor',
+ keyDownHandler: () => {
+ if (!openWhichKey()) {
+ fireVisor();
+ setOpenWhichKey(true);
+ return false;
+ } else {
+ resetVisor();
+ setOpenWhichKey(false);
+ return false;
+ }
+ },
+ runWithInputFocused: true,
+ });
+
registerHotkey({
scopeId: 'global',
description: 'Toggle beveled corners',
diff --git a/js/app/packages/app/component/HelpDrawer.tsx b/js/app/packages/app/component/HelpDrawer.tsx
index 69ed848ab5..b678293cb9 100644
--- a/js/app/packages/app/component/HelpDrawer.tsx
+++ b/js/app/packages/app/component/HelpDrawer.tsx
@@ -23,7 +23,9 @@ export function HelpDrawer(props: { viewId?: ViewId }) {
<Switch>
<Match
when={
- (props.viewId === 'noise' || props.viewId === 'signal') &&
+ (props.viewId === 'noise' ||
+ props.viewId === 'signal' ||
+ props.viewId === 'email') &&
!emailActive()
}
>
@@ -75,7 +77,7 @@ export function HelpDrawer(props: { viewId?: ViewId }) {
],
},
{
- hotkeyTokenSequence: [TOKENS.global.toggleRightPanel],
+ hotkeyTokenSequence: [TOKENS.split.go.toggleRightPanel],
},
]}
/>
@@ -110,6 +112,41 @@ export function HelpDrawer(props: { viewId?: ViewId }) {
}
/>
</Match>
+ <Match when={props.viewId === 'email'}>
+ <HelpDrawerInner
+ title={'Email is better with Macro.'}
+ subtitle={
+ <span>
+ Use{' '}
+ <span class="font-mono bg-edge/20 rounded-xs md-inline-code p-0.3">
+ @mentions
+ </span>{' '}
+ to give email recipients access to anything in Macro. Ask AI to
+ search your emails.
+ </span>
+ }
+ hotkeyExamples={[
+ {
+ hotkeyTokenSequence: [
+ TOKENS.global.createCommand,
+ TOKENS.create.email,
+ ],
+ },
+ {
+ hotkeyTokenSequence: [
+ TOKENS.global.createCommand,
+ TOKENS.create.message,
+ ],
+ },
+ {
+ hotkeyTokenSequence: [
+ TOKENS.split.goCommand,
+ TOKENS.split.go.toggleRightPanel,
+ ],
+ },
+ ]}
+ />
+ </Match>
<Match when={props.viewId === 'comms'}>
<HelpDrawerInner
title={'Message teammates.'}
@@ -207,7 +244,7 @@ export function HelpDrawer(props: { viewId?: ViewId }) {
hotkeyTokenSequence: [TOKENS.global.createNewSplit],
},
{
- hotkeyTokenSequence: [TOKENS.global.toggleRightPanel],
+ hotkeyTokenSequence: [TOKENS.split.go.toggleRightPanel],
},
{
hotkeyTokenSequence: [TOKENS.global.createCommand],
diff --git a/js/app/packages/app/component/HotkeyExample.tsx b/js/app/packages/app/component/HotkeyExample.tsx
index 471466469a..2b07606ca8 100644
--- a/js/app/packages/app/component/HotkeyExample.tsx
+++ b/js/app/packages/app/component/HotkeyExample.tsx
@@ -1,7 +1,7 @@
import { Hotkey } from '@core/component/Hotkey';
-import { useHotkeyCommandByToken } from '@core/hotkey/hotkeys';
import { executedTokens } from '@core/hotkey/state';
import type { HotkeyToken } from '@core/hotkey/tokens';
+import { getHotkeyCommandByToken } from '@core/hotkey/utils';
import ArrowRight from '@icon/regular/arrow-right.svg';
import { createMemo, For, Show } from 'solid-js';
@@ -12,16 +12,14 @@ export interface HotkeyExampleProps {
export function HotkeyExample(props: HotkeyExampleProps) {
const commandSequence = props.hotkeyTokenSequence.map((token) => ({
- command: useHotkeyCommandByToken(token),
+ command: getHotkeyCommandByToken(token),
executed: createMemo(() => executedTokens().includes(token)),
}));
const lowerCaseFirstChar = (str: string) =>
str.charAt(0).toLowerCase() + str.slice(1);
- const lastCommandDescription_ = commandSequence
- .at(-1)
- ?.command()?.description;
+ const lastCommandDescription_ = commandSequence.at(-1)?.command?.description;
const lastCommandDescription = createMemo(() =>
lowerCaseFirstChar(
typeof lastCommandDescription_ === 'function'
@@ -37,7 +35,7 @@ export function HotkeyExample(props: HotkeyExampleProps) {
<For each={commandSequence}>
{(item, index) => (
<>
- <Show when={item.command()}>
+ <Show when={item.command}>
{(command) => (
<Hotkey
token={command().hotkeyToken}
diff --git a/js/app/packages/app/component/MacroJump.tsx b/js/app/packages/app/component/MacroJump.tsx
index 7f1a409340..c2586ed574 100644
--- a/js/app/packages/app/component/MacroJump.tsx
+++ b/js/app/packages/app/component/MacroJump.tsx
@@ -1,3 +1,5 @@
+import { getClippedOverlayRect } from '@app/util/getClippedOverlayRect';
+import { getScrollElementParent } from '@app/util/getScrollElementParent';
import {
isElementVisibleInScrollElViewport,
isElementVisibleInViewport,
@@ -302,85 +304,6 @@ const JumpLabelOverlay: Component<TJumpLabel> = (props) => {
);
};
-function matchScroll(str: string) {
- return str.match(/auto|scroll/);
-}
-
-const getScrollElementParent = (el: HTMLElement | null) => {
- if (!el) {
- return null;
- }
-
- const style = getComputedStyle(el);
-
- const hasScrollableOverflow =
- matchScroll(style.overflow) ||
- matchScroll(style.overflowY) ||
- matchScroll(style.overflowX);
-
- if (hasScrollableOverflow && el.clientHeight !== el.scrollHeight) {
- return el;
- }
-
- return getScrollElementParent(el.parentElement);
-};
-
-function getClippedOverlayRect(
- targetEl: HTMLElement,
- targetElScrollParent: HTMLElement | null
-) {
- const targetRect = targetEl.getBoundingClientRect();
- if (!targetElScrollParent) {
- return {
- rect: {
- left: targetRect.left,
- top: targetRect.top,
- right: targetRect.right,
- bottom: targetRect.bottom,
- width: targetRect.width,
- height: targetRect.height,
- },
- isClippedLeft: false,
- isClippedRight: false,
- isClippedTop: false,
- isClippedBottom: false,
- isFullyClipped: false,
- isPartiallyClipped: false,
- };
- }
- const scrollParentRect = targetElScrollParent.getBoundingClientRect();
-
- // Calculate clipping edges
- const clippedLeft = Math.max(targetRect.left, scrollParentRect.left);
- const clippedTop = Math.max(targetRect.top, scrollParentRect.top);
- const clippedRight = Math.min(targetRect.right, scrollParentRect.right);
- const clippedBottom = Math.min(targetRect.bottom, scrollParentRect.bottom);
-
- const clippedWidth = Math.max(0, clippedRight - clippedLeft);
- const clippedHeight = Math.max(0, clippedBottom - clippedTop);
-
- return {
- rect: {
- left: clippedLeft,
- top: clippedTop,
- width: clippedWidth,
- height: clippedHeight,
- right: clippedLeft + clippedWidth,
- bottom: clippedTop + clippedHeight,
- },
- isClippedLeft: clippedLeft > targetRect.left,
- isClippedRight: clippedRight < targetRect.right,
- isClippedTop: clippedTop > targetRect.top,
- isClippedBottom: clippedBottom < targetRect.bottom,
- isFullyClipped: clippedWidth === 0 || clippedHeight === 0,
- isPartiallyClipped:
- clippedLeft > targetRect.left ||
- clippedRight < targetRect.right ||
- clippedTop > targetRect.top ||
- clippedBottom < targetRect.bottom,
- };
-}
-
function createJumpLabelGenerator() {
// Use 'asdfghjkl' for main characters and ';qwertyuiopzxcvbnm' for prefix characters
const chars = ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'];
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index 0f0c111fed..fc9566808e 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -1,4 +1,5 @@
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
+import { setHotkeyRoot, useSubscribeToKeypress } from '@app/signal/hotkeyRoot';
import { globalSplitManager } from '@app/signal/splitLayout';
import { withAnalytics } from '@coparse/analytics';
import { useIsAuthenticated } from '@core/auth';
@@ -68,6 +69,8 @@ import MacroJump from './MacroJump';
import Onboarding from './Onboarding';
import { SuspenseContextComp } from './SuspenseContext';
import { LAYOUT_ROUTE } from './split-layout/SplitLayoutRoute';
+import Visor from './Visor';
+import { setOpenWhichKey, WhichKey } from './WhichKey';
const { track, identify, TrackingEvents } = withAnalytics();
@@ -295,7 +298,14 @@ const clearBodyInlineStyleColor = () => {
export function Root() {
const isAuthenticated = useIsAuthenticated();
- useHotKeyRoot();
+ setHotkeyRoot(useHotKeyRoot());
+
+ useSubscribeToKeypress((context) => {
+ if (context.commandScopeActivated) {
+ setOpenWhichKey(true);
+ }
+ });
+
useSoundHover();
clearBodyInlineStyleColor();
@@ -374,6 +384,8 @@ export function Root() {
<ChannelsContextProvider>
<Title>{tabTitle()}</Title>
<MacroJump />
+ <Visor />
+ <WhichKey />
<SuspenseContextComp fallback={<RootSuspenseFallback />}>
<IsomorphicRouter
transformUrl={transformShortIdInUrlPathname}
diff --git a/js/app/packages/app/component/Soup.tsx b/js/app/packages/app/component/Soup.tsx
index 278b6b165b..39b5291f10 100644
--- a/js/app/packages/app/component/Soup.tsx
+++ b/js/app/packages/app/component/Soup.tsx
@@ -8,10 +8,12 @@ import { useIsAuthenticated } from '@core/auth';
import type { BlockAliasContext } from '@core/block';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
import { Button } from '@core/component/FormControls/Button';
+import { SegmentedControl } from '@core/component/FormControls/SegmentControls';
import { ContextMenuContent, MenuItem } from '@core/component/Menu';
import { fileTypeToResolvedBlockName } from '@core/constant/allBlocks';
import { fileFolderDrop } from '@core/directive/fileFolderDrop';
import { TOKENS } from '@core/hotkey/tokens';
+import type { RegisterHotkeyReturn } from '@core/hotkey/types';
import type { BlockOrchestrator } from '@core/orchestrator';
import {
DEFAULT_VIEWS,
@@ -54,6 +56,7 @@ import { HelpDrawer } from './HelpDrawer';
import { SuspenseContextComp } from './SuspenseContext';
import { SplitHeaderLeft } from './split-layout/components/SplitHeader';
import { SplitTabs } from './split-layout/components/SplitTabs';
+import { SplitToolbarRight } from './split-layout/components/SplitToolbar';
import type { SplitPanelContextType } from './split-layout/context';
import { SplitPanelContext } from './split-layout/context';
import { useSplitPanelOrThrow } from './split-layout/layoutUtils';
@@ -84,13 +87,13 @@ const ViewWithSearch: Component<{
return (
<ViewTab viewId={props.viewId}>
<Switch>
- {/* <Match
- when={props.viewId === 'emails' && DEFAULT_VIEWS.includes('emails')}
+ <Match
+ when={props.viewId === 'email' && DEFAULT_VIEWS.includes('email')}
>
<Suspense>
<EmailView />
</Suspense>
- </Match> */}
+ </Match>
<Match when={props.viewId === 'all' && DEFAULT_VIEWS.includes('all')}>
<Suspense>
<AllView />
@@ -231,34 +234,40 @@ export function Soup() {
const entityQueryClient = useEntityQueryClient();
- registerHotkey({
- hotkey: ['shift+/'],
- scopeId: splitHotkeyScope,
- description: () =>
- `${showHelpDrawer().has(selectedView() as DefaultView) ? 'Hide' : 'Show'} help drawer`,
- hotkeyToken: TOKENS.split.showHelpDrawer,
- keyDownHandler: () => {
- if (showHelpDrawer().has(selectedView() as DefaultView)) {
- setShowHelpDrawer(new Set<DefaultView>());
- } else {
- setShowHelpDrawer(new Set(DEFAULT_VIEWS));
- }
- return true;
- },
- });
+ const hotkeyDisposers: RegisterHotkeyReturn[] = [];
+
+ hotkeyDisposers.push(
+ registerHotkey({
+ hotkey: ['shift+/'],
+ scopeId: splitHotkeyScope,
+ description: () =>
+ `${showHelpDrawer().has(selectedView() as DefaultView) ? 'Hide' : 'Show'} help drawer`,
+ hotkeyToken: TOKENS.split.showHelpDrawer,
+ keyDownHandler: () => {
+ if (showHelpDrawer().has(selectedView() as DefaultView)) {
+ setShowHelpDrawer(new Set<DefaultView>());
+ } else {
+ setShowHelpDrawer(new Set(DEFAULT_VIEWS));
+ }
+ return true;
+ },
+ })
+ );
- registerHotkey({
- hotkey: ['p'],
- scopeId: splitHotkeyScope,
- description: 'Toggle Preview',
- hotkeyToken: TOKENS.unifiedList.togglePreview,
- keyDownHandler: () => {
- playSound('open');
- setPreview((prev) => !prev);
- return true;
- },
- hide: true,
- });
+ hotkeyDisposers.push(
+ registerHotkey({
+ hotkey: ['p'],
+ scopeId: splitHotkeyScope,
+ description: 'Toggle Preview',
+ hotkeyToken: TOKENS.unifiedList.togglePreview,
+ keyDownHandler: () => {
+ playSound('open');
+ setPreview((prev) => !prev);
+ return true;
+ },
+ // displayPriority: 10,
+ })
+ );
const [isDragging, setIsDragging] = createSignal(false);
const [isValidDrag, setIsValidDrag] = createSignal(true);
@@ -305,7 +314,10 @@ export function Soup() {
let tabsRef: HTMLDivElement | undefined;
- onCleanup(() => setEntityListRef(undefined));
+ onCleanup(() => {
+ setEntityListRef(undefined);
+ hotkeyDisposers.forEach((disposer) => disposer.dispose());
+ });
const TabContextMenu = (props: { value: ViewId; label: string }) => {
const [isModalOpen, setIsModalOpen] = createSignal(false);
@@ -394,9 +406,10 @@ export function Soup() {
>
<SplitHeaderLeft>
<SplitTabs
- list={Object.values(viewsData).map((view) => ({
+ list={Object.values(viewsData).map((view, index) => ({
value: view.id,
label: view.view,
+ index: index,
}))}
active={selectedView}
contextMenu={({ value, label }) => (
@@ -446,32 +459,32 @@ function AllView() {
return <UnifiedListView />;
}
-// function EmailView() {
-// const {
-// emailViewSignal: [emailView, setEmailView],
-// viewsDataStore,
-// selectedView,
-// } = useSplitPanelOrThrow().unifiedListContext;
-// const viewData = createMemo(() => viewsDataStore[selectedView()]);
-
-// return (
-// <>
-// <UnifiedListView />
-// <SplitToolbarRight>
-// <div class="flex flex-row items-center pr-2">
-// <SegmentedControl
-// disabled={!!viewData().searchText}
-// size="SM"
-// label="View"
-// list={['inbox', 'sent', 'drafts']}
-// value={emailView()}
-// onChange={setEmailView}
-// />
-// </div>
-// </SplitToolbarRight>
-// </>
-// );
-// }
+function EmailView() {
+ const {
+ emailViewSignal: [emailView, setEmailView],
+ viewsDataStore,
+ selectedView,
+ } = useSplitPanelOrThrow().unifiedListContext;
+ const viewData = createMemo(() => viewsDataStore[selectedView()]);
+
+ return (
+ <>
+ <UnifiedListView />
+ <SplitToolbarRight>
+ <div class="flex flex-row items-center pr-2">
+ <SegmentedControl
+ disabled={!!viewData().searchText}
+ size="SM"
+ label="View"
+ list={['inbox', 'sent', 'drafts']}
+ value={emailView()}
+ onChange={setEmailView}
+ />
+ </div>
+ </SplitToolbarRight>
+ </>
+ );
+}
export const useUpsertSavedViewMutation = () => {
const queryClient = useQueryClient();
diff --git a/js/app/packages/app/component/SoupContext.tsx b/js/app/packages/app/component/SoupContext.tsx
index 3d75c552d6..7fae55c9c1 100644
--- a/js/app/packages/app/component/SoupContext.tsx
+++ b/js/app/packages/app/component/SoupContext.tsx
@@ -6,6 +6,7 @@ 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 { runCommand } from '@core/hotkey/utils';
import { DEFAULT_VIEWS, type DefaultView, type ViewId } from '@core/types/view';
import { getActualTarget } from '@core/util/getActualTarget';
import { isInteractiveElement } from '@core/util/isInteractiveElement';
@@ -24,11 +25,7 @@ import {
import { storageServiceClient } from '@service-storage/client';
import { createLazyMemo } from '@solid-primitives/memo';
import { useQuery } from '@tanstack/solid-query';
-import {
- registerHotkey,
- runCommand,
- useHotkeyDOMScope,
-} from 'core/hotkey/hotkeys';
+import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
import {
type Accessor,
batch,
@@ -208,16 +205,16 @@ export type NavigationResult = {
};
export function createNavigationEntityListShortcut({
- splitName,
splitHandle,
splitHotkeyScope,
unifiedListContext,
+ goScopeId,
previewState,
}: {
- splitName: Accessor<string>;
splitHandle: SplitHandle;
splitHotkeyScope: string;
unifiedListContext: UnifiedListContext;
+ goScopeId: string;
previewState: Signal<boolean>;
}) {
const {
@@ -1001,7 +998,9 @@ export function createNavigationEntityListShortcut({
registerHotkey({
scopeId: splitHotkeyScope,
- description: 'Root Modify selection',
+ description: () => {
+ return konsoleOpen() ? 'Close command menu' : 'Open command menu';
+ },
hotkey: 'cmd+k',
condition: () => !konsoleOpen() && isViewingList(),
keyDownHandler: (e) => {
@@ -1032,6 +1031,9 @@ export function createNavigationEntityListShortcut({
resetKonsoleMode();
return false;
},
+ displayPriority: 10,
+ hide: konsoleOpen,
+ runWithInputFocused: true,
});
registerEntityHotkey({
@@ -1051,7 +1053,7 @@ export function createNavigationEntityListShortcut({
hotkey: ['shift+arrowdown', 'shift+j'],
scopeId: splitHotkeyScope,
description: 'Select down',
- hotkeyToken: TOKENS.entity.step.end,
+ hotkeyToken: TOKENS.entity.select.end,
keyDownHandler: () => {
const navigationInput: NavigationInput = { axis: 'end', mode: 'step' };
return handleNavigationSelection(navigationInput);
@@ -1076,7 +1078,7 @@ export function createNavigationEntityListShortcut({
registerEntityHotkey({
hotkey: ['shift+arrowup', 'shift+k'],
scopeId: splitHotkeyScope,
- hotkeyToken: TOKENS.entity.step.start,
+ hotkeyToken: TOKENS.entity.select.start,
description: 'Select up',
keyDownHandler: () => {
const navigationInput: NavigationInput = { axis: 'start', mode: 'step' };
@@ -1100,7 +1102,7 @@ export function createNavigationEntityListShortcut({
hotkey: ['shift+g', 'end'],
scopeId: splitHotkeyScope,
hotkeyToken: TOKENS.entity.jump.end,
- description: 'Bottom',
+ description: 'Go to bottom of list',
keyDownHandler: () => {
navigateThroughList({ axis: 'end', mode: 'jump' });
return true;
@@ -1108,28 +1110,27 @@ export function createNavigationEntityListShortcut({
hide: true,
});
- const {
- registerHotkeyReturn: topGScope,
- globalRegisterHotkeyReturn: topGScopeGlobal,
- } = registerEntityHotkey({
- hotkey: ['g'],
- scopeId: splitHotkeyScope,
- description: 'Top',
- keyDownHandler: () => true,
- activateCommandScope: true,
- hide: true,
- });
- registerEntityHotkey({
+ registerHotkey({
hotkey: ['g'],
- scopeId: topGScope.commandScopeId,
- globalCommandScope: topGScopeGlobal.commandScopeId,
- description: 'Top',
+ scopeId: goScopeId,
+ description: 'Go to top of list',
keyDownHandler: () => {
navigateThroughList({ axis: 'start', mode: 'jump' });
return true;
},
});
+ registerHotkey({
+ hotkey: ['shift+g', 'end'],
+ scopeId: goScopeId,
+ hotkeyToken: TOKENS.entity.jump.end,
+ description: 'Go to bottom of list',
+ keyDownHandler: () => {
+ navigateThroughList({ axis: 'end', mode: 'jump' });
+ return true;
+ },
+ });
+
const navigateThroughViews = ({
axis,
}: {
@@ -1142,26 +1143,29 @@ export function createNavigationEntityListShortcut({
setSelectedView(newViewId);
};
- const splitIsUnifiedList = createMemo(() => splitName() === 'unified-list');
+ const splitIsUnifiedList = createMemo(
+ () => splitHandle.content().id === 'unified-list'
+ );
- createEffect(() => {
- for (let i = 0; i < viewIds().length && i < 9; i++) {
- const viewId = viewIds()[i];
- const viewData = viewsData[viewId];
- registerHotkey({
- hotkey: [(i + 1).toString() as ValidHotkey],
- scopeId: splitHotkeyScope,
- description: viewData.view,
- condition: splitIsUnifiedList,
- keyDownHandler: () => {
- setSelectedView(viewData.id);
- return true;
- },
- // displayPriority: 0,
- hide: true,
- });
- }
- });
+ for (let i = 0; i < viewIds().length && i < 9; i++) {
+ const viewId = viewIds()[i];
+ const viewData = viewsData[viewId];
+ registerHotkey({
+ hotkeyToken:
+ TOKENS.soup.tabs[i.toString() as keyof typeof TOKENS.soup.tabs],
+ hotkey: [(i + 1).toString() as ValidHotkey],
+ scopeId: splitHotkeyScope,
+ description: viewData.view,
+ condition: splitIsUnifiedList,
+ keyDownHandler: () => {
+ setSelectedView(viewData.id);
+ return true;
+ },
+ // displayPriority: 0,
+ hide: true,
+ });
+ }
+ 1;
registerHotkey({
hotkey: 'tab',
@@ -1190,8 +1194,10 @@ export function createNavigationEntityListShortcut({
registerEntityHotkey({
hotkey: ['enter'],
+ hotkeyToken: TOKENS.entity.open,
scopeId: splitHotkeyScope,
description: 'Open',
+ hide: true,
keyDownHandler: () => {
const entity = getSelectedEntity()?.entity;
if (!entity) return false;
@@ -1205,6 +1211,10 @@ export function createNavigationEntityListShortcut({
if (keyboardEvent) {
const target = getActualTarget(keyboardEvent);
+ if (entityListRef()?.contains(target)) {
+ return true;
+ }
+
if (isInteractiveElement(target)) {
return false;
}
@@ -1277,17 +1287,36 @@ export function createNavigationEntityListShortcut({
canExecuteKeyDownHandler: () => isViewingList(),
displayPriority: 10,
});
- registerEntityHotkey({
+
+ const clearMultiCondition: () => boolean = () =>
+ isViewingList() && viewData().multiSelectEntities.length > 0;
+ const closeSpotlightCondition = () => splitHandle.isSpotLight();
+ const escapeDescription = () => {
+ if (clearMultiCondition()) {
+ return 'Clear multi selection';
+ }
+ if (closeSpotlightCondition()) {
+ return 'Close spotlight';
+ }
+ return '';
+ };
+ registerHotkey({
hotkey: ['escape'],
scopeId: splitHotkeyScope,
- description: 'Clear multi selection',
+ description: escapeDescription,
+ condition: () => clearMultiCondition() || closeSpotlightCondition(),
keyDownHandler: () => {
- const length = viewData().multiSelectEntities.length;
- setViewDataStore(selectedView(), 'multiSelectEntities', []);
- return length > 1;
+ if (clearMultiCondition()) {
+ const length = viewData().multiSelectEntities.length;
+ setViewDataStore(selectedView(), 'multiSelectEntities', []);
+ return length > 1;
+ }
+ if (closeSpotlightCondition()) {
+ splitHandle.toggleSpotlight();
+ return true;
+ }
+ return false;
},
- canExecuteKeyDownHandler: () =>
- isViewingList() && viewData().multiSelectEntities.length > 0,
});
}
diff --git a/js/app/packages/app/component/UnifiedListEmptyState.tsx b/js/app/packages/app/component/UnifiedListEmptyState.tsx
index 50bb0d878f..2e85a0cd3e 100644
--- a/js/app/packages/app/component/UnifiedListEmptyState.tsx
+++ b/js/app/packages/app/component/UnifiedListEmptyState.tsx
@@ -70,7 +70,9 @@ export function EmptyState(props: {
</Match>
<Match
when={
- (props.viewId === 'noise' || props.viewId === 'signal') &&
+ (props.viewId === 'noise' ||
+ props.viewId === 'signal' ||
+ props.viewId === 'email') &&
emailActive()
}
>
@@ -82,6 +84,12 @@ export function EmptyState(props: {
helpDrawer={'signal'}
/>
</Match>
+ <Match when={props.viewId === 'email' && !emailActive()}>
+ <EmptyStateHelpDrawer
+ message={'Nothing to show. Email not connected.'}
+ helpDrawer={'email'}
+ />
+ </Match>
<Match when={props.viewId === 'people'}>
<EmptyStateHelpDrawer
message={'No messages to show.'}
diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsx
index 613c835ca3..f78a60120f 100644
--- a/js/app/packages/app/component/UnifiedListView.tsx
+++ b/js/app/packages/app/component/UnifiedListView.tsx
@@ -226,6 +226,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {
virtualizerHandleSignal: [virtualizerHandle, setVirtualizerHandle],
entityListRefSignal: [, setEntityListRef],
entitiesSignal: [entities_, setEntities],
+ emailViewSignal: [emailView],
} = unifiedListContext;
const view = createMemo(() => viewsData[selectedView()]);
const selectedEntity = createMemo(() => view()?.selectedEntity);
@@ -869,7 +870,9 @@ export function UnifiedListView(props: UnifiedListViewProps) {
? 'important'
: view().id === VIEWCONFIG_DEFAULTS_IDS_ENUM.all
? 'all'
- : undefined,
+ : view().id === VIEWCONFIG_DEFAULTS_IDS_ENUM.email
+ ? emailView()
+ : undefined,
sort_method: sortType(),
})
diff --git a/js/app/packages/app/component/ViewConfig.tsx b/js/app/packages/app/component/ViewConfig.tsx
index 736b1d2035..0450acf7bf 100644
--- a/js/app/packages/app/component/ViewConfig.tsx
+++ b/js/app/packages/app/component/ViewConfig.tsx
@@ -225,6 +225,12 @@ const ALL_VIEWCONFIG_DEFAULTS = {
},
},
},
+ files: {
+ view: 'Files',
+ filters: {
+ typeFilter: ['document'],
+ },
+ },
people: {
view: 'People',
filters: {
@@ -234,10 +240,38 @@ const ALL_VIEWCONFIG_DEFAULTS = {
showUnreadIndicator: true,
},
},
- files: {
- view: 'Files',
+ email: {
+ view: 'Email',
filters: {
- typeFilter: ['document'],
+ typeFilter: ['email'],
+ },
+ sort: {
+ sortBy: 'updated_at',
+ },
+ display: {
+ showUnreadIndicator: true,
+ },
+ hotkeyOptions: {
+ e: (entity, extra) => {
+ if (extra?.soupContext) {
+ const {
+ emailViewSignal: [emailView],
+ } = extra.soupContext;
+ if (emailView() === 'inbox') {
+ if (entity.type === 'email') {
+ archiveEmail(entity.id, {
+ isDone: entity.done,
+ optimisticallyExclude: true,
+ });
+ }
+ return true;
+ }
+ }
+ if (entity.type === 'email') {
+ archiveEmail(entity.id, { isDone: entity.done });
+ }
+ return true;
+ },
},
},
tasks: {
diff --git a/js/app/packages/app/component/Visor.tsx b/js/app/packages/app/component/Visor.tsx
new file mode 100644
index 0000000000..d0df21a6b7
--- /dev/null
+++ b/js/app/packages/app/component/Visor.tsx
@@ -0,0 +1,290 @@
+import { useSubscribeToKeypress } from '@app/signal/hotkeyRoot';
+import { getClippedOverlayRect } from '@app/util/getClippedOverlayRect';
+import { getScrollElementParent } from '@app/util/getScrollElementParent';
+import { Hotkey } from '@core/component/Hotkey';
+import { activeScope } from '@core/hotkey/state';
+import { TOKENS, tokenMap } from '@core/hotkey/tokens';
+import type { HotkeyCommand, ValidHotkey } from '@core/hotkey/types';
+import {
+ getActiveCommandByToken,
+ getHotkeyCommandByToken,
+ isScopeInActiveBranch,
+ prettyPrintHotkeyString,
+ useIsInCommandScope,
+} from '@core/hotkey/utils';
+import {
+ isElementVisibleInScrollElViewport,
+ isElementVisibleInViewport,
+} from '@core/util/isElementVisibleInViewport';
+import { autoUpdate } from '@floating-ui/dom';
+import {
+ type Accessor,
+ type Component,
+ createEffect,
+ createSignal,
+ createUniqueId,
+ For,
+ on,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
+import { createStore } from 'solid-js/store';
+
+function isElementVisible(element: HTMLElement) {
+ if (
+ element.offsetParent === null ||
+ getComputedStyle(element).visibility === 'hidden'
+ ) {
+ return false;
+ }
+ return true;
+}
+
+type VisorLabel = {
+ id: string;
+ hotkey: ValidHotkey;
+ commands: HotkeyCommand[];
+ targetEl: HTMLElement;
+ targetElScrollParent: HTMLElement | null;
+};
+
+const [isVisorOpen, setIsVisorOpen] = createSignal(false);
+export const fireVisor = () => {
+ setIsVisorOpen(true);
+};
+export const resetVisor = () => {
+ setIsVisorOpen(false);
+};
+
+const VisorInner: Component<{
+ parent?: Accessor<Element | undefined>;
+}> = (props) => {
+ const [visorLabels, setVisorLabels] = createStore<VisorLabel[]>([]);
+ const isInCommandScope = useIsInCommandScope();
+
+ useSubscribeToKeypress((context) => {
+ if (
+ context.eventType === 'keydown' &&
+ context.isNonModifierKeypress &&
+ !context.isEditableFocused &&
+ !getHotkeyCommandByToken(TOKENS.global.toggleVisor)?.hotkeys?.some(
+ (hotkey) => context.pressedKeysString === hotkey
+ ) &&
+ !context.commandScopeActivated
+ ) {
+ resetVisor();
+ }
+ });
+
+ createEffect(
+ on([isInCommandScope, activeScope], () => {
+ const root = props.parent?.() ?? document.getElementById('root')!;
+ const currentScopeId = activeScope();
+ const inCommandScope = isInCommandScope();
+
+ const hotkeyEls = Array.from(
+ root.querySelectorAll<HTMLElement>('[data-hotkey-token]')
+ ).filter((el) => {
+ const scopeElement = el.closest('[data-hotkey-scope]') as HTMLElement;
+ if (!scopeElement) return false;
+
+ const scopeId = scopeElement.dataset.hotkeyScope;
+ return scopeId && isScopeInActiveBranch(scopeId);
+ });
+
+ const newVisorLabels: VisorLabel[] = hotkeyEls
+ .filter((el) => {
+ return (
+ isElementVisible(el) &&
+ isElementVisibleInViewport(el, {
+ padding: {
+ // include bottom navbar height to reduce viewport bottom
+ // bottom: 32,
+ },
+ }) &&
+ isElementVisibleInScrollElViewport(el).isVisible
+ );
+ })
+ .reduce<VisorLabel[]>((acc, hotkeyEl) => {
+ const targetElScrollParent = getScrollElementParent(hotkeyEl);
+ const id = createUniqueId();
+ const tokenString = hotkeyEl.dataset.hotkeyToken ?? '';
+ const token = tokenMap.get(tokenString);
+ if (!token) return acc;
+ const commands = getActiveCommandByToken(token, true);
+ if (!commands || commands.length === 0) return acc;
+
+ let filteredCommands: HotkeyCommand[];
+ if (inCommandScope && currentScopeId) {
+ // When in a command scope, only show commands that belong to this scope
+ filteredCommands = commands.filter(
+ (cmd) => cmd.scopeId === currentScopeId
+ );
+ } else {
+ filteredCommands = commands;
+ }
+
+ if (filteredCommands.length === 0) return acc;
+
+ const firstCommand = filteredCommands[0];
+ if (!firstCommand.hotkeys || firstCommand.hotkeys.length === 0) {
+ return acc;
+ }
+
+ const hotkey = firstCommand.hotkeys[0];
+
+ acc.push({
+ id,
+ hotkey,
+ commands: filteredCommands,
+ targetEl: hotkeyEl,
+ targetElScrollParent,
+ } satisfies VisorLabel);
+ return acc;
+ }, []);
+
+ setVisorLabels(newVisorLabels);
+ })
+ );
+
+ // If user clicks anywhere, exit
+ const handleMousedown = () => {
+ setIsVisorOpen(false);
+ };
+ document.addEventListener('mousedown', handleMousedown);
+
+ onCleanup(() => {
+ document.removeEventListener('mousedown', handleMousedown);
+ });
+
+ return (
+ <div>
+ <For each={visorLabels}>
+ {(jumpLabel) => <VisorLabelOverlay {...jumpLabel} />}
+ </For>
+ </div>
+ );
+};
+
+const Visor: Component<{
+ parent?: Accessor<Element | undefined>;
+}> = (props) => {
+ return (
+ <Show when={isVisorOpen()}>
+ <VisorInner {...props} />
+ </Show>
+ );
+};
+
+const VisorLabelOverlay: Component<VisorLabel> = (props) => {
+ const [targetData, setTargetData] = createStore({
+ isClippedBottom: false,
+ isClippedLeft: false,
+ isClippedRight: false,
+ isClippedTop: false,
+ });
+ let overlayRef!: HTMLDivElement;
+
+ onMount(() => {
+ const overlay = overlayRef;
+
+ // Get the element's position and dimensions to check if it's visible
+ const targetRect = props.targetEl.getBoundingClientRect();
+ if (targetRect.width === 0 || targetRect.height === 0) return null;
+ const {
+ rect: clippedRect,
+ isClippedBottom,
+ isClippedLeft,
+ isClippedRight,
+ isClippedTop,
+ } = getClippedOverlayRect(props.targetEl, props.targetElScrollParent);
+
+ overlay.style.left = `${clippedRect.left}px`;
+ overlay.style.top = `${clippedRect.top}px`;
+ overlay.style.width = `${clippedRect.width}px`;
+ overlay.style.height = `${clippedRect.height}px`;
+
+ setTargetData({
+ isClippedBottom,
+ isClippedLeft,
+ isClippedRight,
+ isClippedTop,
+ });
+
+ const updateOverlay = async () => {
+ const {
+ rect: clippedRect,
+ isFullyClipped,
+ isClippedBottom,
+ isClippedLeft,
+ isClippedRight,
+ isClippedTop,
+ } = getClippedOverlayRect(props.targetEl, props.targetElScrollParent);
+
+ overlay.style.display = isFullyClipped ? 'none' : 'block';
+ overlay.style.left = `${clippedRect.left}px`;
+ overlay.style.top = `${clippedRect.top}px`;
+ overlay.style.width = `${clippedRect.width}px`;
+ overlay.style.height = `${clippedRect.height}px`;
+
+ setTargetData({
+ isClippedBottom,
+ isClippedLeft,
+ isClippedRight,
+ isClippedTop,
+ });
+ };
+ const cleanup = autoUpdate(props.targetEl, overlayRef, updateOverlay);
+ onCleanup(() => {
+ cleanup();
+ });
+ });
+
+ return (
+ <div
+ class={
+ 'highlight-overlay fixed pointer-events-none z-[9999] border-page border'
+ }
+ style={{
+ 'border-left-width': targetData.isClippedLeft ? '0' : '',
+ 'border-top-width': targetData.isClippedTop ? '0' : '',
+ 'border-right-width': targetData.isClippedRight ? '0' : '',
+ 'border-bottom-width': targetData.isClippedBottom ? '0' : '',
+ }}
+ data-target-id={props.id}
+ ref={overlayRef}
+ >
+ <div
+ class="relative w-full h-full border-accent border"
+ style={{
+ 'background-color':
+ 'color-mix(in srgb, var(--color-accent) 10%, transparent)',
+ 'border-left-width': targetData.isClippedLeft ? '0' : '',
+ 'border-top-width': targetData.isClippedTop ? '0' : '',
+ 'border-right-width': targetData.isClippedRight ? '0' : '',
+ 'border-bottom-width': targetData.isClippedBottom ? '0' : '',
+ }}
+ >
+ <div
+ class={
+ 'relative font-mono text-page font-bold w-fit bg-accent border-l-accent border-t-accent border-r-page border-b-page border p-[2px] text-xs z-[1] flex items-center gap-1'
+ }
+ >
+ <Hotkey shortcut={prettyPrintHotkeyString(props.hotkey)} />
+ </div>
+ <div
+ class="absolute inset-0 border-page border"
+ style={{
+ 'border-left-width': targetData.isClippedLeft ? '0' : '',
+ 'border-top-width': targetData.isClippedTop ? '0' : '',
+ 'border-right-width': targetData.isClippedRight ? '0' : '',
+ 'border-bottom-width': targetData.isClippedBottom ? '0' : '',
+ }}
+ />
+ </div>
+ </div>
+ );
+};
+
+export default Visor;
diff --git a/js/app/packages/app/component/WhichKey.tsx b/js/app/packages/app/component/WhichKey.tsx
new file mode 100644
index 0000000000..9811b2e490
--- /dev/null
+++ b/js/app/packages/app/component/WhichKey.tsx
@@ -0,0 +1,152 @@
+import { useSubscribeToKeypress } from '@app/signal/hotkeyRoot';
+import { Hotkey } from '@core/component/Hotkey';
+import { getActiveCommandsFromScope } from '@core/hotkey/getCommands';
+import { activeScope, hotkeyScopeTree } from '@core/hotkey/state';
+import { TOKENS } from '@core/hotkey/tokens';
+import type { HotkeyCommand } from '@core/hotkey/types';
+import {
+ getHotkeyCommandByToken,
+ prettyPrintHotkeyString,
+} from '@core/hotkey/utils';
+import {
+ type Accessor,
+ createMemo,
+ createSignal,
+ For,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
+import { Portal } from 'solid-js/web';
+
+export const [openWhichKey, setOpenWhichKey] = createSignal(false);
+
+type WhichKeyContentProps = {
+ commandsWithActivateScope: Accessor<HotkeyCommand[]>;
+ commandsWithoutActivateScope: Accessor<HotkeyCommand[]>;
+};
+
+function WhichKeyContent(props: WhichKeyContentProps) {
+ return (
+ <Show
+ when={
+ props.commandsWithActivateScope().length > 0 ||
+ props.commandsWithoutActivateScope().length > 0
+ }
+ >
+ <Portal>
+ <div class="absolute z-9999 right-2 bottom-14">
+ {/* <dfiv class="absolute -z-1 top-2 right-2 pattern-edge pattern-diagonal-4 opacity-100 w-full h-full mask-l-from-[calc(100%_-_1rem)] mask-b-from-[calc(100%_-_1rem)]" /> */}
+ <div class="w-[280px] px-6 py-3 h-full bg-dialog/75 backdrop-blur-sm border-2 border-accent text-sm shadow-[0_0_2px_0_var(--color-accent)]">
+ <Show when={props.commandsWithActivateScope().length > 0}>
+ <div class="mb-6">
+ <For each={props.commandsWithActivateScope()}>
+ {(command) => (
+ <div class="grid grid-cols-[8ch_1fr] gap-x-2 mb-1">
+ <div class="justify-self-start bg-panel border border-edge px-1.5 py-0.25 rounded-xs">
+ <Hotkey
+ token={command.hotkeyToken}
+ shortcut={prettyPrintHotkeyString(
+ // Asserting this, because useActiveCommands only returns commands with hotkeys.
+ command.hotkeys!.at(0)!
+ )}
+ />
+ </div>
+ <div class="truncate min-w-0">
+ {typeof command.description === 'function'
+ ? command.description()
+ : command.description}{' '}
+ </div>
+ </div>
+ )}
+ </For>
+ </div>
+ </Show>
+ <For each={props.commandsWithoutActivateScope()}>
+ {(command) => (
+ <div class="grid grid-cols-[8ch_1fr] gap-2 mb-1">
+ <div class="justify-self-start bg-panel border border-edge px-1.5 py-0.25 rounded-xs">
+ <Hotkey
+ token={command.hotkeyToken}
+ shortcut={prettyPrintHotkeyString(
+ // Asserting this, because useActiveCommands only returns commands with hotkeys.
+ command.hotkeys!.at(0)!
+ )}
+ />
+ </div>
+ <div class="truncate min-w-0">
+ {typeof command.description === 'function'
+ ? command.description()
+ : command.description}{' '}
+ </div>
+ </div>
+ )}
+ </For>
+ </div>
+ </div>
+ </Portal>
+ </Show>
+ );
+}
+
+export function WhichKey() {
+ useSubscribeToKeypress((context) => {
+ if (
+ context.eventType === 'keydown' &&
+ context.isNonModifierKeypress &&
+ (!context.commandScopeActivated ||
+ context.commandCaptured?.hotkeyToken === TOKENS.global.createCommand) &&
+ !getHotkeyCommandByToken(TOKENS.global.toggleVisor)?.hotkeys?.some(
+ (hotkey) => context.pressedKeysString === hotkey
+ )
+ ) {
+ setOpenWhichKey(false);
+ }
+ });
+
+ const isInCommandScope = createMemo(() => {
+ const currentScopeId = activeScope();
+ if (!currentScopeId) return false;
+ const scopeNode = hotkeyScopeTree.get(currentScopeId);
+ return scopeNode?.type === 'command';
+ });
+
+ const activeCommands = createMemo(() => {
+ const currentScopeId = activeScope() ?? '';
+ return getActiveCommandsFromScope(currentScopeId, {
+ hideCommandsWithoutHotkeys: true,
+ limitToCurrentScope: isInCommandScope(),
+ hideShadowedCommands: true,
+ });
+ });
+
+ const commandsWithActivateScope = createMemo(() => {
+ return activeCommands().filter((command) => command.activateCommandScopeId);
+ });
+
+ const commandsWithoutActivateScope = createMemo(() => {
+ return activeCommands().filter(
+ (command) => !command.activateCommandScopeId
+ );
+ });
+
+ // If user clicks anywhere, exit
+ onMount(() => {
+ const handleMousedown = () => {
+ setOpenWhichKey(false);
+ };
+ document.addEventListener('mousedown', handleMousedown);
+ onCleanup(() => {
+ document.removeEventListener('mousedown', handleMousedown);
+ });
+ });
+
+ return (
+ <Show when={openWhichKey()}>
+ <WhichKeyContent
+ commandsWithActivateScope={commandsWithActivateScope}
+ commandsWithoutActivateScope={commandsWithoutActivateScope}
+ />
+ </Show>
+ );
+}
diff --git a/js/app/packages/app/component/command/Konsole.tsx b/js/app/packages/app/component/command/Konsole.tsx
index eeff9db225..7ea4eb0279 100644
--- a/js/app/packages/app/component/command/Konsole.tsx
+++ b/js/app/packages/app/component/command/Konsole.tsx
@@ -7,11 +7,7 @@ import type { CommandWithInfo } from '@core/hotkey/getCommands';
import { createFreshSearch } from '@core/util/freshSort';
import { Dialog } from '@kobalte/core/dialog';
import { Command as CommandK, useCommandState } from 'cmdk-solid';
-import {
- registerHotkey,
- runCommand,
- useHotkeyDOMScope,
-} from 'core/hotkey/hotkeys';
+import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
import {
type Accessor,
createEffect,
@@ -46,6 +42,7 @@ import {
konsoleOpen,
lastCommandTime,
rawQuery,
+ setKonsoleOpen,
setLastCommandTime,
setRawQuery,
toggleKonsoleVisibility,
@@ -120,16 +117,7 @@ export function KommandMenuInner(props: {
data: {
id: description.replaceAll(' ', '-'),
name: description,
- hotkeys: command.hotkeys ?? [],
- handler: () => {
- runCommand({
- keyDownHandler: command.keyDownHandler,
- activateCommandScopeId: command.activateCommandScopeId,
- });
- setCommandScopeCommands([]);
- return true;
- },
- activateCommandScopeId: command.activateCommandScopeId,
+ command: command,
},
};
});
@@ -249,6 +237,18 @@ export function KommandMenuInner(props: {
runWithInputFocused: true,
});
+ registerHotkey({
+ hotkey: 'escape',
+ scopeId: konsoleHotkeyScopeId,
+ description: 'Close command menu',
+ keyDownHandler: () => {
+ setKonsoleOpen(false);
+ return true;
+ },
+ runWithInputFocused: true,
+ hide: true,
+ });
+
const CommandKItemWrapper = (props: {
index: number;
item: CommandItemCard;
diff --git a/js/app/packages/app/component/command/KonsoleItem.tsx b/js/app/packages/app/component/command/KonsoleItem.tsx
index 420bcf9815..be01fbe446 100644
--- a/js/app/packages/app/component/command/KonsoleItem.tsx
+++ b/js/app/packages/app/component/command/KonsoleItem.tsx
@@ -18,9 +18,9 @@ import {
type CommandWithInfo,
getActiveCommandsFromScope,
} from '@core/hotkey/getCommands';
-import { runCommand } from '@core/hotkey/hotkeys';
import { pressedKeys } from '@core/hotkey/state';
-import type { ValidHotkey } from '@core/hotkey/types';
+import type { HotkeyCommand } from '@core/hotkey/types';
+import { runCommand } from '@core/hotkey/utils';
import type { BlockOrchestrator } from '@core/orchestrator';
import { type ChannelWithParticipants, idToDisplayName } from '@core/user';
import PushPin from '@phosphor-icons/core/regular/push-pin.svg?component-solid';
@@ -270,10 +270,7 @@ export type CommandPreview = {
id: string;
icon?: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
name: string;
- hotkeys: ValidHotkey[];
- handler: (e: KeyboardEvent) => boolean;
- activateCommandScopeId?: string;
- tags?: string[];
+ command: HotkeyCommand;
};
export type ChannelPreview = {
@@ -392,9 +389,9 @@ export function useCommandItemAction(args: {
break;
}
case 'command': {
- if (item.data.activateCommandScopeId) {
+ if (item.data.command.activateCommandScopeId) {
const commandScopeCommands = getActiveCommandsFromScope(
- item.data.activateCommandScopeId,
+ item.data.command.activateCommandScopeId,
{
sortByScopeLevel: false,
hideShadowedCommands: false,
@@ -409,7 +406,7 @@ export function useCommandItemAction(args: {
setKonsoleOpen(false);
resetQuery();
resetKonsoleMode();
- runCommand({ keyDownHandler: item.data.handler });
+ runCommand(item.data.command);
break;
}
}
@@ -477,7 +474,7 @@ export function filterItemByCategory(item: CommandItemCard) {
currentKonsoleMode() === 'SELECTION_MODIFICATION' &&
item.type === 'command'
) {
- return item.data.tags?.includes(HotkeyTags.SelectionModification);
+ return item.data.command.tags?.includes(HotkeyTags.SelectionModification);
}
return false;
}
@@ -626,12 +623,12 @@ export function CommandItemCard(props: CommandItemProps) {
const CommandItemHotkey = () => {
if (props.item.type !== 'command') return null;
- if (props.item.data.hotkeys.length === 0) return null;
+ if (props.item.data.command.hotkeys?.length === 0) return null;
return (
<div class="pr-2 flex items-center justify-center text-[0.75rem] font-medium text-ink-extra-muted">
<div class="p-2 py-0.5 border border-edge-muted/50 rounded-xs">
<Hotkey
- shortcut={props.item.data.hotkeys.at(0)}
+ shortcut={props.item.data.command.hotkeys?.at(0)}
class="flex gap-1 items-center"
/>
</div>
diff --git a/js/app/packages/app/component/command/useCommandItems.ts b/js/app/packages/app/component/command/useCommandItems.ts
index bdd674e421..860c1866e9 100644
--- a/js/app/packages/app/component/command/useCommandItems.ts
+++ b/js/app/packages/app/component/command/useCommandItems.ts
@@ -46,10 +46,7 @@ export function useCommandItems() {
data: {
id: description.replaceAll(' ', '-'),
name: description,
- hotkeys: command.hotkeys ?? [],
- handler: command.keyDownHandler ?? (() => false),
- activateCommandScopeId: command.activateCommandScopeId,
- tags: command.tags ?? [],
+ command: command,
},
updatedAt: 0,
};
diff --git a/js/app/packages/app/component/dock/Dock.tsx b/js/app/packages/app/component/dock/Dock.tsx
index 79e9b45198..0d7f17c699 100644
--- a/js/app/packages/app/component/dock/Dock.tsx
+++ b/js/app/packages/app/component/dock/Dock.tsx
@@ -2,7 +2,6 @@ import { ENABLE_DOCK_NOTITIFCATIONS, ENABLE_JACK_IN } from '@core/constant/featu
import { GlobalNotificationBell } from '@core/component/GlobalNotificationBell';
import { createMemo, createSignal, onCleanup, onMount, Show } from 'solid-js';
import { isRightPanelOpen, useToggleRightPanel } from '@core/signal/layout';
-import { activeScope, hotkeyScopeTree } from '@core/hotkey/state';
import { useSettingsState } from '@core/constant/SettingsState';
import { useGlobalNotificationSource } from '../GlobalAppState';
import IconPower from '@phosphor-icons/core/regular/power.svg';
@@ -20,7 +19,7 @@ import IconGear from '@macro-icons/macro-gear.svg';
import IconLogo from '@macro-icons/macro-logo.svg';
import { BasicTierLimit } from './BasicTierLimit';
import { setKonsoleOpen } from '../command/state';
-import { runCommand } from '@core/hotkey/hotkeys';
+import { getActiveCommandByToken, runCommand } from '@core/hotkey/utils';
import { Hotkey } from '@core/component/Hotkey';
import { setCreateMenuOpen } from '../Launcher';
import { useHasPaidAccess } from '@core/auth';
@@ -49,24 +48,6 @@ export function Dock() {
return split.content().id === 'unified-list';
});
- // This method of opening the correct help drawer is disgusting,
- // but it works and doesn't require changing anything else.
- function activeSoupDrawerCommand() {
- const currentActiveScope = activeScope();
- if (!currentActiveScope) { return undefined };
- let activeScopeNode = hotkeyScopeTree.get(currentActiveScope);
- if (!activeScopeNode) { return undefined };
- if (activeScopeNode?.type !== 'dom') { return };
- const dom = activeScopeNode.element;
- const closestSplitScope = dom.closest('[data-hotkey-scope^="split"]');
- if (!closestSplitScope || !(closestSplitScope instanceof HTMLElement)) { return };
- const scopeId = closestSplitScope.dataset.hotkeyScope;
- if (!scopeId) { return undefined };
- const splitNode = hotkeyScopeTree.get(scopeId);
- if (!splitNode) { return undefined };
- return splitNode.hotkeyCommands.get('shift+/');
- };
-
async function enterPresentMode() {
try {
playSound('Stab_Destruct');
@@ -192,6 +173,7 @@ export function Dock() {
}}
onClick={() => { setKonsoleOpen(true) }}
class="dock-button-hover"
+ data-hotkey-token={TOKENS.global.commandMenu}
>
<IconLogo
style={{
@@ -230,6 +212,7 @@ export function Dock() {
}}
onClick={() => { setCreateMenuOpen(true) }}
class="dock-button-hover"
+ data-hotkey-token={TOKENS.global.createCommand}
>
<MacroCreateIcon
style={{
@@ -298,7 +281,7 @@ export function Dock() {
<IconButton
onClick={() => {
globalSplitManager()?.returnFocus();
- const showHelp = activeSoupDrawerCommand();
+ const showHelp = getActiveCommandByToken(TOKENS.split.showHelpDrawer);
if (!showHelp) { return };
runCommand(showHelp);
}}
@@ -320,7 +303,7 @@ export function Dock() {
}}
theme={isRightPanelCollapsed() ? 'clear' : 'accent'}
tooltip={{
- hotkeyToken: TOKENS.global.toggleRightPanel,
+ hotkeyToken: TOKENS.split.go.toggleRightPanel,
label: 'Toggle AI Panel',
}}
icon={IconAtom}
diff --git a/js/app/packages/app/component/settings/SettingsWrapper.tsx b/js/app/packages/app/component/settings/SettingsWrapper.tsx
index f8f28fea3d..f735248f72 100644
--- a/js/app/packages/app/component/settings/SettingsWrapper.tsx
+++ b/js/app/packages/app/component/settings/SettingsWrapper.tsx
@@ -1,25 +1,11 @@
import { Show } from 'solid-js';
import { Resize } from '@core/component/Resize';
-import { isSettingsPanelOpen, useToggleSettingsPanel } from '@core/signal/layout/settings';
+import { isSettingsPanelOpen } from '@core/signal/layout/settings';
import { useIsAuthenticated } from '@core/auth';
-import { registerHotkey } from 'core/hotkey/hotkeys';
import { SettingsPanel } from './Settings';
export const SettingsWrapper = () => {
const isAuthenticated = useIsAuthenticated();
- const toggleSettingsPanel = useToggleSettingsPanel();
-
- // Register escape hotkey to close settings
- registerHotkey({
- scopeId: 'settings',
- hotkey: 'escape',
- condition: () => Boolean(isSettingsPanelOpen()),
- description: 'Close settings',
- keyDownHandler: () => {
- toggleSettingsPanel(false);
- return true;
- },
- });
return (
<Show when={isAuthenticated()}>
diff --git a/js/app/packages/app/component/split-layout/SplitLayout.tsx b/js/app/packages/app/component/split-layout/SplitLayout.tsx
index 2c08309040..043c0ae229 100644
--- a/js/app/packages/app/component/split-layout/SplitLayout.tsx
+++ b/js/app/packages/app/component/split-layout/SplitLayout.tsx
@@ -1,11 +1,10 @@
import { useGlobalBlockOrchestrator } from '@app/component/GlobalAppState';
import { activeElement } from '@app/signal/focus';
import { Resize } from '@core/component/Resize';
-import { TOKENS } from '@core/hotkey/tokens';
import { tabTitleSignal } from '@core/signal/tabTitle';
import { createElementSize } from '@solid-primitives/resize-observer';
import { useNavigate } from '@solidjs/router';
-import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
+import { useHotkeyDOMScope } from 'core/hotkey/hotkeys';
import {
type Accessor,
createEffect,
@@ -25,6 +24,7 @@ import {
} from '../SoupContext';
import { SplitContainer } from './components/SplitContainer';
import { SplitLayoutContext, SplitPanelContext } from './context';
+import { useSplitLayout } from './layout';
import {
createSplitLayout,
type SplitContent,
@@ -36,6 +36,7 @@ import {
type SplitState,
} from './layoutManager';
import { decodePairs } from './layoutUtils';
+import { registerSplitHotkeys } from './registerSplitHotkeys';
type SplitLayoutContainerProps = {
pairs: string[];
@@ -44,7 +45,8 @@ type SplitLayoutContainerProps = {
function getParentSplitId(element: Element | null) {
if (!element || !element.isConnected) return null;
- const splitParent = element.closest('[data-split-container]');
+ // Checking the parent element here so that we don't get the split container itself.
+ const splitParent = element.parentElement?.closest('[data-split-container]');
if (!splitParent) return null;
const splitId = splitParent.getAttribute('data-split-id');
if (!splitId) return null;
@@ -134,7 +136,11 @@ function createSplitFocusTracker(props: {
}
// return if panel has a child already with focus.
- if (splitPanelRef.contains(document.activeElement)) return;
+ if (
+ splitPanelRef.contains(document.activeElement) &&
+ splitPanelRef !== document.activeElement
+ )
+ return;
// look for a child to return focus to.
const child = lastFocusedChildBySplitId.get(id);
@@ -284,20 +290,6 @@ export function SplitLayoutContainer(props: SplitLayoutContainerProps) {
onCleanup(() => props.setManager(undefined));
- registerHotkey({
- hotkeyToken: TOKENS.global.createNewSplit,
- hotkey: 'cmd+\\',
- scopeId: 'global',
- description: 'Create new split',
- keyDownHandler: () => {
- const canFit =
- splitManager.resizeContext()?.canFit({ minSize: 400 }) ?? true;
- if (canFit) splitManager.createNewSplit();
- return true;
- },
- runWithInputFocused: true,
- });
-
createEffect(() => {
setTabTitle(splitManager.tabTitle());
});
@@ -348,85 +340,34 @@ function SplitPanel(props: SplitPanelProps) {
const panelSize = createElementSize(panelRef);
const [contentOffsetTop, setContentOffsetTop] = createSignal(0);
- const splitName = createMemo(() => {
- const { type, id } = props.split.content;
- if (type === 'component') return id;
-
- return type;
- });
-
- registerHotkey({
- scopeId: splitHotkeyScope,
- hotkey: 'cmd+escape',
- description: `Close ${splitName()}`,
- keyDownHandler: () => {
- props.handle.close();
- return true;
- },
- runWithInputFocused: true,
- hotkeyToken: TOKENS.split.close,
- });
-
- registerHotkey({
- scopeId: splitHotkeyScope,
- hotkey: 'shift+escape',
- hotkeyToken: TOKENS.split.spotlight.toggle,
- description: `Spotlight ${splitName()}`,
- keyDownHandler: () => {
- props.handle.toggleSpotlight();
- return true;
- },
- runWithInputFocused: true,
- });
-
- registerHotkey({
- scopeId: splitHotkeyScope,
- hotkey: 'escape',
- hotkeyToken: TOKENS.split.spotlight.close,
- condition: () => props.handle.isSpotLight(),
- description: `Spotlight ${splitName()}`,
- keyDownHandler: () => {
- props.handle.toggleSpotlight();
- return true;
- },
- runWithInputFocused: true,
- });
-
- registerHotkey({
- scopeId: splitHotkeyScope,
- hotkey: 'opt+[',
- hotkeyToken: TOKENS.split.back,
- condition: () => props.handle.canGoBack(),
- description: `Go back in split`,
- keyDownHandler: () => {
- props.handle.goBack();
- return true;
- },
- runWithInputFocused: false,
- });
-
- registerHotkey({
- scopeId: splitHotkeyScope,
- hotkey: 'opt+]',
- hotkeyToken: TOKENS.split.forward,
- condition: () => props.handle.canGoForward(),
- description: `Go back in split`,
- keyDownHandler: () => {
- props.handle.goForward();
- return true;
- },
- runWithInputFocused: false,
- });
-
const unifiedListContext = createSoupContext();
const [previewState, setPreviewState] = createSignal(false);
+ const splitLayoutHelpers = useSplitLayout();
+ const { goScope } = registerSplitHotkeys({
+ splitHotkeyScope,
+ insertSplit: splitLayoutHelpers.insertSplit,
+ closeSplit: () => props.handle.close(),
+ toggleSpotlight: () => props.handle.toggleSpotlight(),
+ canGoBack: () => props.handle.canGoBack(),
+ goBack: () => props.handle.goBack(),
+ canGoForward: () => props.handle.canGoForward(),
+ goForward: () => props.handle.goForward(),
+ setSelectedView: (view) => unifiedListContext.setSelectedView(view),
+ replaceSplit: splitLayoutHelpers.replaceSplit,
+ splitName: () => props.handle.displayName(),
+ getSplitCount: () => splitLayoutHelpers.getSplitCount(),
+ isNotUnifiedList: () => {
+ const content = props.handle.content();
+ return !(content.type === 'component' && content.id === 'unified-list');
+ },
+ });
createNavigationEntityListShortcut({
- splitName,
splitHandle: props.handle,
splitHotkeyScope,
unifiedListContext,
+ goScopeId: goScope.commandScopeId,
previewState: [previewState, setPreviewState],
});
diff --git a/js/app/packages/app/component/split-layout/components/SplitHeader.tsx b/js/app/packages/app/component/split-layout/components/SplitHeader.tsx
index 8b3a996341..327c17be99 100644
--- a/js/app/packages/app/component/split-layout/components/SplitHeader.tsx
+++ b/js/app/packages/app/component/split-layout/components/SplitHeader.tsx
@@ -2,7 +2,6 @@ import EntityNavigationIndicator from '@app/component/EntityNavigationIndicator'
import { IconButton } from '@core/component/IconButton';
import { ENABLE_PREVIEW } from '@core/constant/featureFlags';
import { TOKENS } from '@core/hotkey/tokens';
-import { isRightPanelOpen, isSettingsPanelOpen } from '@core/signal/layout';
import CollapseIcon from '@icon/regular/arrows-in.svg';
import ExpandIcon from '@icon/regular/arrows-out.svg';
import CaretLeft from '@icon/regular/caret-left.svg';
@@ -20,6 +19,7 @@ import {
} from 'solid-js';
import { Portal } from 'solid-js/web';
import { SplitLayoutContext, SplitPanelContext } from '../context';
+import { canSpotlight } from '../utils/canSpotlight';
function SplitBackButton() {
const context = useContext(SplitPanelContext);
@@ -28,7 +28,7 @@ function SplitBackButton() {
<IconButton
size="sm"
icon={CaretLeft}
- tooltip={{ label: 'Go Back', hotkeyToken: TOKENS.split.back }}
+ tooltip={{ label: 'Go Back', hotkeyToken: TOKENS.split.go.back }}
disabled={!context.handle.canGoBack()}
theme="current"
onClick={context.handle.goBack}
@@ -43,7 +43,7 @@ function SplitForwardButton() {
<IconButton
size="sm"
icon={CaretRight}
- tooltip={{ label: 'Go Forward', hotkeyToken: TOKENS.split.forward }}
+ tooltip={{ label: 'Go Forward', hotkeyToken: TOKENS.split.go.forward }}
disabled={!context.handle.canGoForward()}
theme="current"
onClick={context.handle.goForward}
@@ -55,21 +55,14 @@ function SplitSpotlightButton() {
const context = useContext(SplitPanelContext);
const layout = useContext(SplitLayoutContext);
if (!context || !layout) return '';
- const show = () => {
- return (
- layout.manager.splits().length > 1 ||
- isSettingsPanelOpen() ||
- isRightPanelOpen()
- );
- };
return (
- <Show when={show()}>
+ <Show when={canSpotlight(layout.manager)}>
<IconButton
size="sm"
icon={context.handle.isSpotLight() ? CollapseIcon : ExpandIcon}
theme="current"
tooltip={{
- hotkeyToken: TOKENS.split.spotlight.toggle,
+ hotkeyToken: TOKENS.window.spotlight.toggle,
label: context.handle.isSpotLight()
? 'Minimize Split'
: 'Spotlight Split',
@@ -89,7 +82,7 @@ function SplitCloseButton() {
iconSize={16}
icon={CloseIcon}
theme="current"
- tooltip={{ label: 'Close', hotkeyToken: TOKENS.split.close }}
+ tooltip={{ label: 'Close', hotkeyToken: TOKENS.window.close }}
onClick={context.handle.close}
/>
);
diff --git a/js/app/packages/app/component/split-layout/components/SplitTabs.tsx b/js/app/packages/app/component/split-layout/components/SplitTabs.tsx
index 91087e4ba4..3a26dd697b 100644
--- a/js/app/packages/app/component/split-layout/components/SplitTabs.tsx
+++ b/js/app/packages/app/component/split-layout/components/SplitTabs.tsx
@@ -1,4 +1,5 @@
import { playSound } from '@app/util/sound';
+import { TOKENS } from '@core/hotkey/tokens';
import type { ViewId } from '@core/types/view';
import { Tabs } from '@kobalte/core';
import { createElementSize } from '@solid-primitives/resize-observer';
@@ -26,7 +27,7 @@ const SCROLL_THRESHOLD = 10;
export function SplitTabs(props: {
// values: readonly View[];
- list: { value: ViewId; label: string }[];
+ list: { value: ViewId; label: string; index: number }[];
active: Accessor<ViewId>;
setButtonsRef?: Setter<HTMLDivElement | null>;
newButton?: JSXElement;
@@ -135,7 +136,7 @@ export function SplitTabs(props: {
/>
<For each={props.list}>
- {({ value, label }, i) => {
+ {({ value, label, index }, i) => {
const isActive = createMemo(() => value === props.active());
let ref: HTMLDivElement | undefined;
@@ -168,6 +169,11 @@ export function SplitTabs(props: {
'text-ink-disabled hover:text-accent/70 hover-transition-text':
!isActive(),
}}
+ data-hotkey-token={
+ TOKENS.soup.tabs[
+ index.toString() as keyof typeof TOKENS.soup.tabs
+ ]
+ }
>
<span class="flex items-baseline gap-1 w-full">
<span class="text-xs font-mono opacity-70 mr-0.5">
diff --git a/js/app/packages/app/component/split-layout/layout.ts b/js/app/packages/app/component/split-layout/layout.ts
index 13d26d93e4..2400d1a3b7 100644
--- a/js/app/packages/app/component/split-layout/layout.ts
+++ b/js/app/packages/app/component/split-layout/layout.ts
@@ -67,10 +67,19 @@ export function useSplitLayout() {
splitPanelContext.handle.reset();
}
+ function getSplitCount() {
+ const splitManager = globalSplitManager();
+ if (!splitManager) {
+ return 0;
+ }
+ return splitManager.splits().length;
+ }
+
return {
replaceOrInsertSplit: replaceOrInsertSplit,
replaceSplit: replaceSplit,
insertSplit: insertSplit,
resetSplit: resetSplit,
+ getSplitCount: getSplitCount,
};
}
diff --git a/js/app/packages/app/component/split-layout/layoutUtils.ts b/js/app/packages/app/component/split-layout/layoutUtils.ts
index f069df2775..a136eb411b 100644
--- a/js/app/packages/app/component/split-layout/layoutUtils.ts
+++ b/js/app/packages/app/component/split-layout/layoutUtils.ts
@@ -1,3 +1,4 @@
+import { globalSplitManager } from '@app/signal/splitLayout';
import type { BlockAlias, BlockName } from '@core/block';
import { isBlockAlias, resolveBlockAlias } from '@core/constant/allBlocks';
import type { ViewId } from '@core/types/view';
@@ -100,6 +101,30 @@ export function globalRemoveFromSplitHistory(
}
}
+export function focusAdjacentSplit(direction: 'left' | 'right') {
+ const splitManager = globalSplitManager();
+ if (!splitManager) return;
+ const activeSplitId = splitManager.activeSplitId();
+ if (!activeSplitId) return;
+ const currentSplitIds = splitManager.splits().map((s) => s.id);
+ const currentSplitIndex = currentSplitIds.indexOf(activeSplitId);
+ const getAdjacentSplitId = () => {
+ if (direction === 'left') {
+ if (currentSplitIndex === 0)
+ return currentSplitIds[currentSplitIds.length - 1];
+ return currentSplitIds[currentSplitIndex - 1];
+ } else {
+ if (currentSplitIndex === currentSplitIds.length - 1)
+ return currentSplitIds[0];
+ return currentSplitIds[currentSplitIndex + 1];
+ }
+ };
+ const adjacentSplitId = getAdjacentSplitId();
+ if (!adjacentSplitId) return;
+ splitManager.activateSplit(adjacentSplitId);
+ splitManager.returnFocus();
+}
+
/**
* Check if there's a unified-list split with a particular view open.
*/
diff --git a/js/app/packages/app/component/split-layout/registerSplitHotkeys.ts b/js/app/packages/app/component/split-layout/registerSplitHotkeys.ts
new file mode 100644
index 0000000000..cf8d6f8076
--- /dev/null
+++ b/js/app/packages/app/component/split-layout/registerSplitHotkeys.ts
@@ -0,0 +1,249 @@
+import { TOKENS } from '@core/hotkey/tokens';
+import {
+ isRightPanelOpen,
+ useBigChat,
+ useToggleRightPanel,
+} from '@core/signal/layout';
+import type { ViewId } from '@core/types/view';
+import { registerHotkey } from 'core/hotkey/hotkeys';
+import { globalSplitManager } from '../../signal/splitLayout';
+import { fireMacroJump } from '../MacroJump';
+import type { SplitContent } from './layoutManager';
+import { focusAdjacentSplit } from './layoutUtils';
+import { canSpotlight } from './utils/canSpotlight';
+
+export function registerSplitHotkeys({
+ splitHotkeyScope,
+ insertSplit,
+ closeSplit,
+ toggleSpotlight,
+ canGoBack,
+ goBack,
+ canGoForward,
+ goForward,
+ setSelectedView,
+ replaceSplit,
+ splitName,
+ getSplitCount,
+ isNotUnifiedList,
+}: {
+ splitHotkeyScope: string;
+ insertSplit: (content: SplitContent) => void;
+ closeSplit: () => void;
+ toggleSpotlight: () => void;
+ canGoBack: () => boolean;
+ goBack: () => void;
+ canGoForward: () => boolean;
+ goForward: () => void;
+ setSelectedView: (view: ViewId) => void;
+ replaceSplit: (content: SplitContent) => void;
+ splitName: () => string;
+ getSplitCount: () => number;
+ isNotUnifiedList: () => boolean;
+}) {
+ const splitManager = globalSplitManager();
+ const canFit = () =>
+ splitManager?.resizeContext()?.canFit({ minSize: 400 }) ?? true;
+
+ const windowScope = registerHotkey({
+ scopeId: splitHotkeyScope,
+ hotkey: 'w',
+ description: 'Window',
+ keyDownHandler: () => {
+ return true;
+ },
+ activateCommandScope: true,
+ });
+
+ registerHotkey({
+ hotkeyToken: TOKENS.window.createNewSplit,
+ hotkey: '\\',
+ scopeId: windowScope.commandScopeId,
+ description: 'Create new split',
+ condition: canFit,
+ keyDownHandler: () => {
+ insertSplit({ type: 'component', id: 'unified-list' });
+ return true;
+ },
+ });
+
+ registerHotkey({
+ scopeId: windowScope.commandScopeId,
+ hotkey: 'w',
+ condition: () => getSplitCount() > 1,
+ description: `Close split`,
+ keyDownHandler: () => {
+ closeSplit();
+ return true;
+ },
+ hotkeyToken: TOKENS.window.close,
+ });
+
+ registerHotkey({
+ scopeId: splitHotkeyScope,
+ hotkey: 'cmd+escape',
+ condition: () => getSplitCount() > 1,
+ description: `Close split`,
+ keyDownHandler: () => {
+ closeSplit();
+ return true;
+ },
+ hotkeyToken: TOKENS.split.close,
+ });
+
+ registerHotkey({
+ scopeId: windowScope.commandScopeId,
+ hotkey: 'm',
+ hotkeyToken: TOKENS.window.spotlight.toggle,
+ description: () => `Maximize ${splitName()}`,
+ condition: () => {
+ if (!splitManager) return false;
+ return canSpotlight(splitManager);
+ },
+ keyDownHandler: () => {
+ toggleSpotlight();
+ return true;
+ },
+ runWithInputFocused: true,
+ });
+
+ const goScope = registerHotkey({
+ scopeId: splitHotkeyScope,
+ hotkey: 'g',
+ description: 'Go',
+ keyDownHandler: () => {
+ return true;
+ },
+ activateCommandScope: true,
+ hotkeyToken: TOKENS.split.goCommand,
+ displayPriority: 10,
+ });
+
+ const goScopeId = goScope.commandScopeId;
+
+ registerHotkey({
+ scopeId: goScopeId,
+ hotkey: '[',
+ hotkeyToken: TOKENS.split.go.back,
+ condition: () => canGoBack(),
+ description: `Go back`,
+ keyDownHandler: () => {
+ goBack();
+ return true;
+ },
+ });
+
+ registerHotkey({
+ scopeId: goScopeId,
+ hotkey: ']',
+ hotkeyToken: TOKENS.split.go.forward,
+ condition: () => canGoForward(),
+ description: `Go forward`,
+ keyDownHandler: () => {
+ goForward();
+ return true;
+ },
+ });
+
+ registerHotkey({
+ scopeId: goScopeId,
+ hotkey: 'h',
+ description: 'Go home',
+ keyDownHandler: () => {
+ replaceSplit({ type: 'component', id: 'unified-list' });
+ return true;
+ },
+ hotkeyToken: TOKENS.split.go.home,
+ });
+
+ registerHotkey({
+ scopeId: splitHotkeyScope,
+ hotkey: 'h',
+ description: 'Go home',
+ condition: isNotUnifiedList,
+ keyDownHandler: () => {
+ replaceSplit({ type: 'component', id: 'unified-list' });
+ return true;
+ },
+ hotkeyToken: TOKENS.split.goHome,
+ displayPriority: 8,
+ });
+
+ registerHotkey({
+ scopeId: goScopeId,
+ hotkey: 'e',
+ description: 'Go to email',
+ keyDownHandler: () => {
+ replaceSplit({ type: 'component', id: 'unified-list' });
+ setSelectedView('email');
+ return true;
+ },
+ hotkeyToken: TOKENS.split.go.email,
+ });
+
+ registerHotkey({
+ scopeId: goScopeId,
+ hotkey: 's',
+ description: 'Go to signal',
+ keyDownHandler: () => {
+ replaceSplit({ type: 'component', id: 'unified-list' });
+ setSelectedView('signal');
+ return true;
+ },
+ hotkeyToken: TOKENS.split.go.inbox,
+ });
+
+ registerHotkey({
+ hotkeyToken: TOKENS.window.focusSplitRight,
+ hotkey: ['arrowright', 'tab', 'l'],
+ scopeId: windowScope.commandScopeId,
+ description: 'Focus split right',
+ keyDownHandler: () => {
+ focusAdjacentSplit('right');
+ return true;
+ },
+ });
+
+ registerHotkey({
+ hotkeyToken: TOKENS.window.focusSplitLeft,
+ hotkey: ['arrowleft', 'shift+tab', 'h'],
+ scopeId: windowScope.commandScopeId,
+ description: 'Focus split left',
+ keyDownHandler: () => {
+ focusAdjacentSplit('left');
+ return true;
+ },
+ });
+
+ const [bigChatOpen, _] = useBigChat();
+ const toggleRightPanel = useToggleRightPanel();
+
+ registerHotkey({
+ hotkeyToken: TOKENS.split.go.toggleRightPanel,
+ hotkey: 'r',
+ scopeId: goScopeId,
+ description: () => {
+ return isRightPanelOpen() ? 'Close AI panel' : 'Open AI panel';
+ },
+ keyDownHandler: () => {
+ toggleRightPanel();
+ return true;
+ },
+ condition: () => {
+ return !bigChatOpen();
+ },
+ });
+
+ registerHotkey({
+ hotkeyToken: TOKENS.split.go.macroJump,
+ hotkey: 'j',
+ scopeId: goScopeId,
+ description: 'Macro Jump',
+ keyDownHandler: () => {
+ fireMacroJump();
+ return true;
+ },
+ });
+
+ return { windowScope, goScope };
+}
diff --git a/js/app/packages/app/component/split-layout/utils/canSpotlight.ts b/js/app/packages/app/component/split-layout/utils/canSpotlight.ts
new file mode 100644
index 0000000000..6a80ec2f1b
--- /dev/null
+++ b/js/app/packages/app/component/split-layout/utils/canSpotlight.ts
@@ -0,0 +1,10 @@
+import { isRightPanelOpen, isSettingsPanelOpen } from '@core/signal/layout';
+import type { SplitManager } from '../layoutManager';
+
+export function canSpotlight(splitManager: SplitManager) {
+ return (
+ splitManager.splits().length > 1 ||
+ isSettingsPanelOpen() ||
+ isRightPanelOpen()
+ );
+}
diff --git a/js/app/packages/app/component/useNavigatedFromJK.ts b/js/app/packages/app/component/useNavigatedFromJK.ts
index b40bd2f8e0..4898d3e8d8 100644
--- a/js/app/packages/app/component/useNavigatedFromJK.ts
+++ b/js/app/packages/app/component/useNavigatedFromJK.ts
@@ -1,3 +1,5 @@
+import { lastExecutedCommand } from '@core/hotkey/state';
+import { TOKENS } from '@core/hotkey/tokens';
import { createMemo } from 'solid-js';
import { useSplitPanelOrThrow } from './split-layout/layoutUtils';
@@ -12,7 +14,9 @@ export function useNavigatedFromJK() {
if (!entities) return false;
return (
entities.length > 0 &&
- document.documentElement.getAttribute('data-modality') === 'keyboard'
+ document.documentElement.getAttribute('data-modality') === 'keyboard' &&
+ (lastExecutedCommand()?.hotkeyToken === TOKENS.entity.step.end ||
+ lastExecutedCommand()?.hotkeyToken === TOKENS.entity.select.end)
);
});
return { navigatedFromJK };
diff --git a/js/app/packages/app/signal/hotkeyRoot.ts b/js/app/packages/app/signal/hotkeyRoot.ts
new file mode 100644
index 0000000000..a20a47ac75
--- /dev/null
+++ b/js/app/packages/app/signal/hotkeyRoot.ts
@@ -0,0 +1,21 @@
+import type { useHotKeyRoot } from '@core/hotkey/hotkeys';
+import type { KeypressContext } from '@core/hotkey/types';
+import { createSignal, onCleanup, onMount } from 'solid-js';
+
+export const [hotkeyRoot, setHotkeyRoot] =
+ createSignal<ReturnType<typeof useHotKeyRoot>>();
+
+/**
+ * Subscribe to keypress events. Automatically cleans up on unmount.
+ */
+export function useSubscribeToKeypress(
+ callback: (context: KeypressContext) => void
+) {
+ onMount(() => {
+ const root = hotkeyRoot();
+ if (!root) return;
+
+ const cleanup = root.subscribeToKeypress(callback);
+ onCleanup(cleanup);
+ });
+}
diff --git a/js/app/packages/app/util/getClippedOverlayRect.ts b/js/app/packages/app/util/getClippedOverlayRect.ts
new file mode 100644
index 0000000000..0513569f4c
--- /dev/null
+++ b/js/app/packages/app/util/getClippedOverlayRect.ts
@@ -0,0 +1,55 @@
+export function getClippedOverlayRect(
+ targetEl: HTMLElement,
+ targetElScrollParent: HTMLElement | null
+) {
+ const targetRect = targetEl.getBoundingClientRect();
+ if (!targetElScrollParent) {
+ return {
+ rect: {
+ left: targetRect.left,
+ top: targetRect.top,
+ right: targetRect.right,
+ bottom: targetRect.bottom,
+ width: targetRect.width,
+ height: targetRect.height,
+ },
+ isClippedLeft: false,
+ isClippedRight: false,
+ isClippedTop: false,
+ isClippedBottom: false,
+ isFullyClipped: false,
+ isPartiallyClipped: false,
+ };
+ }
+ const scrollParentRect = targetElScrollParent.getBoundingClientRect();
+
+ // Calculate clipping edges
+ const clippedLeft = Math.max(targetRect.left, scrollParentRect.left);
+ const clippedTop = Math.max(targetRect.top, scrollParentRect.top);
+ const clippedRight = Math.min(targetRect.right, scrollParentRect.right);
+ const clippedBottom = Math.min(targetRect.bottom, scrollParentRect.bottom);
+
+ const clippedWidth = Math.max(0, clippedRight - clippedLeft);
+ const clippedHeight = Math.max(0, clippedBottom - clippedTop);
+
+ return {
+ rect: {
+ left: clippedLeft,
+ top: clippedTop,
+ width: clippedWidth,
+ height: clippedHeight,
+ right: clippedLeft + clippedWidth,
+ bottom: clippedTop + clippedHeight,
+ },
+ isClippedLeft: clippedLeft > targetRect.left,
+ isClippedRight: clippedRight < targetRect.right,
+ isClippedTop: clippedTop > targetRect.top,
+ isClippedBottom: clippedBottom < targetRect.bottom,
+ isFullyClipped: clippedWidth === 0 || clippedHeight === 0,
+ isPartiallyClipped:
+ clippedLeft > targetRect.left ||
+ clippedRight < targetRect.right ||
+ clippedTop > targetRect.top ||
+ clippedBottom < targetRect.bottom,
+ };
+}
diff --git a/js/app/packages/app/util/getScrollElementParent.ts b/js/app/packages/app/util/getScrollElementParent.ts
new file mode 100644
index 0000000000..00076f5056
--- /dev/null
+++ b/js/app/packages/app/util/getScrollElementParent.ts
@@ -0,0 +1,24 @@
+function matchScroll(str: string) {
+ return str.match(/auto|scroll/);
+}
+
+export const getScrollElementParent = (
+ el: HTMLElement | null
+): HTMLElement | null => {
+ if (!el) {
+ return null;
+ }
+
+ const style = getComputedStyle(el);
+
+ const hasScrollableOverflow =
+ matchScroll(style.overflow) ||
+ matchScroll(style.overflowY) ||
+ matchScroll(style.overflowX);
+
+ if (hasScrollableOverflow && el.clientHeight !== el.scrollHeight) {
+ return el;
+ }
+
+ return getScrollElementParent(el.parentElement);
+};
diff --git a/js/app/packages/core/component/AI/component/input/useChatMarkdownArea.tsx b/js/app/packages/core/component/AI/component/input/useChatMarkdownArea.tsx
index 3a59414dfa..277320ee3b 100644
--- a/js/app/packages/core/component/AI/component/input/useChatMarkdownArea.tsx
+++ b/js/app/packages/core/component/AI/component/input/useChatMarkdownArea.tsx
@@ -44,8 +44,8 @@ import {
import type { PortalScope } from '@core/component/ScopedPortal';
import { shortcutBadgeStyles } from '@core/component/Themes';
import { toast } from '@core/component/Toast/Toast';
-import { useTokenToHotkeyString } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
+import { getPrettyHotkeyStringByToken } from '@core/hotkey/utils';
import { isMobileWidth } from '@core/mobile/mobileWidth';
import type { IOrganizationUser } from '@core/user';
import { handleFileFolderDrop } from '@core/util/upload';
@@ -261,7 +261,7 @@ function MarkdownArea(
// });
// });
- const focusShortcut = useTokenToHotkeyString(TOKENS.chat.input.focus);
+ const focusShortcut = getPrettyHotkeyStringByToken(TOKENS.chat.input.focus);
createEffect(
on(props.mountRef, (ref) => {
@@ -433,7 +433,7 @@ function MarkdownArea(
<span
class={`rounded-md px-1.5 py-0.5 space-x-1 ${shortcutBadgeStyles['muted']}`}
>
- {focusShortcut()}
+ {focusShortcut}
</span>{' '}
to chat with AI
</p>
diff --git a/js/app/packages/core/component/Hotkey.tsx b/js/app/packages/core/component/Hotkey.tsx
index 7657d68a2c..8af52885f7 100644
--- a/js/app/packages/core/component/Hotkey.tsx
+++ b/js/app/packages/core/component/Hotkey.tsx
@@ -1,6 +1,6 @@
import { IS_MAC } from '@core/constant/isMac';
-import { useTokenToHotkeyString } from '@core/hotkey/hotkeys';
import type { HotkeyToken } from '@core/hotkey/tokens';
+import { getPrettyHotkeyStringByToken } from '@core/hotkey/utils';
import { createMemo, For, type JSX, Show, splitProps } from 'solid-js';
import type { Theme } from './Themes';
@@ -84,7 +84,9 @@ export const hotkeyStyles: Record<Theme, { label: string; hotkey: string }> = {
};
const getSymbol = (key: string) =>
- key in symbolMap ? symbolMap[key as keyof typeof symbolMap] : key;
+ key.toUpperCase() in symbolMap
+ ? symbolMap[key.toUpperCase() as keyof typeof symbolMap]
+ : key;
const modifierKeys = Object.keys(modifierMap);
@@ -123,19 +125,18 @@ export const Hotkey = (props: HotkeyProps) => {
'lowercase',
]);
const tokenShortcut = local.token
- ? useTokenToHotkeyString(local.token)
- : () => undefined;
+ ? getPrettyHotkeyStringByToken(local.token)
+ : undefined;
const hotkey = createMemo(() => {
- const tokenShortcut_ = tokenShortcut();
// fallback for when we specify a shortcut directly instead of a hotkey token
- if (local.shortcut && !tokenShortcut_) {
+ if (local.shortcut && !tokenShortcut) {
return breakApartHotkeyString(local.shortcut);
}
- if (!tokenShortcut_) {
+ if (!tokenShortcut) {
return { key: '', modifiers: [] };
}
- return breakApartHotkeyString(tokenShortcut_);
+ return breakApartHotkeyString(tokenShortcut);
});
const normalizedKey = () => {
diff --git a/js/app/packages/core/component/IconButton.tsx b/js/app/packages/core/component/IconButton.tsx
index 895915075c..93dca73050 100644
--- a/js/app/packages/core/component/IconButton.tsx
+++ b/js/app/packages/core/component/IconButton.tsx
@@ -1,4 +1,3 @@
-import { useTokenToHotkeyString } from '@core/hotkey/hotkeys';
import type { HotkeyToken } from '@core/hotkey/tokens';
import { isMobileWidth } from '@core/mobile/mobileWidth';
import { onKeyDownClick, onKeyUpClick } from '@core/util/click';
@@ -121,20 +120,7 @@ export function IconButton(props: IconButtonProps) {
return <>{props.children}</>;
};
- const primaryHotkey = createMemo(() => {
- const tips = tooltips();
- if (!tips) return undefined;
- if (tips[0]?.hotkeyToken) {
- const hotkey = useTokenToHotkeyString(tips[0].hotkeyToken);
- if (hotkey()) {
- return hotkey();
- }
- }
- if (tips[0]?.shortcut) {
- return <BasicHotkey shortcut={tips[0].shortcut} />;
- }
- return undefined;
- });
+ const primaryHotkeyToken = () => tooltips()?.[0]?.hotkeyToken;
const sizeClasses = createMemo(() => {
switch (local.size ?? 'base') {
@@ -175,6 +161,7 @@ export function IconButton(props: IconButtonProps) {
onTouchEnd={local.onTouchEnd}
data-index={local.index}
tabIndex={local.tabIndex}
+ data-hotkey-token={primaryHotkeyToken()}
>
<div
class="flex justify-start items-center"
@@ -197,14 +184,14 @@ export function IconButton(props: IconButtonProps) {
<CaretDown class="flex w-3 h-3" />
</div>
</Show>
- <Show when={props.showShortcut && primaryHotkey()}>
- {(key) => {
+ <Show when={props.showShortcut && primaryHotkeyToken()}>
+ {(token) => {
return (
<div
class="absolute bottom-[-0.5px] right-[-0.5px] text-[7.5px] uppercase pointer-events-none font-semibold"
classList={{ invisible: isMobileWidth() }}
>
- {key()}
+ <BasicHotkey token={token()} />
</div>
);
}}
diff --git a/js/app/packages/core/component/TextButton.tsx b/js/app/packages/core/component/TextButton.tsx
index 6f1504b69a..67379d8b58 100644
--- a/js/app/packages/core/component/TextButton.tsx
+++ b/js/app/packages/core/component/TextButton.tsx
@@ -151,6 +151,7 @@ export function TextButton(props: TextButtonProps) {
}}
tabIndex={props.tabIndex}
ref={props.buttonRef}
+ data-hotkey-token={props.tooltip?.hotkeyToken}
>
{props.icon && (
<div class="flex justify-start items-center h-full">
diff --git a/js/app/packages/core/hotkey/getCommands.ts b/js/app/packages/core/hotkey/getCommands.ts
index 739f874b73..716bcd6468 100644
--- a/js/app/packages/core/hotkey/getCommands.ts
+++ b/js/app/packages/core/hotkey/getCommands.ts
@@ -63,9 +63,6 @@ export function getActiveCommandsFromScope(
);
scopeLevel++;
}
- if (displayOptions.hideShadowedCommands) {
- commands.filter((command) => !command.hotkeyIsShadowed);
- }
commands.sort((a, b) => {
if (displayOptions.sortByScopeLevel) {
if (a.scopeLevel !== b.scopeLevel) {
@@ -75,17 +72,21 @@ export function getActiveCommandsFromScope(
}
return (b.displayPriority ?? 0) - (a.displayPriority ?? 0);
});
- return commands;
+ return displayOptions.hideShadowedCommands
+ ? commands.filter((command) => !command.hotkeyIsShadowed)
+ : commands;
}
const filterCommands = (displayOptions: sortAndFilterOptions) => {
return (command: HotkeyCommand) => {
+ const hideValue =
+ typeof command.hide === 'function' ? command.hide() : command.hide;
return (
(command.hotkeys || !displayOptions.hideCommandsWithoutHotkeys) &&
(!command.condition || command.condition()) &&
(!isEditableInput(activeElement() as HTMLElement) ||
command.runWithInputFocused) &&
- command.hide !== true
+ hideValue !== true
);
};
};
diff --git a/js/app/packages/core/hotkey/hotkeys.ts b/js/app/packages/core/hotkey/hotkeys.ts
index ee861b3269..5ced8fea96 100644
--- a/js/app/packages/core/hotkey/hotkeys.ts
+++ b/js/app/packages/core/hotkey/hotkeys.ts
@@ -4,7 +4,7 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { isMobileWidth } from '@core/mobile/mobileWidth';
import { isEditableInput } from '@core/util/isEditableInput';
import { logger } from '@observability';
-import { createMemo, onCleanup, onMount, untrack } from 'solid-js';
+import { onCleanup, onMount, untrack } from 'solid-js';
import {
EVENT_MODIFIER_KEYS,
EVENT_MODIFIER_NAME_MAP,
@@ -20,18 +20,16 @@ import {
hotkeyTokenMap,
pressedKeys,
setActiveScope,
- setExecutedTokens,
setHotkeyTokenMap,
setPressedKeys,
} from './state';
-import type { HotkeyToken } from './tokens';
import {
type HotkeyCommand,
type HotkeyRegistrationOptions,
isBaseKeyboardValue,
+ type KeypressContext,
type RegisterHotkeyReturn,
type ScopeNode,
- type ValidHotkey,
} from './types';
import {
activateClosestDOMScope,
@@ -40,9 +38,9 @@ import {
getKeyString,
getScopeId,
normalizeEventKeyPress,
- prettyPrintHotkeyString,
registerScope,
removeScope,
+ runCommand,
} from './utils';
/**
@@ -65,7 +63,7 @@ import {
* that displays based on this condition will be reactively updated.
* @param args.scopeId - The scopeId where this hotkey is active.
* @param args.description - Human readable description of what the hotkey
- * does. Keep it short (around three words).
+ * does. Keep it short (around three words). Can be either a string or a callback that returns a string.
* @param args.keyDownHandler - Function called when the hotkey is pressed. If
* it returns true, the event will prevent default and stop propagation.
* @param args.keyUpHandler - Optional function called when the hotkey is
@@ -79,7 +77,8 @@ import {
* @param args.displayPriority - The priority of the command for ordering
* hotkey display UI. 1 is the lowest priority, 10 is the highest.
* @param args.hide - If true, hotkey command can be hidden from the UI. It
- * will still run, but may not be displayed.
+ * will still run, but may not be displayed. Can be either a boolean or a
+ * function that returns a boolean for reactive behavior.
* @param args.icon - Optional icon to display in the command palette.
* @param args.tags - Optional tags for categorizing in the command palette.
* @returns An object with a dispose function to clean up the hotkey
@@ -142,18 +141,17 @@ export function registerHotkey(
// Convert single hotkey to array for consistent handling
const hotkeys = hotkey && !Array.isArray(hotkey) ? [hotkey] : hotkey;
- // Check for duplicate hotkeyToken
+ // Check for existing duplicate hotkeyToken for non-identical command
const existingCommand = hotkeyToken
- ? untrack(() => hotkeyTokenMap().get(hotkeyToken))
+ ? untrack(() => hotkeyTokenMap().get(hotkeyToken)?.at(0))
: undefined;
- if (existingCommand) {
- const existingHotkeys = new Set(existingCommand.hotkeys);
- const newHotkeys = new Set(hotkeys);
-
- // We don't warn if all of the existing hotkeys are in the new hotkeys, on the assumption that the developer has a good reason for specifying "the same" hotkey in multiple places.
+ if (existingCommand && hotkeys && existingCommand.hotkeys) {
+ // Yes, you should be able to register multiple hotkeys with the same token. But if you do this, they should be "the same" hotkey.
+ // Here we check if the existing hotkey strings are the same as the new hotkey strings. This probably isn't exactly what you'd want to check (it especially won't be right if the commmands do not have hotkey strings), but is close enough for now.
+ const existingHotkeys = existingCommand.hotkeys;
if (
- existingHotkeys.size !== newHotkeys.size ||
- ![...existingHotkeys].every((h) => newHotkeys.has(h))
+ existingHotkeys.length !== hotkeys?.length ||
+ !existingHotkeys.every((el, i) => el === hotkeys[i])
) {
logger.log(
`Hotkey token "${hotkeyToken}" is already registered with a different command. ` +
@@ -172,15 +170,18 @@ export function registerHotkey(
let commandScopeId: string | undefined;
if (activateCommandScope) {
commandScopeId = getScopeId('command-scope-' + scopeId);
+ // When a command scope is registered, its parent scope is set as the scopeId of the registered hotkey. It will be registered as a child of that scope. When the command scope is activated, its parent scope will get set to whatever scope is active where it was called, so that when the command scope is deactivated, it willl return to the correct scope.
registerScope({
parentScopeId: scopeId,
scopeId: commandScopeId,
type: 'command',
+ activationKeys: hotkeys,
});
}
const command: HotkeyCommand = {
hotkeyToken,
+ scopeId,
hotkeys,
condition,
description,
@@ -207,10 +208,11 @@ export function registerHotkey(
}
});
- if (hotkeyToken && !existingCommand) {
+ if (hotkeyToken) {
setHotkeyTokenMap((prev) => {
const newMap = new Map(prev);
- newMap.set(hotkeyToken, command);
+ const existingCommands = newMap.get(hotkeyToken) || [];
+ newMap.set(hotkeyToken, [...existingCommands, command]);
return newMap;
});
}
@@ -233,7 +235,15 @@ export function registerHotkey(
if (hotkeyToken) {
setHotkeyTokenMap((prev) => {
const newMap = new Map(prev);
- newMap.delete(hotkeyToken);
+ const existingCommands = newMap.get(hotkeyToken) || [];
+ const newCommands = existingCommands.filter(
+ (c) => c.scopeId !== scopeId
+ );
+ if (newCommands.length > 0) {
+ newMap.set(hotkeyToken, newCommands);
+ } else {
+ newMap.delete(hotkeyToken);
+ }
return newMap;
});
}
@@ -320,7 +330,7 @@ export function useHotkeyDOMScope(
const repairScopeBranch = (scopeNode: ScopeNode, scopeDOM: Element) => {
let currentScope = scopeNode;
let currentDOM: Element | null | undefined = scopeDOM;
- while (currentScope.id !== 'global' && currentDOM) {
+ while (currentScope.scopeId !== 'global' && currentDOM) {
// If the scope is detached, we can stop.
if (currentScope.detached) {
break;
@@ -328,7 +338,7 @@ export function useHotkeyDOMScope(
const parentScopeId = findClosestParentScopeId(currentDOM);
const parentScope = hotkeyScopeTree.get(parentScopeId);
if (!parentScope) break;
- parentScope.childScopeIds.push(currentScope.id);
+ parentScope.childScopeIds.push(currentScope.scopeId);
if (currentScope.type === 'dom') {
currentScope.parentScopeId = parentScopeId;
}
@@ -407,11 +417,17 @@ export function attachGlobalDOMScope(el: Element) {
});
}
+/**
+ * Attaches global hotkey handlers to the document element.
+ * @returns A function to subscribe to keypress events with full context information.
+ */
export function useHotKeyRoot() {
if (isNativeMobilePlatform() || (isMobileWidth() && isTouchDevice)) {
return;
}
+ let onKeypress: ((context: KeypressContext) => void)[] = [];
+
const handleKeyDown = (e: KeyboardEvent) => {
document.documentElement.dataset.modality = 'keyboard';
const key = normalizeEventKeyPress(e);
@@ -504,66 +520,20 @@ export function useHotKeyRoot() {
const pressedKeysString = getKeyString(currentPressedKeys);
let scopeNode = scopeTree.get(currentScopeId);
- let transitionOrCommandFound = false;
+ let commandCaptured: HotkeyCommand | undefined;
+ let commandScopeActivated = false;
while (scopeNode) {
const command = scopeNode.hotkeyCommands.get(pressedKeysString);
- if (
- command &&
- (command.runWithInputFocused || !isEditableFocused) &&
- (!command.condition || command.condition())
- ) {
- if (command.activateCommandScopeId) {
- const newScope = hotkeyScopeTree.get(command.activateCommandScopeId);
- if (newScope) {
- setPressedKeys(new Set<string>());
- setActiveScope(newScope.id);
- if (!transitionOrCommandFound) {
- setExecutedTokens((prev) => {
- if (command.hotkeyToken) {
- return prev.includes(command.hotkeyToken)
- ? prev
- : [...prev, command.hotkeyToken];
- }
- return prev;
- });
- }
- transitionOrCommandFound = true;
- e.preventDefault();
- e.stopPropagation();
- }
- }
- const captured = command.keyDownHandler?.(e);
- if (captured) {
- setPressedKeys(new Set<string>());
- if (!transitionOrCommandFound) {
- setExecutedTokens((prev) => {
- if (command.hotkeyToken) {
- return prev.includes(command.hotkeyToken)
- ? prev
- : [...prev, command.hotkeyToken];
- }
- return prev;
- });
- }
- transitionOrCommandFound = true;
- e.preventDefault();
- e.stopPropagation();
- }
-
- if (
- command.keyUpHandler &&
- e.type === 'keydown' &&
- !hotkeysAwaitingKeyUp.some(
- (h) => h.hotkey === pressedKeysString && h.scopeId === scopeNode?.id
- )
- ) {
- hotkeysAwaitingKeyUp.push({
- hotkey: pressedKeysString as ValidHotkey,
- scopeId: scopeNode.id,
- command: () => command.keyUpHandler?.(e),
- });
- }
+ if (command && (command.runWithInputFocused || !isEditableFocused)) {
+ const result = runCommand(
+ command,
+ e,
+ pressedKeysString,
+ scopeNode.scopeId
+ );
+ commandCaptured = result.commandCaptured;
+ commandScopeActivated = result.commandScopeActivated;
}
if (
@@ -576,7 +546,7 @@ export function useHotKeyRoot() {
activateClosestDOMScope();
}
- if (transitionOrCommandFound) {
+ if (commandCaptured || commandScopeActivated) {
break;
}
@@ -598,65 +568,57 @@ export function useHotKeyRoot() {
}
});
}
- };
-}
-
-// Runs the given hotkey command.
-export function runCommand({
- keyDownHandler,
- activateCommandScopeId,
-}: {
- keyDownHandler?: (e?: KeyboardEvent) => boolean;
- activateCommandScopeId?: string;
-}) {
- if (keyDownHandler) {
- keyDownHandler();
- }
- if (activateCommandScopeId) {
- const newScope = hotkeyScopeTree.get(activateCommandScopeId);
- if (newScope) {
- setActiveScope(newScope.id);
- }
- }
-}
-
-export function runCommandByToken(token: HotkeyToken) {
- const command = useHotkeyCommandByToken(token)();
- if (command) {
- if (command.keyDownHandler) {
- command.keyDownHandler();
- }
- if (command.activateCommandScopeId) {
- const newScope = hotkeyScopeTree.get(command.activateCommandScopeId);
- if (newScope) {
- setActiveScope(newScope.id);
- }
- }
- }
-}
-/**
- * Returns the hotkey command for a given hotkey token.
- * @param token - The hotkey token to look up.
- * @returns The hotkey command, or undefined if the token is not found.
- */
-export function useHotkeyCommandByToken(token: HotkeyToken) {
- return createMemo(() => {
- if (!token) return undefined;
- const map = hotkeyTokenMap();
- const command = map.get(token);
- return command;
- });
-}
+ // Build context object with all relevant information
+ const context: KeypressContext = {
+ pressedKeysString,
+ pressedKeys: currentPressedKeys,
+ event: e,
+ activeScopeId: currentScopeId ?? null,
+ isEditableFocused: isEditableFocused ?? false,
+ commandScopeActivated,
+ commandFound: !!commandCaptured,
+ commandCaptured: commandCaptured,
+ eventType: e.type as 'keydown' | 'keyup',
+ isNonModifierKeypress: ![...currentPressedKeys].every((key) =>
+ ['cmd', 'ctrl', 'opt', 'shift'].includes(key)
+ ),
+ };
+
+ // Notify all subscribers with the context
+ onKeypress.forEach((callback) => callback(context));
+ };
-// Helper function to get the first hotkey for display purposes
-export function useTokenToHotkeyString(token: HotkeyToken) {
- return createMemo(() => {
- if (!token) return undefined;
- const map = hotkeyTokenMap();
- const command = map.get(token);
- return prettyPrintHotkeyString(command?.hotkeys?.[0]);
- });
+ return {
+ /**
+ * Subscribe to keypress events with full context information.
+ * Subscribers receive a context object containing all relevant information.
+ *
+ * @param callback - Function called on every keypress.
+ * @returns A cleanup function to unsubscribe from the keypress events.
+ *
+ * @example
+ * ```ts
+ * subscribeToKeypress((context) => {
+ * // Only handle non-modifier keys without scope activation
+ * if (
+ * !context.commandScopeActivated &&
+ * ![...context.pressedKeys].every((key) =>
+ * ['cmd', 'ctrl', 'opt', 'shift'].includes(key)
+ * )
+ * ) {
+ * // Handle the keypress
+ * }
+ * });
+ * ```
+ */
+ subscribeToKeypress: (callback: (context: KeypressContext) => void) => {
+ onKeypress.push(callback);
+ return () => {
+ onKeypress = onKeypress.filter((c) => c !== callback);
+ };
+ },
+ };
}
// =========================================================================
diff --git a/js/app/packages/core/hotkey/state.ts b/js/app/packages/core/hotkey/state.ts
index 49d7c6b447..3928ea1c07 100644
--- a/js/app/packages/core/hotkey/state.ts
+++ b/js/app/packages/core/hotkey/state.ts
@@ -2,12 +2,13 @@ import { makePersisted } from '@solid-primitives/storage';
import { createSignal } from 'solid-js';
import type { HotkeyToken } from './tokens';
import type { HotkeyCommand, ScopeNode, ValidHotkey } from './types';
+import { updateActiveScopeBranch } from './utils';
const initialTree = new Map<string, ScopeNode>([
[
'global',
{
- id: 'global',
+ scopeId: 'global',
type: 'dom',
element: document.body,
childScopeIds: [],
@@ -20,7 +21,15 @@ const initialTree = new Map<string, ScopeNode>([
export const hotkeyScopeTree = initialTree;
-export const [activeScope, setActiveScope] = createSignal<string>('global');
+export const [activeScope, setActiveScopeInner] =
+ createSignal<string>('global');
+
+export function setActiveScope(
+ ...params: Parameters<typeof setActiveScopeInner>
+) {
+ const scopeId = setActiveScopeInner(...params);
+ updateActiveScopeBranch(scopeId);
+}
export const [pressedKeys, setPressedKeys] = createSignal<Set<string>>(
new Set()
@@ -33,6 +42,9 @@ export const [executedTokens, setExecutedTokens] = makePersisted(
}
);
+export const [lastExecutedCommand, setLastExecutedCommand] =
+ createSignal<HotkeyCommand>();
+
// Tracks hotkeys that need their keyUp handlers called
export const hotkeysAwaitingKeyUp: {
hotkey: ValidHotkey;
@@ -40,6 +52,10 @@ export const hotkeysAwaitingKeyUp: {
command: () => void;
}[] = [];
+export const [activeScopeBranch, setActiveScopeBranch] = createSignal<
+ Set<string>
+>(new Set());
+
export const [hotkeyTokenMap, setHotkeyTokenMap] = createSignal<
- Map<HotkeyToken, HotkeyCommand>
+ Map<HotkeyToken, HotkeyCommand[]>
>(new Map());
diff --git a/js/app/packages/core/hotkey/tokens.ts b/js/app/packages/core/hotkey/tokens.ts
index 0c69d492a5..5eeaac6c49 100644
--- a/js/app/packages/core/hotkey/tokens.ts
+++ b/js/app/packages/core/hotkey/tokens.ts
@@ -2,6 +2,18 @@ export const TOKENS = {
// soup
soup: {
openSearch: 'soup.openSearch',
+ tabs: {
+ '0': 'soup.tabs.0',
+ '1': 'soup.tabs.1',
+ '2': 'soup.tabs.2',
+ '3': 'soup.tabs.3',
+ '4': 'soup.tabs.4',
+ '5': 'soup.tabs.5',
+ '6': 'soup.tabs.6',
+ '7': 'soup.tabs.7',
+ '8': 'soup.tabs.8',
+ '9': 'soup.tabs.9',
+ },
},
// unified list
@@ -15,10 +27,15 @@ export const TOKENS = {
end: 'entity.step.end',
start: 'entity.step.start',
},
+ select: {
+ end: 'entity.select.end',
+ start: 'entity.select.start',
+ },
jump: {
home: 'entity.jump.home',
end: 'entity.jump.end',
},
+ open: 'entity.open',
action: {
markDone: 'entity.action.markDone',
delete: 'entity.action.delete',
@@ -44,14 +61,13 @@ export const TOKENS = {
message: 'global.quickCreate.message',
menuFormat: 'global.quickCreate.menuFormat',
},
- macroJump: 'global.macroJump',
- toggleRightPanel: 'global.toggleRightPanel',
commandMenu: 'global.commandMenu',
toggleBigChat: 'global.toggleBigChat',
instructions: 'global.instructions',
searchMenu: 'global.searchMenu',
toggleSettings: 'global.toggleSettings',
createNewSplit: 'global.createNewSplit',
+ toggleVisor: 'global.toggleVisor',
},
// email
@@ -72,13 +88,30 @@ export const TOKENS = {
// split
split: {
close: 'split.close',
+ goCommand: 'split.goCommand',
+ goHome: 'split.goHome',
+ go: {
+ home: 'split.go.home',
+ email: 'split.go.email',
+ inbox: 'split.go.inbox',
+ docs: 'split.go.docs',
+ toggleRightPanel: 'split.go.toggleRightPanel',
+ macroJump: 'split.go.macroJump',
+ back: 'split.go.back',
+ forward: 'split.go.forward',
+ },
+ showHelpDrawer: 'split.showHelpDrawer',
+ },
+
+ window: {
+ close: 'window.close',
+ createNewSplit: 'window.createNewSplit',
spotlight: {
toggle: 'split.spotlight.toggle',
close: 'split.spotlight.close',
},
- back: 'split.back',
- forward: 'split.forward',
- showHelpDrawer: 'split.showHelpDrawer',
+ focusSplitRight: 'window.focusSplitRight',
+ focusSplitLeft: 'window.focusSplitLeft',
},
// canvas
@@ -185,3 +218,31 @@ export const TOKENS = {
type ExtractValues<T> = T extends object ? ExtractValues<T[keyof T]> : T;
export type HotkeyToken = ExtractValues<typeof TOKENS>;
+
+/**
+ * Builds a Map from token string values to their token references
+ * e.g. 'channel.moveUp' -> TOKENS.channel.moveUp
+ */
+export function buildTokenMap(tokens: typeof TOKENS): Map<string, HotkeyToken> {
+ const map = new Map<string, HotkeyToken>();
+
+ function traverse(obj: any, path: string[] = []) {
+ for (const key in obj) {
+ const value = obj[key];
+ const currentPath = [...path, key];
+
+ if (typeof value === 'string') {
+ // Leaf node - add to map
+ map.set(value, value as HotkeyToken);
+ } else if (typeof value === 'object' && value !== null) {
+ // Nested object - recurse
+ traverse(value, currentPath);
+ }
+ }
+ }
+
+ traverse(tokens);
+ return map;
+}
+
+export const tokenMap = buildTokenMap(TOKENS);
diff --git a/js/app/packages/core/hotkey/types.ts b/js/app/packages/core/hotkey/types.ts
index c924f5fe08..e8ab8f28e1 100644
--- a/js/app/packages/core/hotkey/types.ts
+++ b/js/app/packages/core/hotkey/types.ts
@@ -4,6 +4,8 @@ import type { HotkeyToken } from './tokens';
export interface HotkeyCommand {
// Used to identify the hotkey in UI elements. Needs to be unique to a particular scope.
hotkeyToken?: HotkeyToken;
+ // What scope does this hotkey belong to
+ scopeId: string;
// The hotkey strings, e.g. ['cmd+j', 'ctrl+j']
hotkeys?: ValidHotkey[];
// Condition to check if the hotkey command should run. This is checked on keydown/keyup. If this is fed a reactive value, any hotkey UI that displays hotkeys based on this condition will be reactively updated.
@@ -21,7 +23,7 @@ export interface HotkeyCommand {
// 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;
// If true, hotkey command can be hidden from the UI. It will still run, but will not be displayed.
- hide?: boolean;
+ hide?: boolean | (() => boolean);
// Optional icon to display in the command palette.
icon?: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
// Optional tags for categorizing in the command palette.
@@ -95,8 +97,9 @@ export interface HotkeyRegistrationOptions {
displayPriority?: CommandDisplayPriority;
/**
* 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.
*/
- hide?: boolean;
+ hide?: boolean | (() => boolean);
/**
* Optional icon to display in the command palette.
*/
@@ -113,7 +116,7 @@ export type RegisterHotkeyReturn = {
};
export type ScopeNodeBase = {
- id: string;
+ scopeId: string;
description?: string;
parentScopeId?: string;
childScopeIds: string[];
@@ -132,6 +135,9 @@ export type DOMScopeNode = {
export type CommandScopeNode = {
type: 'command';
+ // The keys that activate this command scope, from the original parent scope.
+ activationKeys?: ValidHotkey[];
+ originalParentScopeId: string;
};
export type ScopeNode = ScopeNodeBase & (DOMScopeNode | CommandScopeNode);
@@ -279,3 +285,31 @@ export type ValidHotkey =
| `cmd+${BaseKeyboardValue}`
| `ctrl+opt+shift+${BaseKeyboardValue}`
| `opt+shift+cmd+${BaseKeyboardValue}`;
+
+/**
+ * Context object passed to keypress subscribers containing all relevant
+ * information about the current keypress event. Subscribers can use this
+ * information to implement their own filtering logic.
+ */
+export interface KeypressContext {
+ /** The normalized hotkey string (e.g., 'cmd+j', 'j') */
+ pressedKeysString: ValidHotkey;
+ /** Set of currently pressed keys */
+ pressedKeys: Set<string>;
+ /** The raw keyboard event */
+ event: KeyboardEvent;
+ /** The currently active scope ID, or null if none */
+ activeScopeId: string | null;
+ /** Whether an editable input element is currently focused */
+ isEditableFocused: boolean;
+ /** Whether a command scope was activated by this keypress */
+ commandScopeActivated: boolean;
+ /** Whether a command was found and executed */
+ commandFound: boolean;
+ /** The command that was executed */
+ commandCaptured: HotkeyCommand | undefined;
+ /** The event type ('keydown' or 'keyup') */
+ eventType: 'keydown' | 'keyup';
+ /** Whether the keypress includes a non-modifier key */
+ isNonModifierKeypress: boolean;
+}
diff --git a/js/app/packages/core/hotkey/utils.ts b/js/app/packages/core/hotkey/utils.ts
index dee0e5a110..8f671885d0 100644
--- a/js/app/packages/core/hotkey/utils.ts
+++ b/js/app/packages/core/hotkey/utils.ts
@@ -1,5 +1,6 @@
import { IS_MAC } from '@core/constant/isMac';
-import { createEffect } from 'solid-js';
+import { logger } from '@observability/logger';
+import { createEffect, createMemo } from 'solid-js';
import {
macOptionReverse,
shiftPunctuationMap,
@@ -8,11 +9,19 @@ import {
import { registerHotkey } from './hotkeys';
import {
activeScope,
+ activeScopeBranch,
hotkeyScopeTree,
hotkeysAwaitingKeyUp,
+ hotkeyTokenMap,
setActiveScope,
+ setActiveScopeBranch,
+ setExecutedTokens,
+ setLastExecutedCommand,
+ setPressedKeys,
} from './state';
+import type { HotkeyToken } from './tokens';
import type {
+ HotkeyCommand,
HotkeyRegistrationOptions,
ScopeNode,
ValidHotkey,
@@ -40,19 +49,20 @@ type RegisterDOMScopeArgs = RegisterScopeArgsBase & {
type RegisterCommandScopeArgs = RegisterScopeArgsBase & {
type: 'command';
+ activationKeys?: ValidHotkey[];
};
type RegisterScopeArgs = RegisterDOMScopeArgs | RegisterCommandScopeArgs;
export function registerScope(args: RegisterScopeArgs) {
const { parentScopeId, type, scopeId, description } = args;
+ const parentScope = hotkeyScopeTree.get(parentScopeId ?? '');
const baseScope = {
- id: scopeId,
+ scopeId: scopeId,
description: description ?? undefined,
parentScopeId: parentScopeId,
childScopeIds: [],
- transitions: new Map(),
hotkeyCommands: new Map(),
unkeyedCommands: [],
detached: args.detached ?? false,
@@ -68,9 +78,14 @@ export function registerScope(args: RegisterScopeArgs) {
: {
...baseScope,
type: 'command',
+ originalParentScopeId: parentScopeId ?? '',
+ activationKeys: args.activationKeys ?? [],
};
hotkeyScopeTree.set(scopeId, newScope);
+ if (parentScope) {
+ parentScope.childScopeIds.push(scopeId);
+ }
}
export function removeScope(scopeId: string) {
@@ -89,7 +104,7 @@ export function removeScope(scopeId: string) {
if (scope.type === 'dom') {
let currentScope = scopeTree.get(activeScope() ?? '');
while (currentScope) {
- if (currentScope.id === scopeId) {
+ if (currentScope.scopeId === scopeId) {
let parentScope = hotkeyScopeTree.get(currentScope.parentScopeId ?? '');
let foundDOMScopeParent = false;
while (parentScope) {
@@ -98,7 +113,7 @@ export function removeScope(scopeId: string) {
parentScope.element instanceof HTMLElement
) {
parentScope.element.focus();
- setActiveScope(parentScope.id);
+ setActiveScope(parentScope.scopeId);
foundDOMScopeParent = true;
break;
}
@@ -149,7 +164,7 @@ export function activateClosestDOMScope() {
currentScope.element instanceof HTMLElement
) {
currentScope.element.focus();
- activeScopeId = currentScope.id;
+ activeScopeId = currentScope.scopeId;
break;
}
@@ -160,6 +175,214 @@ export function activateClosestDOMScope() {
setActiveScope(activeScopeId);
}
+export function updateActiveScopeBranch(activeScopeId: string | undefined) {
+ const branch = new Set<string>();
+
+ if (activeScopeId) {
+ let currentScope = hotkeyScopeTree.get(activeScopeId);
+ while (currentScope) {
+ branch.add(currentScope.scopeId);
+ if (!currentScope.parentScopeId) break;
+ currentScope = hotkeyScopeTree.get(currentScope.parentScopeId);
+ }
+ }
+
+ setActiveScopeBranch(branch);
+}
+
+export function isScopeInActiveBranch(scopeId: string): boolean {
+ return activeScopeBranch().has(scopeId);
+}
+
+/**
+ * Finds the first hotkey command for a given token that is in the current active scope branch
+ */
+export function getActiveCommandByToken(
+ token: HotkeyToken
+): HotkeyCommand | undefined;
+export function getActiveCommandByToken(
+ token: HotkeyToken,
+ includeDependentCommandScopes: true
+): HotkeyCommand[] | undefined;
+export function getActiveCommandByToken(
+ token: HotkeyToken,
+ includeDependentCommandScopes?: boolean
+): HotkeyCommand | HotkeyCommand[] | undefined {
+ const commands = hotkeyTokenMap().get(token);
+ if (!commands || commands.length === 0) return undefined;
+
+ const branch = activeScopeBranch();
+
+ if (includeDependentCommandScopes) {
+ // When showDependentCommandScopes is true, look for commands in command scopes whose closest DOM scope parent is in the active branch. I.e. this is a command in a command scope (or potentiall a chain of command scopes) that could be initiated from the current active scope.
+ for (const command of commands) {
+ const commandScope = hotkeyScopeTree.get(command.scopeId);
+ // Check if command is directly in the active branch
+ if (branch.has(command.scopeId)) {
+ return [command];
+ }
+
+ if (commandScope?.type === 'command') {
+ const originalParentScope = hotkeyScopeTree.get(
+ commandScope.originalParentScopeId
+ );
+ if (!originalParentScope) {
+ logger.error('Original parent scope not found for command scope:', {
+ error: new Error(
+ 'Original parent scope not found for command scope'
+ ),
+ commandScopeId: commandScope?.scopeId,
+ });
+ return [];
+ }
+
+ let reverseActivationCommands: HotkeyCommand[] = [];
+
+ let closestDOMScopeParent: ScopeNode | undefined;
+
+ let currentAncestor: ScopeNode | undefined = originalParentScope;
+ let currentCommandScope: ScopeNode = commandScope;
+ while (currentAncestor) {
+ const activationKey = currentCommandScope.activationKeys?.at(0);
+ if (activationKey) {
+ const activationCommand =
+ originalParentScope.hotkeyCommands.get(activationKey);
+ if (activationCommand) {
+ reverseActivationCommands.push(activationCommand);
+ } else break;
+ }
+ if (currentAncestor.type === 'dom') {
+ closestDOMScopeParent = currentAncestor;
+ break;
+ }
+ if (currentAncestor.originalParentScopeId) {
+ const parentScope = hotkeyScopeTree.get(
+ currentAncestor.originalParentScopeId
+ );
+ currentCommandScope = currentAncestor;
+ currentAncestor = parentScope;
+ } else {
+ break;
+ }
+ }
+
+ if (
+ closestDOMScopeParent &&
+ branch.has(closestDOMScopeParent.scopeId) &&
+ reverseActivationCommands.every(
+ (cmd) => cmd.hotkeys && cmd.hotkeys.length > 0
+ )
+ ) {
+ const activationCommands = reverseActivationCommands.reverse();
+
+ return activationCommands.concat(command);
+ }
+ }
+ }
+
+ return undefined;
+ }
+
+ // Return the first command that's in the active scope branch
+ const command = commands.find((command) => branch.has(command.scopeId));
+ return command;
+}
+
+/**
+ * Returns a hotkey command for a given hotkey token. NOTE: this might not be THE command you are looking for, if there are hotkeys sharing the same token instantiated across different scopes. But this can be used in situations where you don't know or don't care about the scope you are in, e.g. when displaying hotkey metadata.
+ */
+export function getHotkeyCommandByToken(token: HotkeyToken) {
+ const command = hotkeyTokenMap().get(token)?.at(0);
+ return command;
+}
+
+// Helper function to get the primary hotkey string for a given token, pretty printed.
+export function getPrettyHotkeyStringByToken(token: HotkeyToken) {
+ const hotkey = hotkeyTokenMap().get(token)?.at(0)?.hotkeys?.[0];
+ if (!hotkey) return undefined;
+ return prettyPrintHotkeyString(hotkey);
+}
+
+/**
+ * Runs the given hotkey command. This sets the executed tokens and last executed command.
+ * @param command - The hotkey command to run.
+ * @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.
+ */
+export function runCommand(
+ command: HotkeyCommand,
+ e?: KeyboardEvent,
+ pressedKeysString?: string,
+ scopeId?: string
+) {
+ const currentScopeId = activeScope();
+
+ let commandCaptured: HotkeyCommand | undefined;
+ let commandScopeActivated = false;
+
+ if (!command.condition || command.condition()) {
+ if (command.activateCommandScopeId) {
+ const commandScope = hotkeyScopeTree.get(command.activateCommandScopeId);
+ if (commandScope) {
+ // When the command scope is activated, we set its parent scope to the active scope when it was called, so that when the command scope is deactivated, scope will return to the correct scope. The commmand scope will still get cleaned up correctly when it's original parent scope is removed.
+ commandScope.parentScopeId = currentScopeId;
+ setPressedKeys(new Set<string>());
+ setActiveScope(commandScope.scopeId);
+ if (!commandCaptured) {
+ setExecutedTokens((prev) =>
+ command.hotkeyToken
+ ? prev.includes(command.hotkeyToken)
+ ? prev
+ : [...prev, command.hotkeyToken]
+ : prev
+ );
+ }
+ commandScopeActivated = true;
+ e?.preventDefault();
+ e?.stopPropagation();
+ }
+ }
+
+ const captured = command.keyDownHandler?.(e);
+ if (captured) {
+ setPressedKeys(new Set<string>());
+ setLastExecutedCommand(command);
+ commandCaptured = command;
+ setExecutedTokens((prev) =>
+ command.hotkeyToken
+ ? prev.includes(command.hotkeyToken)
+ ? prev
+ : [...prev, command.hotkeyToken]
+ : prev
+ );
+ e?.preventDefault();
+ e?.stopPropagation();
+ }
+
+ if (
+ command.keyUpHandler &&
+ e?.type === 'keydown' &&
+ scopeId &&
+ !hotkeysAwaitingKeyUp.some(
+ (h) => h.hotkey === pressedKeysString && h.scopeId === scopeId
+ )
+ ) {
+ hotkeysAwaitingKeyUp.push({
+ hotkey: pressedKeysString as ValidHotkey,
+ scopeId: scopeId,
+ command: () => command.keyUpHandler?.(e),
+ });
+ }
+ }
+
+ return {
+ commandCaptured: commandCaptured,
+ commandScopeActivated: commandScopeActivated,
+ };
+}
+
export function normalizeEventKeyPress(e: KeyboardEvent): string {
const key = e.key;
if (key === ' ') return 'space';
@@ -181,8 +404,7 @@ export function normalizeEventKeyPress(e: KeyboardEvent): string {
}
// When you specify a hotkey for, e.g. '?', you want it show as '?' even though the actual key pressed was 'shift+/'. This function prints the printed punctuation key rather than the key combo.
-export function prettyPrintHotkeyString(validHotkey?: ValidHotkey) {
- if (!validHotkey) return undefined;
+export function prettyPrintHotkeyString(validHotkey: ValidHotkey) {
if (validHotkey.includes('shift+')) {
const shiftless = validHotkey.replace('shift+', '');
if (shiftless in shiftPunctuationReverseMap) {
@@ -191,6 +413,9 @@ export function prettyPrintHotkeyString(validHotkey?: ValidHotkey) {
];
}
}
+ if (validHotkey.includes('escape')) {
+ return validHotkey.replace('escape', 'esc');
+ }
return validHotkey;
}
@@ -276,3 +501,12 @@ export function registerScopeSignalHotkey(
};
});
}
+
+export const useIsInCommandScope = () => {
+ return createMemo(() => {
+ const currentScopeId = activeScope();
+ if (!currentScopeId) return false;
+ const scopeNode = hotkeyScopeTree.get(currentScopeId);
+ return scopeNode?.type === 'command';
+ });
+};
diff --git a/js/app/packages/core/types/view.ts b/js/app/packages/core/types/view.ts
index dce6134ad8..9b4d99a371 100644
--- a/js/app/packages/core/types/view.ts
+++ b/js/app/packages/core/types/view.ts
@@ -2,6 +2,7 @@ export const DEFAULT_VIEWS = [
'signal',
'noise',
'people',
+ 'email',
'files',
'tasks',
'folders',
diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
index 74ed4d8496..88d3c39174 100644
--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
+++ b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
@@ -14,7 +14,6 @@ import { StaticMarkdown } from 'core/component/LexicalMarkdown/component/core/St
import { unifiedListMarkdownTheme } from 'core/component/LexicalMarkdown/theme';
import { UserIcon } from 'core/component/UserIcon';
import { emailToId, useDisplayName } from 'core/user';
-import { onKeyDownClick, onKeyUpClick } from 'core/util/click';
import type { ParentProps, Ref } from 'solid-js';
import {
createDeferred,
@@ -852,10 +851,6 @@ export function EntityWithEverything(
actionButtonRef()?.focus();
}}
- onKeyDown={onKeyDownClick((e) =>
- props.onClick?.(props.entity, e as any)
- )}
- onKeyUp={onKeyUpClick((e) => props.onClick?.(props.entity, e as any))}
role="button"
tabIndex={0}
ref={mergeRefs(setEntityDivRef, props.ref)}