refactor: update hotkey management and command handling

- Replaced `HotKeyScopeMap` with `HotkeyScope` enum for better type safety and clarity.
- Refactored hotkey scope handling across various components to utilize the new enum.
- Introduced new commands for entry rendering and timeline navigation, enhancing user interaction.
- Improved the use of conditional hotkey scopes for better context awareness.

This refactor aims to streamline hotkey management and improve the overall user experience.

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-05-12 21:13:57 +08:00
parent c3067b9952
commit 0345fc216a
24 changed files with 351 additions and 101 deletions
@@ -5,11 +5,12 @@ import { cn } from "@follow/utils/utils"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import * as React from "react"
import { useHotkeyScope } from "~/hooks/common"
import { HotkeyScope } from "~/constants"
import { useConditionalHotkeyScope } from "~/hooks/common"
const DropdownMenu: typeof DropdownMenuPrimitive.Root = (props) => {
const [open, setOpen] = React.useState(!!props.open)
useHotkeyScope("DropdownMenu", open)
useConditionalHotkeyScope(HotkeyScope.DropdownMenu, open)
return (
<DropdownMenuPrimitive.Root
@@ -1,6 +1,10 @@
export const HotKeyScopeMap = {
Home: "home",
Menu: "menu",
Modal: "modal",
DropdownMenu: "dropdown-menu",
export enum HotkeyScope {
Home = "home",
Menu = "menu",
Modal = "modal",
DropdownMenu = "dropdown-menu",
// Atom Scope
Timeline = "timeline",
EntryRender = "entry-render",
}
@@ -98,11 +98,11 @@ const shortcutConfigs = {
},
scrollUp: {
name: "keys.entry.scrollUp",
key: "PageUp",
key: "K",
},
scrollDown: {
name: "keys.entry.scrollDown",
key: "PageDown",
key: "J",
},
},
audio: {
@@ -4,7 +4,7 @@ import { useHotkeys } from "react-hotkeys-hook"
import { Trans, useTranslation } from "react-i18next"
import { toast } from "sonner"
import { HotKeyScopeMap } from "~/constants"
import { HotkeyScope } from "~/constants"
import { apiClient } from "~/lib/api-fetch"
import { subscription as subscriptionQuery } from "~/queries/subscriptions"
import type { SubscriptionFlatModel } from "~/store/subscription"
@@ -92,7 +92,7 @@ export const useDeleteSubscription = ({ onSuccess }: { onSuccess?: () => void }
const UnfollowInfo = ({ title, undo }: { title: string; undo: () => any }) => {
useHotkeys("ctrl+z,meta+z", undo, {
scopes: HotKeyScopeMap.Home,
scopes: HotkeyScope.Home,
preventDefault: true,
})
return (
@@ -1,18 +1,19 @@
import { useCallback, useLayoutEffect, useRef } from "react"
import { useHotkeysContext } from "react-hotkeys-hook"
import { HotKeyScopeMap } from "~/constants"
import { HotkeyScope } from "~/constants"
const allScopes = Object.keys(HotKeyScopeMap).reduce((acc, key) => {
acc.push(HotKeyScopeMap[key])
const allScopes = Object.keys(HotkeyScope).reduce((acc, key) => {
acc.push(HotkeyScope[key])
return acc
}, [] as string[])
export const useSwitchHotKeyScope = () => {
const { enableScope, disableScope } = useHotkeysContext()
return useCallback(
(scope: keyof typeof HotKeyScopeMap) => {
const nextScope = HotKeyScopeMap[scope]
(scope: keyof typeof HotkeyScope) => {
const nextScope = HotkeyScope[scope]
if (!nextScope) return
for (const key of allScopes) {
@@ -23,27 +24,31 @@ export const useSwitchHotKeyScope = () => {
[disableScope, enableScope],
)
}
export const useHotkeyScopeFn = (scope: keyof typeof HotKeyScopeMap) => {
export const useConditionalHotkeyScopeFn = (scope: HotkeyScope, replaceAll = true) => {
const { enableScope, disableScope, activeScopes } = useHotkeysContext()
const currentScopeRef = useRef(activeScopes)
return useCallback(() => {
const currentScope = currentScopeRef.current
for (const key of allScopes) {
disableScope(key)
if (replaceAll) {
for (const key of allScopes) {
disableScope(key)
}
}
enableScope(scope)
return () => {
disableScope(scope)
for (const key of currentScope) {
enableScope(key)
if (replaceAll) {
for (const key of currentScope) {
enableScope(key)
}
}
}
}, [enableScope, disableScope, scope])
}, [enableScope, disableScope, scope, replaceAll])
}
export const useHotkeyScope = (scope: keyof typeof HotKeyScopeMap, when: boolean) => {
const fn = useHotkeyScopeFn(scope)
export const useConditionalHotkeyScope = (scope: HotkeyScope, when: boolean, append = false) => {
const fn = useConditionalHotkeyScopeFn(scope, !append)
useLayoutEffect(() => {
if (when) {
return fn()
@@ -11,7 +11,7 @@ import { useRealInWideMode } from "~/atoms/settings/ui"
import { useTimelineColumnShow, useTimelineColumnTempShow } from "~/atoms/sidebar"
import { m } from "~/components/common/Motion"
import { FixedModalCloseButton } from "~/components/ui/modal/components/close"
import { HotKeyScopeMap, ROUTE_ENTRY_PENDING } from "~/constants"
import { HotkeyScope, ROUTE_ENTRY_PENDING } from "~/constants"
import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
import { useRouteParams } from "~/hooks/biz/useRouteParams"
import { EntryContent } from "~/modules/entry-content"
@@ -39,7 +39,7 @@ export const RightContentDesktop = () => {
},
{
enabled: showEntryContent && settingWideMode,
scopes: HotKeyScopeMap.Home,
scopes: HotkeyScope.Home,
preventDefault: true,
},
)
@@ -12,7 +12,6 @@ import { debounce } from "es-toolkit/compat"
import type { PropsWithChildren } from "react"
import * as React from "react"
import { Suspense, useEffect, useRef, useState } from "react"
import { useHotkeysContext } from "react-hotkeys-hook"
import { Trans } from "react-i18next"
import { useResizable } from "react-resizable-layout"
import { Outlet } from "react-router"
@@ -31,7 +30,7 @@ import { AppErrorBoundary } from "~/components/common/AppErrorBoundary"
import { ErrorComponentType } from "~/components/errors/enum"
import { PlainModal } from "~/components/ui/modal/stacked/custom-modal"
import { DeclarativeModal } from "~/components/ui/modal/stacked/declarative-modal"
import { HotKeyScopeMap } from "~/constants"
import { HotkeyScope } from "~/constants"
import { ROOT_CONTAINER_ID } from "~/constants/dom"
import { shortcuts } from "~/constants/shortcuts"
import { useDailyTask } from "~/hooks/biz/useDailyTask"
@@ -52,6 +51,7 @@ import { getSelectedFeedIds, resetSelectedFeedIds } from "~/modules/timeline-col
import { UpdateNotice } from "~/modules/update-notice/UpdateNotice"
import { AppNotificationContainer } from "~/modules/upgrade/lazy/index"
import { AppLayoutGridContainerProvider } from "~/providers/app-grid-layout-container-provider"
import { useHotkeyScope } from "~/providers/hotkey-provider"
import { NewUserGuide } from "./index.shared"
@@ -242,11 +242,12 @@ const FeedResponsiveResizerContainer = ({
}
}, [feedColumnShow])
const { activeScopes } = useHotkeysContext()
const activeScopes = useHotkeyScope()
useCommandHotkey({
commandId: COMMAND_ID.layout.toggleTimelineColumn,
shortcut: shortcuts.layout.toggleSidebar.key,
when: activeScopes.includes(HotKeyScopeMap.Home),
when: activeScopes.includes(HotkeyScope.Home),
})
const [delayShowSplitter, setDelayShowSplitter] = useState(feedColumnShow)
@@ -1,9 +1,11 @@
import { useRegisterEntryCommands } from "./commands/entry"
import { useRegisterEntryRenderCommand } from "./commands/entry-render"
import { useRegisterGlobalCommands } from "./commands/global"
import { useRegisterIntegrationCommands } from "./commands/integration"
import { useRegisterLayoutCommands } from "./commands/layout"
import { useRegisterListCommands } from "./commands/list"
import { useRegisterSettingsCommands } from "./commands/settings"
import { useRegisterTimelineCommand } from "./commands/timeline"
export const FollowCommandManager = () => {
useRegisterSettingsCommands()
@@ -12,5 +14,7 @@ export const FollowCommandManager = () => {
useRegisterIntegrationCommands()
useRegisterGlobalCommands()
useRegisterLayoutCommands()
useRegisterTimelineCommand()
useRegisterEntryRenderCommand()
return null
}
@@ -0,0 +1,45 @@
import { EventBus } from "@follow/utils/event-bus"
import { useRegisterCommandEffect } from "../hooks/use-register-command"
import type { Command } from "../types"
import { COMMAND_ID } from "./id"
declare module "@follow/utils/event-bus" {
interface EventBusMap {
"entry-render:scroll-down": never
"entry-render:scroll-up": never
}
}
const LABEL_PREFIX = "Entry Render"
export const useRegisterEntryRenderCommand = () => {
useRegisterCommandEffect([
{
id: COMMAND_ID.entryRender.scrollDown,
run: () => {
EventBus.dispatch(COMMAND_ID.entryRender.scrollDown)
},
category: "follow:entry-render",
label: `${LABEL_PREFIX}: Scroll down`,
},
{
id: COMMAND_ID.entryRender.scrollUp,
run: () => {
EventBus.dispatch(COMMAND_ID.entryRender.scrollUp)
},
category: "follow:entry-render",
label: `${LABEL_PREFIX}: Scroll up`,
},
])
}
type EntryScrollDownCommand = Command<{
id: typeof COMMAND_ID.entryRender.scrollDown
fn: () => void
}>
type EntryScrollUpCommand = Command<{
id: typeof COMMAND_ID.entryRender.scrollUp
fn: () => void
}>
export type EntryRenderCommand = EntryScrollDownCommand | EntryScrollUpCommand
@@ -47,4 +47,13 @@ export const COMMAND_ID = {
layout: {
toggleTimelineColumn: "layout:toggle-timeline-column",
},
timeline: {
switchToNext: "timeline:switch-to-next",
switchToPrevious: "timeline:switch-to-previous",
refetch: "timeline:refetch",
},
entryRender: {
scrollDown: "entry-render:scroll-down",
scrollUp: "entry-render:scroll-up",
},
} as const
@@ -0,0 +1,59 @@
import { EventBus } from "@follow/utils/event-bus"
import { useRegisterCommandEffect } from "../hooks/use-register-command"
import type { Command } from "../types"
import { COMMAND_ID } from "./id"
declare module "@follow/utils/event-bus" {
interface EventBusMap {
"timeline:switch-to-next": never
"timeline:switch-to-previous": never
"timeline:refetch": never
}
}
export const useRegisterTimelineCommand = () => {
useRegisterCommandEffect([
{
id: COMMAND_ID.timeline.switchToNext,
label: "Switch to next timeline",
run: () => {
EventBus.dispatch("timeline:switch-to-next")
},
},
{
id: COMMAND_ID.timeline.switchToPrevious,
label: "Switch to previous timeline",
run: () => {
EventBus.dispatch("timeline:switch-to-previous")
},
},
{
id: COMMAND_ID.timeline.refetch,
label: "Refetch timeline",
run: () => {
EventBus.dispatch("timeline:refetch")
},
},
])
}
export type SwitchToNextTimelineCommand = Command<{
id: typeof COMMAND_ID.timeline.switchToNext
fn: () => void
}>
export type SwitchToPreviousTimelineCommand = Command<{
id: typeof COMMAND_ID.timeline.switchToPrevious
fn: () => void
}>
export type RefetchTimelineCommand = Command<{
id: typeof COMMAND_ID.timeline.refetch
fn: () => void
}>
export type TimelineCommand =
| SwitchToNextTimelineCommand
| SwitchToPreviousTimelineCommand
| RefetchTimelineCommand
@@ -1,10 +1,12 @@
// Entry commands
import type { EntryCommand } from "./entry"
import type { EntryRenderCommand } from "./entry-render"
import type { GlobalCommand } from "./global"
import type { IntegrationCommand } from "./integration"
import type { LayoutCommand } from "./layout"
import type { SettingsCommand } from "./settings"
import type { TimelineCommand } from "./timeline"
export type BasicCommand =
| EntryCommand
@@ -12,3 +14,5 @@ export type BasicCommand =
| IntegrationCommand
| GlobalCommand
| LayoutCommand
| TimelineCommand
| EntryRenderCommand
@@ -8,6 +8,7 @@ export type CommandCategory =
| "follow:updates"
| "follow:help"
| "follow:general"
| "follow:entry-render"
export interface KeybindingOptions {
binding: string
@@ -1,13 +1,18 @@
import { useRefValue } from "@follow/hooks"
import { EventBus } from "@follow/utils/event-bus"
import type { FC } from "react"
import { memo, useLayoutEffect, useState } from "react"
import { useHotkeys } from "react-hotkeys-hook"
import { memo, useEffect, useLayoutEffect, useState } from "react"
import { useMainContainerElement } from "~/atoms/dom"
import { HotKeyScopeMap } from "~/constants"
import { HotkeyScope } from "~/constants"
import { shortcuts } from "~/constants/shortcuts"
import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
import { useRouteEntryId } from "~/hooks/biz/useRouteParams"
import { useConditionalHotkeyScope } from "~/hooks/common"
import { useHotkeyScope } from "~/providers/hotkey-provider"
import { COMMAND_ID } from "../command/commands/id"
import { useCommandHotkey } from "../command/hooks/use-register-hotkey"
export const EntryColumnShortcutHandler: FC<{
refetch: () => void
@@ -16,42 +21,33 @@ export const EntryColumnShortcutHandler: FC<{
}> = memo(({ data, refetch, handleScrollTo }) => {
const dataRef = useRefValue(data!)
useHotkeys(
shortcuts.entries.refetch.key,
() => {
refetch()
},
{ scopes: HotKeyScopeMap.Home },
)
const activeScope = useHotkeyScope()
const when =
activeScope.includes(HotkeyScope.Timeline) && !activeScope.includes(HotkeyScope.EntryRender)
useCommandHotkey({
shortcut: shortcuts.entries.next.key,
commandId: COMMAND_ID.timeline.switchToNext,
when,
})
useCommandHotkey({
shortcut: shortcuts.entries.previous.key,
commandId: COMMAND_ID.timeline.switchToPrevious,
when,
})
useCommandHotkey({
shortcut: shortcuts.entries.refetch.key,
commandId: COMMAND_ID.timeline.refetch,
when,
})
const currentEntryIdRef = useRefValue(useRouteEntryId())
const navigate = useNavigateEntry()
const $mainContainer = useMainContainerElement()
const [enabledArrowKey, setEnabledArrowKey] = useState(false)
// Enable arrow key navigation shortcuts only when focus is on entryContent or entryList,
// entryList shortcuts should not be triggered in the feed col
useLayoutEffect(() => {
if (!$mainContainer) return
const handler = () => {
const target = document.activeElement
const isFocusIn = $mainContainer.contains(target) || $mainContainer === target
setEnabledArrowKey(isFocusIn)
}
handler()
// NOTE: focusin event will bubble to the document
document.addEventListener("focusin", handler)
return () => {
document.removeEventListener("focusin", handler)
}
}, [$mainContainer])
useHotkeys(
shortcuts.entries.next.key,
() => {
useEffect(() => {
return EventBus.subscribe("timeline:switch-to-next", () => {
const data = dataRef.current
const currentActiveEntryIndex = data.indexOf(currentEntryIdRef.current || "")
@@ -63,12 +59,11 @@ export const EntryColumnShortcutHandler: FC<{
navigate({
entryId: nextId,
})
},
{ scopes: HotKeyScopeMap.Home, enabled: enabledArrowKey, preventDefault: true },
)
useHotkeys(
shortcuts.entries.previous.key,
() => {
})
}, [currentEntryIdRef, dataRef, handleScrollTo, navigate])
useEffect(() => {
return EventBus.subscribe("timeline:switch-to-previous", () => {
const data = dataRef.current
const currentActiveEntryIndex = data.indexOf(currentEntryIdRef.current || "")
@@ -81,8 +76,41 @@ export const EntryColumnShortcutHandler: FC<{
navigate({
entryId: nextId,
})
},
{ scopes: HotKeyScopeMap.Home, enabled: enabledArrowKey, preventDefault: true },
)
})
}, [currentEntryIdRef, dataRef, handleScrollTo, navigate])
useEffect(() => {
return EventBus.subscribe("timeline:refetch", () => {
refetch()
})
}, [refetch])
const $mainContainer = useMainContainerElement()
const [isFocusIn, setIsFocusIn] = useState(false)
useConditionalHotkeyScope(HotkeyScope.Timeline, isFocusIn, true)
// Enable arrow key navigation shortcuts only when focus is on entryContent or entryList,
// entryList shortcuts should not be triggered in the feed col
useLayoutEffect(() => {
if (!$mainContainer) return
const handler = () => {
const target = document.activeElement
const isFocusIn = $mainContainer.contains(target) || $mainContainer === target
setIsFocusIn(isFocusIn)
}
handler()
// NOTE: focusin event will bubble to the document
document.addEventListener("focusin", handler)
document.addEventListener("focusout", handler)
return () => {
document.removeEventListener("focusin", handler)
document.removeEventListener("focusout", handler)
}
}, [$mainContainer])
return null
})
@@ -8,7 +8,7 @@ import { useHotkeys } from "react-hotkeys-hook"
import { Trans, useTranslation } from "react-i18next"
import { toast } from "sonner"
import { HotKeyScopeMap } from "~/constants"
import { HotkeyScope } from "~/constants"
import { shortcuts } from "~/constants/shortcuts"
import { useI18n } from "~/hooks/common"
@@ -61,7 +61,7 @@ export const MarkAllReadButton = ({
},
{
preventDefault: true,
scopes: HotKeyScopeMap.Home,
scopes: HotkeyScope.Home,
},
)
@@ -100,7 +100,7 @@ const ConfirmMarkAllReadInfo = ({ undo }: { undo: () => any }) => {
const [countdown] = useCountdown({ countStart: 3 })
useHotkeys("ctrl+z,meta+z", undo, {
scopes: HotKeyScopeMap.Home,
scopes: HotkeyScope.Home,
preventDefault: true,
})
@@ -4,6 +4,8 @@ import type { FeedViewType } from "@follow/constants"
import { useTitle } from "@follow/hooks"
import type { FeedModel, InboxModel } from "@follow/models/types"
import { stopPropagation } from "@follow/utils/dom"
import { EventBus } from "@follow/utils/event-bus"
import { springScrollTo } from "@follow/utils/scroller"
import { cn } from "@follow/utils/utils"
import { ErrorBoundary } from "@sentry/react"
import * as React from "react"
@@ -18,10 +20,13 @@ import { useUISettingKey } from "~/atoms/settings/ui"
import { ShadowDOM } from "~/components/common/ShadowDOM"
import type { TocRef } from "~/components/ui/markdown/components/Toc"
import { useInPeekModal } from "~/components/ui/modal/inspire/InPeekModal"
import { HotkeyScope } from "~/constants"
import { shortcuts } from "~/constants/shortcuts"
import { useRenderStyle } from "~/hooks/biz/useRenderStyle"
import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
import { useAuthQuery } from "~/hooks/common"
import { useAuthQuery, useConditionalHotkeyScope } from "~/hooks/common"
import { useFeedSafeUrl } from "~/hooks/common/useFeedSafeUrl"
import { useHotkeyScope } from "~/providers/hotkey-provider"
import { WrappedElementProvider } from "~/providers/wrapped-element-provider"
import { Queries } from "~/queries"
import { useEntryTranslation } from "~/store/ai/hook"
@@ -29,6 +34,8 @@ import { useEntry } from "~/store/entry"
import { useFeedById } from "~/store/feed"
import { useInboxById } from "~/store/inbox"
import { COMMAND_ID } from "../command/commands/id"
import { useCommandHotkey } from "../command/hooks/use-register-hotkey"
import { EntryContentHTMLRenderer } from "../renderer/html"
import { AISummary } from "./AISummary"
import { EntryTimelineSidebar } from "./components/EntryTimelineSidebar"
@@ -93,7 +100,48 @@ export const EntryContent: Component<EntryContentProps> = ({
})
const isInPeekModal = useInPeekModal()
const [isUserInteraction, setIsUserInteraction] = React.useState(false)
useConditionalHotkeyScope(HotkeyScope.EntryRender, isUserInteraction, true)
const activeScope = useHotkeyScope()
useCommandHotkey({
shortcut: shortcuts.entry.scrollUp.key,
commandId: COMMAND_ID.entryRender.scrollUp,
when: activeScope.includes(HotkeyScope.EntryRender),
})
useCommandHotkey({
shortcut: shortcuts.entry.scrollDown.key,
commandId: COMMAND_ID.entryRender.scrollDown,
when: activeScope.includes(HotkeyScope.EntryRender),
})
useEffect(() => {
return EventBus.subscribe(COMMAND_ID.entryRender.scrollUp, () => {
const currentScroll = scrollerRef.current?.scrollTop
const delta = window.innerHeight
if (typeof currentScroll === "number" && delta) {
springScrollTo(currentScroll - delta, scrollerRef.current!)
}
})
}, [])
useEffect(() => {
return EventBus.subscribe(COMMAND_ID.entryRender.scrollDown, () => {
const currentScroll = scrollerRef.current?.scrollTop
const delta = window.innerHeight
if (typeof currentScroll === "number" && delta) {
springScrollTo(currentScroll + delta, scrollerRef.current!)
}
})
}, [])
useEffect(() => {
return () => setIsUserInteraction(false)
}, [entryId])
if (!entry) return null
const entryContent = isInReadabilityMode
@@ -125,6 +173,8 @@ export const EntryContent: Component<EntryContentProps> = ({
key={entry.entries.id}
>
<article
tabIndex={-1}
onClick={() => setIsUserInteraction(true)}
data-testid="entry-render"
onContextMenu={stopPropagation}
className="@[950px]:max-w-[70ch] @7xl:max-w-[80ch] relative m-auto min-w-0 max-w-[550px]"
@@ -55,7 +55,7 @@ const ShortcutModalContent = () => {
<div className="w-full space-y-6 px-4 pb-5 pt-6">
{Object.keys(shortcuts).map((type) => (
<section key={type}>
<div className="text-text-secondary mb-2 pl-4 text-xs font-medium capitalize">
<div className="text-text-secondary mb-2 pl-3 text-xs font-medium capitalize">
{t(shortcutsType[type])}
</div>
<div className="text-text rounded-md border text-[13px]">
@@ -12,7 +12,7 @@ import { z } from "zod"
import { m } from "~/components/common/Motion"
import { PlainModal } from "~/components/ui/modal/stacked/custom-modal"
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
import { HotKeyScopeMap } from "~/constants"
import { HotkeyScope } from "~/constants"
import { getRouteParams } from "~/hooks/biz/useRouteParams"
import { tipcClient } from "~/lib/client"
@@ -116,7 +116,7 @@ export const CmdNTrigger = () => {
useRegisterGlobalContext("quickAdd", handler)
useHotkeys("meta+n,ctrl+n", handler, {
scopes: HotKeyScopeMap.Home,
scopes: HotkeyScope.Home,
preventDefault: true,
})
@@ -20,7 +20,7 @@ import {
useAudioPlayerAtomValue,
} from "~/atoms/player"
import { VolumeSlider } from "~/components/ui/media/VolumeSlider"
import { HotKeyScopeMap } from "~/constants"
import { HotkeyScope } from "~/constants"
import type { NavigateEntryOptions } from "~/hooks/biz/useNavigateEntry"
import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
import { FeedIcon } from "~/modules/feed/feed-icon"
@@ -118,7 +118,7 @@ const CornerPlayerImpl = ({ hideControls, rounded }: ControlButtonProps) => {
const isFocused = useFocusable()
useHotkeys("space", handleClickPlay, {
preventDefault: true,
scopes: HotKeyScopeMap.Home,
scopes: HotkeyScope.Home,
enabled: isFocused,
})
@@ -16,7 +16,7 @@ import { useLocation } from "react-router"
import { useRootContainerElement } from "~/atoms/dom"
import { useUISettingKey } from "~/atoms/settings/ui"
import { setTimelineColumnShow, useTimelineColumnShow } from "~/atoms/sidebar"
import { HotKeyScopeMap } from "~/constants"
import { HotkeyScope } from "~/constants"
import { shortcuts } from "~/constants/shortcuts"
import { navigateEntry, useBackHome } from "~/hooks/biz/useNavigateEntry"
import { useReduceMotion } from "~/hooks/biz/useReduceMotion"
@@ -102,7 +102,7 @@ export function FeedColumn({ children, className }: PropsWithChildren<{ classNam
setActive((_, i) => timelineList[(i + 1) % timelineList.length]!)
}
},
{ scopes: HotKeyScopeMap.Home },
{ scopes: HotkeyScope.Home },
)
useRegisterGlobalContext("goToDiscover", () => {
@@ -24,7 +24,7 @@ import {
ContextMenuSubTrigger,
ContextMenuTrigger,
} from "~/components/ui/context-menu"
import { HotKeyScopeMap } from "~/constants"
import { HotkeyScope } from "~/constants"
import { useSwitchHotKeyScope } from "~/hooks/common"
export const ContextMenuProvider: Component = ({ children }) => (
@@ -114,7 +114,7 @@ const Item = memo(({ item }: { item: FollowMenuItem }) => {
useHotkeys((item as any as MenuItemText).shortcut!, () => itemRef.current?.click(), {
// enabled: item.enabled !== false && item.shortcut !== undefined,
enabled: item instanceof MenuItemText && !!item.shortcut,
scopes: HotKeyScopeMap.Menu,
scopes: HotkeyScope.Menu,
preventDefault: true,
})
@@ -1,17 +1,17 @@
import { useHotkeysContext } from "react-hotkeys-hook"
import { HotKeyScopeMap } from "~/constants/hotkeys"
import { HotkeyScope } from "~/constants/hotkeys"
import { shortcuts } from "~/constants/shortcuts"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { useCommandHotkey } from "~/modules/command/hooks/use-register-hotkey"
import { useHotkeyScope } from "./hotkey-provider"
export const GlobalHotkeysProvider = () => {
const { activeScopes } = useHotkeysContext()
const activeScopes = useHotkeyScope()
useCommandHotkey({
commandId: COMMAND_ID.global.showShortcuts,
shortcut: shortcuts.layout.showShortcuts.key,
when: activeScopes.includes(HotKeyScopeMap.Home),
when: activeScopes.includes(HotkeyScope.Home),
})
return null
@@ -0,0 +1,42 @@
import type { PropsWithChildren } from "react"
import { createContext, use, useEffect } from "react"
import { HotkeysProvider, useHotkeysContext } from "react-hotkeys-hook"
import { HotkeyScope } from "~/constants"
import { appLog } from "~/lib/log"
import { GlobalHotkeysProvider } from "./global-hotkeys-provider"
const initialActiveScopes = [HotkeyScope.Home]
const HotkeyScopeContext = createContext<HotkeyScope[]>(null!)
export const HotkeyProvider: Component = ({ children }) => {
return (
<HotkeysProvider initiallyActiveScopes={initialActiveScopes}>
<HotkeyScopeProvider>
{children}
<GlobalHotkeysProvider />
</HotkeyScopeProvider>
</HotkeysProvider>
)
}
const HotkeyScopeProvider = ({ children }: PropsWithChildren) => {
const { activeScopes } = useHotkeysContext()
if (import.meta.env.DEV) {
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
appLog("activeScopes change to:", activeScopes)
}, [JSON.stringify(activeScopes)])
}
return <HotkeyScopeContext value={activeScopes as HotkeyScope[]}>{children}</HotkeyScopeContext>
}
export const useHotkeyScope = () => {
const hotkeyScope = use(HotkeyScopeContext)
if (!hotkeyScope) {
throw new Error("HotkeyScopeContext not found")
}
return hotkeyScope
}
@@ -10,15 +10,13 @@ import { Provider } from "jotai"
import type { FC, PropsWithChildren } from "react"
import { Suspense } from "react"
import { GoogleReCaptchaProvider } from "react-google-recaptcha-v3"
import { HotkeysProvider } from "react-hotkeys-hook"
import { ModalStackProvider } from "~/components/ui/modal"
import { HotKeyScopeMap } from "~/constants/hotkeys"
import { jotaiStore } from "~/lib/jotai"
import { persistConfig, queryClient } from "~/lib/query-client"
import { FollowCommandManager } from "~/modules/command/command-manager"
import { GlobalHotkeysProvider } from "./global-hotkeys-provider"
import { HotkeyProvider } from "./hotkey-provider"
import { I18nProvider } from "./i18n-provider"
import { InvalidateQueryProvider } from "./invalidate-query-provider"
import {
@@ -28,7 +26,6 @@ import {
LazyLottieRenderContainer,
LazyPWAPrompt,
LazyReloadPrompt,
// specific import should add `index` postfix
} from "./lazy/index"
import { ServerConfigsProvider } from "./server-configs-provider"
import { SettingSync } from "./setting-sync"
@@ -43,7 +40,7 @@ export const RootProviders: FC<PropsWithChildren> = ({ children }) => (
<Provider store={jotaiStore}>
<MotionProvider>
<PersistQueryClientProvider persistOptions={persistConfig} client={queryClient}>
<HotkeysProvider initiallyActiveScopes={[HotKeyScopeMap.Home]}>
<HotkeyProvider>
<I18nProvider>
<ModalStackProvider>
<Toaster />
@@ -55,7 +52,7 @@ export const RootProviders: FC<PropsWithChildren> = ({ children }) => (
<StableRouterProvider />
<SettingSync />
<FollowCommandManager />
<GlobalHotkeysProvider />
{import.meta.env.DEV && <Devtools />}
{children}
@@ -70,7 +67,7 @@ export const RootProviders: FC<PropsWithChildren> = ({ children }) => (
</Suspense>
</ModalStackProvider>
</I18nProvider>
</HotkeysProvider>
</HotkeyProvider>
<InvalidateQueryProvider />
</PersistQueryClientProvider>