feat(shortcut): support arrow key to view entry content up or down (#62)

* chore: cleanup

Signed-off-by: Innei <i@innei.in>

* chore: add react devtool for debug

Signed-off-by: Innei <i@innei.in>

* feat: arrow key to nav entry column items

Signed-off-by: Innei <i@innei.in>

* feat: focus to main container

Signed-off-by: Innei <i@innei.in>

---------

Signed-off-by: Innei <i@innei.in>
This commit is contained in:
Innei
2024-06-14 16:49:25 +08:00
committed by GitHub
parent 76987019a6
commit f9e636be75
40 changed files with 475 additions and 206 deletions
+2 -1
View File
@@ -17,10 +17,11 @@ export default defineConfig(
// fix later or just always ignore
{
rules: {
"no-console": "warn",
"no-console": ["error", { allow: ["warn", "error", "info"] }],
"unicorn/consistent-function-scoping": "warn",
"unicorn/prefer-module": "off",
"@typescript-eslint/no-floating-promises": "off",
},
settings: {
tailwindcss: {
+2
View File
@@ -60,6 +60,7 @@
"framer-motion": "11.2.9",
"franc-min": "6.2.0",
"hast-util-to-jsx-runtime": "2.3.0",
"hotkeys-js": "3.13.7",
"idb-keyval": "6.2.1",
"immer": "10.1.1",
"jotai": "2.8.2",
@@ -105,6 +106,7 @@
"@vitejs/plugin-react": "^4.3.0",
"electron": "^30.0.9",
"electron-builder": "^24.9.1",
"electron-devtools-installer": "3.2.0",
"electron-vite": "^2.2.0",
"eslint": "^9.3.0",
"eslint-config-hyoban": "3.0.0-beta.16",
+75
View File
@@ -124,6 +124,9 @@ importers:
hast-util-to-jsx-runtime:
specifier: 2.3.0
version: 2.3.0
hotkeys-js:
specifier: 3.13.7
version: 3.13.7
idb-keyval:
specifier: 6.2.1
version: 6.2.1
@@ -254,6 +257,9 @@ importers:
electron-builder:
specifier: ^24.9.1
version: 24.13.3(electron-builder-squirrel-windows@25.0.0-alpha.8(dmg-builder@24.13.3))
electron-devtools-installer:
specifier: 3.2.0
version: 3.2.0
electron-vite:
specifier: ^2.2.0
version: 2.2.0(vite@5.2.12(@types/node@20.12.13))
@@ -2717,6 +2723,9 @@ packages:
engines: {node: '>=14.0.0'}
hasBin: true
electron-devtools-installer@3.2.0:
resolution: {integrity: sha512-t3UczsYugm4OAbqvdImMCImIMVdFzJAHgbwHpkl5jmfu1izVgUcP/mnrPqJIpEeCK1uZGpt+yHgWEN+9EwoYhQ==}
electron-publish@24.13.1:
resolution: {integrity: sha512-2ZgdEqJ8e9D17Hwp5LEq5mLQPjqU3lv/IALvgp+4W8VeNhryfGhYEQC/PgDPMrnWUp+l60Ou5SJLsu+k4mhQ8A==}
@@ -3365,6 +3374,9 @@ packages:
resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==}
engines: {node: '>=10'}
hotkeys-js@3.13.7:
resolution: {integrity: sha512-ygFIdTqqwG4fFP7kkiYlvayZppeIQX2aPpirsngkv1xM1lP0piDY5QEh68nQnIKvz64hfocxhBaD/uK3sSK1yQ==}
htm@3.1.1:
resolution: {integrity: sha512-983Vyg8NwUE7JkZ6NmOqpCZ+sh1bKv2iYTlUkzlWmA5JD2acKoxd4KVxbMmxX/85mtfdnDmTFoNKcg5DGAvxNQ==}
@@ -3416,6 +3428,9 @@ packages:
resolution: {integrity: sha512-5Fytz/IraMjqpwfd34ke28PTVMjZjJG2MPn5t7OE4eUCUNf8BAa7b5WUS9/Qvr6mwOQS7Mk6vdsMno5he+T8Xw==}
engines: {node: '>= 4'}
immediate@3.0.6:
resolution: {integrity: sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==}
immer@10.1.1:
resolution: {integrity: sha512-s2MPrmjovJcoMaHtx6K11Ra7oD05NT97w1IC5zpMkT6Atjr7H8LjaDd81iIxUYpMKSRRNMJE703M1Fhr/TctHw==}
@@ -3679,6 +3694,9 @@ packages:
jsonfile@6.1.0:
resolution: {integrity: sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==}
jszip@3.10.1:
resolution: {integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==}
keyv@4.5.4:
resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==}
@@ -3699,6 +3717,9 @@ packages:
resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}
engines: {node: '>= 0.8.0'}
lie@3.3.0:
resolution: {integrity: sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==}
lilconfig@2.1.0:
resolution: {integrity: sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==}
engines: {node: '>=10'}
@@ -4019,6 +4040,10 @@ packages:
resolution: {integrity: sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==}
engines: {node: '>= 8'}
mkdirp@0.5.6:
resolution: {integrity: sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==}
hasBin: true
mkdirp@1.0.4:
resolution: {integrity: sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==}
engines: {node: '>=10'}
@@ -4195,6 +4220,9 @@ packages:
resolution: {integrity: sha512-sp5bWr5eUoVgNV50vsJyil0XCluM+qMvtba8X4ug5Z/0YtYZsePka+tZgqiZnAyFyf5pwXaSDwYncFdSEzX7PA==}
hasBin: true
pako@1.0.11:
resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==}
parent-module@1.0.1:
resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==}
engines: {node: '>=6'}
@@ -4679,6 +4707,9 @@ packages:
set-blocking@2.0.0:
resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==}
setimmediate@1.0.5:
resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==}
shallowequal@1.1.0:
resolution: {integrity: sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==}
@@ -5076,6 +5107,9 @@ packages:
resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}
engines: {node: '>= 10.0.0'}
unzip-crx-3@0.2.0:
resolution: {integrity: sha512-0+JiUq/z7faJ6oifVB5nSwt589v1KCduqIJupNVDoWSXZtWDmjDGO3RAEOvwJ07w90aoXoP4enKsR7ecMrJtWQ==}
update-browserslist-db@1.0.13:
resolution: {integrity: sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==}
hasBin: true
@@ -5272,6 +5306,9 @@ packages:
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
engines: {node: '>=10'}
yaku@0.16.7:
resolution: {integrity: sha512-Syu3IB3rZvKvYk7yTiyl1bo/jiEFaaStrgv1V2TIJTqYPStSMQVO8EQjg/z+DRzLq/4LIIharNT3iH1hylEIRw==}
yallist@3.1.1:
resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
@@ -8073,6 +8110,13 @@ snapshots:
- electron-builder-squirrel-windows
- supports-color
electron-devtools-installer@3.2.0:
dependencies:
rimraf: 3.0.2
semver: 7.6.2
tslib: 2.6.2
unzip-crx-3: 0.2.0
electron-publish@24.13.1:
dependencies:
'@types/fs-extra': 9.0.13
@@ -9078,6 +9122,8 @@ snapshots:
dependencies:
lru-cache: 6.0.0
hotkeys-js@3.13.7: {}
htm@3.1.1: {}
html-void-elements@3.0.0: {}
@@ -9128,6 +9174,8 @@ snapshots:
ignore@5.3.1: {}
immediate@3.0.6: {}
immer@10.1.1: {}
import-fresh@3.3.0:
@@ -9320,6 +9368,13 @@ snapshots:
optionalDependencies:
graceful-fs: 4.2.11
jszip@3.10.1:
dependencies:
lie: 3.3.0
pako: 1.0.11
readable-stream: 2.3.8
setimmediate: 1.0.5
keyv@4.5.4:
dependencies:
json-buffer: 3.0.1
@@ -9339,6 +9394,10 @@ snapshots:
prelude-ls: 1.2.1
type-check: 0.4.0
lie@3.3.0:
dependencies:
immediate: 3.0.6
lilconfig@2.1.0: {}
lilconfig@3.1.1: {}
@@ -9793,6 +9852,10 @@ snapshots:
minipass: 3.3.6
yallist: 4.0.0
mkdirp@0.5.6:
dependencies:
minimist: 1.2.8
mkdirp@1.0.4: {}
mlly@1.7.0:
@@ -9985,6 +10048,8 @@ snapshots:
dependencies:
optimist: 0.6.1
pako@1.0.11: {}
parent-module@1.0.1:
dependencies:
callsites: 3.1.0
@@ -10470,6 +10535,8 @@ snapshots:
set-blocking@2.0.0: {}
setimmediate@1.0.5: {}
shallowequal@1.1.0: {}
shebang-command@2.0.0:
@@ -10886,6 +10953,12 @@ snapshots:
universalify@2.0.1: {}
unzip-crx-3@0.2.0:
dependencies:
jszip: 3.10.1
mkdirp: 0.5.6
yaku: 0.16.7
update-browserslist-db@1.0.13(browserslist@4.23.0):
dependencies:
browserslist: 4.23.0
@@ -11074,6 +11147,8 @@ snapshots:
y18n@5.0.8: {}
yaku@0.16.7: {}
yallist@3.1.1: {}
yallist@4.0.0: {}
+19 -1
View File
@@ -5,7 +5,7 @@ import path from "node:path"
import { registerIpcMain } from "@egoist/tipc/main"
import { electronApp, optimizer } from "@electron-toolkit/utils"
import { extractElectronWindowOptions } from "@shared/electron"
import { app, BrowserWindow } from "electron"
import { app, BrowserWindow, session } from "electron"
import { registerAppMenu } from "./menu"
import { router } from "./tipc"
@@ -97,6 +97,24 @@ app.whenReady().then(() => {
}
handleOpen(url)
})
// for dev debug
if (process.env.NODE_ENV === "development") {
import("electron-devtools-installer").then(
({ default: installExtension, REACT_DEVELOPER_TOOLS }) => {
installExtension(REACT_DEVELOPER_TOOLS, {
loadExtensionOptions: { allowFileAccess: true },
})
.then((name) => console.info(`Added Extension: ${name}`))
.catch((err) => console.info("An error occurred:", err))
session.defaultSession.getAllExtensions().forEach((e) => {
session.defaultSession.loadExtension(e.path)
})
},
)
}
})
// Quit when all windows are closed, except on macOS. There, it's common
+1 -1
View File
@@ -2,7 +2,7 @@ import { queryClient } from "@renderer/lib/query-client"
import { useEffect } from "react"
import { Outlet } from "react-router-dom"
import { useDark } from "./hooks/useDark"
import { useDark } from "./hooks/common/useDark"
import { RootProviders } from "./providers/root-providers"
import { handlers } from "./tipc"
+12
View File
@@ -0,0 +1,12 @@
/* eslint-disable unicorn/no-unreadable-array-destructuring */
import { createAtomHooks } from "@renderer/lib/jotai"
import { atom } from "jotai"
export const [
,
,
useMainContainerElement,
,
getMainContainerElement,
setMainContainerElement,
] = createAtomHooks(atom<HTMLElement | null>(null))
+1
View File
@@ -0,0 +1 @@
export * from "./dom"
-26
View File
@@ -1,26 +0,0 @@
export abstract class RequestError extends Error {
name = "RequestError"
}
export class UnAuthorizedError extends RequestError {
name = "UnAuthorizedError"
constructor(message?: string) {
super(message)
}
}
export class UnprocessableEntityError extends RequestError {
name = "UnprocessableEntityError"
constructor(message?: string) {
super(message)
}
}
export class UnprocessableFeedError extends RequestError {
name = "UnprocessableEntityError"
constructor(message?: string) {
super(message)
}
}
@@ -1,4 +1,4 @@
import { useDark } from "@renderer/hooks/useDark"
import { useDark } from "@renderer/hooks"
import { Switch } from "./ui/switch"
@@ -1,7 +1,7 @@
import { EntryTranslation } from "@renderer/components/entry-column/translation"
import { FeedIcon } from "@renderer/components/feed-icon"
import { Image } from "@renderer/components/ui/image"
import { useAsRead } from "@renderer/hooks/useAsRead"
import { useAsRead } from "@renderer/hooks"
import dayjs from "@renderer/lib/dayjs"
import { cn } from "@renderer/lib/utils"
import { useEntry } from "@renderer/store/entry/hooks"
@@ -1,3 +1,4 @@
import { useMainContainerElement } from "@renderer/atoms"
import { ActionButton, Button } from "@renderer/components/ui/button"
import {
Popover,
@@ -5,6 +6,7 @@ import {
PopoverContent,
PopoverTrigger,
} from "@renderer/components/ui/popover"
import { useRefValue } from "@renderer/hooks"
import { apiClient } from "@renderer/lib/api-fetch"
import { views } from "@renderer/lib/constants"
import { buildStorageNS } from "@renderer/lib/ns"
@@ -12,12 +14,14 @@ import { getEntriesParams } from "@renderer/lib/utils"
import { useEntries } from "@renderer/queries/entries"
import {
feedActions,
getCurrentEntryId,
subscriptionActions,
useFeedStore,
} from "@renderer/store"
import { entryActions } from "@renderer/store/entry/entry"
import { useEntryIdsByFeedIdOrView } from "@renderer/store/entry/hooks"
import { m } from "framer-motion"
import hotkeys from "hotkeys-js"
import { useAtom, useAtomValue } from "jotai"
import { atomWithStorage } from "jotai/utils"
import { debounce } from "lodash-es"
@@ -30,7 +34,7 @@ import {
useRef,
useState,
} from "react"
import type { ListRange } from "react-virtuoso"
import type { ListRange, VirtuosoHandle, VirtuosoProps } from "react-virtuoso"
import { Virtuoso, VirtuosoGrid } from "react-virtuoso"
import { useEventCallback } from "usehooks-ts"
import { useShallow } from "zustand/react/shallow"
@@ -48,8 +52,6 @@ const unreadOnlyAtom = atomWithStorage<boolean>(
},
)
const { setActiveEntry } = feedActions
export function EntryColumn() {
const activeList = useFeedStore((state) => state.activeList)
const entries = useEntriesByView()
@@ -91,7 +93,7 @@ export function EntryColumn() {
const virtuosoOptions = {
components: {
List: ListContent,
EmptyPlaceholder: EmptyList,
Footer: useCallback(() => {
if (!isFetchingNextPage) return null
return (
@@ -107,7 +109,7 @@ export function EntryColumn() {
endReached: () => entries.hasNextPage && entries.fetchNextPage(),
data: entriesIds,
itemContent: useCallback(
(_, entryId: string) => {
(index: number, entryId: string) => {
if (!entryId) return null
return (
@@ -121,12 +123,12 @@ export function EntryColumn() {
return (
<div
className="relative flex h-full flex-1 flex-col"
onClick={() => setActiveEntry(null)}
onClick={() => feedActions.setActiveEntry(null)}
data-total-count={virtuosoOptions.totalCount}
>
<ListHeader totalCount={virtuosoOptions.totalCount} />
<m.div
key={JSON.stringify(activeList)}
key={`${activeList?.id}-${activeList?.view}`}
className="h-full"
initial={{ opacity: 0.01, y: 100 }}
animate={{ opacity: 1, y: 0 }}
@@ -142,7 +144,7 @@ export function EntryColumn() {
/>
) :
(
<Virtuoso {...virtuosoOptions} />
<EntryList {...virtuosoOptions} />
)}
</m.div>
</div>
@@ -324,3 +326,97 @@ const EmptyList = forwardRef<
</div>
)
})
const EntryList: FC<VirtuosoProps<string, unknown>> = ({
...virtuosoOptions
}) => {
const $mainContainer = useMainContainerElement()
const virtuosoRef = useRef<VirtuosoHandle>(null)
const dataRef = useRefValue(virtuosoOptions.data!)
useEffect(() => {
if (!virtuosoRef.current) return
if (!$mainContainer) return
const virtuoso = virtuosoRef.current
const scope = "entry-list"
const registerKeys = "up,down,j,k"
const focusHandler = () => {
const target = document.activeElement
const isFocusIn =
$mainContainer.contains(target) || $mainContainer === target
if (isFocusIn) {
const currentScope = hotkeys.getScope()
if (currentScope === scope) {
return
}
hotkeys(registerKeys, scope, (handler) => {
const data = dataRef.current
const currentActiveEntryIndex = data.indexOf(
getCurrentEntryId() || "",
)
switch (handler.key) {
case "ArrowDown":
case "ArrowUp": {
const nextIndex =
// NOTE: if the current active entry is not in the list, we should set the active entry to the last one
handler.key === "ArrowUp" && currentActiveEntryIndex === -1 ?
data.length - 1 :
Math.min(
Math.max(
0,
currentActiveEntryIndex +
(handler.key === "ArrowDown" ? 1 : -1),
),
data.length - 1,
)
virtuoso.scrollIntoView({
index: nextIndex,
})
const nextId = data![nextIndex]
feedActions.setActiveEntry(nextId)
}
}
})
hotkeys.setScope(scope)
} else {
hotkeys.unbind(registerKeys, scope)
hotkeys.deleteScope(scope)
hotkeys.setScope("all")
}
}
// NOTE: focusin event will bubble to the document
document.addEventListener("focusin", focusHandler)
focusHandler()
return () => {
hotkeys.unbind(registerKeys, scope)
hotkeys.deleteScope(scope)
document.removeEventListener("focusin", focusHandler)
}
}, [$mainContainer])
const handleKeyDown: React.KeyboardEventHandler<HTMLDivElement> = useCallback(
(e) => {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault()
}
},
[],
)
return (
<Virtuoso
onKeyDown={handleKeyDown}
{...virtuosoOptions}
ref={virtuosoRef}
/>
)
}
@@ -1,6 +1,4 @@
import { useAsRead } from "@renderer/hooks/useAsRead"
import { useBizQuery } from "@renderer/hooks/useBizQuery"
import { useEntryActions, useRead } from "@renderer/hooks/useEntryActions"
import { useAsRead, useBizQuery, useEntryActions, useRead } from "@renderer/hooks"
import { views } from "@renderer/lib/constants"
import { FeedViewType } from "@renderer/lib/enum"
import { showNativeMenu } from "@renderer/lib/native-menu"
@@ -11,7 +9,7 @@ import { feedActions, useFeedStore } from "@renderer/store"
import { useEntry } from "@renderer/store/entry/hooks"
import { franc } from "franc-min"
import type { FC } from "react"
import { memo } from "react"
import { memo, useCallback } from "react"
import { ReactVirtuosoItemPlaceholder } from "../ui/placeholder"
import { ArticleItem } from "./article-item"
@@ -22,9 +20,12 @@ import { SocialMediaItem } from "./social-media-item"
import type { UniversalItemProps } from "./types"
import { VideoItem } from "./video-item"
const LanguageMap: Record<SupportedLanguages, {
code: string
}> = {
const LanguageMap: Record<
SupportedLanguages,
{
code: string
}
> = {
"en": {
code: "eng",
},
@@ -49,7 +50,10 @@ function EntryItemImpl({ entry, view }: { entry: EntryModel, view?: number }) {
entry,
})
let fields = (entry.settings?.translation && view !== undefined) ? (views[view!].translation).split(",") : []
let fields =
entry.settings?.translation && view !== undefined ?
views[view!].translation.split(",") :
[]
fields = fields.filter((field) => {
if (entry.settings?.translation && entry.entries[field]) {
@@ -65,15 +69,18 @@ function EntryItemImpl({ entry, view }: { entry: EntryModel, view?: number }) {
}
})
const translation = useBizQuery(Queries.ai.translation({
id: entry.entries.id,
language: entry.settings?.translation,
fields: fields?.join(",") || "title",
}), {
enabled: !!entry.settings?.translation && !!fields?.length,
})
const translation = useBizQuery(
Queries.ai.translation({
id: entry.entries.id,
language: entry.settings?.translation,
fields: fields?.join(",") || "title",
}),
{
enabled: !!entry.settings?.translation && !!fields?.length,
},
)
const activeEntry = useFeedStore((state) => state.activeEntry)
const activeEntry = useFeedStore((state) => state.activeEntryId)
const asRead = useAsRead(entry)
@@ -110,6 +117,40 @@ function EntryItemImpl({ entry, view }: { entry: EntryModel, view?: number }) {
Item = ArticleItem
}
}
const handleKeyDown: React.KeyboardEventHandler<HTMLDivElement> =
useCallback(() => {}, [])
const handleClick: React.MouseEventHandler<HTMLDivElement> = useCallback(
(e) => {
e.stopPropagation()
feedActions.setActiveEntry(entry.entries.id)
if (!asRead) {
markReadMutation.mutate()
}
},
[asRead, entry.entries.id, markReadMutation],
)
const handleDoubleClick: React.MouseEventHandler<HTMLDivElement> =
useCallback(
() => entry.entries.url && window.open(entry.entries.url, "_blank"),
[entry.entries.url],
)
const handleContextMenu: React.MouseEventHandler<HTMLDivElement> =
useCallback(
(e) => {
e.preventDefault()
showNativeMenu(
items
.filter((item) => !item.disabled)
.map((item) => ({
type: "text",
label: item.name,
click: item.onClick,
})),
e,
)
},
[items],
)
return (
<div
@@ -124,29 +165,10 @@ function EntryItemImpl({ entry, view }: { entry: EntryModel, view?: number }) {
"bg-theme-item-active",
asRead ? "text-zinc-500/90" : "text-zinc-900 dark:text-white/90",
)}
// ref={ref}
onClick={(e) => {
e.stopPropagation()
feedActions.setActiveEntry(entry.entries.id)
if (!asRead) {
markReadMutation.mutate()
}
}}
onDoubleClick={() =>
entry.entries.url && window.open(entry.entries.url, "_blank")}
onContextMenu={(e) => {
e.preventDefault()
showNativeMenu(
items
.filter((item) => !item.disabled)
.map((item) => ({
type: "text",
label: item.name,
click: item.onClick,
})),
e,
)
}}
onKeyDown={handleKeyDown}
onClick={handleClick}
onDoubleClick={handleDoubleClick}
onContextMenu={handleContextMenu}
>
<Item entryId={entry.entries.id} translation={translation.data} />
</div>
@@ -1,6 +1,6 @@
import { useBizQuery } from "@renderer/hooks/useBizQuery"
import { useBizQuery } from "@renderer/hooks"
import { parseHtml } from "@renderer/lib/parse-html"
import type { ActiveEntry } from "@renderer/models"
import type { ActiveEntryId } from "@renderer/models"
import { Queries } from "@renderer/queries"
import { useEntry, useFeedStore } from "@renderer/store"
import { m } from "framer-motion"
@@ -9,7 +9,7 @@ import { useEffect, useState } from "react"
import { LoadingCircle } from "../ui/loading"
import { EntryShare } from "./share"
export const EntryContent = ({ entry }: { entry: ActiveEntry }) => {
export const EntryContent = ({ entry }: { entry: ActiveEntryId }) => {
const activeList = useFeedStore((state) => state.activeList)
if (!entry) {
@@ -2,7 +2,7 @@ import { ActionButton } from "@renderer/components/ui/button"
import {
TooltipProvider,
} from "@renderer/components/ui/tooltip"
import { useEntryActions } from "@renderer/hooks/useEntryActions"
import { useEntryActions } from "@renderer/hooks"
import { useEntry } from "@renderer/store/entry/hooks"
export function EntryShare({
@@ -1,3 +1,4 @@
import { getMainContainerElement } from "@renderer/atoms"
import { FeedIcon } from "@renderer/components/feed-icon"
import {
Tooltip,
@@ -42,6 +43,12 @@ export function FeedItem({
name: feed.feeds.title || "",
view,
})
// focus to main container in order to let keyboard can navigate entry items by arrow keys
requestAnimationFrame(() => {
requestAnimationFrame(() => {
getMainContainerElement()?.focus()
})
})
}
const deleteMutation = useMutation({
@@ -1,4 +1,4 @@
import { useBizQuery } from "@renderer/hooks/useBizQuery"
import { useBizQuery } from "@renderer/hooks"
import { FEED_COLLECTION_LIST, levels, views } from "@renderer/lib/constants"
import { stopPropagation } from "@renderer/lib/dom"
import type { FeedViewType } from "@renderer/lib/enum"
@@ -1,4 +1,4 @@
import { useDark } from "@renderer/hooks/useDark"
import { useDark } from "@renderer/hooks"
import { cn } from "@renderer/lib/utils"
import { useMediaQuery } from "usehooks-ts"
+1 -1
View File
@@ -1,4 +1,4 @@
import { useDark } from "@renderer/hooks/useDark"
import { useDark } from "@renderer/hooks"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
+4
View File
@@ -0,0 +1,4 @@
export * from "./useAsRead"
export * from "./useAuth"
export * from "./useBizQuery"
export * from "./useEntryActions"
@@ -5,6 +5,7 @@ import { entryActions } from "@renderer/store/entry/entry"
import { useMutation, useQuery } from "@tanstack/react-query"
import type { FetchError } from "ofetch"
import { ofetch } from "ofetch"
import { useMemo } from "react"
import { toast } from "sonner"
export const useCollect = (entry: EntryModel | undefined) =>
@@ -112,97 +113,110 @@ export const useEntryActions = ({
const uncollect = useUnCollect(entry)
const read = useRead(entry)
const unread = useUnread(entry)
if (!entry?.entries.url || view === undefined) return { items: [] }
const items = [
[
{
name: "Star",
className: "i-mingcute-star-line",
disabled: !!entry.collections,
onClick: () => {
collect.mutate()
const items = useMemo(() => {
if (!entry || view === undefined) return []
const items = [
[
{
name: "Star",
className: "i-mingcute-star-line",
disabled: !!entry.collections,
onClick: () => {
collect.mutate()
},
},
},
{
name: "Unstar",
className: "i-mingcute-star-fill text-orange-500",
disabled: !entry.collections,
onClick: () => {
uncollect.mutate()
{
name: "Unstar",
className: "i-mingcute-star-fill text-orange-500",
disabled: !entry.collections,
onClick: () => {
uncollect.mutate()
},
},
},
{
name: "Copy Link",
className: "i-mingcute-link-line",
onClick: () => {
if (!entry.entries.url) return
navigator.clipboard.writeText(entry.entries.url)
toast("Link copied to clipboard.", {
duration: 1000,
})
},
},
{
name: "Open in Browser",
className: "i-mingcute-world-2-line",
onClick: () => {
if (!entry.entries.url) return
window.open(entry.entries.url, "_blank")
},
},
{
name: "Save Images to Eagle",
icon: "/eagle.svg",
disabled:
(checkEagle.isLoading ? true : !checkEagle.data) ||
!entry.entries.images?.length,
onClick: async () => {
if (!entry.entries.url || !entry.entries.images?.length) return
const response = await client?.saveToEagle({
url: entry.entries.url,
images: entry.entries.images,
})
if (response?.status === "success") {
toast("Saved to Eagle.", {
duration: 3000,
{
name: "Copy Link",
className: "i-mingcute-link-line",
disabled: !entry.entries.url,
onClick: () => {
if (!entry.entries.url) return
navigator.clipboard.writeText(entry.entries.url)
toast("Link copied to clipboard.", {
duration: 1000,
})
} else {
toast("Failed to save to Eagle.", {
duration: 3000,
},
},
{
name: "Open in Browser",
className: "i-mingcute-world-2-line",
disabled: !entry.entries.url,
onClick: () => {
if (!entry.entries.url) return
window.open(entry.entries.url, "_blank")
},
},
{
name: "Save Images to Eagle",
icon: "/eagle.svg",
disabled:
(checkEagle.isLoading ? true : !checkEagle.data) ||
!entry.entries.images?.length,
onClick: async () => {
if (!entry.entries.url || !entry.entries.images?.length) return
const response = await client?.saveToEagle({
url: entry.entries.url,
images: entry.entries.images,
})
}
if (response?.status === "success") {
toast("Saved to Eagle.", {
duration: 3000,
})
} else {
toast("Failed to save to Eagle.", {
duration: 3000,
})
}
},
},
},
{
name: "Share",
className: "i-mingcute-share-2-line",
onClick: () => {
if (!entry.entries.url) return
client?.showShareMenu(entry.entries.url)
{
name: "Share",
className: "i-mingcute-share-2-line",
onClick: () => {
if (!entry.entries.url) return
client?.showShareMenu(entry.entries.url)
},
},
},
{
name: "Mark as Read",
className: "i-mingcute-round-fill",
disabled: !!entry.read,
onClick: () => {
read.mutate()
{
name: "Mark as Read",
className: "i-mingcute-round-fill",
disabled: !!entry.read,
onClick: () => {
read.mutate()
},
},
},
{
name: "Mark as Unread",
className: "i-mingcute-round-line",
disabled: !entry.read,
onClick: () => {
unread.mutate()
{
name: "Mark as Unread",
className: "i-mingcute-round-line",
disabled: !entry.read,
onClick: () => {
unread.mutate()
},
},
},
],
]
],
]
return items[view] || items[0]
}, [
checkEagle.data,
checkEagle.isLoading,
collect,
entry,
read,
uncollect,
unread,
view,
])
return {
items: items[view] || items[0],
items,
}
}
+3
View File
@@ -0,0 +1,3 @@
export * from "./useDark"
export * from "./usePrevious"
export * from "./useRefValue"
@@ -0,0 +1,14 @@
import { useLayoutEffect, useRef } from "react"
export const useRefValue = <S>(
value: S,
): Readonly<{
current: Readonly<S>
}> => {
const ref = useRef<S>(value)
useLayoutEffect(() => {
ref.current = value
})
return ref
}
+2
View File
@@ -0,0 +1,2 @@
export * from "./biz"
export * from "./common"
+5
View File
@@ -4,6 +4,10 @@ import { router } from "@renderer/router"
import { hc } from "hono/client"
import { ofetch } from "ofetch"
export abstract class RequestError extends Error {
name = "RequestError"
}
export const apiFetch = ofetch.create({
baseURL: import.meta.env.VITE_API_URL,
credentials: "include",
@@ -27,6 +31,7 @@ export const apiFetch = ofetch.create({
},
onResponseError(context) {
if (context.response.status === 401) {
// Or we can present LoginModal here.
router.navigate("/login")
}
},
+21 -1
View File
@@ -1,3 +1,23 @@
import { createStore } from "jotai"
import type { PrimitiveAtom } from "jotai"
import { createStore, useAtom, useAtomValue, useSetAtom } from "jotai"
export const jotaiStore = createStore()
export const createAtomAccessor = <T>(atom: PrimitiveAtom<T>) =>
[
() => jotaiStore.get(atom),
(value: T) => jotaiStore.set(atom, value),
] as const
/**
* @param atom - jotai
* @returns - [atom, useAtom, useAtomValue, useSetAtom, jotaiStore.get, jotaiStore.set]
*/
export const createAtomHooks = <T>(atom: PrimitiveAtom<T>) =>
[
atom,
() => useAtom(atom),
() => useAtomValue(atom),
() => useSetAtom(atom),
...createAtomAccessor(atom),
] as const
+1 -1
View File
@@ -67,7 +67,7 @@ export type DataResponse<T> = {
data?: T
}
export type ActiveEntry = string | null
export type ActiveEntryId = string | null
export type SubscriptionModel = SubscriptionResponse[number]
@@ -5,7 +5,7 @@ import {
AvatarImage,
} from "@renderer/components/ui/avatar"
import { Button } from "@renderer/components/ui/button"
import { useSignOut } from "@renderer/hooks/useAuth"
import { useSignOut } from "@renderer/hooks"
import { views } from "@renderer/lib/constants"
import { cn } from "@renderer/lib/utils"
import { useSession } from "@renderer/queries/auth"
@@ -17,7 +17,7 @@ export function Component() {
const { activeEntry, activeList } = useFeedStore(
useShallow((state) => ({
activeList: state.activeList,
activeEntry: state.activeEntry,
activeEntry: state.activeEntryId,
})),
)
const { setActiveEntry } = feedActions
@@ -1,3 +1,4 @@
import { setMainContainerElement } from "@renderer/atoms"
import { FeedColumn } from "@renderer/components/feed-column"
import { Outlet } from "react-router-dom"
@@ -7,9 +8,9 @@ export function Component() {
<div className="w-64 shrink-0 border-r">
<FeedColumn />
</div>
<div className="flex flex-1 bg-background">
<main ref={setMainContainerElement} className="flex flex-1 bg-background !outline-none" tabIndex={-1}>
<Outlet />
</div>
</main>
</div>
)
}
+13 -12
View File
@@ -20,7 +20,7 @@ import {
} from "@renderer/components/ui/select"
import { Switch } from "@renderer/components/ui/switch"
import { ViewSelectContent } from "@renderer/components/view-select-content"
import { useBizQuery } from "@renderer/hooks/useBizQuery"
import { useBizQuery } from "@renderer/hooks"
import { apiClient } from "@renderer/lib/api-fetch"
import { client } from "@renderer/lib/client"
import { FeedViewType } from "@renderer/lib/enum"
@@ -75,7 +75,9 @@ export function Component() {
isPrivate: values.isPrivate,
...(isSubscribed && { feedId: feed.data?.feed.id }),
}
const $method = isSubscribed ? apiClient.subscriptions.$patch : apiClient.subscriptions.$post
const $method = isSubscribed ?
apiClient.subscriptions.$patch :
apiClient.subscriptions.$post
return $method({
// @ts-expect-error
@@ -96,16 +98,15 @@ export function Component() {
client?.invalidateQuery(
Queries.subscription.byView(Number.parseInt(variables.view)).key,
)
Queries.feed.byId({ id: feed.data?.feed.id }).invalidate()
client?.invalidateQuery(
Queries.feed.byId({ id: feed.data?.feed.id }).key,
)
toast(
isSubscribed ? "🎉 Updated." : "🎉 Followed.",
{
duration: 1000,
},
)
const feedId = feed.data?.feed.id
if (feedId) {
Queries.feed.byId({ id: feedId }).invalidate()
client?.invalidateQuery(Queries.feed.byId({ id: feedId }).key)
}
toast(isSubscribed ? "🎉 Updated." : "🎉 Followed.", {
duration: 1000,
})
if (!isSubscribed) {
window.close()
+1 -1
View File
@@ -1,7 +1,7 @@
import { ActionCard } from "@renderer/components/settings/action-card"
import { SettingsTitle } from "@renderer/components/settings/title"
import { Button } from "@renderer/components/ui/button"
import { useBizQuery } from "@renderer/hooks/useBizQuery"
import { useBizQuery } from "@renderer/hooks"
import { apiClient } from "@renderer/lib/api-fetch"
import type { ActionsResponse } from "@renderer/models"
import { Queries } from "@renderer/queries"
+1 -1
View File
@@ -1,7 +1,7 @@
import type { Session } from "@auth/core/types"
import type { GetSessionParams } from "@hono/auth-js/react"
import { authConfigManager } from "@hono/auth-js/react"
import { useBizQuery } from "@renderer/hooks/useBizQuery"
import { useBizQuery } from "@renderer/hooks"
import { defineQuery } from "@renderer/lib/defineQuery"
import type { FetchError } from "ofetch"
import { ofetch } from "ofetch"
+1 -1
View File
@@ -1,4 +1,4 @@
import { useBizInfiniteQuery, useBizQuery } from "@renderer/hooks/useBizQuery"
import { useBizInfiniteQuery, useBizQuery } from "@renderer/hooks"
import { apiClient } from "@renderer/lib/api-fetch"
import { defineQuery } from "@renderer/lib/defineQuery"
import { entryActions } from "@renderer/store/entry/entry"
+1 -7
View File
@@ -1,7 +1,4 @@
import {
UnprocessableFeedError,
} from "@renderer/biz/error"
import { useBizQuery } from "@renderer/hooks/useBizQuery"
import { useBizQuery } from "@renderer/hooks"
import { apiClient } from "@renderer/lib/api-fetch"
import { defineQuery } from "@renderer/lib/defineQuery"
@@ -16,9 +13,6 @@ export const feed = {
defineQuery(
["feed", id, url],
async () => {
if (!id && !url) {
throw new UnprocessableFeedError("id or url is required")
}
const res = await apiClient.feeds.$get({
query: {
id,
+14 -11
View File
@@ -1,16 +1,18 @@
import type { ActiveEntry, ActiveList } from "@renderer/models"
import type { ActiveEntryId, ActiveList } from "@renderer/models"
import { create } from "zustand"
import { getStoreActions } from "./utils/helper"
interface FeedStoreActions {
setActiveList: (value: ActiveList) => void
setActiveEntry: (value: ActiveEntry) => void
setActiveEntry: (value: ActiveEntryId) => void
}
interface FeedStoreState {
activeList: ActiveList
activeEntry: ActiveEntry
activeEntryId: ActiveEntryId
}
type FeedStore = FeedStoreState & { actions: Readonly<FeedStoreActions> }
type FeedStore = FeedStoreState & Readonly<FeedStoreActions>
export const useFeedStore = create<FeedStore>((set) => ({
activeList: {
level: "view",
@@ -18,17 +20,18 @@ export const useFeedStore = create<FeedStore>((set) => ({
name: "Articles",
view: 0,
},
activeEntry: null,
activeEntryId: null,
activeEntryIndex: null,
// Actions
actions: {
setActiveEntry: (value) => set({ activeEntry: value }),
setActiveList: (value) => set({ activeList: value }),
},
setActiveEntry: (value) => set({ activeEntryId: value }),
setActiveList: (value) => set({ activeList: value }),
}))
export const feedActions = useFeedStore.getState().actions
export const feedActions = getStoreActions(useFeedStore)
export const getCurrentFeedId = () => useFeedStore.getState().activeList.id
export const getCurrentEntryId = () => useFeedStore.getState().activeEntryId
/** Hooks */
export const useFeedActiveList = () =>