refactor: streamline entry action handling and replace ActionButton with CommandActionButton (#2194)

This commit is contained in:
Innei
2024-12-17 20:33:30 +08:00
committed by GitHub
10 changed files with 316 additions and 234 deletions
@@ -0,0 +1,28 @@
import type { ActionButtonProps } from "@follow/components/ui/button/action-button.js"
import { ActionButton } from "@follow/components/ui/button/action-button.js"
import { forwardRef } from "react"
import { useCommand } from "~/modules/command/hooks/use-command"
import type { FollowCommandId } from "~/modules/command/types"
export interface CommandActionButtonProps extends ActionButtonProps {
commandId: FollowCommandId
onClick: () => void
}
export const CommandActionButton = forwardRef<HTMLButtonElement, CommandActionButtonProps>(
(props, ref) => {
const command = useCommand(props.commandId)
if (!command) return null
const { icon, label } = command
return (
<ActionButton
ref={ref}
{...props}
icon={icon}
onClick={props.onClick}
tooltip={label.title}
/>
)
},
)
+18 -28
View File
@@ -1,6 +1,5 @@
import { isMobile } from "@follow/components/hooks/useMobile.js"
import { FeedViewType } from "@follow/constants"
import type { ReactNode } from "react"
import { useCallback, useMemo } from "react"
import { useShowAISummary } from "~/atoms/ai-summary"
@@ -16,7 +15,7 @@ import { whoami } from "~/atoms/user"
import { shortcuts } from "~/constants/shortcuts"
import { tipcClient } from "~/lib/client"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { getCommand, useCommands, useRunCommandFn } from "~/modules/command/hooks/use-command"
import { useRunCommandFn } from "~/modules/command/hooks/use-command"
import type { FollowCommandId } from "~/modules/command/types"
import { useEntry } from "~/store/entry"
import { useFeedById } from "~/store/feed"
@@ -62,11 +61,10 @@ export const useEntryReadabilityToggle = ({ id, url }: { id: string; url: string
export type EntryActionItem = {
id: FollowCommandId
name: string
icon?: ReactNode
active?: boolean
shortcut?: string
onClick: () => void
hide?: boolean
shortcut?: string
active?: boolean
}
export const useEntryActions = ({ entryId, view }: { entryId: string; view?: FeedViewType }) => {
@@ -87,12 +85,11 @@ export const useEntryActions = ({ entryId, view }: { entryId: string; view?: Fee
const isShowAISummary = useShowAISummary()
const isShowAITranslation = useShowAITranslation()
const commands = useCommands()
const runCmdFn = useRunCommandFn()
const actionConfigs = useMemo(() => {
void commands
if (!entryId) return []
const hasEntry = !!entry
const actionConfigs: EntryActionItem[] = useMemo(() => {
if (!hasEntry) return []
return [
{
id: COMMAND_ID.integration.saveToEagle,
@@ -192,32 +189,27 @@ export const useEntryActions = ({ entryId, view }: { entryId: string; view?: Fee
{
id: COMMAND_ID.entry.read,
onClick: runCmdFn(COMMAND_ID.entry.read, [{ entryId }]),
hide: !entry || !!entry.read || !!entry.collections || !!inList,
hide: !hasEntry || !entry.read || !!entry.collections || !!inList,
shortcut: shortcuts.entry.toggleRead.key,
},
{
id: COMMAND_ID.entry.unread,
onClick: runCmdFn(COMMAND_ID.entry.unread, [{ entryId }]),
hide: !entry || !entry.read || !!entry.collections || !!inList,
hide: !hasEntry || !entry.read || !!entry.collections || !!inList,
shortcut: shortcuts.entry.toggleRead.key,
},
]
.filter((config) => !config.hide)
.map((config) => {
const cmd = getCommand(config.id)
if (!cmd) return null
return {
...config,
name: cmd.label.title,
icon: cmd.icon,
}
})
.filter((i) => i !== null)
].filter((config) => !config.hide)
}, [
entry,
entry?.collections,
entry?.entries.url,
entry?.read,
entry?.settings?.summary,
entry?.settings?.translation,
entry?.view,
entryId,
feed?.id,
feed?.ownerUserId,
hasEntry,
inList,
isInbox,
isShowAISummary,
@@ -225,8 +217,6 @@ export const useEntryActions = ({ entryId, view }: { entryId: string; view?: Fee
isShowSourceContent,
runCmdFn,
view,
commands,
])
return actionConfigs
@@ -1,7 +1,6 @@
import { PassviseFragment } from "@follow/components/common/Fragment.js"
import { useMobile } from "@follow/components/hooks/useMobile.js"
import { AutoResizeHeight } from "@follow/components/ui/auto-resize-height/index.js"
import { ActionButton } from "@follow/components/ui/button/index.js"
import { Skeleton } from "@follow/components/ui/skeleton/index.jsx"
import type { MediaModel } from "@follow/shared/hono"
import { LRUCache } from "@follow/utils/lru-cache"
@@ -11,6 +10,7 @@ import { useLayoutEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useGeneralSettingKey } from "~/atoms/settings/general"
import { CommandActionButton } from "~/components/ui/button/command-button"
import { RelativeTime } from "~/components/ui/datetime"
import { Media } from "~/components/ui/media"
import { usePreviewMedia } from "~/components/ui/media/hooks"
@@ -143,12 +143,7 @@ const ActionBar = ({ entryId }: { entryId: string }) => {
item.id !== COMMAND_ID.entry.openInBrowser,
)
.map((item) => (
<ActionButton
icon={item.icon}
onClick={item.onClick}
tooltip={item.name}
key={item.name}
/>
<CommandActionButton commandId={item.id} onClick={item.onClick} key={item.id} />
))}
</div>
)
@@ -15,6 +15,7 @@ import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
import { useContextMenu } from "~/hooks/common/useContextMenu"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { getCommand } from "~/modules/command/hooks/use-command"
import type { FlatEntryModel } from "~/store/entry"
import { entryActions } from "~/store/entry"
@@ -106,12 +107,18 @@ export const EntryItemWrapper: FC<
] as string[]
).includes(item.id),
)
.map((item) => ({
type: "text" as const,
label: item.name,
click: () => item.onClick(),
shortcut: item.shortcut,
})),
.map((item) => {
const cmd = getCommand(item.id)
if (!cmd) return null
return {
type: "text" as const,
label: cmd?.label.title || "aa",
click: () => item.onClick(),
shortcut: item.shortcut,
}
}),
{
type: "separator" as const,
},
@@ -1,6 +1,6 @@
import { ActionButton } from "@follow/components/ui/button/index.js"
import type { FeedViewType } from "@follow/constants"
import { CommandActionButton } from "~/components/ui/button/command-button"
import { useHasModal } from "~/components/ui/modal/stacked/hooks"
import { shortcuts } from "~/constants/shortcuts"
import { useEntryActions } from "~/hooks/biz/useEntryActions"
@@ -36,14 +36,13 @@ export const EntryHeaderActions = ({ entryId, view }: { entryId: string; view?:
)
.map((config) => {
return (
<ActionButton
<CommandActionButton
active={config.active}
key={config.id}
tooltip={config.name}
icon={config.icon}
disableTriggerShortcut={hasModal}
commandId={config.id}
onClick={config.onClick}
shortcut={config.shortcut}
active={config.active}
disableTriggerShortcut={hasModal}
/>
)
})
@@ -10,6 +10,8 @@ import {
} from "~/components/ui/dropdown-menu/dropdown-menu"
import { useEntryActions } from "~/hooks/biz/useEntryActions"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { useCommand } from "~/modules/command/hooks/use-command"
import type { FollowCommandId } from "~/modules/command/types"
export const MoreActions = ({ entryId, view }: { entryId: string; view?: FeedViewType }) => {
const actionConfigs = useEntryActions({ entryId, view })
@@ -36,16 +38,25 @@ export const MoreActions = ({ entryId, view }: { entryId: string; view?: FeedVie
</DropdownMenuTrigger>
<DropdownMenuContent>
{availableActions.map((config) => (
<DropdownMenuItem
key={config.id}
className="pl-3"
icon={config.icon}
onSelect={config.onClick}
>
{config.name}
</DropdownMenuItem>
<CommandDropdownMenuItem key={config.id} commandId={config.id} onClick={config.onClick} />
))}
</DropdownMenuContent>
</DropdownMenu>
)
}
const CommandDropdownMenuItem = ({
commandId,
onClick,
}: {
commandId: FollowCommandId
onClick: () => void
}) => {
const command = useCommand(commandId)
if (!command) return null
return (
<DropdownMenuItem key={command.id} className="pl-3" icon={command.icon} onSelect={onClick}>
{command.label.title}
</DropdownMenuItem>
)
}
@@ -1,4 +1,4 @@
import { ActionButton, MotionButtonBase } from "@follow/components/ui/button/index.js"
import { MotionButtonBase } from "@follow/components/ui/button/index.js"
import { RootPortal } from "@follow/components/ui/portal/index.js"
import { findElementInShadowDOM } from "@follow/utils/dom"
import { clsx, cn } from "@follow/utils/utils"
@@ -10,6 +10,7 @@ import { useEventCallback } from "usehooks-ts"
import { useUISettingKey } from "~/atoms/settings/ui"
import { HeaderTopReturnBackButton } from "~/components/mobile/button"
import { CommandActionButton } from "~/components/ui/button/command-button"
import { useScrollTracking, useTocItems } from "~/components/ui/markdown/components/hooks"
import { ENTRY_CONTENT_RENDER_CONTAINER_ID } from "~/constants/dom"
import type { EntryActionItem } from "~/hooks/biz/useEntryActions"
@@ -17,6 +18,8 @@ import { useEntryActions } from "~/hooks/biz/useEntryActions"
import { useEntry } from "~/store/entry/hooks"
import { COMMAND_ID } from "../command/commands/id"
import { useCommand } from "../command/hooks/use-command"
import type { FollowCommandId } from "../command/types"
import { useEntryContentScrollToTop, useEntryTitleMeta } from "./atoms"
import type { EntryHeaderProps } from "./header.shared"
@@ -87,13 +90,12 @@ function EntryHeaderImpl({ view, entryId, className }: EntryHeaderProps) {
)}
>
{actionConfigs.map((item) => (
<ActionButton
icon={item.icon}
<CommandActionButton
key={item.id}
commandId={item.id}
onClick={item.onClick}
active={item.active}
shortcut={item.shortcut}
onClick={item.onClick}
tooltip={item.name}
key={item.name}
/>
))}
</div>
@@ -177,18 +179,14 @@ const HeaderRightActions = ({
>
<div className="flex flex-col items-center py-2">
{actions.map((item) => (
<MotionButtonBase
<CommandMotionButton
key={item.id}
commandId={item.id}
onClick={() => {
setCtxOpen(false)
item.onClick?.()
}}
key={item.name}
layout={false}
className="flex w-full items-center gap-2 px-4 py-2"
>
{item.icon}
{item.name}
</MotionButtonBase>
/>
))}
</div>
</m.div>
@@ -200,6 +198,28 @@ const HeaderRightActions = ({
</div>
)
}
const CommandMotionButton = ({
commandId,
onClick,
}: {
commandId: FollowCommandId
onClick: () => void
}) => {
const command = useCommand(commandId)
if (!command) return null
return (
<MotionButtonBase
onClick={onClick}
layout={false}
className="flex w-full items-center gap-2 px-4 py-2"
>
{command.icon}
{command.label.title}
</MotionButtonBase>
)
}
const TableOfContentsIcon = ({ className = "size-6" }) => {
return (
<svg
@@ -0,0 +1,169 @@
import { useFocusable } from "@follow/components/common/Focusable.jsx"
import { stopPropagation } from "@follow/utils/dom"
import { cn, getOS } from "@follow/utils/utils"
import * as React from "react"
import { useState } from "react"
import type { Options } from "react-hotkeys-hook"
import { useHotkeys } from "react-hotkeys-hook"
import { KbdCombined } from "../kbd/Kbd"
import { Tooltip, TooltipContent, TooltipPortal, TooltipTrigger } from "../tooltip"
export interface ActionButtonProps {
icon?: React.ReactNode | React.FC<ComponentType>
tooltip?: React.ReactNode
tooltipSide?: "top" | "bottom"
active?: boolean
disabled?: boolean
shortcut?: string
disableTriggerShortcut?: boolean
enableHoverableContent?: boolean
size?: "sm" | "md" | "base"
/**
* @description only trigger shortcut when focus with in `<Focusable />`
* @default false
*/
shortcutOnlyFocusWithIn?: boolean
}
const actionButtonStyleVariant = {
size: {
base: tw`text-xl size-8`,
sm: tw`text-sm size-6`,
},
}
export const ActionButton = React.forwardRef<
HTMLButtonElement,
ComponentType<ActionButtonProps> & React.HTMLAttributes<HTMLButtonElement>
>(
(
{
icon,
tooltip,
className,
tooltipSide,
children,
active,
shortcut,
disabled,
disableTriggerShortcut,
enableHoverableContent,
size = "base",
shortcutOnlyFocusWithIn,
onClick,
...rest
},
ref,
) => {
const finalShortcut =
getOS() === "Windows" ? shortcut?.replace("meta", "ctrl").replace("Meta", "Ctrl") : shortcut
const buttonRef = React.useRef<HTMLButtonElement>(null)
React.useImperativeHandle(ref, () => buttonRef.current!)
const [loading, setLoading] = useState(false)
const Trigger = (
<button
ref={buttonRef}
// @see https://github.com/radix-ui/primitives/issues/2248#issuecomment-2147056904
onFocusCapture={stopPropagation}
className={cn(
"no-drag-region inline-flex items-center justify-center",
active && "bg-zinc-500/15 hover:bg-zinc-500/20",
"rounded-md duration-200 hover:bg-theme-button-hover data-[state=open]:bg-theme-button-hover",
"disabled:cursor-not-allowed disabled:opacity-50",
actionButtonStyleVariant.size[size],
className,
)}
type="button"
disabled={disabled}
onClick={
typeof onClick === "function"
? async (e) => {
if (loading) return
setLoading(true)
try {
await (onClick(e) as void | Promise<void>)
} finally {
setLoading(false)
}
}
: onClick
}
{...rest}
>
{loading ? (
<i className="i-mgc-loading-3-cute-re animate-spin" />
) : typeof icon === "function" ? (
React.createElement(icon, {
className: "size-4 grayscale text-current",
})
) : (
icon
)}
{children}
</button>
)
return (
<>
{finalShortcut && !disableTriggerShortcut && (
<HotKeyTrigger
shortcut={finalShortcut}
fn={() => buttonRef.current?.click()}
shortcutOnlyFocusWithIn={shortcutOnlyFocusWithIn}
/>
)}
{tooltip ? (
<Tooltip disableHoverableContent={!enableHoverableContent}>
<TooltipTrigger aria-label={typeof tooltip === "string" ? tooltip : undefined} asChild>
{Trigger}
</TooltipTrigger>
<TooltipPortal>
<TooltipContent className="flex items-center gap-1" side={tooltipSide ?? "bottom"}>
{tooltip}
{!!finalShortcut && (
<div className="ml-1">
<KbdCombined className="text-foreground/80">{finalShortcut}</KbdCombined>
</div>
)}
</TooltipContent>
</TooltipPortal>
</Tooltip>
) : (
Trigger
)}
</>
)
},
)
const HotKeyTrigger = ({
shortcut,
fn,
options,
shortcutOnlyFocusWithIn,
}: {
shortcut: string
fn: () => void
options?: Options
shortcutOnlyFocusWithIn?: boolean
}) => {
const isFocusWithIn = useFocusable()
const enabledInOptions = options?.enabled || true
useHotkeys(shortcut, fn, {
preventDefault: true,
enabled: shortcutOnlyFocusWithIn
? isFocusWithIn
? enabledInOptions
: false
: enabledInOptions,
...options,
})
return null
}
+3 -165
View File
@@ -1,18 +1,11 @@
import { useFocusable } from "@follow/components/common/Focusable.jsx"
import { useMobile } from "@follow/components/hooks/useMobile.js"
import { LoadingCircle } from "@follow/components/ui/loading/index.jsx"
import { stopPropagation } from "@follow/utils/dom"
import { cn, getOS } from "@follow/utils/utils"
import { cn } from "@follow/utils/utils"
import type { VariantProps } from "class-variance-authority"
import type { HTMLMotionProps } from "framer-motion"
import { m } from "framer-motion"
import * as React from "react"
import { useState } from "react"
import type { Options } from "react-hotkeys-hook"
import { useHotkeys } from "react-hotkeys-hook"
import { KbdCombined } from "../kbd/Kbd"
import { Tooltip, TooltipContent, TooltipPortal, TooltipTrigger } from "../tooltip"
import { styledButtonVariant } from "./variants"
export interface BaseButtonProps {
@@ -21,163 +14,6 @@ export interface BaseButtonProps {
// BIZ buttons
export interface ActionButtonProps {
icon?: React.ReactNode | React.FC<ComponentType>
tooltip?: React.ReactNode
tooltipSide?: "top" | "bottom"
active?: boolean
disabled?: boolean
shortcut?: string
disableTriggerShortcut?: boolean
enableHoverableContent?: boolean
size?: "sm" | "md" | "base"
/**
* @description only trigger shortcut when focus with in `<Focusable />`
* @default false
*/
shortcutOnlyFocusWithIn?: boolean
}
const actionButtonStyleVariant = {
size: {
base: tw`text-xl size-8`,
sm: tw`text-sm size-6`,
},
}
export const ActionButton = React.forwardRef<
HTMLButtonElement,
ComponentType<ActionButtonProps> & React.HTMLAttributes<HTMLButtonElement>
>(
(
{
icon,
tooltip,
className,
tooltipSide,
children,
active,
shortcut,
disabled,
disableTriggerShortcut,
enableHoverableContent,
size = "base",
shortcutOnlyFocusWithIn,
onClick,
...rest
},
ref,
) => {
const finalShortcut =
getOS() === "Windows" ? shortcut?.replace("meta", "ctrl").replace("Meta", "Ctrl") : shortcut
const buttonRef = React.useRef<HTMLButtonElement>(null)
React.useImperativeHandle(ref, () => buttonRef.current!)
const [loading, setLoading] = useState(false)
const Trigger = (
<button
ref={buttonRef}
// @see https://github.com/radix-ui/primitives/issues/2248#issuecomment-2147056904
onFocusCapture={stopPropagation}
className={cn(
"no-drag-region inline-flex items-center justify-center",
active && "bg-zinc-500/15 hover:bg-zinc-500/20",
"rounded-md duration-200 hover:bg-theme-button-hover data-[state=open]:bg-theme-button-hover",
"disabled:cursor-not-allowed disabled:opacity-50",
actionButtonStyleVariant.size[size],
className,
)}
type="button"
disabled={disabled}
onClick={
typeof onClick === "function"
? async (e) => {
if (loading) return
setLoading(true)
try {
await (onClick(e) as void | Promise<void>)
} finally {
setLoading(false)
}
}
: onClick
}
{...rest}
>
{loading ? (
<i className="i-mgc-loading-3-cute-re animate-spin" />
) : typeof icon === "function" ? (
React.createElement(icon, {
className: "size-4 grayscale text-current",
})
) : (
icon
)}
{children}
</button>
)
return (
<>
{finalShortcut && !disableTriggerShortcut && (
<HotKeyTrigger
shortcut={finalShortcut}
fn={() => buttonRef.current?.click()}
shortcutOnlyFocusWithIn={shortcutOnlyFocusWithIn}
/>
)}
{tooltip ? (
<Tooltip disableHoverableContent={!enableHoverableContent}>
<TooltipTrigger aria-label={typeof tooltip === "string" ? tooltip : undefined} asChild>
{Trigger}
</TooltipTrigger>
<TooltipPortal>
<TooltipContent className="flex items-center gap-1" side={tooltipSide ?? "bottom"}>
{tooltip}
{!!finalShortcut && (
<div className="ml-1">
<KbdCombined className="text-foreground/80">{finalShortcut}</KbdCombined>
</div>
)}
</TooltipContent>
</TooltipPortal>
</Tooltip>
) : (
Trigger
)}
</>
)
},
)
const HotKeyTrigger = ({
shortcut,
fn,
options,
shortcutOnlyFocusWithIn,
}: {
shortcut: string
fn: () => void
options?: Options
shortcutOnlyFocusWithIn?: boolean
}) => {
const isFocusWithIn = useFocusable()
const enabledInOptions = options?.enabled || true
useHotkeys(shortcut, fn, {
preventDefault: true,
enabled: shortcutOnlyFocusWithIn
? isFocusWithIn
? enabledInOptions
: false
: enabledInOptions,
...options,
})
return null
}
const motionBaseMap = {
pc: {
whileFocus: { scale: 1.02 },
@@ -298,3 +134,5 @@ export const IconButton = React.forwardRef<
</button>
)
})
export { ActionButton, type ActionButtonProps } from "./action-button"
@@ -0,0 +1,25 @@
import type * as React from "react"
export interface BaseButtonProps {
isLoading?: boolean
}
// BIZ buttons
export interface ActionButtonProps {
icon?: React.ReactNode | React.FC<ComponentType>
tooltip?: React.ReactNode
tooltipSide?: "top" | "bottom"
active?: boolean
disabled?: boolean
shortcut?: string
disableTriggerShortcut?: boolean
enableHoverableContent?: boolean
size?: "sm" | "md" | "base"
/**
* @description only trigger shortcut when focus with in `<Focusable />`
* @default false
*/
shortcutOnlyFocusWithIn?: boolean
}