release(mobile): Release v0.2.0

release(mobile): Release v0.2.0
This commit is contained in:
DIYgod
2025-05-25 09:58:17 +08:00
committed by GitHub
254 changed files with 8255 additions and 2846 deletions
+2
View File
@@ -7,3 +7,5 @@ apps/external/postcss.config.cjs
apps/mobile/android
apps/mobile/ios
apps/mobile/native/example
+2 -2
View File
@@ -632,7 +632,7 @@ state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
Copyright (C) 2024-Present RSSNext
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -652,7 +652,7 @@ Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
Folo Copyright (C) 2024-Present RSSNext
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
+1
View File
@@ -48,6 +48,7 @@ Feel free to try it using the following methods:
| iOS | <a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604" target="_blank"><img src="https://github.com/user-attachments/assets/a94d8698-2a11-4f43-9b0a-b756b17b61f7" alt="App Store" height="55"/></a> |
| macOS | <a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604" target="_blank"><img src="https://github.com/user-attachments/assets/0d47f902-7fa3-494e-ad28-9ab11af5e6d4" alt="Microsoft Store" height="55"/></a> <a href="https://github.com/RSSNext/Folo/releases/latest" target="_blank"><img src="https://github.com/user-attachments/assets/cf61e197-d756-4606-a8ad-fb591f79fdfc" alt="App Store" height="55"/></a> |
| Windows | <a href="https://apps.microsoft.com/detail/9nvfzpv0v0ht?mode=direct" target="_blank"><img src="https://github.com/user-attachments/assets/b3112bab-9dd0-4893-9488-890dcb368f70" alt="Microsoft Store" height="55"/></a> <a href="https://github.com/RSSNext/Folo/releases/latest" target="_blank"><img src="https://github.com/user-attachments/assets/cf61e197-d756-4606-a8ad-fb591f79fdfc" alt="App Store" height="55"/></a> |
| Android | <a href="https://play.google.com/store/apps/details?id=is.follow" target="_blank"><img src="https://github.com/user-attachments/assets/17ce1d5b-e906-4d42-aec2-66877da9fd95" alt="Google Play" height="55"/></a> |
| Linux | <a href="https://github.com/RSSNext/Folo/releases/latest" target="_blank"><img src="https://github.com/user-attachments/assets/cf61e197-d756-4606-a8ad-fb591f79fdfc" alt="App Store" height="55"/></a> |
You can also install using the following methods maintained by our community:
+2
View File
@@ -2,6 +2,8 @@
## Shiny new things
- **New Keyboard Shortcuts System**: Introduced a comprehensive command shortcut system supporting multiple categories including global operations, layout controls, timeline navigation, content rendering, subscription management, and entry actions. Access all available shortcuts and customize key bindings via `Settings` -> `Shortcuts`.
## Improvements
## No longer broken
@@ -51,6 +51,7 @@ export const viteRenderBaseConfig = {
codeInspectorPlugin({
bundler: "vite",
hotKeys: ["altKey"],
editor: "cursor",
}),
sentryVitePlugin({
+4
View File
@@ -107,6 +107,10 @@ const config: ForgeConfig = {
name: "Folo",
schemes: ["follow"],
},
{
name: "Folo",
schemes: ["folo"],
},
],
afterCopy: [
+3 -2
View File
@@ -2,7 +2,7 @@ import "./side-effects"
import { electronApp, optimizer } from "@electron-toolkit/utils"
import { callWindowExpose } from "@follow/shared/bridge"
import { APP_PROTOCOL, DEV } from "@follow/shared/constants"
import { DEV, LEGACY_APP_PROTOCOL } from "@follow/shared/constants"
import { env } from "@follow/shared/env.desktop"
import { createBuildSafeHeaders } from "@follow/utils/headers"
import { IMAGE_PROXY_URL } from "@follow/utils/img-proxy"
@@ -101,7 +101,7 @@ function bootstrap() {
})
// Set app user model id for windows
electronApp.setAppUserModelId(`re.${APP_PROTOCOL}`)
electronApp.setAppUserModelId(`re.${LEGACY_APP_PROTOCOL}`)
session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
details.requestHeaders = buildSafeHeaders({
@@ -117,6 +117,7 @@ function bootstrap() {
updateProxy()
registerUpdater()
registerAppTray()
updateNotificationsToken()
app.on("open-url", (_, url) => {
if (mainWindow && !mainWindow.isDestroyed()) {
+12 -13
View File
@@ -2,7 +2,7 @@ import path from "node:path"
import { getRendererHandlers, registerIpcMain } from "@egoist/tipc/main"
import { PushReceiver } from "@eneris/push-receiver"
import { APP_PROTOCOL, DEV } from "@follow/shared/constants"
import { APP_PROTOCOL, DEV, LEGACY_APP_PROTOCOL } from "@follow/shared/constants"
import { env } from "@follow/shared/env.desktop"
import type { MessagingData } from "@follow/shared/hono"
import { app, nativeTheme, Notification, protocol, shell } from "electron"
@@ -18,7 +18,7 @@ import { registerAppMenu } from "./menu"
import type { RendererHandlers } from "./renderer-handlers"
import { initializeSentry } from "./sentry"
import { router } from "./tipc"
import { createMainWindow, getMainWindow } from "./window"
import { getMainWindowOrCreate } from "./window"
if (process.argv.length === 3 && process.argv[2]!.startsWith("follow-dev:")) {
process.env.NODE_ENV = "development"
@@ -31,14 +31,16 @@ export function initializeAppStage0() {
initializeSentry()
}
export const initializeAppStage1 = () => {
if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient(APP_PROTOCOL, process.execPath, [
path.resolve(process.argv[1]!),
])
const protocols = [LEGACY_APP_PROTOCOL, APP_PROTOCOL]
for (const protocol of protocols) {
if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient(protocol, process.execPath, [path.resolve(process.argv[1]!)])
}
} else {
app.setAsDefaultProtocolClient(protocol)
}
} else {
app.setAsDefaultProtocolClient(APP_PROTOCOL)
}
registerIpcMain(router)
@@ -184,10 +186,7 @@ const registerPushNotifications = async () => {
body: data.description,
})
notification.on("click", () => {
let mainWindow = getMainWindow()
if (!mainWindow) {
mainWindow = createMainWindow()
}
const mainWindow = getMainWindowOrCreate()
mainWindow.restore()
mainWindow.focus()
const handlers = getRendererHandlers<RendererHandlers>(mainWindow.webContents)
+1
View File
@@ -27,6 +27,7 @@ export const updateNotificationsToken = async (newCredentials?: Credentials) =>
channel: notificationChannel,
},
})
logger.info("updateNotificationsToken success: ", credentials.fcm.token)
} catch (error) {
logger.error("updateNotificationsToken error: ", error)
}
-11
View File
@@ -135,18 +135,7 @@ export const registerAppMenu = () => {
{ role: "zoomIn", label: t("menu.zoomIn") },
{ role: "zoomOut", label: t("menu.zoomOut") },
{ type: "separator" },
{
type: "normal",
label: t("menu.zenMode"),
accelerator: "Ctrl+Shift+Z",
click: () => {
const mainWindow = getMainWindow()
if (!mainWindow) return
const caller = callWindowExpose(mainWindow)
caller.zenMode()
},
},
{ role: "togglefullscreen", label: t("menu.toggleFullScreen") },
],
},
@@ -51,4 +51,7 @@ export const settingRoute = {
updateProxy()
return result
}),
getMessagingToken: t.procedure.action(async () => {
return store.get("notifications-credentials")
}),
}
+12 -3
View File
@@ -2,9 +2,9 @@ import path from "node:path"
import { fileURLToPath } from "node:url"
import { is } from "@electron-toolkit/utils"
import { APP_PROTOCOL } from "@follow/shared"
import { LEGACY_APP_PROTOCOL } from "@follow/shared"
import { callWindowExpose, WindowState } from "@follow/shared/bridge"
import { DEV } from "@follow/shared/constants"
import { APP_PROTOCOL, DEV } from "@follow/shared/constants"
import type { BrowserWindowConstructorOptions } from "electron"
import { app, BrowserWindow, screen, shell } from "electron"
import type { Event } from "electron/main"
@@ -112,7 +112,16 @@ export function createWindow(
const handleExternalProtocol = async (e: Event, url: string, window: BrowserWindow) => {
const { protocol } = new URL(url)
const ignoreProtocols = ["http", "https", APP_PROTOCOL, "file", "code", "cursor", "app"]
const ignoreProtocols = [
"http",
"https",
LEGACY_APP_PROTOCOL,
APP_PROTOCOL,
"file",
"code",
"cursor",
"app",
]
if (ignoreProtocols.includes(protocol.slice(0, -1))) {
return
}
+1
View File
@@ -6,6 +6,7 @@ declare global {
api?: { canWindowBlur: boolean }
platform: NodeJS.Platform
}
export const APP_NAME = "Folo"
}
declare module "virtual:pwa-register/react" {
+1 -2
View File
@@ -62,8 +62,7 @@
setTheme()
// Can not get window.electron so check userAgent
const isElectron = navigator.userAgent.includes("Electron")
const isRN = window.__RN__
document.documentElement.dataset.buildType = isRN ? "rn" : isElectron ? "electron" : "web"
document.documentElement.dataset.buildType = isElectron ? "electron" : "web"
</script>
<script>
const isMobile = window.innerWidth < 1024
+1
View File
@@ -89,6 +89,7 @@
"shiki": "3.3.0",
"sonner": "2.0.3",
"tinykeys": "3.0.0",
"title-case": "4.3.2",
"tldts": "7.0.4",
"ufo": "1.6.1",
"use-context-selector": "2.0.0",
@@ -4,6 +4,8 @@ import { atom } from "jotai"
import { createAtomHooks } from "~/lib/jotai"
export const [, , useAppIsReady, , appIsReady, setAppIsReady] = createAtomHooks(atom(false))
export const [, , useAppMessagingToken, , appMessagingToken, setAppMessagingToken] =
createAtomHooks(atom<string | null>(null))
export const [, , useAppSearchOpen, , , setAppSearchOpen] = createAtomHooks(atom(false))
@@ -101,7 +101,7 @@ function transformMenuItemsForNative(nextItems: FollowMenuItem[]): ElectronMenuI
click: item.click,
enabled:
(!item.disabled && item.click !== undefined) || (!!item.submenu && item.submenu.length > 0),
accelerator: item.shortcut?.replace("Meta", "CmdOrCtrl"),
accelerator: item.shortcut?.replace("$mod", "CmdOrCtrl"),
checked: typeof item.checked === "boolean" ? item.checked : undefined,
submenu:
item.submenu.length > 0
@@ -215,10 +215,12 @@ export class BaseMenuItemText {
}
}
export type MenuItemTextConfig = BaseMenuItemTextConfig & {
hide?: boolean
submenu?: MenuItemInput[]
}
export type MenuItemTextConfig = Prettify<
BaseMenuItemTextConfig & {
hide?: boolean
submenu?: MenuItemInput[]
}
>
export class MenuItemText extends BaseMenuItemText {
protected __submenu: FollowMenuItem[]
@@ -10,7 +10,7 @@ import { getDefaultLanguage } from "~/lib/language"
export const DEFAULT_ACTION_LANGUAGE = "default"
const createDefaultSettings = (): GeneralSettings => ({
export const createDefaultGeneralSettings = (): GeneralSettings => ({
...defaultGeneralSettings,
language: getDefaultLanguage(),
})
@@ -26,7 +26,7 @@ const {
useSettingValue: useGeneralSettingValueInternal,
settingAtom: __generalSettingAtom,
} = createSettingAtom("general", createDefaultSettings)
} = createSettingAtom("general", createDefaultGeneralSettings)
const [
useGeneralSettingKey,
@@ -3,7 +3,7 @@ import { defaultUISettings } from "@follow/shared/settings/defaults"
import { enhancedUISettingKeys } from "@follow/shared/settings/enhanced"
import type { UISettings } from "@follow/shared/settings/interface"
import { jotaiStore } from "@follow/utils/jotai"
import { atom, useAtomValue, useSetAtom } from "jotai"
import { atom, useAtomValue } from "jotai"
import { useEventCallback } from "usehooks-ts"
import { getDefaultLanguage } from "~/lib/language"
@@ -11,7 +11,7 @@ import { DEFAULT_ACTION_ORDER } from "~/modules/customize-toolbar/constant"
import { hookEnhancedSettings } from "./general"
export const createDefaultSettings = (): UISettings => ({
export const createDefaultUISettings = (): UISettings => ({
...defaultUISettings,
// Action Order
@@ -33,7 +33,7 @@ const {
getSettings: getUISettingsInternal,
useSettingValue: useUISettingValueInternal,
settingAtom: __uiSettingAtom,
} = createSettingAtom("ui", createDefaultSettings)
} = createSettingAtom("ui", createDefaultUISettings)
const [useUISettingKey, useUISettingSelector, useUISettingKeys, getUISettings, useUISettingValue] =
hookEnhancedSettings(
@@ -69,10 +69,10 @@ export const useIsZenMode = () => useAtomValue(zenModeAtom)
export const getIsZenMode = () => jotaiStore.get(zenModeAtom)
export const useSetZenMode = () => {
const setZenMode = useSetAtom(zenModeAtom)
return useEventCallback((checked: boolean) => {
setZenMode(checked)
})
return setZenMode
}
export const setZenMode = (checked: boolean) => {
jotaiStore.set(zenModeAtom, checked)
}
export const useToggleZenMode = () => {
@@ -0,0 +1,27 @@
import type { FocusableProps } from "@follow/components/common/Focusable/Focusable.js"
import { Focusable as FocusableComponent } from "@follow/components/common/Focusable/Focusable.js"
import { FloatingLayerScope, HotkeyScope } from "~/constants"
interface BizFocusableProps extends Omit<FocusableProps, "scope"> {
scope: HotkeyScope
}
export const Focusable = FocusableComponent as Component<
Prettify<BizFocusableProps> &
React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
>
export const FocusablePresets = {
isNotFloatingLayerScope: (v: Set<string>) => !FloatingLayerScope.some((s) => v.has(s)),
isSubscriptionList: (scope: Set<string>) => {
return (
scope.size === 0 ||
scope.has(HotkeyScope.SubscriptionList) ||
(scope.has(HotkeyScope.Home) && scope.size === 1)
)
},
isSubscriptionOrTimeline: (v: Set<string>) => {
return v.has(HotkeyScope.SubscriptionList) || v.has(HotkeyScope.Timeline) || v.size === 0
},
}
@@ -44,7 +44,7 @@ export const NotFound = () => {
}, [])
const navigate = useNavigate()
if (window.__RN__ && location.pathname.endsWith("/index.html")) {
if (location.pathname.endsWith("/index.html")) {
return <Navigate to="/" />
}
@@ -1,22 +1,31 @@
import { Focusable } from "@follow/components/common/Focusable/index.js"
import { SYSTEM_CAN_UNDER_BLUR_WINDOW } from "@follow/shared/constants"
import { cn } from "@follow/utils/utils"
import type * as React from "react"
import type { ComponentPropsWithoutRef, ElementType } from "react"
import { useUISettingKey } from "~/atoms/settings/ui"
type Props = Component<
React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
>
const MacOSVibrancy: Props = ({ children, ...rest }) => <Focusable {...rest}>{children}</Focusable>
type Props<T extends ElementType = "div"> = {
as?: T
ref?: React.Ref<HTMLElement>
} & ComponentPropsWithoutRef<T>
const Noop: Props = ({ children, className, ...rest }) => (
<Focusable className={cn("bg-sidebar", className)} {...rest}>
{children}
</Focusable>
)
const MacOSVibrancy = <T extends ElementType = "div">({ children, as, ...rest }: Props<T>) => {
const Component = as || "div"
return <Component {...rest}>{children}</Component>
}
export const WindowUnderBlur: Props = SYSTEM_CAN_UNDER_BLUR_WINDOW
? (props) => {
const Noop = <T extends ElementType = "div">({ children, className, as, ...rest }: Props<T>) => {
const Component = as || "div"
return (
<Component className={cn("bg-sidebar", className)} {...rest}>
{children}
</Component>
)
}
export const WindowUnderBlur = SYSTEM_CAN_UNDER_BLUR_WINDOW
? <T extends ElementType = "div">(props: Props<T>) => {
const opaqueSidebar = useUISettingKey("opaqueSidebar")
if (opaqueSidebar) {
return <Noop {...props} />
@@ -7,18 +7,21 @@ import {
} from "@follow/components/ui/tooltip/index.js"
import { stopPropagation } from "@follow/utils/dom"
import dayjs from "dayjs"
import { useCallback, useEffect, useRef, useState } from "react"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useGeneralSettingSelector } from "~/atoms/settings/general"
import { useUISettingKey } from "~/atoms/settings/ui"
export { RelativeTime } from "@follow/components/ui/datetime/index.js"
const formatTemplateStringShort = "ll"
export const RelativeDay = ({ date }: { date: Date }) => {
const { t } = useTranslation("common")
const language = useGeneralSettingSelector((s) => s.language)
const dateFormatValue = useUISettingKey("dateFormat")
const formatTemplateString = "lll"
const dateFormat = dateFormatValue === "default" ? formatTemplateString : dateFormatValue
const formatDateString = useCallback(
(date: Date) => {
const now = new Date()
@@ -35,21 +38,10 @@ export const RelativeDay = ({ date }: { date: Date }) => {
} else if (diffDays === 1) {
return t("time.yesterday")
} else {
let locale: Intl.Locale
try {
locale = new Intl.Locale(language.replace("_", "-"))
} catch {
locale = new Intl.Locale("en-US")
}
return date.toLocaleDateString(locale, {
weekday: "long",
month: "short",
day: "numeric",
})
return dayjs(date).format("ll")
}
},
[t, language],
[t],
)
const timerRef = useRef<any>(null)
@@ -70,7 +62,7 @@ export const RelativeDay = ({ date }: { date: Date }) => {
}
}, [date, formatDateString, language])
const formated = dayjs(date).format(formatTemplateStringShort)
const formated = useMemo(() => dayjs(date).format(dateFormat), [dateFormat, date])
if (formated === dateString) {
return <>{dateString}</>
@@ -1,23 +1,20 @@
import { Divider } from "@follow/components/ui/divider/Divider.js"
import { Kbd } from "@follow/components/ui/kbd/Kbd.js"
import { RootPortal } from "@follow/components/ui/portal/index.js"
import { useTypeScriptHappyCallback } from "@follow/hooks"
import { cn } from "@follow/utils/utils"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import * as React from "react"
import { Focusable } from "~/components/common/Focusable"
import { HotkeyScope } from "~/constants"
import { useConditionalHotkeyScope } from "~/hooks/common"
const DropdownMenu: typeof DropdownMenuPrimitive.Root = (props) => {
const [open, setOpen] = React.useState(!!props.open)
useConditionalHotkeyScope(HotkeyScope.DropdownMenu, open)
return (
<DropdownMenuPrimitive.Root
{...props}
onOpenChange={useTypeScriptHappyCallback(
(open) => {
setOpen(open)
props.onOpenChange?.(open)
},
[props.onOpenChange],
@@ -94,16 +91,18 @@ const DropdownMenuContent = ({
}) => {
return (
<RootPortal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"bg-material-medium backdrop-blur-background text-text shadow-context-menu z-[60] min-w-32 overflow-hidden rounded-[6px] border p-1",
"motion-scale-in-75 motion-duration-150 text-body lg:animate-none",
className,
)}
{...props}
/>
<Focusable scope={HotkeyScope.DropdownMenu} className="contents">
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"bg-material-medium backdrop-blur-background text-text shadow-context-menu z-[60] min-w-32 overflow-hidden rounded-[6px] border p-1",
"motion-scale-in-75 motion-duration-150 text-body lg:animate-none",
className,
)}
{...props}
/>
</Focusable>
</RootPortal>
)
}
@@ -116,12 +115,14 @@ const DropdownMenuItem = ({
icon,
active,
highlightColor = "accent",
shortcut,
...props
}: React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
icon?: React.ReactNode | ((props?: { isActive?: boolean }) => React.ReactNode)
active?: boolean
highlightColor?: "accent" | "gray"
shortcut?: string
} & { ref?: React.Ref<React.ElementRef<typeof DropdownMenuPrimitive.Item> | null> }) => (
<DropdownMenuPrimitive.Item
ref={ref}
@@ -144,8 +145,14 @@ const DropdownMenuItem = ({
</span>
)}
{props.children}
{/* Justify Fill */}
{!!icon && <span className="ml-1.5 size-4" />}
{!!shortcut && (
<Kbd wrapButton={false} className="ml-auto">
{shortcut}
</Kbd>
)}
</DropdownMenuPrimitive.Item>
)
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
@@ -1,10 +1,14 @@
import { useViewport } from "@follow/components/hooks/useViewport.js"
import { EllipsisHorizontalTextWithTooltip } from "@follow/components/ui/typography/EllipsisWithTooltip.js"
import { nextFrame } from "@follow/utils/dom"
import { EventBus } from "@follow/utils/event-bus"
import { cn } from "@follow/utils/utils"
import * as HoverCard from "@radix-ui/react-hover-card"
import { AnimatePresence, m } from "motion/react"
import { memo, use, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react"
import { useRealInWideMode } from "~/atoms/settings/ui"
import { COMMAND_ID } from "~/modules/command/commands/id"
import {
useWrappedElementPosition,
useWrappedElementSize,
@@ -172,6 +176,7 @@ const TocHoverCard: React.FC<TocHoverCardProps> = ({
style={{ paddingLeft: `${(heading.depth - rootDepth) * 12}px` }}
>
<button
tabIndex={1}
className={cn(
"group flex w-full cursor-pointer justify-between py-1",
index === currentScrollRange[0] ? "text-accent" : "",
@@ -179,11 +184,16 @@ const TocHoverCard: React.FC<TocHoverCardProps> = ({
type="button"
onClick={() => {
handleScrollTo(index, heading.$heading, heading.anchorId)
nextFrame(() => {
EventBus.dispatch(COMMAND_ID.layout.focusToEntryRender, {
highlightBoundary: false,
})
})
}}
>
<span className="group-hover:text-accent/80 select-none duration-200">
<EllipsisHorizontalTextWithTooltip className="group-hover:text-accent/80 max-w-prose select-none truncate duration-200">
{heading.title}
</span>
</EllipsisHorizontalTextWithTooltip>
<span className="ml-4 select-none text-[8px] opacity-50">
H{heading.depth}
@@ -1,4 +1,4 @@
import { Focusable } from "@follow/components/common/Focusable/index.js"
"~/components/common/Focusable.js"
import { Spring } from "@follow/components/constants/spring.js"
import { ActionButton, MotionButtonBase } from "@follow/components/ui/button/index.js"
import type { HTMLMediaState } from "@follow/hooks"
@@ -23,7 +23,9 @@ import { createContext, useContext, useContextSelector } from "use-context-selec
import { useEventCallback } from "usehooks-ts"
import { AudioPlayer } from "~/atoms/player"
import { Focusable } from "~/components/common/Focusable"
import { IconScaleTransition } from "~/components/ux/transition/icon"
import { HotkeyScope } from "~/constants"
import { VolumeSlider } from "./VolumeSlider"
@@ -137,7 +139,11 @@ export const VideoPlayer = ({
)
return (
<Focusable className="center group relative size-full" ref={wrapperRef}>
<Focusable
className="center group relative size-full"
ref={wrapperRef}
scope={HotkeyScope.VideoPlayer}
>
{element}
<div className="center pointer-events-none absolute inset-0">
<m.div
@@ -27,11 +27,11 @@ import { useEventCallback } from "usehooks-ts"
import { useUISettingKey } from "~/atoms/settings/ui"
import { AppErrorBoundary } from "~/components/common/AppErrorBoundary"
import { Focusable } from "~/components/common/Focusable"
import { SafeFragment } from "~/components/common/Fragment"
import { m } from "~/components/common/Motion"
import { ErrorComponentType } from "~/components/errors/enum"
import { ElECTRON_CUSTOM_TITLEBAR_HEIGHT } from "~/constants"
import { useSwitchHotKeyScope } from "~/hooks/common"
import { ElECTRON_CUSTOM_TITLEBAR_HEIGHT, HotkeyScope } from "~/constants"
import { modalStackAtom } from "./atom"
import { MODAL_STACK_Z_INDEX, modalMontionConfig } from "./constants"
@@ -192,8 +192,6 @@ export const ModalInternal = memo(function Modal({
}
}, [currentIsClosing])
useShortcutScope()
const modalStyle = resizeableStyle
const { handleSelectStart, handleDetectSelectEnd, isSelectingRef } = useModalSelect()
const handleClickOutsideToDismiss = useCallback(
@@ -253,7 +251,8 @@ export const ModalInternal = memo(function Modal({
onPointerDownOutside={preventDefault}
onOpenAutoFocus={openAutoFocus}
>
<div
<Focusable
scope={HotkeyScope.Modal}
ref={setEdgeElementRef}
className={cn(
"no-drag-region fixed",
@@ -282,7 +281,7 @@ export const ModalInternal = memo(function Modal({
<CustomModalComponent>{finalChildren}</CustomModalComponent>
</ModalContext>
</div>
</div>
</Focusable>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
@@ -304,7 +303,8 @@ export const ModalInternal = memo(function Modal({
onPointerDownOutside={preventDefault}
onOpenAutoFocus={openAutoFocus}
>
<div
<Focusable
scope={HotkeyScope.Modal}
ref={setEdgeElementRef}
onContextMenu={preventDefault}
className={cn(
@@ -395,7 +395,7 @@ export const ModalInternal = memo(function Modal({
</div>
</ResizeSwitch>
</m.div>
</div>
</Focusable>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
@@ -403,16 +403,6 @@ export const ModalInternal = memo(function Modal({
)
})
const useShortcutScope = () => {
const switchHotkeyScope = useSwitchHotKeyScope()
useEffect(() => {
switchHotkeyScope("Modal")
return () => {
switchHotkeyScope("Home")
}
}, [switchHotkeyScope])
}
const ModalContext: FC<
PropsWithChildren & {
modalContextProps: CurrentModalContentProps
@@ -14,4 +14,9 @@ export const ROUTE_FEED_IN_LIST = "list-"
export const ROUTE_FEED_IN_INBOX = "inbox-"
export const ROUTE_TIMELINE_OF_VIEW = "view-"
// Inbox subscription's feedId is `inbox-${inboxId}`, we need to convert it between unread and entry store.
export const INBOX_PREFIX_ID = "inbox-"
export const getInboxOrFeedIdFromFeedId = (id: string) =>
id.startsWith(INBOX_PREFIX_ID) ? id.slice(INBOX_PREFIX_ID.length) : id
export const getInboxIdWithPrefix = (id: string) =>
id.startsWith(INBOX_PREFIX_ID) ? id : INBOX_PREFIX_ID + id
@@ -1,7 +1,9 @@
import { IN_ELECTRON } from "@follow/shared/constants"
const OpenInBrowser = (_t?: any) =>
IN_ELECTRON ? "keys.entry.openInBrowser" : "keys.entry.openInNewTab"
IN_ELECTRON
? tShortcuts("command.subscription.open_in_browser.title")
: tShortcuts("command.subscription.open_in_tab.title")
export const COPY_MAP = {
OpenInBrowser,
@@ -3,9 +3,19 @@ export enum HotkeyScope {
Menu = "menu",
Modal = "modal",
DropdownMenu = "dropdown-menu",
Recording = "recording",
// Atom Scope
VideoPlayer = "video-player",
Timeline = "timeline",
EntryRender = "entry-render",
SubscriptionList = "subscription-list",
SubLayer = "sub-layer",
}
export const FloatingLayerScope = [
HotkeyScope.Modal,
HotkeyScope.DropdownMenu,
HotkeyScope.Menu,
HotkeyScope.Recording,
] as const
@@ -1,168 +0,0 @@
import { transformShortcut } from "@follow/utils/utils"
import { COPY_MAP } from "~/constants"
type Shortcuts = Record<
string,
Record<string, { name: I18nKeysForShortcuts; key: string; extra?: string }>
>
const shortcutConfigs = {
subscriptions: {
add: {
name: tShortcuts("keys.subscriptions.add"),
key: "Meta+T",
},
switchToView: {
name: tShortcuts("keys.subscriptions.switchToView"),
key: "1, 2, 3, 4, 5, 6",
},
switchNextView: {
name: tShortcuts("keys.subscriptions.switchNextView"),
key: "Tab, ArrowRight",
},
switchPreviousView: {
name: tShortcuts("keys.subscriptions.switchPreviousView"),
key: "Shift+Tab, ArrowLeft",
},
nextSubscription: {
name: tShortcuts("keys.subscriptions.nextSubscription"),
key: "J, ArrowDown",
},
previousSubscription: {
name: tShortcuts("keys.subscriptions.previousSubscription"),
key: "K, ArrowUp",
},
toggleFolderCollapse: {
name: tShortcuts("keys.subscriptions.toggleFolderCollapse"),
key: "Z",
},
},
layout: {
toggleSidebar: {
name: tShortcuts("keys.layout.toggleSidebar"),
key: "Meta+B, [",
},
showShortcuts: {
name: tShortcuts("keys.layout.showShortcuts"),
key: "H",
},
toggleWideMode: {
name: tShortcuts("keys.layout.toggleWideMode"),
key: "Meta+[",
},
zenMode: {
name: tShortcuts("keys.layout.zenMode"),
key: "Ctrl+Shift+Z",
},
},
entries: {
refetch: {
name: tShortcuts("keys.entries.refetch"),
key: "R",
},
previous: {
name: tShortcuts("keys.entries.previous"),
key: "K, ArrowUp",
},
next: {
name: tShortcuts("keys.entries.next"),
key: "J, ArrowDown",
},
markAllAsRead: {
name: tShortcuts("keys.entries.markAllAsRead"),
key: "Shift+Meta+A",
},
toggleUnreadOnly: {
name: tShortcuts("keys.entries.toggleUnreadOnly"),
key: "U",
},
},
entry: {
toggleRead: {
name: tShortcuts("keys.entry.toggleRead"),
key: "M",
},
toggleStarred: {
name: tShortcuts("keys.entry.toggleStarred"),
key: "S",
},
openInBrowser: {
name: COPY_MAP.OpenInBrowser(),
key: "B",
extra: "Double Click",
},
tts: {
name: tShortcuts("keys.entry.tts"),
key: "Shift+Meta+V",
},
copyLink: {
name: tShortcuts("keys.entry.copyLink"),
key: "Shift+Meta+C",
},
copyTitle: {
name: tShortcuts("keys.entry.copyTitle"),
key: "Shift+Meta+B",
},
tip: {
name: tShortcuts("keys.entry.tip"),
key: "Shift+Meta+T",
},
share: {
name: tShortcuts("keys.entry.share"),
key: "Meta+Alt+S",
},
scrollUp: {
name: tShortcuts("keys.entry.scrollUp"),
key: "K, ArrowUp",
},
scrollDown: {
name: tShortcuts("keys.entry.scrollDown"),
key: "J, ArrowDown",
},
nextEntry: {
name: tShortcuts("keys.entries.next"),
key: "L, ArrowRight",
},
previousEntry: {
name: tShortcuts("keys.entries.previous"),
key: "H, ArrowLeft",
},
},
audio: {
"play/pause": {
name: tShortcuts("keys.audio.playPause"),
key: "Space",
},
},
misc: {
quickSearch: {
name: tShortcuts("keys.misc.quickSearch"),
key: "Meta+K",
},
},
} as const
function transformShortcuts<T extends Shortcuts>(configs: T) {
const result = configs
for (const category in configs) {
for (const shortcutKey in configs[category]) {
const config = configs[category][shortcutKey]
result[category]![shortcutKey]!.key = transformShortcut(config!.key)
}
}
return result
}
export const shortcuts = transformShortcuts(shortcutConfigs) satisfies Shortcuts
export const shortcutsType: { [key in keyof typeof shortcuts]: I18nKeysForShortcuts } = {
subscriptions: "keys.type.subscriptions",
layout: "keys.type.layout",
entries: "keys.type.entries",
entry: "keys.type.entry",
audio: "keys.type.audio",
misc: "keys.type.misc",
}
+1 -4
View File
@@ -18,10 +18,7 @@ declare global {
export const ELECTRON: boolean
export interface Window {
SENTRY_RELEASE: typeof SENTRY_RELEASE
/**
* @link apps/mobile/src/components/common/FollowWebView.tsx
*/
__RN__?: boolean
ReactNativeWebView?: {
postMessage: (message: string) => void
}
@@ -1,6 +1,7 @@
import { isMobile } from "@follow/components/hooks/useMobile.js"
import { FeedViewType, UserRole, views } from "@follow/constants"
import { IN_ELECTRON } from "@follow/shared/constants"
import { doesTextContainHTML } from "@follow/utils/utils"
import { useMemo } from "react"
import { useShowAISummaryAuto, useShowAISummaryOnce } from "~/atoms/ai-summary"
@@ -16,11 +17,11 @@ import {
} from "~/atoms/readability"
import { useShowSourceContent } from "~/atoms/source-content"
import { useUserRole, whoami } from "~/atoms/user"
import { shortcuts } from "~/constants/shortcuts"
import { apiClient } from "~/lib/api-fetch"
import { tipcClient } from "~/lib/client"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { getCommand, useRunCommandFn } from "~/modules/command/hooks/use-command"
import { useCommandShortcuts } from "~/modules/command/hooks/use-command-binding"
import type { FollowCommandId } from "~/modules/command/types"
import { useToolbarOrderMap } from "~/modules/customize-toolbar/hooks"
import { useEntry } from "~/store/entry"
@@ -130,10 +131,6 @@ export class EntryActionMenuItem extends MenuItemText {
}
export type EntryActionItem = EntryActionMenuItem | MenuItemSeparator
function hasHTMLTags(text?: string | null): boolean {
return /<[^>]+>/.test(text || "")
}
export const useEntryActions = ({
entryId,
view,
@@ -158,7 +155,7 @@ export const useEntryActions = ({
const inList = !!listId
const inbox = useInboxById(entry?.inboxId)
const isInbox = !!inbox
const isContentContainsHTMLTags = hasHTMLTags(entry?.entries.content)
const isContentContainsHTMLTags = doesTextContainHTML(entry?.entries.content)
const isShowSourceContent = useShowSourceContent()
const isShowAISummaryAuto = useShowAISummaryAuto(entry)
@@ -171,6 +168,8 @@ export const useEntryActions = ({
const userRole = useUserRole()
const shortcuts = useCommandShortcuts()
const actionConfigs: EntryActionItem[] = useMemo(() => {
if (!hasEntry) return []
@@ -210,33 +209,39 @@ export const useEntryActions = ({
onClick: runCmdFn(COMMAND_ID.integration.saveToCubox, [{ entryId }]),
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.integration.saveToZotero,
onClick: runCmdFn(COMMAND_ID.integration.saveToZotero, [{ entryId }]),
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.entry.tip,
onClick: runCmdFn(COMMAND_ID.entry.tip, [
{ entryId, feedId: feed?.id, userId: feed?.ownerUserId },
]),
hide: isInbox || feed?.ownerUserId === whoami()?.id,
shortcut: shortcuts.entry.tip.key,
// shortcut: shortcuts.entry.tip.key,
shortcut: shortcuts[COMMAND_ID.entry.tip],
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.entry.star,
onClick: runCmdFn(COMMAND_ID.entry.star, [{ entryId, view }]),
active: !!entry?.collections,
shortcut: shortcuts.entry.toggleStarred.key,
shortcut: shortcuts[COMMAND_ID.entry.star],
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.entry.copyTitle,
onClick: runCmdFn(COMMAND_ID.entry.copyTitle, [{ entryId }]),
shortcut: shortcuts.entry.copyTitle.key,
shortcut: shortcuts[COMMAND_ID.entry.copyTitle],
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.entry.copyLink,
onClick: runCmdFn(COMMAND_ID.entry.copyLink, [{ entryId }]),
hide: !entry?.entries.url,
shortcut: shortcuts.entry.copyLink.key,
shortcut: shortcuts[COMMAND_ID.entry.copyLink],
entryId,
}),
new EntryActionMenuItem({
@@ -293,25 +298,27 @@ export const useEntryActions = ({
id: COMMAND_ID.entry.share,
onClick: runCmdFn(COMMAND_ID.entry.share, [{ entryId }]),
hide: !entry?.entries.url || !("share" in navigator || IN_ELECTRON),
shortcut: shortcuts.entry.share.key,
shortcut: shortcuts[COMMAND_ID.entry.share],
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.entry.readAbove,
onClick: runCmdFn(COMMAND_ID.entry.readAbove, [{ publishedAt: entry.entries.publishedAt }]),
hide: !hasEntry || !!entry.collections,
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.entry.read,
onClick: runCmdFn(COMMAND_ID.entry.read, [{ entryId }]),
hide: !hasEntry || !!entry.collections || !!inList,
hide: !hasEntry || !!entry.collections,
active: !!entry?.read,
shortcut: shortcuts.entry.toggleRead.key,
shortcut: shortcuts[COMMAND_ID.entry.read],
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.entry.readBelow,
onClick: runCmdFn(COMMAND_ID.entry.readBelow, [{ publishedAt: entry.entries.publishedAt }]),
hide: !hasEntry || !!entry.collections,
entryId,
}),
MENU_ITEM_SEPARATOR,
@@ -325,15 +332,17 @@ export const useEntryActions = ({
new EntryActionMenuItem({
id: COMMAND_ID.entry.tts,
onClick: runCmdFn(COMMAND_ID.entry.tts, [
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
{ entryId, entryContent: entry?.entries.content! },
]),
hide: !IN_ELECTRON || compact || !entry?.entries.content,
shortcut: shortcuts.entry.tts.key,
shortcut: shortcuts[COMMAND_ID.entry.tts],
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.entry.readability,
onClick: runCmdFn(COMMAND_ID.entry.readability, [
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
{ entryId, entryUrl: entry?.entries.url! },
]),
hide:
@@ -360,32 +369,33 @@ export const useEntryActions = ({
return configs
}, [
compact,
entry?.collections,
entry?.entries.content,
entry?.entries.publishedAt,
entry?.entries.url,
entry?.read,
entry?.settings?.readability,
entry?.view,
hasEntry,
runCmdFn,
entryId,
isEntryInReadability,
feed?.id,
feed?.ownerUserId,
feed?.siteUrl,
hasEntry,
imageLength,
inList,
isInbox,
shortcuts,
view,
entry?.collections,
entry?.entries.url,
entry?.entries.publishedAt,
entry?.entries.content,
entry?.view,
entry?.read,
entry?.settings?.readability,
imageLength,
isShowSourceContent,
isShowAISummaryAuto,
isShowAISummaryOnce,
userRole,
isShowAITranslationAuto,
isShowAITranslationOnce,
isShowSourceContent,
inList,
compact,
isEntryInReadability,
isContentContainsHTMLTags,
runCmdFn,
userRole,
view,
])
return actionConfigs
@@ -17,6 +17,8 @@ import { apiClient } from "~/lib/api-fetch"
import { UrlBuilder } from "~/lib/url-builder"
import { useBoostModal } from "~/modules/boost/hooks"
import { useFeedClaimModal } from "~/modules/claim"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { useCommandShortcuts } from "~/modules/command/hooks/use-command-binding"
import { FeedForm } from "~/modules/discover/FeedForm"
import { InboxForm } from "~/modules/discover/InboxForm"
import { ListForm } from "~/modules/discover/ListForm"
@@ -45,11 +47,11 @@ const ConfirmDestroyModalContent = ({ onConfirm }: { onConfirm: () => void }) =>
return (
<div className="w-[540px]">
<div className="mb-4">
<i className="i-mingcute-warning-fill -mb-1 mr-1 size-5 text-red-500" />
<i className="i-mingcute-warning-fill text-red -mb-1 mr-1 size-5" />
{t("sidebar.feed_actions.unfollow_feed_many_warning")}
</div>
<div className="flex justify-end">
<Button buttonClassName="bg-red-600" onClick={onConfirm}>
<Button buttonClassName="bg-red" onClick={onConfirm}>
{t("words.confirm")}
</Button>
</div>
@@ -106,6 +108,8 @@ export const useFeedActions = ({
const isInMASReview = useIsInMASReview()
const shortcuts = useCommandShortcuts()
const items = useMemo(() => {
const related = feed || inbox
if (!related) return []
@@ -115,10 +119,10 @@ export const useFeedActions = ({
const items: MenuItemInput[] = [
new MenuItemText({
label: t("sidebar.feed_actions.mark_all_as_read"),
shortcut: "Meta+Shift+A",
shortcut: shortcuts[COMMAND_ID.subscription.markAllAsRead],
disabled: isEntryList,
click: () =>
subscriptionActions.markReadByFeedIds({
subscriptionActions.markReadByIds({
feedIds: isMultipleSelection ? feedIds : [feedId],
}),
supportMultipleSelection: true,
@@ -137,8 +141,10 @@ export const useFeedActions = ({
}),
...(isFeedOwner
? [
MenuItemSeparator.default,
new MenuItemText({
label: t("sidebar.feed_actions.feed_owned_by_you"),
disabled: true,
}),
new MenuItemText({
label: t("sidebar.feed_actions.reset_feed"),
@@ -146,6 +152,7 @@ export const useFeedActions = ({
resetFeed(feedId)
},
}),
MenuItemSeparator.default,
]
: []),
...(!isInMASReview
@@ -269,7 +276,7 @@ export const useFeedActions = ({
: isEntryList
? t("sidebar.feed_actions.unfollow_feed")
: t("sidebar.feed_actions.unfollow"),
shortcut: "Meta+Backspace",
shortcut: "$mod+Backspace",
disabled: isInbox,
supportMultipleSelection: true,
click: () => {
@@ -292,8 +299,8 @@ export const useFeedActions = ({
}),
new MenuItemText({
label: t("sidebar.feed_actions.navigate_to_feed"),
shortcut: "Meta+G",
disabled: isInbox || !isEntryList || getRouteParams().feedId === feedId,
shortcut: "$mod+G",
disabled: getRouteParams().feedId === feedId,
click: () => {
navigateEntry({ feedId })
},
@@ -304,14 +311,14 @@ export const useFeedActions = ({
which: t(IN_ELECTRON ? "words.browser" : "words.newTab"),
}),
disabled: isEntryList,
shortcut: "O",
shortcut: shortcuts[COMMAND_ID.subscription.openInBrowser],
click: () => window.open(UrlBuilder.shareFeed(feedId, view), "_blank"),
}),
new MenuItemText({
label: t("sidebar.feed_actions.open_site_in_browser", {
which: t(IN_ELECTRON ? "words.browser" : "words.newTab"),
}),
shortcut: "Meta+O",
shortcut: shortcuts[COMMAND_ID.subscription.openSiteInBrowser],
disabled: isEntryList,
click: () => {
const feed = getFeedById(feedId)
@@ -324,7 +331,7 @@ export const useFeedActions = ({
new MenuItemText({
label: t("sidebar.feed_actions.copy_feed_url"),
disabled: isEntryList,
shortcut: "Meta+C",
shortcut: "$mod+C",
click: () => {
const { url, siteUrl } = feed || {}
const copied = url || siteUrl
@@ -334,7 +341,7 @@ export const useFeedActions = ({
}),
new MenuItemText({
label: t("sidebar.feed_actions.copy_feed_id"),
shortcut: "Meta+Shift+C",
shortcut: "$mod+Shift+C",
disabled: isEntryList,
click: () => {
navigator.clipboard.writeText(feedId)
@@ -363,7 +370,9 @@ export const useFeedActions = ({
feed,
inbox,
t,
shortcuts,
isEntryList,
isInMASReview,
isInbox,
listByView,
categories,
@@ -395,18 +404,33 @@ export const useListActions = ({ listId, view }: { listId: string; view?: FeedVi
const { present } = useModalStack()
const { mutateAsync: deleteSubscription } = useDeleteSubscription({})
const shortcuts = useCommandShortcuts()
const navigateEntry = useNavigateEntry()
const items = useMemo(() => {
if (!list) return []
const items: MenuItemInput[] = [
list.ownerUserId === whoami()?.id &&
new MenuItemText({
label: t("sidebar.feed_actions.list_owned_by_you"),
}),
list.ownerUserId !== whoami()?.id && MenuItemSeparator.default,
...(list.ownerUserId === whoami()?.id
? [
new MenuItemText({
label: t("sidebar.feed_actions.list_owned_by_you"),
disabled: true,
}),
MenuItemSeparator.default,
]
: []),
new MenuItemText({
label: t("sidebar.feed_actions.mark_all_as_read"),
shortcut: shortcuts[COMMAND_ID.subscription.markAllAsRead],
click: () => {
subscriptionActions.markReadByIds({
feedIds: list.feedIds,
})
},
}),
MenuItemSeparator.default,
new MenuItemText({
label: t("sidebar.feed_actions.edit"),
shortcut: "E",
@@ -419,12 +443,12 @@ export const useListActions = ({ listId, view }: { listId: string; view?: FeedVi
}),
new MenuItemText({
label: t("sidebar.feed_actions.unfollow"),
shortcut: "Meta+Backspace",
shortcut: "$mod+Backspace",
click: () => deleteSubscription({ subscription }),
}),
new MenuItemText({
label: t("sidebar.feed_actions.navigate_to_list"),
shortcut: "Meta+G",
shortcut: "$mod+G",
disabled: getRouteParams().feedId === listId,
click: () => {
navigateEntry({ listId })
@@ -435,20 +459,20 @@ export const useListActions = ({ listId, view }: { listId: string; view?: FeedVi
label: t("sidebar.feed_actions.open_list_in_browser", {
which: t(IN_ELECTRON ? "words.browser" : "words.newTab"),
}),
shortcut: "O",
shortcut: shortcuts[COMMAND_ID.subscription.openInBrowser],
click: () => window.open(UrlBuilder.shareList(listId, view), "_blank"),
}),
MenuItemSeparator.default,
new MenuItemText({
label: t("sidebar.feed_actions.copy_list_url"),
shortcut: "Meta+C",
shortcut: "$mod+C",
click: () => {
navigator.clipboard.writeText(UrlBuilder.shareList(listId, view))
},
}),
new MenuItemText({
label: t("sidebar.feed_actions.copy_list_id"),
shortcut: "Meta+Shift+C",
shortcut: "$mod+Shift+C",
click: () => {
navigator.clipboard.writeText(listId)
},
@@ -456,7 +480,7 @@ export const useListActions = ({ listId, view }: { listId: string; view?: FeedVi
]
return items
}, [list, t, present, deleteSubscription, subscription, navigateEntry, listId, view])
}, [list, t, shortcuts, listId, present, deleteSubscription, subscription, navigateEntry, view])
return items
}
@@ -483,7 +507,7 @@ export const useInboxActions = ({ inboxId }: { inboxId: string }) => {
MenuItemSeparator.default,
new MenuItemText({
label: t("sidebar.feed_actions.copy_email_address"),
shortcut: "Meta+Shift+C",
shortcut: "$mod+Shift+C",
click: () => {
navigator.clipboard.writeText(`${inboxId}${env.VITE_INBOXES_EMAIL}`)
},
@@ -54,7 +54,8 @@ export const useNavigateEntry = () => {
*/
export const navigateEntry = (options: NavigateEntryOptions) => {
const { entryId, feedId, view, folderName, inboxId, listId, timelineId, backPath } = options || {}
const { params } = getReadonlyRoute()
const route = getReadonlyRoute()
const { params } = route
let finalFeedId = feedId || params.feedId || ROUTE_FEED_PENDING
let finalTimelineId = timelineId || params.timelineId || ROUTE_FEED_PENDING
const finalEntryId = entryId || ROUTE_ENTRY_PENDING
@@ -95,7 +96,7 @@ export const navigateEntry = (options: NavigateEntryOptions) => {
const path = `/timeline/${finalTimelineId}/${finalFeedId}/${finalEntryId}`
const currentPath = getReadonlyRoute().location.pathname + getReadonlyRoute().location.search
const currentPath = route.location.pathname + route.location.search
if (path === currentPath) return
return getStableRouterNavigate()?.(path)
}
@@ -4,12 +4,11 @@ import { useHotkeys } from "react-hotkeys-hook"
import { Trans, useTranslation } from "react-i18next"
import { toast } from "sonner"
import { HotkeyScope } from "~/constants"
import { apiClient } from "~/lib/api-fetch"
import { subscription as subscriptionQuery } from "~/queries/subscriptions"
import type { SubscriptionFlatModel } from "~/store/subscription"
import { subscriptionActions } from "~/store/subscription"
import { feedUnreadActions } from "~/store/unread"
import { unreadActions } from "~/store/unread"
import { navigateEntry } from "./useNavigateEntry"
import { getRouteParams } from "./useRouteParams"
@@ -35,13 +34,13 @@ export const useDeleteSubscription = ({ onSuccess }: { onSuccess?: () => void }
subscriptionActions.unfollow([subscription.feedId]).then(([feed]) => {
subscriptionQuery.all().invalidate()
feedUnreadActions.updateByFeedId(subscription.feedId, 0)
unreadActions.updateById(subscription.feedId, 0)
if (!subscription) return
if (!feed) return
const undo = async () => {
// TODO store action
await apiClient.subscriptions.$post({
const { unread } = await apiClient.subscriptions.$post({
json: {
url: feed.type === "feed" ? feed.url : undefined,
listId: feed.type === "list" ? feed.id : undefined,
@@ -50,9 +49,9 @@ export const useDeleteSubscription = ({ onSuccess }: { onSuccess?: () => void }
isPrivate: subscription.isPrivate,
},
})
unreadActions.upsertMany(unread)
subscriptionQuery.all().invalidate()
feedUnreadActions.fetchUnreadByView(subscription.view)
toast.dismiss(toastId)
}
@@ -65,7 +64,7 @@ export const useDeleteSubscription = ({ onSuccess }: { onSuccess?: () => void }
<span className="flex items-center gap-1">
{t("words.undo")}
<Kbd className="border-border inline-flex items-center border bg-transparent text-white">
Meta+Z
$mod+Z
</Kbd>
</span>
),
@@ -92,7 +91,6 @@ export const useDeleteSubscription = ({ onSuccess }: { onSuccess?: () => void }
const UnfollowInfo = ({ title, undo }: { title: string; undo: () => any }) => {
useHotkeys("ctrl+z,meta+z", undo, {
scopes: HotkeyScope.Home,
preventDefault: true,
})
return (
@@ -2,5 +2,4 @@ export * from "./useBizQuery"
export * from "./useContextMenu"
export * from "./useI18n"
export * from "./usePreventOverscrollBounce"
export * from "./useSwitchHotkeyScope"
export * from "./useSyncTheme"
@@ -1,57 +0,0 @@
import { useCallback, useLayoutEffect, useRef } from "react"
import { useHotkeysContext } from "react-hotkeys-hook"
import { HotkeyScope } from "~/constants"
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 HotkeyScope) => {
const nextScope = HotkeyScope[scope]
if (!nextScope) return
for (const key of allScopes) {
disableScope(key)
}
enableScope(nextScope)
},
[disableScope, enableScope],
)
}
export const useConditionalHotkeyScopeFn = (scope: HotkeyScope, replaceAll = true) => {
const { enableScope, disableScope, activeScopes } = useHotkeysContext()
const currentScopeRef = useRef(activeScopes)
return useCallback(() => {
const currentScope = currentScopeRef.current
if (replaceAll) {
for (const key of allScopes) {
disableScope(key)
}
}
enableScope(scope)
return () => {
disableScope(scope)
if (replaceAll) {
for (const key of currentScope) {
enableScope(key)
}
}
}
}, [enableScope, disableScope, scope, replaceAll])
}
export const useConditionalHotkeyScope = (scope: HotkeyScope, when: boolean, append = false) => {
const fn = useConditionalHotkeyScopeFn(scope, !append)
useLayoutEffect(() => {
if (when) {
return fn()
}
}, [fn, when])
}
@@ -18,19 +18,12 @@ const parseAccelerator = (
}
export const registerAppGlobalShortcuts = () => {
// @see src/main/menu.ts
// @see layer/main/menu.ts
const shortcuts: ShortcutDefinition[] = [
{
accelerator: "CmdOrCtrl+,",
action: () => window.router.showSettings(),
},
{
accelerator: "Ctrl+Shift+Z",
action: () => {
const caller = callWindowExposeRenderer()
caller.zenMode()
},
},
{
accelerator: "CmdOrCtrl+T",
action: () => {
@@ -4,7 +4,7 @@ import { initializeDefaultGeneralSettings } from "~/atoms/settings/general"
import { initializeDefaultIntegrationSettings } from "~/atoms/settings/integration"
import { initializeDefaultUISettings } from "~/atoms/settings/ui"
import { appLog } from "~/lib/log"
import { EntryService, FeedService, FeedUnreadService, SubscriptionService } from "~/services"
import { EntryService, FeedService, SubscriptionService, UnreadService } from "~/services"
import { InboxService } from "~/services/inbox"
import type { Hydratable } from "~/services/interface"
import { ListService } from "~/services/list"
@@ -20,7 +20,7 @@ export const hydrateDatabaseToStore = async () => {
const hydrates: Hydratable[] = [
FeedService,
SubscriptionService,
FeedUnreadService,
UnreadService,
EntryService,
ListService,
InboxService,
@@ -1,33 +1,41 @@
import { defaultSettings } from "@follow/shared/settings/defaults"
import { isEqual } from "es-toolkit/compat"
import { getGeneralSettings, setGeneralSetting } from "~/atoms/settings/general"
import { getUISettings } from "~/atoms/settings/ui"
import {
createDefaultGeneralSettings,
getGeneralSettings,
setGeneralSetting,
} from "~/atoms/settings/general"
import { createDefaultUISettings, getUISettings } from "~/atoms/settings/ui"
import { defineMigration } from "../helper"
function hasSettingsChanged(
currentSettings: Record<string, any>,
defaultSettings: Record<string, any>,
): boolean {
for (const key in defaultSettings) {
const defaultValue = defaultSettings[key]
const currentValue = currentSettings[key]
if (currentValue === undefined) {
continue
}
if (!isEqual(defaultValue, currentValue)) {
return true
}
}
return false
}
export const v1 = defineMigration({
version: "v1",
migrate: () => {
const settings = getGeneralSettings()
const uiSettings = getUISettings()
let enabledEnhancedSettings = false
for (const key in defaultSettings.ui) {
const defaultValue = defaultSettings.ui[key]
const currentValue = uiSettings[key]
if (defaultValue !== currentValue) {
enabledEnhancedSettings = true
break
}
}
for (const key in defaultSettings.general) {
const defaultValue = defaultSettings.general[key]
const currentValue = settings[key]
if (defaultValue !== currentValue) {
enabledEnhancedSettings = true
break
}
}
const enabledEnhancedSettings =
hasSettingsChanged(uiSettings, createDefaultUISettings()) ||
hasSettingsChanged(settings, createDefaultGeneralSettings())
setGeneralSetting("enhancedSettings", enabledEnhancedSettings)
},
})
@@ -12,7 +12,10 @@ export type DefinedQuery<TQueryKey extends QueryKey, TData> = Readonly<{
cancel: (key?: (key: TQueryKey) => QueryKey) => Promise<void>
remove: (key?: (key: TQueryKey) => QueryKey) => Promise<void>
invalidate: (key?: (key: TQueryKey) => QueryKey) => Promise<void>
invalidate: (options?: {
keyExtractor?: (key: TQueryKey) => QueryKey
exact?: boolean
}) => Promise<void>
invalidateRoot: () => void
refetch: () => Promise<TData | undefined>
@@ -107,12 +110,14 @@ export function defineQuery<
const queryKey = typeof keyExtactor === "function" ? keyExtactor(key) : key
queryClient.removeQueries({ queryKey })
},
invalidate: async (keyExtactor) => {
const queryKey = typeof keyExtactor === "function" ? keyExtactor(key) : key
invalidate: async (args) => {
const { keyExtractor, exact } = args || {}
const queryKey = typeof keyExtractor === "function" ? keyExtractor(key) : key
await queryClient.invalidateQueries({
queryKey,
refetchType: "all",
exact,
})
options?.onInvalidate?.()
},
@@ -65,8 +65,27 @@ export const parseHtml = (
},
style: Style,
video: ({ node, ...props }) =>
createElement(Media, { ...props, popper: true, type: "video" }),
video: ({ node, ...props }) => {
const sourceElement = Array.isArray(props.children)
? props.children.find((i) => i.type === "source")
: // Children is only the source element
props.children &&
typeof props.children === "object" &&
"type" in props.children &&
props.children.type === "source"
? props.children
: null
const src = props.src || sourceElement?.props.src
return createElement(Media, {
...props,
popper: true,
type: "video",
previewImageUrl: props.poster,
src,
})
},
p: ({ node, ref, ...props }) => {
if (node?.children && node.children.length !== 1) {
for (const item of node.children) {
@@ -21,12 +21,15 @@ import {
} from "~/components/ui/dropdown-menu/dropdown-menu"
import { actionActions, useActionByIndex } from "~/store/action"
import { useSettingModal } from "../settings/modal/use-setting-modal"
type Action = {
title: string
icon: React.ReactNode
config?: () => React.ReactNode
configInline?: boolean
enabled: boolean
settingsPath?: string
onInit: (data: ActionModel) => void
onRemove: (data: ActionModel) => void
}
@@ -65,6 +68,7 @@ export const TargetActionList = ({ index }: { index: number }) => {
const star = useActionByIndex(index, (a) => a.result.star)
const rewriteRules = useActionByIndex(index, (a) => a.result.rewriteRules)
const webhooks = useActionByIndex(index, (a) => a.result.webhooks)
const settingModalPresent = useSettingModal()
const disabled = useActionByIndex(index, (a) => a.result.disabled)
const { t } = useTranslation("settings")
@@ -77,6 +81,7 @@ export const TargetActionList = ({ index }: { index: number }) => {
title: t("actions.action_card.generate_summary"),
icon: <i className="i-mgc-ai-cute-re" />,
enabled: !!summary,
settingsPath: "general",
onInit: (data) => {
data.result.summary = true
},
@@ -88,6 +93,7 @@ export const TargetActionList = ({ index }: { index: number }) => {
title: t("actions.action_card.translate_into"),
icon: <i className="i-mgc-translate-2-ai-cute-re" />,
enabled: !!translation,
settingsPath: "general",
onInit: (data) => {
data.result.translation = true
},
@@ -119,7 +125,8 @@ export const TargetActionList = ({ index }: { index: number }) => {
},
{
title: t("actions.action_card.new_entry_notification"),
icon: <i className="i-mgc-bell-ringing-cute-re" />,
icon: <i className="i-mgc-notification-cute-re" />,
settingsPath: "notifications",
enabled: !!newEntryNotification,
onInit: (data) => {
data.result.newEntryNotification = true
@@ -366,6 +373,18 @@ export const TargetActionList = ({ index }: { index: number }) => {
<div className="flex items-center gap-2">
{action.icon}
<span className="shrink grow truncate">{action.title}</span>
{action.settingsPath && (
<Button
buttonClassName="ml-4"
variant="outline"
size="sm"
onClick={() => {
settingModalPresent(action.settingsPath)
}}
>
{t("actions.action_card.settings")}
</Button>
)}
</div>
{action.configInline && action.config && action.config()}
@@ -11,6 +11,8 @@ import {
useRealInWideMode,
useUISettingKey,
} from "~/atoms/settings/ui"
import { Focusable } from "~/components/common/Focusable"
import { HotkeyScope } from "~/constants"
import { useRouteParams } from "~/hooks/biz/useRouteParams"
import { EntryColumn } from "~/modules/entry-column"
import { AppLayoutGridContainerProvider } from "~/providers/app-grid-layout-container-provider"
@@ -40,7 +42,7 @@ export function CenterColumnDesktop() {
})
return (
<div ref={containerRef} className="relative flex min-w-0 grow">
<Focusable scope={HotkeyScope.Home} ref={containerRef} className="relative flex min-w-0 grow">
<div
className={cn("h-full shrink-0", inWideMode ? "flex-1" : "border-r", "will-change-[width]")}
data-hide-in-print
@@ -56,6 +58,6 @@ export function CenterColumnDesktop() {
<PanelSplitter {...separatorProps} cursor={separatorCursor} isDragging={isDragging} />
)}
<Outlet />
</div>
</Focusable>
)
}
@@ -4,14 +4,13 @@ import { useWheel } from "@use-gesture/react"
import { easeOut } from "motion/react"
import type { FC, PropsWithChildren } from "react"
import { useState } from "react"
import { useHotkeys } from "react-hotkeys-hook"
import { useParams } from "react-router"
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 { HotkeyScope, ROUTE_ENTRY_PENDING } from "~/constants"
import { ROUTE_ENTRY_PENDING } from "~/constants"
import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
import { useRouteParams } from "~/hooks/biz/useRouteParams"
import { EntryContent } from "~/modules/entry-content"
@@ -32,18 +31,6 @@ export const RightContentDesktop = () => {
const feedColumnShow = useTimelineColumnShow()
const shouldHeaderPaddingLeft = feedColumnTempShow && !feedColumnShow && settingWideMode
useHotkeys(
"Escape",
() => {
navigate({ entryId: null })
},
{
enabled: showEntryContent && settingWideMode,
scopes: HotkeyScope.Home,
preventDefault: true,
},
)
if (!showEntryContent) {
return null
}
@@ -1,5 +1,6 @@
import type { DragEndEvent } from "@dnd-kit/core"
import { DndContext, PointerSensor, pointerWithin, useSensor, useSensors } from "@dnd-kit/core"
import { useGlobalFocusableScope } from "@follow/components/common/Focusable/hooks.js"
import { PanelSplitter } from "@follow/components/ui/divider/index.js"
import { Kbd } from "@follow/components/ui/kbd/Kbd.js"
import { RootPortal } from "@follow/components/ui/portal/index.jsx"
@@ -30,7 +31,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 { HotkeyScope } from "~/constants"
import { FloatingLayerScope } from "~/constants"
import { ROOT_CONTAINER_ID } from "~/constants/dom"
import { useDailyTask } from "~/hooks/biz/useDailyTask"
import { useBatchUpdateSubscription } from "~/hooks/biz/useSubscriptionActions"
@@ -39,18 +40,17 @@ import { EnvironmentIndicator } from "~/modules/app/EnvironmentIndicator"
import { NetworkStatusIndicator } from "~/modules/app/NetworkStatusIndicator"
import { LoginModalContent } from "~/modules/auth/LoginModalContent"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { useCommandBinding } from "~/modules/command/hooks/use-register-hotkey"
import { useCommandBinding } from "~/modules/command/hooks/use-command-binding"
import { DebugRegistry } from "~/modules/debug/registry"
import { CmdF } from "~/modules/panel/cmdf"
import { SearchCmdK } from "~/modules/panel/cmdk"
import { CmdNTrigger } from "~/modules/panel/cmdn"
import { CornerPlayer } from "~/modules/player/corner-player"
import { FeedColumn } from "~/modules/timeline-column"
import { getSelectedFeedIds, resetSelectedFeedIds } from "~/modules/timeline-column/atom"
import { FeedColumn } from "~/modules/subscription-column"
import { getSelectedFeedIds, resetSelectedFeedIds } from "~/modules/subscription-column/atom"
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"
@@ -241,11 +241,11 @@ const FeedResponsiveResizerContainer = ({
}
}, [feedColumnShow])
const activeScopes = useHotkeyScope()
const activeScopes = useGlobalFocusableScope()
useCommandBinding({
commandId: COMMAND_ID.layout.toggleTimelineColumn,
when: activeScopes.includes(HotkeyScope.Home),
commandId: COMMAND_ID.layout.toggleSubscriptionColumn,
when: !FloatingLayerScope.some((scope) => activeScopes.has(scope)),
})
const [delayShowSplitter, setDelayShowSplitter] = useState(feedColumnShow)
@@ -12,7 +12,7 @@ import { Link } from "react-router"
import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
import { FeedList } from "../../timeline-column/FeedList"
import { SubscriptionList } from "../../subscription-column/SubscriptionList"
import { MobileFloatBar } from "./float-bar.mobile"
export function FeedColumnMobile({ asWidget }: { asWidget?: boolean }) {
@@ -37,7 +37,7 @@ export function FeedColumnMobile({ asWidget }: { asWidget?: boolean }) {
</span>
<div className="center inline-flex">
<Link to="/discover" tabIndex={-1}>
<ActionButton shortcut="Meta+T" tooltip={t("words.discover")}>
<ActionButton shortcut="$mod+T" tooltip={t("words.discover")}>
<i className="i-mgc-add-cute-re text-text-secondary size-5" />
</ActionButton>
</Link>
@@ -47,7 +47,7 @@ export function FeedColumnMobile({ asWidget }: { asWidget?: boolean }) {
<SwipeWrapper active={view}>
{views.map((item, index) => (
<section key={item.name} className="size-full flex-none shrink-0 snap-center">
<FeedList
<SubscriptionList
ref={setFeedListScrollRef}
className="flex size-full flex-col text-sm"
view={index}
@@ -1,4 +1,5 @@
import { getReadonlyRoute } from "@follow/components/atoms/route.js"
import { useGlobalFocusableScope } from "@follow/components/common/Focusable/hooks.js"
import { MotionButtonBase } from "@follow/components/ui/button/index.js"
import { ScrollArea } from "@follow/components/ui/scroll-area/index.js"
import { Routes } from "@follow/constants"
@@ -6,14 +7,24 @@ import { ELECTRON_BUILD } from "@follow/shared/constants"
import { springScrollTo } from "@follow/utils/scroller"
import { cn, getOS } from "@follow/utils/utils"
import { useEffect, useRef, useState } from "react"
import { useHotkeys } from "react-hotkeys-hook"
import { useTranslation } from "react-i18next"
import { NavigationType, Outlet, useLocation, useNavigate, useNavigationType } from "react-router"
import { Focusable } from "~/components/common/Focusable"
import { FABContainer, FABPortable } from "~/components/ui/fab"
import { HotkeyScope } from "~/constants"
import { useSubViewTitleValue } from "./hooks"
export function SubviewLayout() {
return (
<Focusable className="contents" scope={HotkeyScope.SubLayer}>
<SubviewLayoutInner />
</Focusable>
)
}
function SubviewLayoutInner() {
const navigate = useNavigate()
const prevLocation = useRef(getReadonlyRoute().location).current
const title = useSubViewTitleValue()
@@ -53,6 +64,17 @@ export function SubviewLayout() {
// electron window has pt-[calc(var(--fo-window-padding-top)_-10px)]
const isElectronWindows = ELECTRON_BUILD && getOS() === "Windows"
const backHandler = () => {
if (prevLocation.pathname === location.pathname) {
navigate({ pathname: "" })
} else {
navigate(-1)
}
}
const activeScope = useGlobalFocusableScope()
useHotkeys("Escape", backHandler, {
enabled: activeScope.has(HotkeyScope.SubLayer),
})
return (
<div className="relative flex size-full">
<div
@@ -64,13 +86,7 @@ export function SubviewLayout() {
)}
>
<MotionButtonBase
onClick={() => {
if (prevLocation.pathname === location.pathname) {
navigate({ pathname: "" })
} else {
navigate(prevLocation)
}
}}
onClick={backHandler}
className="no-drag-region hover:text-accent inline-flex items-center gap-1 duration-200"
>
<i className="i-mingcute-left-line" />
@@ -1,7 +1,8 @@
import { EventBus } from "@follow/utils/event-bus"
import { useTranslation } from "react-i18next"
import { useRegisterCommandEffect } from "../hooks/use-register-command"
import type { Command } from "../types"
import type { Command, CommandCategory } from "../types"
import { COMMAND_ID } from "./id"
declare module "@follow/utils/event-bus" {
@@ -12,10 +13,10 @@ declare module "@follow/utils/event-bus" {
"entry-render:previous-entry": never
}
}
const LABEL_PREFIX = "Entry Render"
const category = "follow:entry-render"
const category: CommandCategory = "category.entry_render"
export const useRegisterEntryRenderCommand = () => {
const { t } = useTranslation("shortcuts")
useRegisterCommandEffect([
{
id: COMMAND_ID.entryRender.scrollDown,
@@ -23,7 +24,10 @@ export const useRegisterEntryRenderCommand = () => {
EventBus.dispatch(COMMAND_ID.entryRender.scrollDown)
},
category,
label: `${LABEL_PREFIX}: Scroll down`,
label: {
title: t("command.entry.scroll_down.title"),
description: t("command.entry.scroll_down.description"),
},
},
{
id: COMMAND_ID.entryRender.scrollUp,
@@ -31,7 +35,10 @@ export const useRegisterEntryRenderCommand = () => {
EventBus.dispatch(COMMAND_ID.entryRender.scrollUp)
},
category,
label: `${LABEL_PREFIX}: Scroll up`,
label: {
title: t("command.entry.scroll_up.title"),
description: t("command.entry.scroll_up.description"),
},
},
{
id: COMMAND_ID.entryRender.nextEntry,
@@ -40,7 +47,10 @@ export const useRegisterEntryRenderCommand = () => {
EventBus.dispatch(COMMAND_ID.entryRender.nextEntry)
},
category,
label: `${LABEL_PREFIX}: Next entry`,
label: {
title: t("command.entry.next_entry.title"),
description: t("command.entry.next_entry.description"),
},
},
{
id: COMMAND_ID.entryRender.previousEntry,
@@ -49,7 +59,10 @@ export const useRegisterEntryRenderCommand = () => {
EventBus.dispatch(COMMAND_ID.entryRender.previousEntry)
},
category,
label: `${LABEL_PREFIX}: Previous entry`,
label: {
title: t("command.entry.previous_entry.title"),
description: t("command.entry.previous_entry.description"),
},
},
])
}
@@ -28,9 +28,11 @@ import { useTipModal } from "~/modules/wallet/hooks"
import { entryActions, useEntryStore } from "~/store/entry"
import { useRegisterFollowCommand } from "../hooks/use-register-command"
import type { Command } from "../types"
import type { Command, CommandCategory } from "../types"
import { COMMAND_ID } from "./id"
const category: CommandCategory = "category.entry"
const useCollect = () => {
const { t } = useTranslation()
return useMutation({
@@ -120,8 +122,7 @@ export const useRegisterEntryCommands = () => {
id: COMMAND_ID.entry.tip,
label: t("entry_actions.tip"),
icon: <i className="i-mgc-power-outline" />,
// keyBinding: shortcuts.entry.tip.key,
// when: !isInbox && feed?.ownerUserId !== whoami()?.id && !!populatedEntry,
category,
run: ({ userId, feedId, entryId }) => {
openTipModal({
userId,
@@ -134,6 +135,7 @@ export const useRegisterEntryCommands = () => {
{
id: COMMAND_ID.entry.star,
label: t("entry_actions.star"),
category,
icon: (props) => (
<i
className={cn(
@@ -147,15 +149,7 @@ export const useRegisterEntryCommands = () => {
toast.error("Failed to star: entry is not available", { duration: 3000 })
return
}
// if (type === "toolbar") {
// const absoluteStarAnimationUri = new URL(StarAnimationUri, import.meta.url).href
// mountLottie(absoluteStarAnimationUri, {
// x: e.clientX - 90,
// y: e.clientY - 70,
// height: 126,
// width: 252,
// })
// }
if (entry.collections) {
uncollect.mutate(entry.entries.id)
} else {
@@ -167,6 +161,7 @@ export const useRegisterEntryCommands = () => {
id: COMMAND_ID.entry.delete,
label: t("entry_actions.delete"),
icon: <i className="i-mgc-delete-2-cute-re" />,
category,
run: ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
if (!entry) {
@@ -180,6 +175,7 @@ export const useRegisterEntryCommands = () => {
id: COMMAND_ID.entry.copyLink,
label: t("entry_actions.copy_link"),
icon: <i className="i-mgc-link-cute-re" />,
category,
run: ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
if (!entry) {
@@ -197,6 +193,7 @@ export const useRegisterEntryCommands = () => {
id: COMMAND_ID.entry.exportAsPDF,
label: t("entry_actions.export_as_pdf"),
icon: <i className="i-mgc-pdf-cute-re" />,
category,
run: ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
@@ -212,6 +209,7 @@ export const useRegisterEntryCommands = () => {
id: COMMAND_ID.entry.copyTitle,
label: t("entry_actions.copy_title"),
icon: <i className="i-mgc-copy-cute-re" />,
category,
run: ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
if (!entry) {
@@ -230,6 +228,7 @@ export const useRegisterEntryCommands = () => {
label: t("entry_actions.open_in_browser", {
which: t(IN_ELECTRON ? "words.browser" : "words.newTab"),
}),
category,
icon: <i className="i-mgc-world-2-cute-re" />,
run: ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
@@ -244,6 +243,7 @@ export const useRegisterEntryCommands = () => {
id: COMMAND_ID.entry.viewSourceContent,
label: t("entry_actions.view_source_content"),
icon: <i className="i-mgc-web-cute-re" />,
category,
run: ({ entryId, siteUrl }) => {
if (!getShowSourceContent()) {
const entry = useEntryStore.getState().flatMapEntries[entryId]
@@ -276,6 +276,7 @@ export const useRegisterEntryCommands = () => {
id: COMMAND_ID.entry.share,
label: t("entry_actions.share"),
icon: <i className="i-mgc-share-forward-cute-re" />,
category,
run: ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
if (!entry || !entry.entries.url) {
@@ -300,6 +301,7 @@ export const useRegisterEntryCommands = () => {
{
id: COMMAND_ID.entry.readAbove,
label: t("entry_actions.mark_above_as_read"),
category,
run: ({ publishedAt }: { publishedAt: string }) => {
return markAllByRoute({
startTime: new Date(publishedAt).getTime() + 1,
@@ -310,6 +312,7 @@ export const useRegisterEntryCommands = () => {
{
id: COMMAND_ID.entry.read,
label: t("entry_actions.mark_as_read"),
category,
icon: (props) => (
<i className={cn(props?.isActive ? "i-mgc-round-cute-re" : "i-mgc-round-cute-fi")} />
),
@@ -329,6 +332,7 @@ export const useRegisterEntryCommands = () => {
{
id: COMMAND_ID.entry.readBelow,
label: t("entry_actions.mark_below_as_read"),
category,
run: ({ publishedAt }: { publishedAt: string }) => {
return markAllByRoute({
startTime: 1,
@@ -340,6 +344,7 @@ export const useRegisterEntryCommands = () => {
id: COMMAND_ID.entry.imageGallery,
label: t("entry_actions.image_gallery"),
icon: <i className="i-mgc-pic-cute-fi" />,
category,
run: ({ entryId }) => {
openGalleryModal(entryId)
},
@@ -347,6 +352,7 @@ export const useRegisterEntryCommands = () => {
{
id: COMMAND_ID.entry.tts,
label: t("entry_content.header.play_tts"),
category,
icon: <i className="i-mgc-voice-cute-re" />,
run: async ({ entryId, entryContent }) => {
if (getAudioPlayerAtomValue().entryId === entryId) {
@@ -370,6 +376,7 @@ export const useRegisterEntryCommands = () => {
},
{
id: COMMAND_ID.entry.readability,
category,
label: {
title: t("entry_content.header.readability"),
description: t("entry_content.header.readability_description"),
@@ -396,6 +403,7 @@ export const useRegisterEntryCommands = () => {
id: COMMAND_ID.entry.toggleAISummary,
label: t("entry_actions.toggle_ai_summary"),
icon: <i className="i-mgc-ai-cute-re" />,
category,
run: () => {
if (role === UserRole.Trial) {
presentActivationModal()
@@ -408,6 +416,7 @@ export const useRegisterEntryCommands = () => {
id: COMMAND_ID.entry.toggleAITranslation,
label: t("entry_actions.toggle_ai_translation"),
icon: <i className="i-mgc-translate-2-ai-cute-re" />,
category,
run: () => {
if (role === UserRole.Trial) {
presentActivationModal()
@@ -1,19 +1,56 @@
import { EventBus } from "@follow/utils/event-bus"
import { useTranslation } from "react-i18next"
import { useShortcutsModal } from "~/modules/modal/shortcuts"
import { useRegisterCommandEffect } from "../hooks/use-register-command"
import type { Command } from "../types"
import type { Command, CommandCategory } from "../types"
import { COMMAND_ID } from "./id"
declare module "@follow/utils/event-bus" {
interface EventBusMap {
"global:toggle-corner-play": void
"global:quick-add": void
}
}
const category: CommandCategory = "category.global"
export const useRegisterGlobalCommands = () => {
const showShortcuts = useShortcutsModal()
const { t } = useTranslation("shortcuts")
useRegisterCommandEffect([
{
id: COMMAND_ID.global.showShortcuts,
label: "Show shortcuts",
label: {
title: t("command.global.show_shortcuts.title"),
description: t("command.global.show_shortcuts.description"),
},
run: () => {
showShortcuts()
},
category,
},
{
id: COMMAND_ID.global.toggleCornerPlay,
label: {
title: t("command.global.toggle_corner_play.title"),
description: t("command.global.toggle_corner_play.description"),
},
run: () => {
EventBus.dispatch("global:toggle-corner-play")
},
category,
},
{
id: COMMAND_ID.global.quickAdd,
label: {
title: t("command.global.quick_add.title"),
description: t("command.global.quick_add.description"),
},
run: () => {
EventBus.dispatch("global:quick-add")
},
category,
},
])
}
@@ -23,4 +60,14 @@ export type ShowShortcutsCommand = Command<{
fn: () => void
}>
export type GlobalCommand = ShowShortcutsCommand
export type ToggleCornerPlayCommand = Command<{
id: typeof COMMAND_ID.global.toggleCornerPlay
fn: () => void
}>
export type QuickAddCommand = Command<{
id: typeof COMMAND_ID.global.quickAdd
fn: () => void
}>
export type GlobalCommand = ShowShortcutsCommand | ToggleCornerPlayCommand | QuickAddCommand
@@ -26,6 +26,7 @@ export const COMMAND_ID = {
saveToOutline: "integration:save-to-outline",
saveToReadeck: "integration:save-to-readeck",
saveToCubox: "integration:save-to-cubox",
saveToZotero: "integration:save-to-zotero",
},
list: {
edit: "list:edit",
@@ -43,17 +44,22 @@ export const COMMAND_ID = {
},
global: {
showShortcuts: "global:show-shortcuts",
toggleCornerPlay: "global:toggle-corner-play",
quickAdd: "global:quick-add",
},
layout: {
toggleTimelineColumn: "layout:toggle-timeline-column",
toggleSubscriptionColumn: "layout:toggle-subscription-column",
focusToTimeline: "layout:focus-to-timeline",
focusToSubscription: "layout:focus-to-subscription",
focusToEntryRender: "layout:focus-to-entry-render",
toggleWideMode: "layout:toggle-wide-mode",
toggleZenMode: "layout:toggle-zen-mode",
},
timeline: {
switchToNext: "timeline:switch-to-next",
switchToPrevious: "timeline:switch-to-previous",
refetch: "timeline:refetch",
enter: "timeline:enter",
unreadOnly: "timeline:unread-only",
},
entryRender: {
scrollDown: "entry-render:scroll-down",
@@ -75,5 +81,8 @@ export const COMMAND_ID = {
previousSubscription: "subscription:previous",
toggleFolderCollapse: "subscription:toggle-folder-collapse",
markAllAsRead: "subscription:mark-all-as-read",
openInBrowser: "subscription:open-in-browser",
openSiteInBrowser: "subscription:open-site-in-browser",
},
} as const
@@ -6,6 +6,7 @@ import {
SimpleIconsOutline,
SimpleIconsReadeck,
SimpleIconsReadwise,
SimpleIconsZotero,
} from "@follow/components/ui/platform-icon/icons.js"
import { IN_ELECTRON } from "@follow/shared/constants"
import { tracker } from "@follow/tracker"
@@ -28,7 +29,7 @@ import { useEntryStore } from "~/store/entry"
import { useRegisterCommandEffect } from "../hooks/use-register-command"
import { defineFollowCommand } from "../registry/command"
import type { Command } from "../types"
import type { Command, CommandCategory } from "../types"
import { COMMAND_ID } from "./id"
export const useRegisterIntegrationCommands = () => {
@@ -39,8 +40,10 @@ export const useRegisterIntegrationCommands = () => {
useRegisterOutlineCommands()
useRegisterReadeckCommands()
useRegisterCuboxCommands()
useRegisterZoteroCommands()
}
const category: CommandCategory = "category.integration"
const useRegisterEagleCommands = () => {
const { t } = useTranslation()
const { view } = useRouteParams()
@@ -123,6 +126,7 @@ const useRegisterReadwiseCommands = () => {
id: COMMAND_ID.integration.saveToReadwise,
label: t("entry_actions.save_to_readwise"),
icon: <SimpleIconsReadwise />,
category,
run: async ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
if (!entry) {
@@ -191,6 +195,7 @@ const useRegisterInstapaperCommands = () => {
id: COMMAND_ID.integration.saveToInstapaper,
label: t("entry_actions.save_to_instapaper"),
icon: <SimpleIconsInstapaper />,
category,
run: async ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
if (!entry) {
@@ -300,6 +305,7 @@ const useRegisterObsidianCommands = () => {
id: COMMAND_ID.integration.saveToObsidian,
label: t("entry_actions.save_to_obsidian"),
icon: <SimpleIconsObsidian />,
category,
run: async ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
if (!entry) {
@@ -344,6 +350,7 @@ const useRegisterOutlineCommands = () => {
id: COMMAND_ID.integration.saveToOutline,
label: t("entry_actions.save_to_outline"),
icon: <SimpleIconsOutline />,
category,
run: async ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
if (!entry) {
@@ -407,6 +414,7 @@ const useRegisterReadeckCommands = () => {
id: COMMAND_ID.integration.saveToReadeck,
label: t("entry_actions.save_to_readeck"),
icon: <SimpleIconsReadeck />,
category,
run: async ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
if (!entry) {
@@ -475,6 +483,7 @@ const useRegisterCuboxCommands = () => {
id: COMMAND_ID.integration.saveToCubox,
label: t("entry_actions.save_to_cubox"),
icon: <SimpleIconsCubox />,
category,
run: async ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
if (!entry) {
@@ -521,6 +530,146 @@ const useRegisterCuboxCommands = () => {
)
}
const useRegisterZoteroCommands = () => {
const { t } = useTranslation()
const enableZotero = useIntegrationSettingKey("enableZotero")
const zoteroUserID = useIntegrationSettingKey("zoteroUserID")
const zoteroToken = useIntegrationSettingKey("zoteroToken")
const zoterAvailable = enableZotero && !!zoteroUserID && !!zoteroToken
// GET https://api.zotero.org/items/new?itemType=webpage
const buildZoteroWebpageRequestBody = (entry: FlatEntryModel) => {
// Zotero API only support ISO 8601 format and without millsecond
const accessDate = `${entry.entries.insertedAt.slice(0, 19)}Z`
// should return an array, because this API endpoint also support multi-item upload
return [
{
itemType: "webpage",
title: entry.entries.title || "",
creators: [
{
creatorType: "author",
firstName: entry.entries.author || "",
lastName: "",
},
],
abstractNote: entry.entries.description || "",
websiteTitle: entry.entries.title || "",
websiteType: "",
date: entry.entries.publishedAt || "",
shortTitle: "",
url: entry.entries.url || "",
accessDate: accessDate || "",
language: entry.entries.language || "",
rights: "",
extra: "",
tags: [],
collections: [],
relations: {},
},
]
}
useRegisterCommandEffect(
!zoterAvailable
? []
: defineFollowCommand({
id: COMMAND_ID.integration.saveToZotero,
label: t("entry_actions.save_to_zotero"),
icon: <SimpleIconsZotero />,
category,
run: async ({ entryId }) => {
const entry = useEntryStore.getState().flatMapEntries[entryId]
if (!entry) {
toast.error("Failed to save to Zotero: entry is not available", { duration: 3000 })
return
}
try {
tracker.integration({
type: "zotero",
event: "save",
})
const requestBody = buildZoteroWebpageRequestBody(entry)
const response = await ofetch(`https://api.zotero.org/users/${zoteroUserID}/items`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Zotero-API-Key": zoteroToken,
},
body: requestBody,
})
if (response.failed && Object.keys(response.failed).length > 0) {
response.failed.forEach((failedObj) => {
toast.error(failedObj.message, { duration: 3000 })
})
}
if (response.success && Object.keys(response.success).length > 0) {
toast.success(t("entry_actions.saved_to_zotero"), {
duration: 3000,
})
}
} catch (error) {
const errorObj = error as FetchError
switch (errorObj.statusCode) {
case 400: {
toast.error(
`${t("entry_actions.failed_to_save_to_zotero")}: Invalid type/field; unparseable JSON`,
{
duration: 3000,
},
)
break
}
case 409: {
toast.error(
`${t("entry_actions.failed_to_save_to_zotero")}: The target library is locked.`,
{
duration: 3000,
},
)
break
}
case 412: {
toast.error(
`${t("entry_actions.failed_to_save_to_zotero")}: The version provided in If-Unmodified-Since-Version is out of date, or the provided Zotero-Write-Token has already been submitted.`,
{
duration: 3000,
},
)
break
}
case 413: {
toast.error(
`${t("entry_actions.failed_to_save_to_zotero")}: Too many items submitted`,
{
duration: 3000,
},
)
break
}
default: {
toast.error(
`${t("entry_actions.failed_to_save_to_zotero")}: ${errorObj.message} || ""`,
{
duration: 3000,
},
)
}
}
}
},
}),
)
}
const getDescription = (entry: FlatEntryModel) => {
const actionLanguage = getActionLanguage()
const { saveSummaryAsDescription } = getIntegrationSettings()
@@ -595,6 +744,11 @@ export type SaveToCuboxCommand = Command<{
fn: (payload: { entryId: string }) => void
}>
export type SaveToZoteroCommand = Command<{
id: typeof COMMAND_ID.integration.saveToZotero
fn: (payload: { entryId: string }) => void
}>
export type IntegrationCommand =
| SaveToEagleCommand
| SaveToReadwiseCommand
@@ -603,3 +757,4 @@ export type IntegrationCommand =
| SaveToOutlineCommand
| SaveToReadeckCommand
| SaveToCuboxCommand
| SaveToZoteroCommand
@@ -1,39 +1,84 @@
import { EventBus } from "@follow/utils/event-bus"
import { useTranslation } from "react-i18next"
import { getIsZenMode, getUISettings, setUISetting, setZenMode } from "~/atoms/settings/ui"
import { setTimelineColumnShow } from "~/atoms/sidebar"
import { useRegisterCommandEffect } from "../hooks/use-register-command"
import type { Command } from "../types"
import type { Command, CommandCategory } from "../types"
import { COMMAND_ID } from "./id"
interface FocusEvent {
highlightBoundary: boolean
}
declare module "@follow/utils/event-bus" {
interface EventBusMap {
"layout:focus-to-timeline": never
"layout:focus-to-subscription": never
"layout:focus-to-timeline": FocusEvent
"layout:focus-to-subscription": FocusEvent
"layout:focus-to-entry-render": FocusEvent
}
}
const category: CommandCategory = "category.layout"
export const useRegisterLayoutCommands = () => {
const { t } = useTranslation("shortcuts")
useRegisterCommandEffect([
{
id: COMMAND_ID.layout.toggleTimelineColumn,
label: "Toggle timeline column",
id: COMMAND_ID.layout.toggleSubscriptionColumn,
label: {
title: t("command.layout.toggle_subscription_column.title"),
description: t("command.layout.toggle_subscription_column.description"),
},
category,
run: () => {
setTimelineColumnShow((show) => !show)
},
},
{
id: COMMAND_ID.layout.focusToTimeline,
label: "Focus to timeline",
label: t("command.layout.focus_to_timeline.title"),
category,
run: () => {
EventBus.dispatch(COMMAND_ID.layout.focusToTimeline)
EventBus.dispatch(COMMAND_ID.layout.focusToTimeline, { highlightBoundary: true })
},
},
{
id: COMMAND_ID.layout.focusToSubscription,
label: "Focus to subscription",
label: t("command.layout.focus_to_subscription.title"),
category,
run: () => {
EventBus.dispatch(COMMAND_ID.layout.focusToSubscription)
EventBus.dispatch(COMMAND_ID.layout.focusToSubscription, { highlightBoundary: true })
},
},
{
id: COMMAND_ID.layout.focusToEntryRender,
label: t("command.layout.focus_to_entry_render.title"),
category,
run: () => {
EventBus.dispatch(COMMAND_ID.layout.focusToEntryRender, { highlightBoundary: true })
},
},
{
id: COMMAND_ID.layout.toggleWideMode,
label: {
title: t("command.layout.toggle_wide_mode.title"),
description: t("command.layout.toggle_wide_mode.description"),
},
category,
run: () => {
const { wideMode } = getUISettings()
setUISetting("wideMode", !wideMode)
},
},
{
id: COMMAND_ID.layout.toggleZenMode,
label: {
title: t("command.layout.toggle_zen_mode.title"),
description: t("command.layout.toggle_zen_mode.description"),
},
category,
run: () => {
setZenMode(!getIsZenMode())
},
},
])
@@ -45,7 +90,7 @@ export type FocusToSubscriptionCommand = Command<{
}>
export type ToggleTimelineColumnCommand = Command<{
id: typeof COMMAND_ID.layout.toggleTimelineColumn
id: typeof COMMAND_ID.layout.toggleSubscriptionColumn
fn: () => void
}>
@@ -53,7 +98,25 @@ export type FocusToTimelineCommand = Command<{
id: typeof COMMAND_ID.layout.focusToTimeline
fn: () => void
}>
export type FocusToEntryRenderCommand = Command<{
id: typeof COMMAND_ID.layout.focusToEntryRender
fn: () => void
}>
export type ToggleWideModeCommand = Command<{
id: typeof COMMAND_ID.layout.toggleWideMode
fn: () => void
}>
export type ToggleZenModeCommand = Command<{
id: typeof COMMAND_ID.layout.toggleZenMode
fn: () => void
}>
export type LayoutCommand =
| ToggleTimelineColumnCommand
| FocusToTimelineCommand
| FocusToSubscriptionCommand
| FocusToEntryRenderCommand
| ToggleWideModeCommand
| ToggleZenModeCommand
@@ -10,8 +10,10 @@ import { UrlBuilder } from "~/lib/url-builder"
import { ListForm } from "~/modules/discover/ListForm"
import { useRegisterCommandEffect } from "../hooks/use-register-command"
import type { CommandCategory } from "../types"
import { COMMAND_ID } from "./id"
const category: CommandCategory = "category.list"
export const useRegisterListCommands = () => {
const { t } = useTranslation()
@@ -23,7 +25,7 @@ export const useRegisterListCommands = () => {
{
id: COMMAND_ID.list.edit,
label: t("sidebar.feed_actions.edit"),
// keyBinding: "E",
category,
run: ({ listId }) => {
if (!listId) return
present({
@@ -35,14 +37,13 @@ export const useRegisterListCommands = () => {
{
id: COMMAND_ID.list.unfollow,
label: t("sidebar.feed_actions.unfollow"),
// keyBinding: "Meta+Backspace",
category,
run: ({ subscription }) => deleteSubscription({ subscription }),
},
{
id: COMMAND_ID.list.navigateTo,
label: t("sidebar.feed_actions.navigate_to_list"),
// keyBinding: "Meta+G",
// when: routeListId !== listId,
category,
run: ({ listId }) => {
if (!listId) return
navigateEntry({ listId })
@@ -53,7 +54,7 @@ export const useRegisterListCommands = () => {
label: t("sidebar.feed_actions.open_list_in_browser", {
which: IN_ELECTRON ? t("words.browser") : t("words.newTab"),
}),
// keyBinding: "O",
category,
run: ({ listId }) => {
if (!listId) return
const { view } = getRouteParams()
@@ -63,7 +64,7 @@ export const useRegisterListCommands = () => {
{
id: COMMAND_ID.list.copyUrl,
label: t("sidebar.feed_actions.copy_list_url"),
// keyBinding: "Meta+C",
category,
run: async ({ listId }) => {
if (!listId) return
const { view } = getRouteParams()
@@ -76,7 +77,7 @@ export const useRegisterListCommands = () => {
{
id: COMMAND_ID.list.copyId,
label: t("sidebar.feed_actions.copy_list_id"),
// keyBinding: "Meta+Shift+C",
category,
run: async ({ listId }) => {
if (!listId) return
await navigator.clipboard.writeText(listId)
@@ -5,7 +5,7 @@ import { useSetTheme } from "~/hooks/common"
import { useShowCustomizeToolbarModal } from "~/modules/customize-toolbar/modal"
import { useRegisterCommandEffect } from "../hooks/use-register-command"
import type { Command } from "../types"
import type { Command, CommandCategory } from "../types"
import { COMMAND_ID } from "./id"
export const useRegisterSettingsCommands = () => {
@@ -13,6 +13,7 @@ export const useRegisterSettingsCommands = () => {
useRegisterThemeCommands()
}
const category: CommandCategory = "category.settings"
const useCustomizeToolbarCommand = () => {
const [t] = useTranslation("settings")
const showModal = useShowCustomizeToolbarModal()
@@ -20,7 +21,7 @@ const useCustomizeToolbarCommand = () => {
{
id: COMMAND_ID.settings.customizeToolbar,
label: t("customizeToolbar.title"),
category: "follow:settings",
category,
icon: <i className="i-mgc-settings-7-cute-re" />,
run() {
showModal()
@@ -38,7 +39,7 @@ const useRegisterThemeCommands = () => {
{
id: COMMAND_ID.settings.changeThemeToAuto,
label: `To ${t("appearance.theme.system")}`,
category: "follow:settings",
category,
icon: <i className="i-mgc-settings-7-cute-re" />,
when: theme !== "system",
run() {
@@ -48,7 +49,7 @@ const useRegisterThemeCommands = () => {
{
id: COMMAND_ID.settings.changeThemeToDark,
label: `To ${t("appearance.theme.dark")}`,
category: "follow:settings",
category,
icon: <i className="i-mingcute-moon-line" />,
when: theme !== "dark",
run() {
@@ -58,7 +59,7 @@ const useRegisterThemeCommands = () => {
{
id: COMMAND_ID.settings.changeThemeToLight,
label: `To ${t("appearance.theme.light")}`,
category: "follow:settings",
category,
icon: <i className="i-mingcute-sun-line" />,
when: theme !== "light",
run() {
@@ -1,7 +1,11 @@
import { EventBus } from "@follow/utils/event-bus"
import { useTranslation } from "react-i18next"
import type { BizRouteParams } from "~/hooks/biz/useRouteParams"
import { getRouteParams } from "~/hooks/biz/useRouteParams"
import { useRegisterCommandEffect } from "../hooks/use-register-command"
import type { Command } from "../types"
import type { Command, CommandCategory } from "../types"
import { COMMAND_ID } from "./id"
declare module "@follow/utils/event-bus" {
@@ -18,88 +22,168 @@ declare module "@follow/utils/event-bus" {
"subscription:next": never
"subscription:previous": never
"subscription:toggle-folder-collapse": never
"subscription:mark-all-as-read": BizRouteParams
"subscription:open-in-browser": never
"subscription:open-site-in-browser": never
}
}
const LABEL_PREFIX = "Subscription"
const category: CommandCategory = "category.subscription"
export const useRegisterSubscriptionCommands = () => {
const { t } = useTranslation("shortcuts")
useRegisterCommandEffect([
{
id: COMMAND_ID.subscription.switchTabToNext,
label: `${LABEL_PREFIX}: Switch to next tab`,
label: {
title: t("command.subscription.switch_tab_to_next.title"),
description: t("command.subscription.switch_tab_to_next.description"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.switchTabToNext)
},
},
{
id: COMMAND_ID.subscription.switchTabToPrevious,
label: `${LABEL_PREFIX}: Switch to previous tab`,
label: {
title: t("command.subscription.switch_tab_to_previous.title"),
description: t("command.subscription.switch_tab_to_previous.description"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.switchTabToPrevious)
},
},
{
id: COMMAND_ID.subscription.switchTabToArticle,
label: `${LABEL_PREFIX}: Switch to article tab`,
label: {
title: t("command.subscription.switch_tab_to_article.title"),
description: t("command.subscription.switch_tab_to_article.description"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.switchTabToArticle)
},
},
{
id: COMMAND_ID.subscription.switchTabToSocial,
label: `${LABEL_PREFIX}: Switch to social tab`,
label: {
title: t("command.subscription.switch_tab_to_social.title"),
description: t("command.subscription.switch_tab_to_social.description"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.switchTabToSocial)
},
},
{
id: COMMAND_ID.subscription.switchTabToPicture,
label: `${LABEL_PREFIX}: Switch to picture tab`,
label: {
title: t("command.subscription.switch_tab_to_picture.title"),
description: t("command.subscription.switch_tab_to_picture.description"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.switchTabToPicture)
},
},
{
id: COMMAND_ID.subscription.switchTabToVideo,
label: `${LABEL_PREFIX}: Switch to video tab`,
label: {
title: t("command.subscription.switch_tab_to_video.title"),
description: t("command.subscription.switch_tab_to_video.description"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.switchTabToVideo)
},
},
{
id: COMMAND_ID.subscription.switchTabToAudio,
label: `${LABEL_PREFIX}: Switch to audio tab`,
label: {
title: t("command.subscription.switch_tab_to_audio.title"),
description: t("command.subscription.switch_tab_to_audio.description"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.switchTabToAudio)
},
},
{
id: COMMAND_ID.subscription.switchTabToNotification,
label: `${LABEL_PREFIX}: Switch to notification tab`,
label: {
title: t("command.subscription.switch_tab_to_notification.title"),
description: t("command.subscription.switch_tab_to_notification.description"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.switchTabToNotification)
},
},
{
id: COMMAND_ID.subscription.nextSubscription,
label: `${LABEL_PREFIX}: Next Subscription`,
label: {
title: t("command.subscription.next_subscription.title"),
description: t("command.subscription.next_subscription.description"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.nextSubscription)
},
},
{
id: COMMAND_ID.subscription.previousSubscription,
label: `${LABEL_PREFIX}: Previous Subscription`,
label: {
title: t("command.subscription.previous_subscription.title"),
description: t("command.subscription.previous_subscription.description"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.previousSubscription)
},
},
{
id: COMMAND_ID.subscription.toggleFolderCollapse,
label: `${LABEL_PREFIX}: Toggle Folder Collapse`,
label: {
title: t("command.subscription.toggle_folder_collapse.title"),
description: t("command.subscription.toggle_folder_collapse.description"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.toggleFolderCollapse)
},
},
{
id: COMMAND_ID.subscription.markAllAsRead,
label: {
title: t("command.subscription.mark_all_as_read.title"),
},
category,
run: () => {
const routeParams = getRouteParams()
EventBus.dispatch(COMMAND_ID.subscription.markAllAsRead, routeParams)
},
},
{
id: COMMAND_ID.subscription.openInBrowser,
label: {
title: t("command.subscription.open_in_browser.title"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.openInBrowser)
},
},
{
id: COMMAND_ID.subscription.openSiteInBrowser,
label: {
title: t("command.subscription.open_site_in_browser.title"),
},
category,
run: () => {
EventBus.dispatch(COMMAND_ID.subscription.openSiteInBrowser)
},
},
])
}
@@ -158,6 +242,21 @@ type ToggleFolderCollapseCommand = Command<{
fn: () => void
}>
type MarkAllAsReadCommand = Command<{
id: typeof COMMAND_ID.subscription.markAllAsRead
fn: () => void
}>
type OpenInBrowserCommand = Command<{
id: typeof COMMAND_ID.subscription.openInBrowser
fn: () => void
}>
type OpenSiteInBrowserCommand = Command<{
id: typeof COMMAND_ID.subscription.openSiteInBrowser
fn: () => void
}>
export type SubscriptionCommand =
| SwitchTabToNextCommand
| SwitchTabToPreviousCommand
@@ -170,3 +269,6 @@ export type SubscriptionCommand =
| NextSubscriptionCommand
| PreviousSubscriptionCommand
| ToggleFolderCollapseCommand
| MarkAllAsReadCommand
| OpenInBrowserCommand
| OpenSiteInBrowserCommand
@@ -1,7 +1,10 @@
import { EventBus } from "@follow/utils/event-bus"
import { useTranslation } from "react-i18next"
import { setGeneralSetting } from "~/atoms/settings/general"
import { useRegisterCommandEffect } from "../hooks/use-register-command"
import type { Command } from "../types"
import type { Command, CommandCategory } from "../types"
import { COMMAND_ID } from "./id"
declare module "@follow/utils/event-bus" {
@@ -12,11 +15,18 @@ declare module "@follow/utils/event-bus" {
"timeline:enter": never
}
}
const category: CommandCategory = "category.timeline"
export const useRegisterTimelineCommand = () => {
const { t } = useTranslation("shortcuts")
useRegisterCommandEffect([
{
id: COMMAND_ID.timeline.switchToNext,
label: "Switch to next timeline",
label: {
title: t("command.timeline.switch_to_next.title"),
description: t("command.timeline.switch_to_next.description"),
},
category,
run: () => {
EventBus.dispatch("timeline:switch-to-next")
@@ -24,23 +34,35 @@ export const useRegisterTimelineCommand = () => {
},
{
id: COMMAND_ID.timeline.switchToPrevious,
label: "Switch to previous timeline",
label: {
title: t("command.timeline.switch_to_previous.title"),
description: t("command.timeline.switch_to_previous.description"),
},
category,
run: () => {
EventBus.dispatch("timeline:switch-to-previous")
},
},
{
id: COMMAND_ID.timeline.refetch,
label: "Refetch timeline",
label: {
title: t("command.timeline.refetch.title"),
description: t("command.timeline.refetch.description"),
},
category,
run: () => {
EventBus.dispatch("timeline:refetch")
},
},
{
id: COMMAND_ID.timeline.enter,
label: "Enter Selected Entry",
run: () => {
EventBus.dispatch("timeline:enter")
id: COMMAND_ID.timeline.unreadOnly,
label: {
title: t("command.timeline.toggle_unread_only.title"),
description: t("command.timeline.toggle_unread_only.description"),
},
category,
run: (unreadOnly: boolean) => {
setGeneralSetting("unreadOnly", unreadOnly)
},
},
])
@@ -61,13 +83,13 @@ export type RefetchTimelineCommand = Command<{
fn: () => void
}>
export type EnterTimelineCommand = Command<{
id: typeof COMMAND_ID.timeline.enter
fn: () => void
export type UnreadOnlyTimelineCommand = Command<{
id: typeof COMMAND_ID.timeline.unreadOnly
fn: (unreadOnly: boolean) => void
}>
export type TimelineCommand =
| SwitchToNextTimelineCommand
| SwitchToPreviousTimelineCommand
| RefetchTimelineCommand
| EnterTimelineCommand
| UnreadOnlyTimelineCommand
@@ -0,0 +1,214 @@
import { getStorageNS } from "@follow/utils/ns"
import { transformShortcut } from "@follow/utils/utils"
import { useAtomValue, useSetAtom } from "jotai"
import { atomWithStorage, selectAtom } from "jotai/utils"
import { useCallback, useMemo } from "react"
import { COMMAND_ID } from "../commands/id"
import type { CommandCategory, FollowCommandId } from "../types"
import { getCommand } from "./use-command"
import type { RegisterHotkeyOptions } from "./use-register-hotkey"
import { useCommandHotkey } from "./use-register-hotkey"
export const defaultCommandShortcuts = {
// Layout commands
[COMMAND_ID.layout.toggleSubscriptionColumn]: transformShortcut("$mod+B"),
[COMMAND_ID.layout.toggleWideMode]: transformShortcut("$mod+["),
[COMMAND_ID.layout.toggleZenMode]: transformShortcut("$mod+Shift+Z"),
// Subscription commands
[COMMAND_ID.subscription.markAllAsRead]: transformShortcut("Shift+$mod+A"),
[COMMAND_ID.subscription.openInBrowser]: "O",
[COMMAND_ID.subscription.openSiteInBrowser]: transformShortcut("$mod+O"),
[COMMAND_ID.subscription.previousSubscription]: "K, ArrowUp",
[COMMAND_ID.subscription.nextSubscription]: "J, ArrowDown",
[COMMAND_ID.subscription.switchTabToNext]: "Tab",
[COMMAND_ID.subscription.switchTabToPrevious]: transformShortcut("Shift+Tab"),
[COMMAND_ID.subscription.toggleFolderCollapse]: "Z",
// Timeline commands
[COMMAND_ID.timeline.refetch]: "R",
[COMMAND_ID.timeline.unreadOnly]: "U",
[COMMAND_ID.timeline.switchToPrevious]: "K, ArrowUp",
[COMMAND_ID.timeline.switchToNext]: "J, ArrowDown",
// Entry commands
[COMMAND_ID.entry.copyLink]: transformShortcut("Shift+$mod+C"),
[COMMAND_ID.entry.copyTitle]: transformShortcut("Shift+$mod+B"),
[COMMAND_ID.entry.openInBrowser]: "B",
[COMMAND_ID.entry.read]: "M",
[COMMAND_ID.entry.share]: transformShortcut("$mod+Alt+S"),
[COMMAND_ID.entry.star]: "S",
[COMMAND_ID.entry.tip]: transformShortcut("Shift+$mod+T"),
[COMMAND_ID.entry.tts]: transformShortcut("Shift+$mod+V"),
// Entry render commands
[COMMAND_ID.entryRender.nextEntry]: "L, ArrowRight",
[COMMAND_ID.entryRender.previousEntry]: "H, ArrowLeft",
[COMMAND_ID.entryRender.scrollUp]: "K, ArrowUp",
[COMMAND_ID.entryRender.scrollDown]: "J, ArrowDown",
// Global commands
[COMMAND_ID.global.toggleCornerPlay]: "Space",
[COMMAND_ID.global.quickAdd]: transformShortcut("$mod+N"),
[COMMAND_ID.global.showShortcuts]: "?",
} as const
const overrideCommandShortcutsAtom = atomWithStorage<
Partial<Record<AllowCustomizeCommandId, string>>
>(getStorageNS("command-shortcuts"), {}, undefined, {
getOnInit: true,
})
export const useCommandShortcutItems = () => {
const commandShortcuts = useCommandShortcuts()
return useMemo(() => {
const groupedCommands = {} as Record<CommandCategory, FollowCommandId[]>
for (const commandKey in commandShortcuts) {
const command = getCommand(commandKey as FollowCommandId)
if (!command) {
continue
}
groupedCommands[command.category] ??= []
groupedCommands[command.category].push(commandKey as FollowCommandId)
}
return groupedCommands
}, [commandShortcuts])
}
export const allowCustomizeCommands = new Set([
COMMAND_ID.layout.toggleSubscriptionColumn,
COMMAND_ID.layout.toggleWideMode,
COMMAND_ID.layout.toggleZenMode,
COMMAND_ID.subscription.markAllAsRead,
COMMAND_ID.subscription.openInBrowser,
COMMAND_ID.subscription.openSiteInBrowser,
COMMAND_ID.subscription.switchTabToNext,
COMMAND_ID.subscription.switchTabToPrevious,
COMMAND_ID.subscription.toggleFolderCollapse,
COMMAND_ID.timeline.refetch,
COMMAND_ID.timeline.unreadOnly,
COMMAND_ID.entry.copyLink,
COMMAND_ID.entry.copyTitle,
COMMAND_ID.entry.openInBrowser,
COMMAND_ID.entry.read,
COMMAND_ID.entry.share,
COMMAND_ID.entry.star,
COMMAND_ID.entry.tip,
COMMAND_ID.entry.tts,
] as const)
type ExtractSetType<T extends Set<unknown>> = T extends Set<infer U> ? U : never
export type AllowCustomizeCommandId = ExtractSetType<typeof allowCustomizeCommands>
export type BindingCommandId = keyof typeof defaultCommandShortcuts
export const useCommandShortcut = (commandId: BindingCommandId): string => {
return useAtomValue(
useMemo(
() =>
selectAtom(overrideCommandShortcutsAtom, (v) => {
return v[commandId] ?? defaultCommandShortcuts[commandId]
}),
[commandId],
),
)
}
export const useSetCustomCommandShortcut = () => {
const setOverrideCommandShortcuts = useSetAtom(overrideCommandShortcutsAtom)
return useCallback(
(commandId: AllowCustomizeCommandId, shortcut: string | null) => {
setOverrideCommandShortcuts((prev) => {
if (shortcut === null) {
const { [commandId]: _, ...rest } = prev
return rest
}
return { ...prev, [commandId]: shortcut }
})
},
[setOverrideCommandShortcuts],
)
}
/**
*
* @deprecated Use `useCommandShortcut` for more granular control
*/
export const useCommandShortcuts = () => {
const overrideCommandShortcuts = useAtomValue(overrideCommandShortcutsAtom)
return {
...defaultCommandShortcuts,
...overrideCommandShortcuts,
}
}
export const useIsShortcutConflict = (
shortcut: string,
excludeCommandId?: AllowCustomizeCommandId,
) => {
const overrideCommandShortcuts = useAtomValue(overrideCommandShortcutsAtom)
return useMemo(() => {
const allShortcuts = {
...defaultCommandShortcuts,
...overrideCommandShortcuts,
}
// Check if the shortcut conflicts with any existing shortcuts
for (const [commandId, existingShortcut] of Object.entries(allShortcuts)) {
// Skip the command we're excluding (useful when editing an existing shortcut)
if (excludeCommandId && commandId === excludeCommandId) {
continue
}
// Normalize shortcuts for comparison (handle multiple shortcuts separated by comma)
const normalizedShortcut = shortcut.trim().toLowerCase()
const normalizedExisting = existingShortcut.toLowerCase()
// Check if shortcuts match exactly or if one is contained in the other's alternatives
const shortcutAlternatives = normalizedShortcut.split(",").map((s) => s.trim())
const existingAlternatives = normalizedExisting.split(",").map((s) => s.trim())
for (const shortcutAlt of shortcutAlternatives) {
for (const existingAlt of existingAlternatives) {
if (shortcutAlt === existingAlt) {
return {
hasConflict: true,
conflictingCommandId: commandId as FollowCommandId,
}
}
}
}
}
return {
hasConflict: false,
conflictingCommandId: null,
}
}, [shortcut, excludeCommandId, overrideCommandShortcuts])
}
export const useCommandBinding = <T extends BindingCommandId>({
commandId,
when = true,
args,
}: Omit<RegisterHotkeyOptions<T>, "shortcut">) => {
const commandShortcut = useCommandShortcut(commandId)
return useCommandHotkey({
shortcut: commandShortcut,
commandId,
when,
args,
})
}
@@ -1,44 +0,0 @@
import { shortcuts } from "~/constants/shortcuts"
import { COMMAND_ID } from "../commands/id"
const defaultCommandShortcuts = {
[COMMAND_ID.entry.read]: shortcuts.entry.toggleRead.key,
[COMMAND_ID.entry.openInBrowser]: shortcuts.entry.openInBrowser.key,
[COMMAND_ID.entry.star]: shortcuts.entry.toggleStarred.key,
[COMMAND_ID.entry.copyLink]: shortcuts.entry.copyLink.key,
[COMMAND_ID.entry.copyTitle]: shortcuts.entry.copyTitle.key,
[COMMAND_ID.entry.tts]: shortcuts.entry.tts.key,
[COMMAND_ID.entry.tip]: shortcuts.entry.tip.key,
[COMMAND_ID.entry.share]: shortcuts.entry.share.key,
[COMMAND_ID.entryRender.scrollUp]: shortcuts.entry.scrollUp.key,
[COMMAND_ID.entryRender.scrollDown]: shortcuts.entry.scrollDown.key,
[COMMAND_ID.timeline.switchToNext]: shortcuts.entries.next.key,
[COMMAND_ID.timeline.switchToPrevious]: shortcuts.entries.previous.key,
[COMMAND_ID.timeline.refetch]: shortcuts.entries.refetch.key,
[COMMAND_ID.layout.toggleTimelineColumn]: shortcuts.layout.toggleSidebar.key,
[COMMAND_ID.subscription.nextSubscription]: shortcuts.subscriptions.nextSubscription.key,
[COMMAND_ID.subscription.previousSubscription]: shortcuts.subscriptions.previousSubscription.key,
[COMMAND_ID.subscription.switchTabToNext]: shortcuts.subscriptions.switchNextView.key,
[COMMAND_ID.subscription.switchTabToPrevious]: shortcuts.subscriptions.switchPreviousView.key,
[COMMAND_ID.global.showShortcuts]: shortcuts.layout.showShortcuts.key,
[COMMAND_ID.entryRender.nextEntry]: shortcuts.entry.nextEntry.key,
[COMMAND_ID.entryRender.previousEntry]: shortcuts.entry.previousEntry.key,
[COMMAND_ID.subscription.toggleFolderCollapse]: shortcuts.subscriptions.toggleFolderCollapse.key,
} as const
export type BindingCommandId = keyof typeof defaultCommandShortcuts
// eslint-disable-next-line @eslint-react/hooks-extra/no-unnecessary-use-prefix, @eslint-react/hooks-extra/ensure-custom-hooks-using-other-hooks
export const useCommandShortcut = (commandId: BindingCommandId): string => {
const commandShortcut = defaultCommandShortcuts[commandId]
return commandShortcut
}
@@ -1,7 +1,7 @@
import { jotaiStore } from "@follow/utils/jotai"
import { useAtomValue } from "jotai"
import { selectAtom } from "jotai/utils"
import { useCallback, useMemo } from "react"
import { useMemo } from "react"
import { CommandRegistry } from "../registry/registry"
import type { FollowCommandId, FollowCommandMap } from "../types"
@@ -25,14 +25,16 @@ export function useCommand<T extends FollowCommandId>(id: T): FollowCommandMap[T
}
const noop = () => {}
export function useRunCommandFn() {
return useCallback(
<T extends FollowCommandId>(id: T, args: Parameters<FollowCommandMap[T]["run"]>) => {
const cmd = getCommand(id)
if (!cmd) return noop
// @ts-expect-error - The type should be discriminated
return () => cmd.run(...args)
},
[],
)
const runCommand = <T extends FollowCommandId>(
id: T,
args: Parameters<FollowCommandMap[T]["run"]>,
) => {
const cmd = getCommand(id)
if (!cmd) return noop
// @ts-expect-error - The type should be discriminated
return () => cmd.run(...args)
}
export function useRunCommandFn() {
return runCommand
}
@@ -1,15 +1,15 @@
import { useRefValue } from "@follow/hooks"
import { checkIsEditableElement } from "@follow/utils/dom"
import { useEffect } from "react"
import { tinykeys } from "tinykeys"
import type { FollowCommand, FollowCommandId } from "../types"
import { getCommand } from "./use-command"
import type { BindingCommandId } from "./use-command-shortcut"
import { useCommandShortcut } from "./use-command-shortcut"
export interface HotkeyOptions {
forceInputElement?: true
}
interface RegisterHotkeyOptions<T extends FollowCommandId> {
export interface RegisterHotkeyOptions<T extends FollowCommandId> {
shortcut: string
commandId: T
args?: Parameters<Extract<FollowCommand, { id: T }>["run"]>
@@ -18,7 +18,9 @@ interface RegisterHotkeyOptions<T extends FollowCommandId> {
options?: HotkeyOptions
}
const IGNORE_INPUT_ELEMENT = [HTMLInputElement, HTMLTextAreaElement]
const SPECIAL_KEYS_MAPPINGS = {
"?": "Shift+Slash",
}
export const useCommandHotkey = <T extends FollowCommandId>({
shortcut,
@@ -27,6 +29,7 @@ export const useCommandHotkey = <T extends FollowCommandId>({
args,
options,
}: RegisterHotkeyOptions<T>) => {
const argsRef = useRefValue(args)
useEffect(() => {
if (!when) {
return
@@ -42,13 +45,15 @@ export const useCommandHotkey = <T extends FollowCommandId>({
// Create a handler for each shortcut
shortcuts.forEach((key) => {
keyMap[key] = (event) => {
let nextKey = key
if (SPECIAL_KEYS_MAPPINGS[key]) {
nextKey = SPECIAL_KEYS_MAPPINGS[key]
}
keyMap[nextKey] = (event) => {
const { target } = event
if (
!options?.forceInputElement &&
(IGNORE_INPUT_ELEMENT.some((el) => target instanceof el) ||
(target as HTMLElement).getAttribute("contenteditable") === "true")
) {
if (!options?.forceInputElement && checkIsEditableElement(target as HTMLElement)) {
return
}
@@ -57,7 +62,7 @@ export const useCommandHotkey = <T extends FollowCommandId>({
const command = getCommand(commandId)
if (!command) return
const args = argsRef.current
if (Array.isArray(args)) {
// It should be safe to spread the args here because we are checking if it is an array
// @ts-expect-error - A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
@@ -76,20 +81,5 @@ export const useCommandHotkey = <T extends FollowCommandId>({
})
return tinykeys(document.documentElement, keyMap)
}, [shortcut, commandId, when, args])
}
export const useCommandBinding = <T extends BindingCommandId>({
commandId,
when = true,
args,
}: Omit<RegisterHotkeyOptions<T>, "shortcut">) => {
const commandShortcut = useCommandShortcut(commandId)
return useCommandHotkey({
shortcut: commandShortcut,
commandId,
when,
args,
})
}, [shortcut, commandId, when, argsRef, options?.forceInputElement])
}
@@ -16,7 +16,7 @@ export function createCommand<
id: options.id,
run: options.run,
icon: options.icon,
category: options.category ?? "follow:general",
category: options.category ?? "category.global",
get label() {
let { label } = options
label = typeof label === "function" ? label?.() : label
@@ -0,0 +1,448 @@
import { useReplaceGlobalFocusableScope } from "@follow/components/common/Focusable/hooks.js"
import { KbdCombined } from "@follow/components/ui/kbd/Kbd.js"
import { RootPortal } from "@follow/components/ui/portal/index.js"
import { Tooltip, TooltipContent, TooltipTrigger } from "@follow/components/ui/tooltip/index.js"
import { cn } from "@follow/utils/utils"
import type { FC, RefObject, SVGProps } from "react"
import { memo, useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useOnClickOutside } from "usehooks-ts"
import { HotkeyScope } from "~/constants"
import { useCommand } from "../hooks/use-command"
import type { AllowCustomizeCommandId } from "../hooks/use-command-binding"
import {
allowCustomizeCommands,
defaultCommandShortcuts,
useCommandShortcutItems,
useCommandShortcuts,
useIsShortcutConflict,
useSetCustomCommandShortcut,
} from "../hooks/use-command-binding"
import type { CommandCategory, FollowCommandId } from "../types"
export const ShortcutsGuideline = () => {
const { t } = useTranslation("shortcuts")
const commandShortcuts = useCommandShortcutItems()
return (
<div className="mt-4 space-y-6">
{Object.entries(commandShortcuts).map(([type, commands]) => (
<section key={type}>
<div className="text-text-secondary mb-2 pl-3 text-sm font-medium capitalize">
{t(type as CommandCategory)}
</div>
<div className="text-text rounded-md border text-[13px]">
{commands.map((commandId) => (
<CommandShortcutItem key={commandId} commandId={commandId} />
))}
</div>
</section>
))}
</div>
)
}
export const ShortcutSetting = () => {
const { t } = useTranslation("shortcuts")
const commandShortcuts = useCommandShortcutItems()
return (
<div>
<p className="mb-6 mt-4 space-y-2 text-sm">{t("settings.shortcuts.description")}</p>
{Object.entries(commandShortcuts).map(([type, commands]) => (
<section key={type} className="mb-8">
<div className="text-text border-border mb-4 border-b pb-2 text-base font-medium">
{t(type as CommandCategory)}
</div>
<div className="space-y-4">
{commands.map((commandId) => (
<EditableCommandShortcutItem key={commandId} commandId={commandId} />
))}
</div>
</section>
))}
</div>
)
}
const EditableCommandShortcutItem = memo(({ commandId }: { commandId: FollowCommandId }) => {
const command = useCommand(commandId)
const commandShortcuts = useCommandShortcuts()
const [isEditing, setIsEditing] = useState(false)
const setCustomCommandShortcut = useSetCustomCommandShortcut()
const allowCustomize = allowCustomizeCommands.has(commandId as AllowCustomizeCommandId)
if (!command) return null
const isUserCustomize = commandShortcuts[commandId] !== defaultCommandShortcuts[commandId]
return (
<div
className={
"relative box-content grid h-8 grid-cols-[auto_200px] items-center justify-between gap-x-8 py-1.5"
}
>
<div className="flex min-w-0 flex-col gap-1">
<div className="text-text flex items-center gap-2 text-sm">
{command.label.title}
{isUserCustomize && (
<Tooltip>
<TooltipTrigger asChild>
<div
className="bg-accent/10 text-accent hover:bg-accent/20 inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium transition-all duration-200"
title="User customized shortcut"
>
<div className="bg-accent mr-1 size-2 rounded-full" />
Custom
</div>
</TooltipTrigger>
<TooltipContent>This shortcut is customized by you</TooltipContent>
</Tooltip>
)}
</div>
{!!command.label.description && (
<small className="text-text-secondary text-xs">{command.label.description}</small>
)}
</div>
<ShortcutInputWrapper
commandId={commandId}
shortcut={commandShortcuts[commandId]}
isEditing={isEditing}
isUserCustomize={isUserCustomize}
allowCustomize={allowCustomize}
onEditingChange={setIsEditing}
onShortcutChange={(shortcut) => {
setCustomCommandShortcut(commandId as AllowCustomizeCommandId, shortcut)
setIsEditing(false)
}}
/>
</div>
)
})
interface ShortcutInputWrapperProps {
commandId: FollowCommandId
shortcut: string
isEditing: boolean
isUserCustomize: boolean
allowCustomize: boolean
onEditingChange: (editing: boolean) => void
onShortcutChange: (shortcut: string | null) => void
}
const ShortcutInputWrapper = memo(
({
commandId,
shortcut,
isEditing,
isUserCustomize,
allowCustomize,
onEditingChange,
onShortcutChange,
}: ShortcutInputWrapperProps) => {
const conflictResult = useIsShortcutConflict(shortcut, commandId as AllowCustomizeCommandId)
const hasConflict = allowCustomize && conflictResult.hasConflict
const conflictingCommandId = allowCustomize ? conflictResult.conflictingCommandId : null
const conflictCommand = useCommand(conflictingCommandId as FollowCommandId)
const getBorderColor = () => {
if (hasConflict) {
return "border-red/70 hover:!border-red"
}
if (isEditing) {
return "border-border bg-material-ultra-thick"
}
if (allowCustomize) {
return "border-border/50 bg-material-ultra-thin data-[customized=true]:bg-accent/10 data-[customized=true]:border-accent/50"
}
return "border-transparent"
}
const getBackgroundColor = () => {
if (hasConflict && !isEditing) {
return "bg-red/5"
}
if (isEditing) {
return "bg-material-ultra-thick"
}
return ""
}
return (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
data-customized={isUserCustomize}
className={cn(
"flex h-full cursor-text justify-end rounded-md border px-1 duration-200",
allowCustomize && "hover:!border-border hover:!bg-material-medium",
getBorderColor(),
getBackgroundColor(),
!allowCustomize && "pointer-events-none",
)}
onClick={() => {
if (allowCustomize) {
onEditingChange(!isEditing)
}
}}
>
{isEditing ? (
<KeyRecorder
onBlur={() => {
onEditingChange(false)
}}
onChange={(keys) => {
onShortcutChange(Array.isArray(keys) ? keys.join("+") : null)
}}
/>
) : (
<KbdCombined kbdProps={{ wrapButton: false }} joint={false}>
{shortcut}
</KbdCombined>
)}
</button>
</TooltipTrigger>
{hasConflict && (
<RootPortal>
<TooltipContent className="max-w-xs">
<div className="space-y-1">
<div className="font-medium text-red-400">Shortcut Conflict</div>
<div className="text-xs">
This shortcut conflicts with command:
<p className="text-sm font-medium">{conflictCommand?.label.title}</p>
</div>
</div>
</TooltipContent>
</RootPortal>
)}
</Tooltip>
)
},
)
const KeyRecorder: FC<{
onChange: (keys: string[] | null) => void
onBlur: () => void
}> = ({ onChange, onBlur }) => {
const { currentKeys } = useShortcutRecorder()
const setGlobalScope = useReplaceGlobalFocusableScope()
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
const { rollback } = setGlobalScope(HotkeyScope.Recording)
if (ref.current) {
ref.current.focus()
}
return () => {
rollback()
}
}, [setGlobalScope])
useOnClickOutside(ref as RefObject<HTMLElement>, () => {
if (currentKeys.length > 0) {
onChange(currentKeys)
}
onBlur()
})
return (
<div
className="text-text-secondary flex h-full items-center justify-center px-1 text-xs"
tabIndex={-1}
role="textbox"
ref={ref}
>
{currentKeys.length > 0 ? (
<div className="pr-4">
<KbdCombined kbdProps={{ wrapButton: false }} joint={false}>
{currentKeys.join("+")}
</KbdCombined>
</div>
) : (
<span className="text-text-secondary pr-4">Press keys to record</span>
)}
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<button
type="button"
className="hover:text-text absolute inset-y-0 right-0 z-[1] flex items-center justify-center px-1"
onClick={(e) => {
e.stopPropagation()
if (currentKeys.length === 0) {
onChange(null)
} else {
onBlur()
}
}}
>
{currentKeys.length > 0 ? (
<i className="i-mingcute-close-circle-fill size-4" />
) : (
<FamiconsArrowUndoCircle className="size-4" />
)}
</button>
</TooltipTrigger>
<TooltipContent>{currentKeys.length > 0 ? "Undo" : "Reset"}</TooltipContent>
</Tooltip>
</div>
)
}
function FamiconsArrowUndoCircle(props: SVGProps<SVGSVGElement>) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="1em"
height="1em"
viewBox="0 0 512 512"
{...props}
>
{/* Icon from Famicons by Family - https://github.com/familyjs/famicons/blob/main/LICENSE */}
<path
fill="currentColor"
d="M256 48C141.13 48 48 141.13 48 256s93.13 208 208 208s208-93.13 208-208S370.87 48 256 48m97.67 281.1c-24.07-25.21-51.51-38.68-108.58-38.68v37.32a8.32 8.32 0 0 1-14.05 6L146.58 254a8.2 8.2 0 0 1 0-11.94L231 162.29a8.32 8.32 0 0 1 14.05 6v37.32c88.73 0 117.42 55.64 122.87 117.09c.73 7.72-8.85 12.05-14.25 6.4"
/>
</svg>
)
}
const CommandShortcutItem = memo(({ commandId }: { commandId: FollowCommandId }) => {
const command = useCommand(commandId)
const commandShortcuts = useCommandShortcuts()
if (!command) return null
return (
<div className={"odd:bg-fill-quinary flex h-9 items-center justify-between px-3 py-1.5"}>
<div>{command.label.title}</div>
<div>
<KbdCombined joint>{commandShortcuts[commandId]}</KbdCombined>
</div>
</div>
)
})
///////
const MODIFIER_KEYS_MAP = {
Control: "Control",
Alt: "Alt",
Shift: "Shift",
Meta: "Meta",
} as const
const MODIFIER_KEYS_SET = new Set<string>(Object.values(MODIFIER_KEYS_MAP))
const F_KEY_REGEX = /^F(?:[1-9]|1[0-2])$/
function getKeySortValue(key: string): number {
if (key === MODIFIER_KEYS_MAP.Meta) return 0
if (key === MODIFIER_KEYS_MAP.Control) return 1
if (key === MODIFIER_KEYS_MAP.Alt) return 2
if (key === MODIFIER_KEYS_MAP.Shift) return 3
if (F_KEY_REGEX.test(key)) return 4
return 5
}
function sortShortcutKeys(keys: string[]): string[] {
return [...keys].sort((a, b) => {
const sortValueA = getKeySortValue(a)
const sortValueB = getKeySortValue(b)
if (sortValueA !== sortValueB) {
return sortValueA - sortValueB
}
return a.localeCompare(b)
})
}
const useShortcutRecorder = () => {
const [currentKeys, setCurrentKeys] = useState<string[]>([])
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
event.preventDefault()
event.stopPropagation()
event.stopImmediatePropagation()
const { altKey, ctrlKey, metaKey, shiftKey, key: eventKey } = event
let mainKeyPressed = eventKey
if (mainKeyPressed.length === 1 && mainKeyPressed >= "a" && mainKeyPressed <= "z") {
mainKeyPressed = mainKeyPressed.toUpperCase()
} else if (mainKeyPressed === " ") {
mainKeyPressed = "Space"
}
const pressedKeysSet = new Set<string>()
// 添加修饰键
if (metaKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Meta)
if (ctrlKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Control)
if (altKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Alt)
if (shiftKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Shift)
// If mainKeyPressed (from event.key) is not a modifier key, add it as the main key.
// If mainKeyPressed is a modifier key (e.g., user only pressed Shift key, event.key is "Shift"),
// it has already been handled and added to pressedKeysSet by the above if (shiftKey) logic,
// so we don't need to add it again here.
if (!MODIFIER_KEYS_SET.has(mainKeyPressed)) {
pressedKeysSet.add(mainKeyPressed)
}
const currentCombination = Array.from(pressedKeysSet)
// --- Start validation rules ---
const nonModifierKeysInCombo = currentCombination.filter((key) => !MODIFIER_KEYS_SET.has(key))
// Rule 2: Pure modifier key combinations are not allowed (e.g., just Shift, or Ctrl+Alt)
if (nonModifierKeysInCombo.length === 0) {
// When only modifier keys are pressed, currentCombination will still contain these modifiers.
// For example, pressing only Shift, currentCombination is ["Shift"]
// Here we don't update the state, indicating this is an invalid recording.
// You can provide temporary UI feedback here, e.g.: "Recording: Shift"
console.info(
"Recording (invalid - modifiers only):",
sortShortcutKeys(currentCombination).join(" + "),
)
return
}
// Typically shortcuts have only one "main" function key (e.g., Ctrl+A, Shift+F1)
// If multiple non-modifier keys are detected (e.g., theoretically user pressing A and B simultaneously),
// this is usually not a standard shortcut recording scenario
// This check is mainly for code robustness, as `keydown` events typically focus on one main key at a time.
if (nonModifierKeysInCombo.length > 1) {
console.warn(
"Recording (invalid - multiple main keys, this shouldn't normally happen):",
sortShortcutKeys(currentCombination).join(" + "),
)
return
}
const primaryKey = nonModifierKeysInCombo[0]
// Rule 3: Fn keys (F1-F12) can be single keys or modifier+Fn key combinations
if (F_KEY_REGEX.test(primaryKey ?? "")) {
setCurrentKeys(sortShortcutKeys(currentCombination))
return
}
// Rule 1: Single "ASCII" main keys are allowed (here referring to all non-modifier, non-F keys)
// Examples: A, 1, Space, Enter, ArrowUp, etc. They can be used alone or with modifiers.
// For these keys, as long as they're not pure modifier combinations, they're considered valid.
setCurrentKeys(sortShortcutKeys(currentCombination))
}
window.addEventListener("keydown", handleKeyDown)
return () => {
window.removeEventListener("keydown", handleKeyDown)
}
}, [setCurrentKeys])
return { currentKeys }
}
@@ -2,13 +2,8 @@ import type { ReactNode } from "react"
import type { BasicCommand } from "./commands/types"
export type CommandCategory =
| "follow:settings"
| "follow:layout"
| "follow:updates"
| "follow:help"
| "follow:general"
| "follow:entry-render"
type ExtractCategory<T extends string> = T extends `category.${string}` ? T : never
export type CommandCategory = ExtractCategory<Parameters<typeof tShortcuts>[0]>
export interface KeybindingOptions {
binding: string
@@ -90,12 +90,14 @@ export const DiscoverFeedForm = ({
noDescription,
routeParams,
viewportClassName,
rootClassName,
}: {
route: RSSHubRoute
routePrefix: string
noDescription?: boolean
routeParams?: RouteParams
viewportClassName?: string
rootClassName?: string
}) => {
const { t } = useTranslation()
const keys = useMemo(
@@ -226,9 +228,8 @@ export const DiscoverFeedForm = ({
<div className={cn("flex h-full flex-col", "mx-auto")} ref={rootContainerRef}>
<Form {...form}>
<ScrollArea.ScrollArea
flex
rootClassName={cn(isInModal && "-mx-4 px-4 -mt-4", "max-h-[calc(100vh-200px)] grow")}
viewportClassName={cn("pt-4", viewportClassName)}
rootClassName={cn(isInModal && "-mx-4 -mt-4", rootClassName)}
viewportClassName={cn("pt-4 px-4 max-h-[calc(100vh-200px)]", viewportClassName)}
>
<div className="flex">
<div className="w-0 grow truncate">
@@ -74,7 +74,7 @@ export function DiscoverTransform() {
route={data?.rsshub.routes["/transform/html/:url/:routeParams"]!}
routeParams={transformRouteParams}
noDescription
viewportClassName="pt-0"
viewportClassName="pt-0 max-h-none"
/>
</div>
)}
@@ -25,6 +25,7 @@ import { useTranslation } from "react-i18next"
import { toast } from "sonner"
import { z } from "zod"
import { getGeneralSettings } from "~/atoms/settings/general"
import { Autocomplete } from "~/components/ui/auto-completion"
import { useCurrentModal, useIsInModal } from "~/components/ui/modal/stacked/hooks"
import { getRouteParams } from "~/hooks/biz/useRouteParams"
@@ -32,11 +33,12 @@ import { useAuthQuery, useI18n } from "~/hooks/common"
import { apiClient } from "~/lib/api-fetch"
import { tipcClient } from "~/lib/client"
import { toastFetchError } from "~/lib/error-parser"
import { entries as entriesQuery } from "~/queries/entries"
import { feed as feedQuery, useFeedQuery } from "~/queries/feed"
import { subscription as subscriptionQuery } from "~/queries/subscriptions"
import { useFeedByIdOrUrl } from "~/store/feed"
import { useSubscriptionByFeedId } from "~/store/subscription"
import { feedUnreadActions } from "~/store/unread"
import { unreadActions } from "~/store/unread"
import { ViewSelectorRadioGroup } from "../shared/ViewSelectorRadioGroup"
import { FeedSummary } from "./FeedSummary"
@@ -242,13 +244,24 @@ const FeedInnerForm = ({
return $method({
json: body,
})
}) as unknown as Promise<
| ReturnType<typeof apiClient.subscriptions.$post>
| ReturnType<typeof apiClient.subscriptions.$patch>
>
},
onSuccess: (_, variables) => {
if (isSubscribed && variables.view !== `${subscription?.view}`) {
feedUnreadActions.fetchUnreadByView(subscription?.view)
} else {
feedUnreadActions.fetchUnreadByView(Number.parseInt(variables.view))
onSuccess: (data, variables) => {
if (getGeneralSettings().hidePrivateSubscriptionsInTimeline) {
entriesQuery
.entries({
feedId: "all",
view: Number(variables.view),
excludePrivate: true,
})
.invalidate({ exact: true })
}
if ("unread" in data) {
unreadActions.upsertMany(data.unread)
}
subscriptionQuery.all().invalidate()
tipcClient?.invalidateQuery(subscriptionQuery.all().key)
@@ -1,5 +1,5 @@
import { Skeleton } from "@follow/components/ui/skeleton/index.js"
import type { FeedOrListRespModel } from "@follow/models"
import type { FeedAnalyticsModel, FeedOrListRespModel, ListAnalyticsModel } from "@follow/models"
import type { FC } from "react"
import { useMemo } from "react"
import { useTranslation } from "react-i18next"
@@ -11,11 +11,7 @@ import { FollowSummary } from "../feed/feed-summary"
export interface FeedSummaryProps {
feed: FeedOrListRespModel
analytics?: {
updatesPerWeek: number | null
subscriptionCount: number | null
latestEntryPublishedAt: string | null
}
analytics?: FeedAnalyticsModel | ListAnalyticsModel
showAnalytics?: boolean
}
@@ -28,7 +24,7 @@ export const FeedSummary: FC<FeedSummaryProps> = ({ feed, analytics, showAnalyti
{showAnalytics && (
<div className="text-callout mt-2 flex h-6 justify-between gap-4 pl-10">
{!analytics ? (
{!analytics && !("updatedAt" in feed && "updatedAt" in feed && feed.updatedAt) ? (
<Skeleton className="mt-1 h-5 w-40" />
) : (
<div className="text-text-secondary flex items-center gap-3">
@@ -42,12 +38,14 @@ export const FeedSummary: FC<FeedSummaryProps> = ({ feed, analytics, showAnalyti
</span>
</div>
)}
{analytics?.updatesPerWeek ? (
{analytics && "updatesPerWeek" in analytics && analytics?.updatesPerWeek ? (
<div className="flex items-center gap-1.5">
<i className="i-mgc-safety-certificate-cute-re" />
<span>{t("feed.entry_week", { count: analytics.updatesPerWeek ?? 0 })}</span>
</div>
) : analytics?.latestEntryPublishedAt ? (
) : analytics &&
"latestEntryPublishedAt" in analytics &&
analytics?.latestEntryPublishedAt ? (
<div className="flex items-center gap-1.5">
<i className="i-mgc-safe-alert-cute-re" />
<span>{t("feed.updated_at")}</span>
@@ -57,6 +55,13 @@ export const FeedSummary: FC<FeedSummaryProps> = ({ feed, analytics, showAnalyti
/>
</div>
) : null}
{"updatedAt" in feed && feed.updatedAt ? (
<div className="flex items-center gap-1.5">
<i className="i-mgc-safety-certificate-cute-re" />
<span>{t("feed.updated_at")}</span>
<RelativeTime date={feed.updatedAt} displayAbsoluteTimeAfterDay={Infinity} />
</div>
) : null}
</div>
)}
</div>
@@ -1,5 +1,4 @@
import { Button } from "@follow/components/ui/button/index.js"
import { Card, CardHeader } from "@follow/components/ui/card/index.jsx"
import {
Form,
FormControl,
@@ -13,7 +12,7 @@ import { Input } from "@follow/components/ui/input/index.js"
import { LoadingCircle } from "@follow/components/ui/loading/index.jsx"
import { Switch } from "@follow/components/ui/switch/index.jsx"
import { FeedViewType } from "@follow/constants"
import type { ListModel } from "@follow/models/types"
import type { ListAnalyticsModel, ListModel } from "@follow/models/types"
import { tracker } from "@follow/tracker"
import { cn } from "@follow/utils/utils"
import { zodResolver } from "@hookform/resolvers/zod"
@@ -24,21 +23,23 @@ import { useTranslation } from "react-i18next"
import { toast } from "sonner"
import { z } from "zod"
import { getGeneralSettings } from "~/atoms/settings/general"
import { useCurrentModal } from "~/components/ui/modal/stacked/hooks"
import { useI18n } from "~/hooks/common"
import { apiClient } from "~/lib/api-fetch"
import { tipcClient } from "~/lib/client"
import { getFetchErrorMessage, toastFetchError } from "~/lib/error-parser"
import { getNewIssueUrl } from "~/lib/issues"
import { FollowSummary } from "~/modules/feed/feed-summary"
import { entries as entriesQuery } from "~/queries/entries"
import { lists as listsQuery, useList } from "~/queries/lists"
import { subscription as subscriptionQuery } from "~/queries/subscriptions"
import { useListById } from "~/store/list"
import { useSubscriptionByFeedId } from "~/store/subscription"
import { feedUnreadActions } from "~/store/unread"
import { unreadActions } from "~/store/unread"
import { useTOTPModalWrapper } from "../profile/hooks"
import { ViewSelectorRadioGroup } from "../shared/ViewSelectorRadioGroup"
import { FeedSummary } from "./FeedSummary"
const formSchema = z.object({
view: z.string(),
@@ -90,6 +91,7 @@ export const ListForm: Component<{
onSuccess,
subscriptionData: feedQuery.data?.subscription,
analytics: feedQuery.data?.analytics,
list,
}}
/>
@@ -163,6 +165,7 @@ const ListInnerForm = ({
onSuccess,
subscriptionData,
list,
analytics,
}: {
defaultValues?: z.infer<typeof formSchema>
id?: string
@@ -175,6 +178,7 @@ const ListInnerForm = ({
title?: string | null
}
list: ListModel
analytics?: ListAnalyticsModel
}) => {
const subscription = useSubscriptionByFeedId(id || "") || subscriptionData
const isSubscribed = !!subscription
@@ -216,13 +220,25 @@ const ListInnerForm = ({
return $method({
json: body,
})
}) as unknown as Promise<
| ReturnType<typeof apiClient.subscriptions.$post>
| ReturnType<typeof apiClient.subscriptions.$patch>
>
},
onSuccess: (_, variables) => {
if (isSubscribed && variables.view !== `${subscription?.view}`) {
feedUnreadActions.fetchUnreadByView(subscription?.view)
} else {
feedUnreadActions.fetchUnreadByView(Number.parseInt(variables.view))
onSuccess: (data, variables) => {
if (getGeneralSettings().hidePrivateSubscriptionsInTimeline) {
entriesQuery
.entries({
feedId: "all",
view: Number(variables.view),
excludePrivate: true,
})
.invalidate({ exact: true })
}
if ("unread" in data) {
const { unread } = data
unreadActions.upsertMany(unread)
}
subscriptionQuery.all().invalidate()
tipcClient?.invalidateQuery(subscriptionQuery.all().key)
@@ -260,11 +276,7 @@ const ListInnerForm = ({
return (
<div className="flex flex-1 flex-col gap-y-4">
<Card>
<CardHeader>
<FollowSummary feed={list} />
</CardHeader>
</Card>
<FeedSummary feed={list} analytics={analytics} showAnalytics />
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-1 flex-col gap-y-4">
<FormField
@@ -1,148 +1,36 @@
import { isMobile } from "@follow/components/hooks/useMobile.js"
import { EmptyIcon } from "@follow/components/icons/empty.js"
import { ActionButton } from "@follow/components/ui/button/action-button.js"
import { Card, CardContent } from "@follow/components/ui/card/index.jsx"
import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js"
import { ResponsiveSelect } from "@follow/components/ui/select/responsive.js"
import { EllipsisHorizontalTextWithTooltip } from "@follow/components/ui/typography/EllipsisWithTooltip.js"
import { CategoryMap, RSSHubCategories } from "@follow/constants"
import { nextFrame } from "@follow/utils/dom"
import { isASCII } from "@follow/utils/utils"
import { keepPreviousData } from "@tanstack/react-query"
import { useCallback, useEffect, useMemo, useState } from "react"
import { flushSync } from "react-dom"
import { useTranslation } from "react-i18next"
import { Link } from "react-router"
import { setUISetting, useUISettingKey } from "~/atoms/settings/ui"
import { DrawerModalLayout } from "~/components/ui/modal/stacked/custom-modal"
import { useCurrentModal, useModalStack } from "~/components/ui/modal/stacked/hooks"
import { useAuthQuery } from "~/hooks/common"
import { Queries } from "~/queries"
import { FeedIcon } from "../feed/feed-icon"
import { RecommendationContent } from "./RecommendationContent"
const LanguageOptions = [
{
label: "All",
label: "words.all",
value: "all",
},
{
label: "English",
label: "words.english",
value: "eng",
},
{
label: "中文",
label: "words.chinese",
value: "cmn",
},
] as const
]
type Language = (typeof LanguageOptions)[number]["value"]
type DiscoverCategories = (typeof RSSHubCategories)[number] | string
type Language = "all" | "eng" | "cmn"
const LanguageMap = {
all: "all",
eng: "en",
cmn: "zh-CN",
} as const
const fetchRsshubPopular = (category: DiscoverCategories, lang: Language) => {
return Queries.discover.rsshubCategory({
category: "popular",
categories: category === "all" ? "popular" : `popular,${category}`,
lang: LanguageMap[lang],
})
}
let firstLoad = true
export function Recommendations() {
const { t } = useTranslation()
const { present } = useModalStack()
const { t: tCommon } = useTranslation("common")
const [category, setCategory] = useState<DiscoverCategories>("all")
const lang = useUISettingKey("discoverLanguage")
const rsshubPopular = useAuthQuery(fetchRsshubPopular(category, lang), {
meta: {
persist: true,
},
staleTime: 1000 * 60 * 60 * 24, // 1 day
refetchOnMount: firstLoad ? "always" : true,
placeholderData: keepPreviousData,
})
firstLoad = false
const { data, isLoading } = rsshubPopular
const keys = useMemo(() => {
if (!data) {
return []
}
return Object.keys(data).sort((a, b) => {
const aname = data[a].name
const bname = data[b].name
const aRouteName = data[a].routes[Object.keys(data[a].routes)[0]].name
const bRouteName = data[b].routes[Object.keys(data[b].routes)[0]].name
const ia = isASCII(aname) && isASCII(aRouteName)
const ib = isASCII(bname) && isASCII(bRouteName)
if (ia && ib) {
return aname.toLowerCase() < bname.toLowerCase() ? -1 : 1
} else if (ia || ib) {
return ia > ib ? -1 : 1
} else {
return 0
}
})
}, [data])
const handleCategoryChange = useCallback(
(value: DiscoverCategories) => {
flushSync(() => {
setCategory(value)
})
rsshubPopular.refetch()
},
[rsshubPopular],
)
const handleLangChange = useCallback(
(value: string) => {
flushSync(() => {
setUISetting("discoverLanguage", value as Language)
})
rsshubPopular.refetch()
},
[rsshubPopular],
)
const handleShowCategoryContent = (selectedCategory: DiscoverCategories) => {
present({
id: `category-content-${selectedCategory}`,
CustomModalComponent: !isMobile() ? DrawerModalLayout : undefined,
content: () => {
return (
<RecommendationDrawerContent
keys={keys}
data={data}
selectedCategory={selectedCategory}
handleCategoryChange={handleCategoryChange}
/>
)
},
title: t(`discover.category.${selectedCategory}` as any, { ns: "common" }),
})
}
if (isLoading) {
return null
}
if (!data) {
return null
const handleLangChange = (value: string) => {
setUISetting("discoverLanguage", value as Language)
}
return (
@@ -160,7 +48,8 @@ export function Recommendations() {
onValueChange={handleLangChange}
triggerClassName="h-8 rounded border-0"
size="sm"
items={LanguageOptions as any}
items={LanguageOptions}
renderItem={(item) => <>{tCommon(item.label as any)}</>}
/>
</div>
</div>
@@ -168,274 +57,30 @@ export function Recommendations() {
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4">
{RSSHubCategories.map((cat) => (
<Card
key={cat}
className="cursor-pointer transition-all duration-200 hover:scale-[102%] hover:shadow-lg"
style={{
backgroundImage: `linear-gradient(-135deg, ${CategoryMap[cat]?.color}80, ${CategoryMap[cat]?.color})`,
}}
onClick={() => handleShowCategoryContent(cat)}
>
<CardContent className="group relative flex aspect-square flex-col overflow-hidden p-0">
<div className="absolute right-2 top-2 size-12 rotate-12 opacity-20">
<div className="text-5xl">{CategoryMap[cat]?.emoji}</div>
</div>
<div className="flex size-full flex-col items-start justify-end p-6 text-left">
<div className="mb-3 text-4xl transition-transform duration-300 group-hover:scale-[1.2]">
{CategoryMap[cat]?.emoji}
<Link to={`/discover/category/${cat}`} key={cat}>
<Card
className="cursor-pointer transition-all duration-200 hover:scale-[102%] hover:shadow-lg"
style={{
backgroundImage: `linear-gradient(-135deg, ${CategoryMap[cat]?.color}80, ${CategoryMap[cat]?.color})`,
}}
>
<CardContent className="group relative flex aspect-square flex-col overflow-hidden p-0">
<div className="absolute right-2 top-2 size-12 rotate-12 opacity-20">
<div className="text-5xl">{CategoryMap[cat]?.emoji}</div>
</div>
<div className="text-lg font-bold text-white drop-shadow-sm">
{t(`discover.category.${cat}`, { ns: "common" })}
<div className="flex size-full flex-col items-start justify-end p-6 text-left">
<div className="mb-3 text-4xl transition-transform duration-300 group-hover:scale-[1.2]">
{CategoryMap[cat]?.emoji}
</div>
<div className="text-lg font-bold text-white drop-shadow-sm">
{t(`discover.category.${cat}`, { ns: "common" })}
</div>
</div>
</div>
</CardContent>
</Card>
</CardContent>
</Card>
</Link>
))}
</div>
</div>
)
}
const RecommendationDrawerContent = ({
keys,
data,
selectedCategory,
handleCategoryChange,
}: {
keys: string[]
data: any
selectedCategory: string
handleCategoryChange: (category: string) => void
}) => {
const { t } = useTranslation()
const filteredItems = keys
.map((key) => {
if (selectedCategory !== "all") {
const categories = new Set<string>()
for (const route in data![key].routes) {
const routeData = data![key].routes[route]!
if (routeData.categories) {
routeData.categories.forEach((c) => categories.add(c))
}
}
if (!categories.has(selectedCategory as string)) {
return null
}
}
return {
key,
data: data![key],
routePrefix: key,
}
})
.filter(Boolean)
const { dismiss } = useCurrentModal()
// Delay rendering to avoid layout shift
const [ready, setReady] = useState(false)
useEffect(() => {
nextFrame(() => {
setReady(true)
})
}, [])
return (
<div className="absolute inset-0 flex flex-col">
<h1 className="text-title2 mt-4 pl-8 font-semibold">
{t(`discover.category.${selectedCategory}` as any, { ns: "common" })}
</h1>
{/* Close */}
<ActionButton
className="absolute right-4 top-4 z-10"
onClick={dismiss}
tooltip={t("words.close", { ns: "common" })}
>
<i className="i-mgc-close-cute-re" />
</ActionButton>
<div className="bg-border m-4 h-px shrink-0" />
{filteredItems.length > 0 ? (
<ScrollArea rootClassName="w-full -mt-4" viewportClassName="px-8 pt-4 pb-8">
{ready && (
<div
className="animate-in fade-in duration-300"
style={{
columnCount: isMobile() ? 1 : 2,
columnGap: "16px",
width: "100%",
}}
>
{filteredItems.map(
(item) =>
item && (
<div key={item.key} className="mb-4 break-inside-avoid">
<RecommendationListItem
data={item.data}
routePrefix={item.routePrefix}
setCategory={handleCategoryChange}
/>
</div>
),
)}
</div>
)}
</ScrollArea>
) : (
<div className="flex h-full -translate-y-12 flex-col items-center justify-center text-center">
<div className="mb-4 text-6xl">
<EmptyIcon />
</div>
<p className="text-text text-title2">
{t("common.noContent", { defaultValue: "No content found in this category" })}
</p>
<p className="text-text-secondary text-body mt-2">
{t("discover.tryAnotherCategory", {
defaultValue: "Try selecting another category or language",
})}
</p>
</div>
)}
</div>
)
}
const RecommendationListItem = ({
data,
routePrefix,
setCategory,
}: {
data: any
routePrefix: string
setCategory: (category: string) => void
}) => {
const { t } = useTranslation()
const { present } = useModalStack()
const { maintainers, categories, routes } = useMemo(() => {
const maintainers = new Set<string>()
const categories = new Set<string>()
const routes = Object.keys(data.routes)
for (const route in data.routes) {
const routeData = data.routes[route]!
if (routeData.maintainers) {
routeData.maintainers.forEach((m) => maintainers.add(m))
}
if (routeData.categories) {
routeData.categories.forEach((c) => categories.add(c))
}
}
categories.delete("popular")
return {
maintainers: Array.from(maintainers),
categories: Array.from(categories) as unknown as typeof RSSHubCategories,
routes,
}
}, [data])
return (
<Card className="shadow-background border-border overflow-hidden rounded-lg border transition-shadow duration-200 hover:shadow-md">
<div className="border-border flex items-center gap-3 border-b p-4">
<div className="bg-background size-8 overflow-hidden rounded-full">
<FeedIcon className="mr-0 size-8" size={32} siteUrl={`https://${data.url}`} />
</div>
<div className="flex w-full flex-1 justify-between">
<h3 className="text-title3 line-clamp-1 font-medium">
<a
href={`https://${data.url}`}
target="_blank"
rel="noreferrer"
className="hover:underline"
>
{data.name}
</a>
</h3>
<div className="flex flex-wrap gap-1.5 text-xs">
{categories.map((c) => (
<button
onClick={() => {
if (!RSSHubCategories.includes(c)) return
setCategory(c)
}}
key={c}
type="button"
className={`bg-accent/10 cursor-pointer rounded-full px-2 py-0.5 duration-200 ${
!RSSHubCategories.includes(c) ? "pointer-events-none opacity-50" : ""
}`}
>
{RSSHubCategories.includes(c)
? t(`discover.category.${c}`, { ns: "common" })
: c.charAt(0).toUpperCase() + c.slice(1)}
</button>
))}
</div>
</div>
</div>
<div className="p-4">
<ul className="text-text mb-3">
{routes.map((route) => {
const routeData = data.routes[route]!
if (Array.isArray(routeData.path)) {
routeData.path = routeData.path.find((p) => p === route) ?? routeData.path[0]
}
return (
<li
key={route}
className="hover:bg-material-opaque -mx-4 flex items-center rounded p-1 px-5 transition-colors"
role="button"
onClick={() => {
present({
id: `recommendation-content-${route}`,
content: () => (
<RecommendationContent
routePrefix={routePrefix}
route={data.routes[route]!}
/>
),
icon: <FeedIcon className="size-4" size={16} siteUrl={`https://${data.url}`} />,
title: `${data.name} - ${data.routes[route]!.name}`,
})
}}
>
<div className="bg-accent mr-2 size-1.5 rounded-full" />
<div className="relative h-5 grow">
<div className="absolute inset-0">
<EllipsisHorizontalTextWithTooltip className="text-sm">
{routeData.name}
</EllipsisHorizontalTextWithTooltip>
</div>
</div>
</li>
)
})}
</ul>
{maintainers.length > 0 && (
<div className="text-text-secondary mt-2 flex items-center text-xs">
<i className="i-mgc-hammer-cute-re mr-1 shrink-0 translate-y-0.5 self-start" />
<span>
{maintainers.map((m, i) => (
<span key={m}>
<a
href={`https://github.com/${m}`}
className="hover:underline"
target="_blank"
rel="noreferrer"
>
@{m}
</a>
{i < maintainers.length - 1 ? ", " : ""}
</span>
))}
</span>
</div>
)}
</div>
</Card>
)
}
@@ -1,4 +1,7 @@
import { useFocusable, useFocusActions } from "@follow/components/common/Focusable/hooks.js"
import {
useFocusActions,
useGlobalFocusableScope,
} from "@follow/components/common/Focusable/hooks.js"
import { useScrollViewElement } from "@follow/components/ui/scroll-area/hooks.js"
import { useRefValue } from "@follow/hooks"
import { nextFrame } from "@follow/utils/dom"
@@ -9,11 +12,10 @@ import { memo, useEffect } from "react"
import { HotkeyScope } from "~/constants"
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 { useCommandBinding, useCommandHotkey } from "../command/hooks/use-register-hotkey"
import { useCommandBinding } from "../command/hooks/use-command-binding"
import { useCommandHotkey } from "../command/hooks/use-register-hotkey"
export const EntryColumnShortcutHandler: FC<{
refetch: () => void
@@ -22,10 +24,9 @@ export const EntryColumnShortcutHandler: FC<{
}> = memo(({ data, refetch, handleScrollTo }) => {
const dataRef = useRefValue(data!)
const activeScope = useHotkeyScope()
const activeScope = useGlobalFocusableScope()
const when =
activeScope.includes(HotkeyScope.Timeline) && !activeScope.includes(HotkeyScope.EntryRender)
const when = activeScope.has(HotkeyScope.Timeline) && !activeScope.has(HotkeyScope.EntryRender)
useCommandBinding({
commandId: COMMAND_ID.timeline.switchToNext,
@@ -43,14 +44,14 @@ export const EntryColumnShortcutHandler: FC<{
})
useCommandHotkey({
commandId: COMMAND_ID.timeline.enter,
shortcut: "Enter",
commandId: COMMAND_ID.layout.focusToEntryRender,
shortcut: "Enter, L, ArrowRight",
when,
})
useCommandHotkey({
commandId: COMMAND_ID.layout.focusToSubscription,
shortcut: "Backspace, Escape",
shortcut: "Backspace, Escape, H, ArrowLeft",
when,
})
@@ -99,15 +100,16 @@ export const EntryColumnShortcutHandler: FC<{
const $scrollArea = useScrollViewElement()
const { highlightBoundary } = useFocusActions()
useEffect(() => {
return EventBus.subscribe(COMMAND_ID.layout.focusToTimeline, () => {
$scrollArea?.focus()
nextFrame(highlightBoundary)
})
return EventBus.subscribe(
COMMAND_ID.layout.focusToTimeline,
({ highlightBoundary: highlight }) => {
$scrollArea?.focus()
if (highlight) {
nextFrame(highlightBoundary)
}
},
)
}, [$scrollArea, highlightBoundary])
const isFocusIn = useFocusable()
useConditionalHotkeyScope(HotkeyScope.Timeline, isFocusIn, true)
return null
})
@@ -2,6 +2,7 @@ import { isMobile } from "@follow/components/hooks/useMobile.js"
import { Skeleton } from "@follow/components/ui/skeleton/index.jsx"
import { IN_ELECTRON } from "@follow/shared/constants"
import { stopPropagation } from "@follow/utils/dom"
import { formatDuration } from "@follow/utils/duration"
import { transformVideoUrl } from "@follow/utils/url-for-video"
import { cn } from "@follow/utils/utils"
import { useHover } from "@use-gesture/react"
@@ -77,6 +78,16 @@ export function VideoItem({ entryId, entryPreview, translation }: UniversalItemP
}
}, [hovered])
const duration = useMemo(() => {
const seconds = entry?.entries.attachments?.find(
(attachment) => attachment.duration_in_seconds,
)?.duration_in_seconds
if (seconds) {
return formatDuration(Number.parseInt(seconds.toString()))
}
return 0
}, [entry?.entries.attachments])
if (!entry) return null
return (
<GridItem entryId={entryId} entryPreview={entryPreview} translation={translation}>
@@ -107,7 +118,7 @@ export function VideoItem({ entryId, entryPreview, translation }: UniversalItemP
}
}}
>
<div className="overflow-x-auto" ref={ref}>
<div className="relative overflow-x-auto" ref={ref}>
{miniIframeSrc && showPreview ? (
<ViewTag
src={miniIframeSrc}
@@ -139,6 +150,11 @@ export function VideoItem({ entryId, entryPreview, translation }: UniversalItemP
No media available
</div>
)}
{!!duration && (
<div className="absolute bottom-2 right-2 rounded-md bg-black/50 px-1 py-0.5 text-xs font-medium text-white">
{duration}
</div>
)}
</div>
</div>
</GridItem>
@@ -39,7 +39,7 @@ const useParseDate = (date: string) =>
}
}, [date])
const dateItemclassName = tw`relative flex items-center text-sm lg:text-base gap-1 bg-background px-4 font-bold text-zinc-800 dark:text-neutral-400 h-7`
const dateItemclassName = tw`relative flex items-center text-sm lg:text-base gap-1 bg-background px-4 font-bold text-text h-7`
export const DateItem = memo(({ date, view, isSticky }: DateItemProps) => {
if (view === FeedViewType.SocialMedia) {
return <SocialMediaDateItem date={date} className={dateItemclassName} isSticky={isSticky} />
@@ -13,22 +13,26 @@ export const FooterMarkItem = ({ view }: { view: FeedViewType }) => {
const SocialMediaFooterMarkItem = () => {
return (
<FlatMarkAllReadButton
className="justify-start"
buttonClassName="w-[645px] mx-auto mb-4 pl-7 py-4"
iconClassName="mr-1 text-lg"
which="above"
/>
<div className="relative w-full">
<FlatMarkAllReadButton
className="justify-center"
buttonClassName="w-[645px] mx-auto mb-4 pl-7 py-4"
iconClassName="mr-1 text-lg"
which="above"
/>
</div>
)
}
const GridFooterMarkItem = () => {
return (
<FlatMarkAllReadButton
buttonClassName="w-full py-4"
iconClassName="mr-1 text-base"
which="above"
/>
<div className="relative w-full">
<FlatMarkAllReadButton
buttonClassName="w-full py-4"
iconClassName="mr-1 text-base"
which="above"
/>
</div>
)
}
@@ -1,16 +1,19 @@
import { useGlobalFocusableScope } from "@follow/components/common/Focusable/hooks.js"
import { ActionButton, Button } from "@follow/components/ui/button/index.js"
import { Kbd, KbdCombined } from "@follow/components/ui/kbd/Kbd.js"
import { useCountdown } from "@follow/hooks"
import { EventBus } from "@follow/utils/event-bus"
import { cn } from "@follow/utils/utils"
import type { FC, ReactNode } from "react"
import { useState } from "react"
import { useEffect, useState } from "react"
import { useHotkeys } from "react-hotkeys-hook"
import { Trans, useTranslation } from "react-i18next"
import { toast } from "sonner"
import { HotkeyScope } from "~/constants"
import { shortcuts } from "~/constants/shortcuts"
import { useI18n } from "~/hooks/common"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { useCommandBinding, useCommandShortcuts } from "~/modules/command/hooks/use-command-binding"
import type { MarkAllFilter } from "../hooks/useMarkAll"
import { markAllByRoute } from "../hooks/useMarkAll"
@@ -30,9 +33,16 @@ export const MarkAllReadButton = ({
const { t } = useTranslation()
const { t: commonT } = useTranslation("common")
useHotkeys(
shortcuts.entries.markAllAsRead.key,
() => {
const activeScope = useGlobalFocusableScope()
useCommandBinding({
commandId: COMMAND_ID.subscription.markAllAsRead,
when: [HotkeyScope.Timeline, HotkeyScope.SubscriptionList].some((scope) =>
activeScope.has(scope),
),
})
useEffect(() => {
return EventBus.subscribe(COMMAND_ID.subscription.markAllAsRead, () => {
let cancel = false
const undo = () => {
toast.dismiss(id)
@@ -51,20 +61,17 @@ export const MarkAllReadButton = ({
<span className="flex items-center gap-1">
{t("mark_all_read_button.undo")}
<Kbd className="border-border inline-flex items-center border bg-transparent text-white">
Meta+Z
$mod+z
</Kbd>
</span>
),
onClick: undo,
},
})
},
{
preventDefault: true,
scopes: HotkeyScope.Home,
},
)
})
}, [t])
const markAllAsReadShortcut = useCommandShortcuts()[COMMAND_ID.subscription.markAllAsRead]
return (
<ActionButton
tooltip={
@@ -77,9 +84,7 @@ export const MarkAllReadButton = ({
/>
{shortcut && (
<div className="ml-1">
<KbdCombined className="text-text-secondary">
{shortcuts.entries.markAllAsRead.key}
</KbdCombined>
<KbdCombined className="text-text-secondary">{markAllAsReadShortcut}</KbdCombined>
</div>
)}
</>
@@ -100,7 +105,6 @@ const ConfirmMarkAllReadInfo = ({ undo }: { undo: () => any }) => {
const [countdown] = useCountdown({ countStart: 3 })
useHotkeys("ctrl+z,meta+z", undo, {
scopes: HotkeyScope.Home,
preventDefault: true,
})
@@ -8,10 +8,10 @@ import { useGeneralSettingKey } from "~/atoms/settings/general"
import { useRouteParams } from "~/hooks/biz/useRouteParams"
import { useAuthQuery } from "~/hooks/common"
import { apiClient, apiFetch } from "~/lib/api-fetch"
import { Queries } from "~/queries"
import { entries, useEntries } from "~/queries/entries"
import { entryActions, getEntry, useEntryIdsByFeedIdOrView } from "~/store/entry"
import { useFolderFeedsByFeedId } from "~/store/subscription"
import { feedUnreadActions } from "~/store/unread"
import { useIsPreviewFeed } from "./useIsPreviewFeed"
@@ -51,6 +51,9 @@ const useRemoteEntries = (): UseEntriesReturn => {
const isPreview = useIsPreviewFeed()
const unreadOnly = useGeneralSettingKey("unreadOnly")
const hidePrivateSubscriptionsInTimeline = useGeneralSettingKey(
"hidePrivateSubscriptionsInTimeline",
)
const folderIds = useFolderFeedsByFeedId({
feedId,
@@ -64,6 +67,7 @@ const useRemoteEntries = (): UseEntriesReturn => {
listId,
view,
...(unreadOnly === true && !isPreview && { read: false }),
...(hidePrivateSubscriptionsInTimeline === true && { excludePrivate: true }),
}
if (feedId && listId && isBizId(feedId)) {
@@ -71,7 +75,16 @@ const useRemoteEntries = (): UseEntriesReturn => {
}
return params
}, [feedId, folderIds, inboxId, listId, unreadOnly, view, isPreview])
}, [
feedId,
folderIds,
inboxId,
listId,
unreadOnly,
isPreview,
view,
hidePrivateSubscriptionsInTimeline,
])
const query = useEntries(entriesOptions)
const [fetchedTime, setFetchedTime] = useState<number>()
@@ -134,6 +147,9 @@ const useLocalEntries = (): UseEntriesReturn => {
const { feedId, view, inboxId, listId, isAllFeeds } = useRouteParams()
const unreadOnly = useGeneralSettingKey("unreadOnly")
const hidePrivateSubscriptionsInTimeline = useGeneralSettingKey(
"hidePrivateSubscriptionsInTimeline",
)
const folderIds = useFolderFeedsByFeedId({
feedId,
@@ -145,6 +161,7 @@ const useLocalEntries = (): UseEntriesReturn => {
{
unread: unreadOnly,
view,
excludePrivate: hidePrivateSubscriptionsInTimeline,
},
)
@@ -284,9 +301,9 @@ export const useEntriesByView = ({ onReset }: { onReset?: () => void }) => {
hasUpdate: query.hasUpdate,
refetch: useCallback(() => {
const promise = query.refetch()
feedUnreadActions.fetchUnreadByView(view)
Queries.subscription.unreadAll().invalidate()
return promise
}, [query, view]),
}, [query]),
entriesIds: sortEntries,
groupedCounts,
}
@@ -1,3 +1,4 @@
import { getGeneralSettings } from "~/atoms/settings/general"
import { getRouteParams } from "~/hooks/biz/useRouteParams"
import { getFolderFeedsByFeedId, subscriptionActions } from "~/store/subscription"
@@ -17,27 +18,32 @@ export const markAllByRoute = async (filter?: MarkAllFilter) => {
if (!routerParams) return
if (typeof routerParams.feedId === "number" || routerParams.isAllFeeds) {
subscriptionActions.markReadByView(view, filter)
const { hidePrivateSubscriptionsInTimeline } = getGeneralSettings()
subscriptionActions.markReadByView({
view,
filter,
excludePrivate: hidePrivateSubscriptionsInTimeline,
})
} else if (inboxId) {
subscriptionActions.markReadByFeedIds({
subscriptionActions.markReadByIds({
inboxId,
view,
filter,
})
} else if (listId) {
subscriptionActions.markReadByFeedIds({
subscriptionActions.markReadByIds({
listId,
view,
filter,
})
} else if (folderIds?.length) {
subscriptionActions.markReadByFeedIds({
subscriptionActions.markReadByIds({
feedIds: folderIds,
view,
filter,
})
} else if (routerParams.feedId) {
subscriptionActions.markReadByFeedIds({
subscriptionActions.markReadByIds({
feedIds: routerParams.feedId?.split(","),
view,
filter,
@@ -1,4 +1,3 @@
import { Focusable } from "@follow/components/common/Focusable/index.js"
import { useMobile } from "@follow/components/hooks/useMobile.js"
import { FeedViewType, views } from "@follow/constants"
import { useTitle } from "@follow/hooks"
@@ -7,8 +6,9 @@ import type { Range, Virtualizer } from "@tanstack/react-virtual"
import { memo, useCallback, useEffect, useRef } from "react"
import { useGeneralSettingKey } from "~/atoms/settings/general"
import { Focusable } from "~/components/common/Focusable"
import { FeedNotFound } from "~/components/errors/FeedNotFound"
import { FEED_COLLECTION_LIST, ROUTE_FEED_PENDING } from "~/constants"
import { FEED_COLLECTION_LIST, HotkeyScope, ROUTE_FEED_PENDING } from "~/constants"
import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
import { useRouteParams, useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
import { useFeedQuery } from "~/queries/feed"
@@ -118,6 +118,7 @@ function EntryColumnImpl() {
const ListComponent = views[view]!.gridMode ? EntryColumnGrid : EntryList
return (
<Focusable
scope={HotkeyScope.Timeline}
data-hide-in-print
className="@container relative flex h-full flex-1 flex-col"
onClick={
@@ -1,6 +1,7 @@
import { useMobile } from "@follow/components/hooks/useMobile.js"
import type { FeedViewType } from "@follow/constants"
import { views } from "@follow/constants"
import { EventBus } from "@follow/utils/event-bus"
import { cn } from "@follow/utils/utils"
import type { FC, PropsWithChildren } from "react"
import { useCallback, useState } from "react"
@@ -18,7 +19,7 @@ import { useEntryIsRead } from "~/hooks/biz/useAsRead"
import { useEntryActions } from "~/hooks/biz/useEntryActions"
import { useFeedActions } from "~/hooks/biz/useFeedActions"
import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
import { getRouteParams, useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
import { useContextMenu } from "~/hooks/common/useContextMenu"
import { COMMAND_ID } from "~/modules/command/commands/id"
import type { FlatEntryModel } from "~/store/entry"
@@ -69,9 +70,17 @@ export const EntryItemWrapper: FC<
(e) => {
e.stopPropagation()
const shouldNavigate = getRouteParams().entryId !== entry.entries.id
if (!shouldNavigate) return
if (!asRead) {
entryActions.markRead({ feedId: entry.feedId, entryId: entry.entries.id, read: true })
}
setTimeout(
() => EventBus.dispatch(COMMAND_ID.layout.focusToEntryRender, { highlightBoundary: false }),
60,
)
navigate({
entryId: entry.entries.id,
})
@@ -11,13 +11,15 @@ import { useTranslation } from "react-i18next"
import { useNavigate } from "react-router"
import { previewBackPath } from "~/atoms/preview"
import { setGeneralSetting, useGeneralSettingKey } from "~/atoms/settings/general"
import { useGeneralSettingKey } from "~/atoms/settings/general"
import { useTimelineColumnShow } from "~/atoms/sidebar"
import { useWhoami } from "~/atoms/user"
import { FEED_COLLECTION_LIST, ROUTE_ENTRY_PENDING } from "~/constants"
import { shortcuts } from "~/constants/shortcuts"
import { useFollow } from "~/hooks/biz/useFollow"
import { getRouteParams, useRouteParams } from "~/hooks/biz/useRouteParams"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { useRunCommandFn } from "~/modules/command/hooks/use-command"
import { useCommandShortcuts } from "~/modules/command/hooks/use-command-binding"
import { EntryHeader } from "~/modules/entry-content/header"
import { useRefreshFeedMutation } from "~/queries/feed"
import { getFeedById, useFeedById, useFeedHeaderTitle } from "~/store/feed"
@@ -64,7 +66,8 @@ export const EntryListHeader: FC<{
const titleStyleBasedView = ["pl-6", "pl-7", "pl-7", "pl-7", "px-5", "pl-6"]
const feedColumnShow = useTimelineColumnShow()
const commandShortcuts = useCommandShortcuts()
const runCmdFn = useRunCommandFn()
return (
<div
className={cn(
@@ -134,8 +137,8 @@ export const EntryListHeader: FC<{
? t("entry_list_header.show_unread_only")
: t("entry_list_header.show_all")
}
shortcut={shortcuts.entries.toggleUnreadOnly.key}
onClick={() => setGeneralSetting("unreadOnly", !unreadOnly)}
shortcut={commandShortcuts[COMMAND_ID.timeline.unreadOnly]}
onClick={() => runCmdFn(COMMAND_ID.timeline.unreadOnly, [!unreadOnly])()}
>
{unreadOnly ? (
<i className="i-mgc-round-cute-fi" />
@@ -10,14 +10,15 @@ import { cn, isBizId } from "@follow/utils/utils"
import type { FC } from "react"
import { useTranslation } from "react-i18next"
import { setGeneralSetting, useGeneralSettingKey } from "~/atoms/settings/general"
import { useGeneralSettingKey } from "~/atoms/settings/general"
import { useWhoami } from "~/atoms/user"
import { HeaderTopReturnBackButton } from "~/components/mobile/button"
import { FEED_COLLECTION_LIST } from "~/constants"
import { LOGO_MOBILE_ID } from "~/constants/dom"
import { shortcuts } from "~/constants/shortcuts"
import { useRouteParams } from "~/hooks/biz/useRouteParams"
import { FeedColumnMobile } from "~/modules/app-layout/feed-column/mobile"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { useRunCommandFn } from "~/modules/command/hooks/use-command"
import { useRefreshFeedMutation } from "~/queries/feed"
import { useFeedById, useFeedHeaderTitle } from "~/store/feed"
@@ -60,6 +61,7 @@ export const EntryListHeader: FC<EntryListHeaderProps> = ({ refetch, isRefreshin
const isList = !!listId
const showQuickTimeline = useGeneralSettingKey("showQuickTimeline")
const runCmdFn = useRunCommandFn()
return (
<div
@@ -130,8 +132,7 @@ export const EntryListHeader: FC<EntryListHeaderProps> = ({ refetch, isRefreshin
? t("entry_list_header.show_unread_only")
: t("entry_list_header.show_all")
}
shortcut={shortcuts.entries.toggleUnreadOnly.key}
onClick={() => setGeneralSetting("unreadOnly", !unreadOnly)}
onClick={() => runCmdFn(COMMAND_ID.timeline.unreadOnly, [!unreadOnly])()}
>
{unreadOnly ? (
<i className="i-mgc-round-cute-fi" />
@@ -25,8 +25,9 @@ import {
useSetZenMode,
useUISettingKey,
} from "~/atoms/settings/ui"
import { shortcuts } from "~/constants/shortcuts"
import { useAIDailyReportModal } from "~/modules/ai/ai-daily/useAIDailyReportModal"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { useCommandShortcuts } from "~/modules/command/hooks/use-command-binding"
import { setMasonryColumnValue, useMasonryColumnValue } from "../atoms"
@@ -146,9 +147,10 @@ export const WideModeButton = () => {
const { t } = useTranslation()
const setIsZenMode = useSetZenMode()
const shortcuts = useCommandShortcuts()
return (
<ActionButton
shortcut={shortcuts.layout.toggleWideMode.key}
shortcut={shortcuts[COMMAND_ID.layout.toggleWideMode]}
onClick={() => {
if (isZenMode) {
setIsZenMode(false)
@@ -3,7 +3,7 @@ import { useCallback } from "react"
import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
import { useRouteParams } from "~/hooks/biz/useRouteParams"
import { InboxItem, ListItem } from "~/modules/timeline-column/FeedItem"
import { InboxItem, ListItem } from "~/modules/subscription-column/FeedItem"
import { useSubscriptionStore } from "~/store/subscription"
export const TimelineTabs = () => {
@@ -242,7 +242,7 @@ export const EntryList: FC<EntryListProps> = memo(
"bg-background",
isActiveStickyItem
? "sticky top-0 z-[1]"
: "absolute left-0 top-0 w-full will-change-transform",
: "absolute left-0 top-0 z-[1] w-full will-change-transform",
)}
style={
!isActiveStickyItem
@@ -2,6 +2,7 @@ import { useMobile } from "@follow/components/hooks/useMobile.js"
import { EllipsisHorizontalTextWithTooltip } from "@follow/components/ui/typography/index.js"
import { clsx, cn, formatEstimatedMins, formatTimeToSeconds, isSafari } from "@follow/utils/utils"
import { useMemo } from "react"
import { titleCase } from "title-case"
import { AudioPlayer, useAudioPlayerAtomSelector } from "~/atoms/player"
import { useGeneralSettingKey } from "~/atoms/settings/general"
@@ -68,9 +69,6 @@ export function ListItem({
lineClampDescription += 1
}
// for tailwind
// line-clamp-[1] line-clamp-[2] line-clamp-[3] line-clamp-[4] line-clamp-[5] line-clamp-[6] line-clamp-[7] line-clamp-[8]
// FIXME: Safari bug, not support line-clamp cross elements
return {
global: !envIsSafari
@@ -157,8 +155,8 @@ export function ListItem({
{entry.entries.title ? (
<EntryTranslation
className={cn("hyphens-auto font-medium", lineClamp.title)}
source={entry.entries.title}
target={translation?.title}
source={titleCase(entry.entries.title ?? "")}
target={titleCase(translation?.title ?? "")}
/>
) : (
<EntryTranslation
@@ -5,7 +5,7 @@ import { CommandActionButton } from "~/components/ui/button/CommandActionButton"
import { useHasModal } from "~/components/ui/modal/stacked/hooks"
import { useSortedEntryActions } from "~/hooks/biz/useEntryActions"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { useCommandBinding } from "~/modules/command/hooks/use-register-hotkey"
import { useCommandBinding } from "~/modules/command/hooks/use-command-binding"
import { useEntry } from "~/store/entry/hooks"
export const EntryHeaderActions = ({
@@ -2,7 +2,7 @@ import { AvatarGroup } from "@follow/components/ui/avatar-group/index.js"
import { FeedViewType } from "@follow/constants"
import { useWhoami } from "~/atoms/user"
import { getRouteParams } from "~/hooks/biz/useRouteParams"
import { getRouteParams, useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
import { useAuthQuery } from "~/hooks/common"
import { useAppLayoutGridContainerWidth } from "~/providers/app-grid-layout-container-provider"
import { Queries } from "~/queries"
@@ -32,8 +32,12 @@ export const EntryReadHistory: Component<{ entryId: string }> = ({ entryId }) =>
const me = useWhoami()
const entryHistory = useEntryReadHistory(entryId)
const inboxId = useRouteParamsSelector((s) => s.inboxId)
const { data } = useAuthQuery(Queries.entries.entryReadingHistory(entryId), {
refetchInterval: 1000 * 60,
enabled: !inboxId,
refetchIntervalInBackground: false,
})
const totalCount = data?.total || 0
@@ -60,17 +64,19 @@ export const EntryReadHistory: Component<{ entryId: string }> = ({ entryId }) =>
))}
</AvatarGroup>
<div
style={{
margin: "-8px",
zIndex: LIMIT + 1,
}}
className="no-drag-region border-border bg-material-opaque ring-background relative flex size-7 items-center justify-center rounded-full border ring-2"
>
<span className="text-text-secondary text-[10px] font-medium tabular-nums">
+{Math.min(totalCount - LIMIT, 99)}
</span>
</div>
{totalCount > LIMIT && (
<div
style={{
margin: "-8px",
zIndex: LIMIT + 1,
}}
className="no-drag-region border-border bg-material-opaque ring-background relative flex size-7 items-center justify-center rounded-full border ring-2"
>
<span className="text-text-secondary text-[10px] font-medium tabular-nums">
+{Math.min(totalCount - LIMIT, 99)}
</span>
</div>
)}
</div>
)
}
@@ -1,5 +1,6 @@
import { formatEstimatedMins, formatTimeToSeconds } from "@follow/utils/utils"
import { useMemo } from "react"
import { titleCase } from "title-case"
import { useUISettingKey } from "~/atoms/settings/ui"
import { useWhoami } from "~/atoms/user"
@@ -74,8 +75,8 @@ export const EntryTitle = ({ entryId, compact }: EntryLinkProps) => {
className="cursor-link hover:multi-[scale-[1.01];opacity-95] inline-block select-text break-words text-[1.7rem] font-bold leading-normal duration-200"
>
<EntryTranslation
source={entry.entries.title}
target={translation.data?.title}
source={titleCase(entry.entries.title ?? "")}
target={titleCase(translation.data?.title ?? "")}
className="text-text inline-block select-text hyphens-auto duration-200"
inline={false}
bilingual
@@ -1,10 +1,11 @@
import {
Focusable,
useFocusable,
useFocusActions,
useGlobalFocusableScope,
} from "@follow/components/common/Focusable/index.js"
import { MemoedDangerousHTMLStyle } from "@follow/components/common/MemoedDangerousHTMLStyle.js"
import { Spring } from "@follow/components/constants/spring.js"
import { MotionButtonBase } from "@follow/components/ui/button/index.js"
import { RootPortal } from "@follow/components/ui/portal/index.js"
import { ScrollArea } from "@follow/components/ui/scroll-area/index.js"
import type { FeedViewType } from "@follow/constants"
import { useTitle } from "@follow/hooks"
@@ -14,27 +15,29 @@ import { EventBus } from "@follow/utils/event-bus"
import { springScrollTo } from "@follow/utils/scroller"
import { cn, combineCleanupFunctions } from "@follow/utils/utils"
import { ErrorBoundary } from "@sentry/react"
import type { JSAnimation, Variants } from "motion/react"
import { AnimatePresence, m, useAnimationControls } from "motion/react"
import * as React from "react"
import { useEffect, useMemo, useRef, useState } from "react"
import { useEntryIsInReadability } from "~/atoms/readability"
import { useIsZenMode, useUISettingKey } from "~/atoms/settings/ui"
import { Focusable } from "~/components/common/Focusable"
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 { useRenderStyle } from "~/hooks/biz/useRenderStyle"
import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
import { useConditionalHotkeyScope } from "~/hooks/common"
import { useFeedSafeUrl } from "~/hooks/common/useFeedSafeUrl"
import { useHotkeyScope } from "~/providers/hotkey-provider"
import { WrappedElementProvider } from "~/providers/wrapped-element-provider"
import { useEntry } from "~/store/entry"
import { useFeedById } from "~/store/feed"
import { useInboxById } from "~/store/inbox"
import { COMMAND_ID } from "../command/commands/id"
import { useCommandBinding, useCommandHotkey } from "../command/hooks/use-register-hotkey"
import { useCommandBinding } from "../command/hooks/use-command-binding"
import { useCommandHotkey } from "../command/hooks/use-register-hotkey"
import { EntryContentHTMLRenderer } from "../renderer/html"
import { AISummary } from "./AISummary"
import { EntryTimelineSidebar } from "./components/EntryTimelineSidebar"
@@ -55,6 +58,12 @@ import {
} from "./index.shared"
import { EntryContentLoading } from "./loading"
const pageMotionVariants = {
initial: { opacity: 0, y: 25 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: 25, transition: { duration: 0 } },
} satisfies Variants
export const EntryContent: Component<EntryContentProps> = ({
entryId,
noMedia,
@@ -77,27 +86,32 @@ export const EntryContent: Component<EntryContentProps> = ({
const scrollerRef = useRef<HTMLDivElement | null>(null)
useEffect(() => {
const scrollAndFocus = () => {
scrollerRef.current?.scrollTo(0, 0)
}
scrollAndFocus()
return combineCleanupFunctions(
EventBus.subscribe(COMMAND_ID.timeline.switchToNext, scrollAndFocus),
EventBus.subscribe(COMMAND_ID.timeline.switchToPrevious, scrollAndFocus),
)
}, [entryId])
const safeUrl = useFeedSafeUrl(entryId)
const customCSS = useUISettingKey("customCSS")
const isInPeekModal = useInPeekModal()
const [isUserInteraction, setIsUserInteraction] = useState(false)
const isZenMode = useIsZenMode()
const [panelPortalElement, setPanelPortalElement] = useState<HTMLDivElement | null>(null)
const animationController = useAnimationControls()
const prevEntryId = useRef<string | undefined>(undefined)
const scrollAnimationRef = useRef<JSAnimation<any> | null>(null)
useEffect(() => {
if (prevEntryId.current !== entryId) {
scrollAnimationRef.current?.stop()
nextFrame(() => {
scrollerRef.current?.scrollTo({ top: 0 })
})
animationController.start(pageMotionVariants.exit).then(() => {
animationController.start(pageMotionVariants.animate)
})
prevEntryId.current = entryId
}
}, [animationController, entryId])
if (!entry) return null
return (
@@ -110,22 +124,23 @@ export const EntryContent: Component<EntryContentProps> = ({
compact={compact}
/>
)}
<div className="w-full" ref={setPanelPortalElement} />
<Focusable
scope={HotkeyScope.EntryRender}
className="@container relative flex size-full flex-col overflow-hidden print:size-auto print:overflow-visible"
onFocus={() => setIsUserInteraction(true)}
>
<RegisterCommands
scrollerRef={scrollerRef}
isUserInteraction={isUserInteraction}
setIsUserInteraction={setIsUserInteraction}
/>
<RootPortal to={panelPortalElement}>
<RegisterCommands scrollAnimationRef={scrollAnimationRef} scrollerRef={scrollerRef} />
</RootPortal>
<EntryTimelineSidebar entryId={entry.entries.id} />
<EntryScrollArea className={className} scrollerRef={scrollerRef}>
{/* Indicator for the entry */}
<div
className="animate-in fade-in slide-in-from-bottom-24 f-motion-reduce:fade-in-0 f-motion-reduce:slide-in-from-bottom-0 select-text duration-200 ease-in-out"
key={entry.entries.id}
<m.div
initial={pageMotionVariants.initial}
animate={animationController}
transition={Spring.presets.bouncy}
className="select-text"
>
{!isZenMode && (
<>
@@ -155,8 +170,6 @@ export const EntryContent: Component<EntryContentProps> = ({
)}
<article
tabIndex={-1}
onFocus={() => 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]"
@@ -217,7 +230,7 @@ export const EntryContent: Component<EntryContentProps> = ({
<SupportCreator entryId={entryId} />
</article>
</div>
</m.div>
</EntryScrollArea>
<SourceContentPanel src={safeUrl ?? "#"} />
</Focusable>
@@ -235,6 +248,7 @@ const EntryScrollArea: Component<{
}
return (
<ScrollArea.ScrollArea
focusable={false}
mask={false}
rootClassName={cn(
"h-0 min-w-0 grow overflow-y-auto print:h-auto print:overflow-visible",
@@ -294,18 +308,17 @@ const Renderer: React.FC<{
const RegisterCommands = ({
scrollerRef,
isUserInteraction,
setIsUserInteraction,
scrollAnimationRef,
}: {
scrollerRef: React.RefObject<HTMLDivElement | null>
isUserInteraction: boolean
setIsUserInteraction: (isUserInteraction: boolean) => void
}) => {
const containerFocused = useFocusable()
useConditionalHotkeyScope(HotkeyScope.EntryRender, isUserInteraction && containerFocused, true)
const activeScope = useHotkeyScope()
const when = activeScope.includes(HotkeyScope.EntryRender)
scrollAnimationRef: React.RefObject<JSAnimation<any> | null>
}) => {
const isAlreadyScrolledBottomRef = useRef(false)
const [showKeepScrollingPanel, setShowKeepScrollingPanel] = useState(false)
const activeScope = useGlobalFocusableScope()
const when = activeScope.has(HotkeyScope.EntryRender)
useCommandBinding({
commandId: COMMAND_ID.entryRender.scrollUp,
@@ -336,34 +349,117 @@ const RegisterCommands = ({
const { highlightBoundary } = useFocusActions()
useEffect(() => {
const checkScrollBottom = ($scroller: HTMLDivElement) => {
const currentScroll = $scroller.scrollTop
const { scrollHeight, clientHeight } = $scroller
if (isAlreadyScrolledBottomRef.current) {
EventBus.dispatch(COMMAND_ID.timeline.switchToNext)
setShowKeepScrollingPanel(false)
isAlreadyScrolledBottomRef.current = false
springScrollTo(0, $scroller)
return
}
if (scrollHeight && clientHeight) {
isAlreadyScrolledBottomRef.current =
Math.abs(currentScroll + clientHeight - scrollHeight) < 2
setShowKeepScrollingPanel(isAlreadyScrolledBottomRef.current)
}
}
const checkScrollBottomByWheel = () => {
isAlreadyScrolledBottomRef.current = false
setShowKeepScrollingPanel(false)
}
scrollerRef.current?.addEventListener("wheel", checkScrollBottomByWheel)
const cleanupScrollAnimation = () => {
scrollAnimationRef.current?.stop()
scrollAnimationRef.current = null
}
return combineCleanupFunctions(
() => {
scrollerRef.current?.removeEventListener("wheel", checkScrollBottomByWheel)
},
cleanupScrollAnimation,
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!)
cleanupScrollAnimation()
scrollAnimationRef.current = springScrollTo(currentScroll - delta, scrollerRef.current!)
}
checkScrollBottom(scrollerRef.current!)
}),
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!)
}
}),
EventBus.subscribe(COMMAND_ID.timeline.enter, () => {
const $scroller = scrollerRef.current
if ($scroller) {
springScrollTo(0, $scroller)
$scroller.focus()
nextFrame(highlightBoundary)
setIsUserInteraction(true)
if (!$scroller) {
return
}
}),
)
}, [highlightBoundary, scrollerRef, setIsUserInteraction])
return null
const currentScroll = $scroller.scrollTop
const delta = window.innerHeight
if (typeof currentScroll === "number" && delta) {
cleanupScrollAnimation()
scrollAnimationRef.current = springScrollTo(currentScroll + delta, $scroller)
}
checkScrollBottom($scroller)
}),
EventBus.subscribe(
COMMAND_ID.layout.focusToEntryRender,
({ highlightBoundary: highlight }) => {
const $scroller = scrollerRef.current
if (!$scroller) {
return
}
$scroller.focus()
if (highlight) {
nextFrame(highlightBoundary)
}
},
),
)
}, [highlightBoundary, scrollAnimationRef, scrollerRef])
return (
<AnimatePresence>
{showKeepScrollingPanel && (
<FloatPanel side="bottom">
Already scrolled to the bottom.
<br />
Keep pressing to jump to the next article
</FloatPanel>
)}
</AnimatePresence>
)
}
const FloatPanel: React.FC<{ children: React.ReactNode; side: "bottom" | "top" }> = ({
children,
side,
}) => (
<m.div
initial={{ opacity: 0, y: 32 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 32 }}
transition={{ duration: 0.2 }}
className={cn(
"bg-material-ultra-thick text-text backdrop-blur-background absolute left-1/2 z-50 -translate-x-1/2 select-none rounded-2xl px-6 py-3 text-center text-[15px] font-medium shadow-xl",
side === "bottom" ? "bottom-8" : "top-8",
)}
style={{
boxShadow: "0 4px 24px 0 rgba(0,0,0,0.10), 0 1.5px 4px 0 rgba(0,0,0,0.08)",
WebkitBackdropFilter: "blur(16px)",
backdropFilter: "blur(16px)",
maxWidth: 360,
width: "calc(100vw - 32px)",
}}
>
{children}
</m.div>
)
@@ -51,7 +51,7 @@ export function FollowSummary({
</EllipsisHorizontalTextWithTooltip>
</div>
</div>
{!simple && (
{!simple && feed.description && (
<EllipsisHorizontalTextWithTooltip className="text-text/80 text-body truncate pl-10 font-normal">
{feed.description}
</EllipsisHorizontalTextWithTooltip>
@@ -1,26 +1,21 @@
import { MotionButtonBase } from "@follow/components/ui/button/index.js"
import { KbdCombined } from "@follow/components/ui/kbd/Kbd.js"
import { ScrollArea } from "@follow/components/ui/scroll-area/index.js"
import { clsx, cn } from "@follow/utils/utils"
import { clsx } from "@follow/utils/utils"
import { m, useDragControls } from "motion/react"
import { useCallback, useEffect } from "react"
import { useCallback } from "react"
import { useTranslation } from "react-i18next"
import { useUISettingKey } from "~/atoms/settings/ui"
import { PlainModal } from "~/components/ui/modal/stacked/custom-modal"
import { useCurrentModal, useModalStack } from "~/components/ui/modal/stacked/hooks"
import { shortcuts, shortcutsType } from "~/constants/shortcuts"
import { useSwitchHotKeyScope } from "~/hooks/common"
import { ShortcutsGuideline } from "../command/shortcuts/SettingShortcuts"
const ShortcutModalContent = () => {
const { dismiss } = useCurrentModal()
const modalOverlay = useUISettingKey("modalOverlay")
const dragControls = useDragControls()
const switchScope = useSwitchHotKeyScope()
useEffect(() => {
switchScope("Home")
}, [])
const { t } = useTranslation("shortcuts")
return (
<m.div
@@ -52,32 +47,8 @@ const ShortcutModalContent = () => {
<i className="i-mgc-close-cute-re" />
</MotionButtonBase>
<ScrollArea.ScrollArea scrollbarClassName="w-2" rootClassName="w-full h-full">
<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-3 text-xs font-medium capitalize">
{t(shortcutsType[type])}
</div>
<div className="text-text rounded-md border text-[13px]">
{Object.keys(shortcuts[type]).map((action, index) => (
<div
key={`${type}-${action}`}
className={cn(
"flex h-9 items-center justify-between px-3 py-1.5",
index % 2 && "bg-fill-quinary",
)}
>
<div>{t(shortcuts[type][action].name)}</div>
<div>
<KbdCombined joint>
{`${shortcuts[type][action].key}${shortcuts[type][action].extra ? `, ${shortcuts[type][action].extra}` : ""}`}
</KbdCombined>
</div>
</div>
))}
</div>
</section>
))}
<div className="w-full space-y-6 px-4 pb-5">
<ShortcutsGuideline />
</div>
</ScrollArea.ScrollArea>
</m.div>
@@ -70,7 +70,7 @@ function Outtro() {
<Trans
i18nKey="new_user_guide.step.shortcuts.description2"
components={{
kbd: <Kbd>H</Kbd>,
kbd: <Kbd>?</Kbd>,
}}
/>
</p>
@@ -32,7 +32,7 @@ import { searchActions, useSearchStore, useSearchType } from "~/store/search"
import { SearchType } from "~/store/search/constants"
import type { SearchInstance } from "~/store/search/types"
import { getSubscriptionByFeedId } from "~/store/subscription"
import { useFeedUnreadStore } from "~/store/unread"
import { getUnreadById } from "~/store/unread/getters"
import styles from "./cmdk.module.css"
@@ -209,7 +209,7 @@ export const SearchCmdK: React.FC = () => {
entryId={ROUTE_ENTRY_PENDING}
id={feed.item.id!}
icon={feed.item.type === "feed" ? feed.item.siteUrl : undefined}
subtitle={useFeedUnreadStore.getState().data[feed.item.id!]?.toString()}
subtitle={getUnreadById(feed.item.id)?.toString()}
/>
))}
</Command.Group>
@@ -1,21 +1,25 @@
import { useGlobalFocusableScopeSelector } from "@follow/components/common/Focusable/hooks.js"
import { Form, FormControl, FormField, FormItem } from "@follow/components/ui/form/index.jsx"
import { useRegisterGlobalContext } from "@follow/shared/bridge"
import { tracker } from "@follow/tracker"
import { EventBus } from "@follow/utils/event-bus"
import { cn } from "@follow/utils/utils"
import { zodResolver } from "@hookform/resolvers/zod"
import { useLayoutEffect } from "react"
import { useEffect, useLayoutEffect } from "react"
import { useForm } from "react-hook-form"
import { useHotkeys } from "react-hotkeys-hook"
import { useTranslation } from "react-i18next"
import { useEventCallback } from "usehooks-ts"
import { z } from "zod"
import { FocusablePresets } from "~/components/common/Focusable"
import { m } from "~/components/common/Motion"
import { PlainModal } from "~/components/ui/modal/stacked/custom-modal"
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
import { HotkeyScope } from "~/constants"
import { getRouteParams } from "~/hooks/biz/useRouteParams"
import { tipcClient } from "~/lib/client"
import { COMMAND_ID } from "../command/commands/id"
import { useCommandBinding } from "../command/hooks/use-command-binding"
import { FeedForm } from "../discover/FeedForm"
const CmdNPanel = () => {
@@ -102,7 +106,7 @@ const CmdNPanel = () => {
export const CmdNTrigger = () => {
const { t } = useTranslation()
const { present } = useModalStack()
const handler = () => {
const handler = useEventCallback(() => {
present({
title: t("quick_add.title"),
content: CmdNPanel,
@@ -111,14 +115,18 @@ export const CmdNTrigger = () => {
id: "quick-add",
clickOutsideToDismiss: true,
})
}
})
useCommandBinding({
commandId: COMMAND_ID.global.quickAdd,
when: useGlobalFocusableScopeSelector(FocusablePresets.isNotFloatingLayerScope),
})
useEffect(() => {
return EventBus.subscribe(COMMAND_ID.global.quickAdd, handler)
}, [handler])
useRegisterGlobalContext("quickAdd", handler)
useHotkeys("meta+n,ctrl+n", handler, {
scopes: HotkeyScope.Home,
preventDefault: true,
})
return null
}
@@ -1,16 +1,16 @@
import { useFocusable } from "@follow/components/common/Focusable/index.js"
import { useGlobalFocusableScopeSelector } from "@follow/components/common/Focusable/index.js"
import { Spring } from "@follow/components/constants/spring.js"
import { useMobile } from "@follow/components/hooks/useMobile.js"
import { Tooltip, TooltipContent, TooltipTrigger } from "@follow/components/ui/tooltip/index.jsx"
import { FeedViewType } from "@follow/constants"
import { tracker } from "@follow/tracker"
import { EventBus } from "@follow/utils/event-bus"
import { cn } from "@follow/utils/utils"
import * as Slider from "@radix-ui/react-slider"
import dayjs from "dayjs"
import { AnimatePresence, m } from "motion/react"
import { useEffect, useMemo, useState } from "react"
import Marquee from "react-fast-marquee"
import { useHotkeys } from "react-hotkeys-hook"
import { useTranslation } from "react-i18next"
import {
@@ -19,8 +19,8 @@ import {
useAudioPlayerAtomSelector,
useAudioPlayerAtomValue,
} from "~/atoms/player"
import { FocusablePresets } from "~/components/common/Focusable"
import { VolumeSlider } from "~/components/ui/media/VolumeSlider"
import { HotkeyScope } from "~/constants"
import type { NavigateEntryOptions } from "~/hooks/biz/useNavigateEntry"
import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
import { FeedIcon } from "~/modules/feed/feed-icon"
@@ -28,6 +28,9 @@ import { useEntry } from "~/store/entry"
import { useFeedById } from "~/store/feed"
import { useListById } from "~/store/list"
import { COMMAND_ID } from "../command/commands/id"
import { useCommandBinding } from "../command/hooks/use-command-binding"
const handleClickPlay = () => {
AudioPlayer.togglePlayAndPause()
}
@@ -115,13 +118,17 @@ const CornerPlayerImpl = ({ hideControls, rounded }: ControlButtonProps) => {
const feed = useFeedById(entry?.feedId)
const list = useListById(listId)
const isFocused = useFocusable()
useHotkeys("space", handleClickPlay, {
preventDefault: true,
scopes: HotkeyScope.Home,
enabled: isFocused,
useCommandBinding({
commandId: COMMAND_ID.global.toggleCornerPlay,
when: useGlobalFocusableScopeSelector(FocusablePresets.isSubscriptionOrTimeline),
})
useEffect(() => {
return EventBus.subscribe(COMMAND_ID.global.toggleCornerPlay, () => {
handleClickPlay()
})
}, [])
useEffect(() => {
setNowPlaying({
title: entry?.entries.title || undefined,
@@ -14,12 +14,13 @@ import { useEventCallback } from "usehooks-ts"
import { m } from "~/components/common/Motion"
import { useFollow } from "~/hooks/biz/useFollow"
import { useI18n } from "~/hooks/common"
import { useAuthQuery, useI18n } from "~/hooks/common"
import { defineQuery } from "~/lib/defineQuery"
import { replaceImgUrlIfNeed } from "~/lib/img-proxy"
import { FeedIcon } from "~/modules/feed/feed-icon"
import { useUserSubscriptionsQuery } from "~/modules/profile/hooks"
import { useSubscriptionStore } from "~/store/subscription"
import { useUserById } from "~/store/user"
import { userActions, useUserById } from "~/store/user"
type ItemVariant = "loose" | "compact"
@@ -35,16 +36,25 @@ export const SubscriptionItems = ({
userId: string
itemStyle: ItemVariant
}) => {
const profile = useAuthQuery(
defineQuery(["profiles", userId], async () => {
return userActions.getOrFetchProfile(userId!)
}),
{
enabled: !!userId,
},
)
const userInfo = useUserById(userId)
const subscriptions = useUserSubscriptionsQuery(userId)
if (!userInfo) return null
const renderUserData = profile.data || userInfo
return subscriptions.isLoading ? (
<LoadingWithIcon
size="large"
icon={
<Avatar className="aspect-square size-4">
<AvatarImage src={replaceImgUrlIfNeed(userInfo.image || undefined)} />
<AvatarFallback>{userInfo.name?.slice(0, 2)}</AvatarFallback>
<AvatarImage src={replaceImgUrlIfNeed(renderUserData?.image || undefined)} />
<AvatarFallback>{renderUserData?.name?.slice(0, 2)}</AvatarFallback>
</Avatar>
}
className="center h-48 w-full max-w-full"
@@ -105,7 +105,9 @@ export const SettingTabbedSegment: Component<{
}
export const SettingDescription: Component = ({ children, className }) => (
<small className={cn("text-text-secondary text-body block w-4/5", className)}>{children}</small>
<small className={cn("text-text-secondary text-body block w-4/5 leading-snug", className)}>
{children}
</small>
)
export const SettingActionItem = ({
@@ -113,12 +113,12 @@ export function SettingModalLayout(
onResizeStop={handleResizeStop}
enable={resizableOnly("bottomRight")}
defaultSize={{
width: 800,
height: 700,
width: 950,
height: 800,
}}
maxHeight="80vh"
minHeight={500}
minWidth={600}
maxHeight="90vh"
minHeight={600}
minWidth={700}
maxWidth="95vw"
className="flex !select-none flex-col"
>

Some files were not shown because too many files have changed in this diff Show More