feat(reader): support custom css, fixed #256

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2024-10-30 22:01:18 +08:00
parent 2d11eb2d92
commit b251fa9421
18 changed files with 277 additions and 61 deletions
+1
View File
@@ -68,6 +68,7 @@
"nanoid": "5.0.7",
"ofetch": "1.4.1",
"path-to-regexp": "8.2.0",
"plain-shiki": "0.0.12",
"re-resizable": "6.10.0",
"react-blurhash": "^0.3.0",
"react-error-boundary": "4.1.2",
+2
View File
@@ -34,6 +34,7 @@ export const createDefaultSettings = (): UISettings => ({
codeHighlightThemeDark: "github-dark",
guessCodeLanguage: true,
hideRecentReader: false,
customCSS: "",
// View
pictureViewMasonry: true,
@@ -56,6 +57,7 @@ export const uiServerSyncWhiteListKeys: (keyof UISettings)[] = [
"uiFontFamily",
"readerFontFamily",
"opaqueSidebar",
"customCSS",
]
const isZenModeAtom = atom((get) => {
@@ -87,6 +87,7 @@ export const ShadowDOM: FC<
const uiFont = useUISettingKey("uiFontFamily")
const reduceMotion = useReduceMotion()
const usePointerCursor = useUISettingKey("usePointerCursor")
const customCSS = useUISettingKey("customCSS")
return (
<root.div {...rest}>
@@ -105,6 +106,7 @@ export const ShadowDOM: FC<
className="font-theme"
>
{injectHostStyles ? stylesElements : null}
<MemoedDangerousHTMLStyle>{customCSS}</MemoedDangerousHTMLStyle>
{props.children}
</div>
</ShadowDOMContext.Provider>
@@ -2,7 +2,7 @@ import { Divider } from "@follow/components/ui/divider/index.js"
import { RootPortalProvider } from "@follow/components/ui/portal/provider.js"
import { EllipsisHorizontalTextWithTooltip } from "@follow/components/ui/typography/index.js"
import { useRefValue } from "@follow/hooks"
import { nextFrame, stopPropagation } from "@follow/utils/dom"
import { nextFrame, preventDefault, stopPropagation } from "@follow/utils/dom"
import { cn, getOS } from "@follow/utils/utils"
import * as Dialog from "@radix-ui/react-dialog"
import type { BoundingBox } from "framer-motion"
@@ -289,7 +289,8 @@ export const ModalInternal = memo(
<Dialog.Content
asChild
aria-describedby={undefined}
onPointerDownOutside={(event) => event.preventDefault()}
// @ts-expect-error
onPointerDownOutside={preventDefault}
onOpenAutoFocus={openAutoFocus}
>
<div
@@ -2,7 +2,7 @@ import { cn } from "@follow/utils/utils"
const benefits = [
{
level: "Lv1",
level: 1,
benefits: [
{
icon: "i-mgc-certificate-cute-fi",
@@ -14,20 +14,20 @@ const benefits = [
],
},
{
level: "Lv2",
level: 2,
benefits: [
{ icon: "i-mgc-rocket-cute-re", text: "Faster feed refresh time", comingSoon: true },
],
},
{
level: "Lv3",
level: 3,
benefits: [
{ icon: "i-mgc-eye-2-cute-re", text: "More developer attention" },
{ icon: "i-mgc-rocket-cute-re", text: "Faster feed refresh time", comingSoon: true },
],
},
{
level: "Lv4",
level: 4,
benefits: [
{ icon: "i-mgc-eye-2-cute-re", text: "More developer attention" },
{ icon: "i-mgc-magic-2-cute-re", text: "AI summary for feed", comingSoon: true },
@@ -57,7 +57,7 @@ const BoostLevel = ({
level,
benefits,
}: {
level: string
level: number
benefits: { icon?: string; text: string; comingSoon?: boolean }[]
}) => {
return (
@@ -65,7 +65,7 @@ const BoostLevel = ({
<div className="flex flex-col">
<h3 className="flex items-center gap-2 text-xl font-semibold text-theme-accent">
<span className="grow border-t border-gray-300 dark:border-gray-700" />
<span>{level}</span>
<span>Lv. {level}</span>
<span className="grow border-t border-gray-300 dark:border-gray-700" />
</h3>
<ul className="ml-4 list-inside list-disc space-y-1">
@@ -0,0 +1,73 @@
import { useIsDark } from "@follow/hooks"
import { nextFrame } from "@follow/utils/dom"
import { cn } from "@follow/utils/utils"
import { createPlainShiki } from "plain-shiki"
import { useLayoutEffect, useRef } from "react"
import css from "shiki/langs/css.mjs"
import githubDark from "shiki/themes/github-dark.mjs"
import githubLight from "shiki/themes/github-light.mjs"
import { shiki } from "~/components/ui/code-highlighter/shiki/shared"
shiki.loadLanguageSync(css)
shiki.loadThemeSync(githubDark)
shiki.loadThemeSync(githubLight)
export const CSSEditor: Component<{
onChange: (value: string) => void
defaultValue?: string
}> = ({ onChange, className, defaultValue }) => {
const ref = useRef<HTMLDivElement>(null)
const isDark = useIsDark()
useLayoutEffect(() => {
let dispose: () => void
if (ref.current) {
ref.current.focus()
// Move cursor to the end of the content
const selection = window.getSelection()
const range = document.createRange()
range.selectNodeContents(ref.current)
range.collapse(false)
selection?.removeAllRanges()
selection?.addRange(range)
ref.current.textContent = defaultValue ?? ""
const { dispose: disposeShiki } = createPlainShiki(shiki).mount(ref.current, {
lang: "css",
themes: {
light: "github-light",
dark: "github-dark",
},
defaultTheme: isDark ? "dark" : "light",
})
dispose = disposeShiki
}
return () => dispose?.()
}, [isDark])
return (
<div
className={cn("size-full", className)}
ref={ref}
contentEditable
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Tab") {
e.preventDefault()
const selection = window.getSelection()
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0)
const tabNode = document.createTextNode("\u00A0\u00A0\u00A0\u00A0") // Using four non-breaking spaces as a tab
range.insertNode(tabNode)
range.setStartAfter(tabNode)
range.setEndAfter(tabNode)
selection.removeAllRanges()
selection.addRange(range)
}
}
nextFrame(() => {
onChange(ref.current?.textContent ?? "")
})
}}
/>
)
}
@@ -5,7 +5,7 @@ import { ScrollArea } from "@follow/components/ui/scroll-area/index.js"
import { FeedViewType, views } from "@follow/constants"
import { useTitle, useTypeScriptHappyCallback } from "@follow/hooks"
import type { FeedModel } from "@follow/models/types"
import { clsx, cn, isBizId } from "@follow/utils/utils"
import { clsx, isBizId } from "@follow/utils/utils"
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import type {
@@ -223,13 +223,13 @@ function EntryColumnImpl() {
</AutoResizeHeight>
<m.div
key={`${routeFeedId}-${view}`}
className="relative h-0 grow"
className="relative mt-2 h-0 grow"
initial={{ opacity: 0.01, y: 100 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0.01, y: -100 }}
>
<ScrollArea.ScrollArea
scrollbarClassName={cn("mt-3", !views[view].wideMode ? "w-[5px] p-0" : "")}
scrollbarClassName={!views[view].wideMode ? "w-[5px] p-0" : ""}
mask={false}
ref={scrollRef}
rootClassName={clsx("h-full", views[view].wideMode ? "mt-2" : "")}
@@ -1,45 +1 @@
import type { SettingPageConfig } from "./utils"
function getSettings() {
const map = import.meta.glob("../../pages/settings/\\(settings\\)/*", { eager: true })
const settings = [] as {
name: I18nKeysForSettings
iconName: string
path: string
Component: () => JSX.Element
priority: number
loader: () => SettingPageConfig
}[]
for (const path in map) {
const prefix = "(settings)"
const postfix = ".tsx"
const lastItem = path.split("/").pop()
if (!lastItem) continue
let p = lastItem.slice(0, -postfix.length)
if (p.includes(prefix)) {
p = p.replace(prefix, "")
}
if (p === "index" || p === "layout") continue
const Module = map[path] as {
Component: () => JSX.Element
loader: () => SettingPageConfig
}
if (!Module.loader) continue
settings.push({
...Module.loader(),
Component: Module.Component,
loader: Module.loader,
path: p,
})
}
return settings.sort((a, b) => a.priority - b.priority)
}
export const settings = /* #__PURE__ */ getSettings()
export const SETTING_MODAL_ID = "setting-modal"
@@ -2,7 +2,7 @@ import { useMemo } from "react"
import { useUserRole } from "~/atoms/user"
import { settings } from "../constants"
import { settings } from "../settings-glob"
import type { SettingPageContext } from "../utils"
export const useSettingPageContext = (): SettingPageContext => {
@@ -8,7 +8,7 @@ import { Trans } from "react-i18next"
import { ModalClose } from "~/components/ui/modal/stacked/components"
import { SettingsTitle } from "~/modules/settings/title"
import { settings } from "../constants"
import { settings } from "../settings-glob"
import { SettingTabProvider, useSettingTab } from "./context"
import { SettingModalLayout } from "./layout"
@@ -16,6 +16,7 @@ import { useResizeableModal } from "~/components/ui/modal/stacked/hooks"
import { ElECTRON_CUSTOM_TITLEBAR_HEIGHT } from "~/constants"
import { useActivationModal } from "~/modules/activation"
import { SETTING_MODAL_ID } from "../constants"
import { SettingSyncIndicator } from "../helper/SyncIndicator"
import { useAvailableSettings, useSettingPageContext } from "../hooks/use-setting-ctx"
import { SettingsSidebarTitle } from "../title"
@@ -82,7 +83,11 @@ export function SettingModalLayout(
}, [])
return (
<div className={cn("h-full", !isResizeable && "center")} ref={edgeElementRef}>
<div
id={SETTING_MODAL_ID}
className={cn("h-full", !isResizeable && "center")}
ref={edgeElementRef}
>
<m.div
exit={{
opacity: 0,
@@ -0,0 +1,45 @@
import type { SettingPageConfig } from "./utils"
function getSettings() {
const map = import.meta.glob("../../pages/settings/\\(settings\\)/*", { eager: true })
const settings = [] as {
name: I18nKeysForSettings
iconName: string
path: string
Component: () => JSX.Element
priority: number
loader: () => SettingPageConfig
}[]
for (const path in map) {
const prefix = "(settings)"
const postfix = ".tsx"
const lastItem = path.split("/").pop()
if (!lastItem) continue
let p = lastItem.slice(0, -postfix.length)
if (p.includes(prefix)) {
p = p.replace(prefix, "")
}
if (p === "index" || p === "layout") continue
const Module = map[path] as {
Component: () => JSX.Element
loader: () => SettingPageConfig
}
if (!Module.loader) continue
settings.push({
...Module.loader(),
Component: Module.Component,
loader: Module.loader,
path: p,
})
}
return settings.sort((a, b) => a.priority - b.priority)
}
export const settings = /* #__PURE__ */ getSettings()
@@ -1,3 +1,4 @@
import { Button } from "@follow/components/ui/button/index.js"
import {
Select,
SelectContent,
@@ -8,20 +9,31 @@ import {
import { useIsDark, useThemeAtomValue } from "@follow/hooks"
import { IN_ELECTRON } from "@follow/shared/constants"
import { getOS } from "@follow/utils/utils"
import { useForceUpdate } from "framer-motion"
import { useEffect, useRef } from "react"
import { useTranslation } from "react-i18next"
import { bundledThemesInfo } from "shiki/themes"
import {
getUISettings,
setUISetting,
useUISettingKey,
useUISettingSelector,
useUISettingValue,
} from "~/atoms/settings/ui"
import { setFeedColumnShow, useFeedColumnShow } from "~/atoms/sidebar"
import { useCurrentModal, useModalStack } from "~/components/ui/modal/stacked/hooks"
import { isElectronBuild } from "~/constants"
import { useSetTheme } from "~/hooks/common"
import { SettingDescription, SettingSwitch, SettingTabbedSegment } from "../control"
import { CSSEditor } from "../../editor/css-editor"
import { SETTING_MODAL_ID } from "../constants"
import {
SettingActionItem,
SettingDescription,
SettingSwitch,
SettingTabbedSegment,
} from "../control"
import { createDefineSettingItem } from "../helper/builder"
import { createSettingBuilder } from "../helper/setting-builder"
import { SettingItemGroup } from "../section"
@@ -71,6 +83,7 @@ export const SettingAppearance = () => {
}),
ZenMode,
ThumbnailRatio,
CustomCSS,
{
type: "title",
@@ -290,3 +303,90 @@ const ThumbnailRatio = () => {
</SettingItemGroup>
)
}
const CustomCSS = () => {
const { t } = useTranslation("settings")
const { present } = useModalStack()
return (
<SettingItemGroup>
<SettingActionItem
label={t("appearance.custom_css.label")}
action={() => {
present({
title: t("appearance.custom_css.label"),
content: CustomCSSModal,
clickOutsideToDismiss: false,
overlay: false,
resizeable: true,
resizeDefaultSize: {
width: 700,
height: 400,
},
})
}}
buttonText={t("appearance.custom_css.button")}
/>
<SettingDescription>{t("appearance.custom_css.description")}</SettingDescription>
</SettingItemGroup>
)
}
const CustomCSSModal = () => {
const initialCSS = useRef(getUISettings().customCSS)
const { t } = useTranslation("common")
const { dismiss } = useCurrentModal()
useEffect(() => {
return () => {
setUISetting("customCSS", initialCSS.current)
}
}, [])
useEffect(() => {
const modal = document.querySelector(`#${SETTING_MODAL_ID}`) as HTMLDivElement
if (!modal) return
const prevOverlay = getUISettings().modalOverlay
setUISetting("modalOverlay", false)
modal.style.display = "none"
return () => {
setUISetting("modalOverlay", prevOverlay)
modal.style.display = "block"
}
}, [])
const [forceUpdate, key] = useForceUpdate()
return (
<form
className="relative flex h-full max-w-full flex-col"
onSubmit={(e) => {
e.preventDefault()
if (initialCSS.current !== getUISettings().customCSS) {
initialCSS.current = getUISettings().customCSS
}
dismiss()
}}
>
<CSSEditor
defaultValue={initialCSS.current}
key={key}
className="h-0 grow rounded-lg border p-3 font-mono"
onChange={(value) => {
setUISetting("customCSS", value)
}}
/>
<div className="mt-2 flex shrink-0 justify-end gap-2">
<Button
variant="outline"
onClick={(e) => {
e.preventDefault()
setUISetting("customCSS", initialCSS.current)
forceUpdate()
}}
>
{t("words.reset")}
</Button>
<Button type="submit">{t("words.save")}</Button>
</div>
</form>
)
}
+1 -1
View File
@@ -4,8 +4,8 @@ import { useContext } from "react"
import { useTranslation } from "react-i18next"
import { useLoaderData } from "react-router-dom"
import { settings } from "./constants"
import { IsInSettingIndependentWindowContext } from "./context"
import { settings } from "./settings-glob"
import type { SettingPageConfig } from "./utils"
export const SettingsSidebarTitle = ({ path, className }: { path: string; className?: string }) => {
+2
View File
@@ -31,9 +31,11 @@
"words.record": "record",
"words.record_one": "record",
"words.record_other": "records",
"words.reset": "Reset",
"words.result": "result",
"words.result_one": "result",
"words.result_other": "results",
"words.save": "Save",
"words.submit": "Submit",
"words.update": "Update",
"words.which.all": "All"
+3
View File
@@ -53,6 +53,9 @@
"appearance.code_highlight_theme": "Code highlight theme",
"appearance.content": "Content",
"appearance.content_font": "Content Font",
"appearance.custom_css.button": "Edit",
"appearance.custom_css.description": "Custom CSS style for content",
"appearance.custom_css.label": "Custom CSS",
"appearance.custom_font": "Custom Font",
"appearance.fonts": "Fonts",
"appearance.general": "General",
@@ -29,11 +29,13 @@ export interface UISettings {
usePointerCursor: boolean | null
uiFontFamily: string
readerFontFamily: string
// Content
readerRenderInlineStyle: boolean
codeHighlightThemeLight: string
codeHighlightThemeDark: string
guessCodeLanguage: boolean
hideRecentReader: boolean
customCSS: string
// view
pictureViewMasonry: boolean
+24
View File
@@ -486,6 +486,9 @@ importers:
path-to-regexp:
specifier: 8.2.0
version: 8.2.0
plain-shiki:
specifier: 0.0.12
version: 0.0.12(shiki@1.22.0)
re-resizable:
specifier: 6.10.0
version: 6.10.0(patch_hash=yitcmpfwcomg2fky72uc3lhk2i)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
@@ -525,6 +528,9 @@ importers:
react-virtuoso:
specifier: 4.12.0
version: 4.12.0(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
react18-use:
specifier: 0.3.0
version: 0.3.0(react@18.3.1)
rehype-infer-description-meta:
specifier: 2.0.0
version: 2.0.0
@@ -8135,6 +8141,11 @@ packages:
pkg-types@1.2.1:
resolution: {integrity: sha512-sQoqa8alT3nHjGuTjuKgOnvjo4cljkufdtLMnO2LBP/wRwuDlo1tkaEdMxCRhyGRPacv/ztlZgDPm2b7FAmEvw==}
plain-shiki@0.0.12:
resolution: {integrity: sha512-jaR0Rhm0wWOn1unMrt0yOTYI83y+ntabQ///GxYyRSYFRsNJZRrT7dpWbtX/QRFL44cznutwCT5EiEXj1KwXVQ==}
peerDependencies:
shiki: ^1.22.0
plist@3.1.0:
resolution: {integrity: sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==}
engines: {node: '>=10.4.0'}
@@ -8674,6 +8685,11 @@ packages:
react: '>=16 || >=17 || >= 18'
react-dom: '>=16 || >=17 || >= 18'
react18-use@0.3.0:
resolution: {integrity: sha512-h/s6y9CRE/LV3QZvEtS4iBg5UThXTyHCjbfxzHEHEoRISaQa9SVQ7pdTnUt7M83URP1QRJ2bVSDwMpBIvmi50w==}
peerDependencies:
react: '>=18.0.0'
react@18.3.1:
resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}
engines: {node: '>=0.10.0'}
@@ -18968,6 +18984,10 @@ snapshots:
mlly: 1.7.2
pathe: 1.1.2
plain-shiki@0.0.12(shiki@1.22.0):
dependencies:
shiki: 1.22.0
plist@3.1.0:
dependencies:
'@xmldom/xmldom': 0.8.10
@@ -19453,6 +19473,10 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1(react@18.3.1)
react18-use@0.3.0(react@18.3.1):
dependencies:
react: 18.3.1
react@18.3.1:
dependencies:
loose-envify: 1.4.0