From b251fa9421417c75d71707c8f08850f2cc902e1a Mon Sep 17 00:00:00 2001 From: Innei Date: Wed, 30 Oct 2024 22:01:18 +0800 Subject: [PATCH] feat(reader): support custom css, fixed #256 Signed-off-by: Innei --- apps/renderer/package.json | 1 + apps/renderer/src/atoms/settings/ui.ts | 2 + .../src/components/common/ShadowDOM.tsx | 2 + .../src/components/ui/modal/stacked/modal.tsx | 5 +- .../src/modules/boost/level-benefits.tsx | 12 +-- .../src/modules/editor/css-editor.tsx | 73 +++++++++++++ .../src/modules/entry-column/index.tsx | 6 +- .../src/modules/settings/constants.ts | 46 +------- .../modules/settings/hooks/use-setting-ctx.ts | 2 +- .../src/modules/settings/modal/content.tsx | 2 +- .../src/modules/settings/modal/layout.tsx | 7 +- .../src/modules/settings/settings-glob.ts | 45 ++++++++ .../src/modules/settings/tabs/apperance.tsx | 102 +++++++++++++++++- apps/renderer/src/modules/settings/title.tsx | 2 +- locales/common/en.json | 2 + locales/settings/en.json | 3 + packages/shared/src/interface/settings.ts | 2 + pnpm-lock.yaml | 24 +++++ 18 files changed, 277 insertions(+), 61 deletions(-) create mode 100644 apps/renderer/src/modules/editor/css-editor.tsx create mode 100644 apps/renderer/src/modules/settings/settings-glob.ts diff --git a/apps/renderer/package.json b/apps/renderer/package.json index 0aa35d51d..ccc6ff174 100644 --- a/apps/renderer/package.json +++ b/apps/renderer/package.json @@ -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", diff --git a/apps/renderer/src/atoms/settings/ui.ts b/apps/renderer/src/atoms/settings/ui.ts index 98bbe652c..3b730d55c 100644 --- a/apps/renderer/src/atoms/settings/ui.ts +++ b/apps/renderer/src/atoms/settings/ui.ts @@ -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) => { diff --git a/apps/renderer/src/components/common/ShadowDOM.tsx b/apps/renderer/src/components/common/ShadowDOM.tsx index 20f75beca..b2e38bacb 100644 --- a/apps/renderer/src/components/common/ShadowDOM.tsx +++ b/apps/renderer/src/components/common/ShadowDOM.tsx @@ -87,6 +87,7 @@ export const ShadowDOM: FC< const uiFont = useUISettingKey("uiFontFamily") const reduceMotion = useReduceMotion() const usePointerCursor = useUISettingKey("usePointerCursor") + const customCSS = useUISettingKey("customCSS") return ( @@ -105,6 +106,7 @@ export const ShadowDOM: FC< className="font-theme" > {injectHostStyles ? stylesElements : null} + {customCSS} {props.children} diff --git a/apps/renderer/src/components/ui/modal/stacked/modal.tsx b/apps/renderer/src/components/ui/modal/stacked/modal.tsx index 8df897b99..e56d7bd97 100644 --- a/apps/renderer/src/components/ui/modal/stacked/modal.tsx +++ b/apps/renderer/src/components/ui/modal/stacked/modal.tsx @@ -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( event.preventDefault()} + // @ts-expect-error + onPointerDownOutside={preventDefault} onOpenAutoFocus={openAutoFocus} >
{ return ( @@ -65,7 +65,7 @@ const BoostLevel = ({

- {level} + Lv. {level}

    diff --git a/apps/renderer/src/modules/editor/css-editor.tsx b/apps/renderer/src/modules/editor/css-editor.tsx new file mode 100644 index 000000000..395dbce9c --- /dev/null +++ b/apps/renderer/src/modules/editor/css-editor.tsx @@ -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(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 ( +
    { + 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 ?? "") + }) + }} + /> + ) +} diff --git a/apps/renderer/src/modules/entry-column/index.tsx b/apps/renderer/src/modules/entry-column/index.tsx index 4037b7cad..072aa755d 100644 --- a/apps/renderer/src/modules/entry-column/index.tsx +++ b/apps/renderer/src/modules/entry-column/index.tsx @@ -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() { 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" diff --git a/apps/renderer/src/modules/settings/hooks/use-setting-ctx.ts b/apps/renderer/src/modules/settings/hooks/use-setting-ctx.ts index 95268f1ef..7219ef070 100644 --- a/apps/renderer/src/modules/settings/hooks/use-setting-ctx.ts +++ b/apps/renderer/src/modules/settings/hooks/use-setting-ctx.ts @@ -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 => { diff --git a/apps/renderer/src/modules/settings/modal/content.tsx b/apps/renderer/src/modules/settings/modal/content.tsx index ad0d4b316..b5b683bd3 100644 --- a/apps/renderer/src/modules/settings/modal/content.tsx +++ b/apps/renderer/src/modules/settings/modal/content.tsx @@ -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" diff --git a/apps/renderer/src/modules/settings/modal/layout.tsx b/apps/renderer/src/modules/settings/modal/layout.tsx index 8e05d74fd..34a86a26e 100644 --- a/apps/renderer/src/modules/settings/modal/layout.tsx +++ b/apps/renderer/src/modules/settings/modal/layout.tsx @@ -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 ( -
    +
    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() diff --git a/apps/renderer/src/modules/settings/tabs/apperance.tsx b/apps/renderer/src/modules/settings/tabs/apperance.tsx index f77af2442..53d29c8da 100644 --- a/apps/renderer/src/modules/settings/tabs/apperance.tsx +++ b/apps/renderer/src/modules/settings/tabs/apperance.tsx @@ -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 = () => { ) } + +const CustomCSS = () => { + const { t } = useTranslation("settings") + const { present } = useModalStack() + return ( + + { + 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")} + /> + {t("appearance.custom_css.description")} + + ) +} + +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 ( +
    { + e.preventDefault() + if (initialCSS.current !== getUISettings().customCSS) { + initialCSS.current = getUISettings().customCSS + } + dismiss() + }} + > + { + setUISetting("customCSS", value) + }} + /> + +
    + + +
    + + ) +} diff --git a/apps/renderer/src/modules/settings/title.tsx b/apps/renderer/src/modules/settings/title.tsx index 16206333e..7abe847ee 100644 --- a/apps/renderer/src/modules/settings/title.tsx +++ b/apps/renderer/src/modules/settings/title.tsx @@ -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 }) => { diff --git a/locales/common/en.json b/locales/common/en.json index 92813c86a..0584828ed 100644 --- a/locales/common/en.json +++ b/locales/common/en.json @@ -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" diff --git a/locales/settings/en.json b/locales/settings/en.json index c286a9d2c..e961b9efa 100644 --- a/locales/settings/en.json +++ b/locales/settings/en.json @@ -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", diff --git a/packages/shared/src/interface/settings.ts b/packages/shared/src/interface/settings.ts index db6bb1910..e762b0703 100644 --- a/packages/shared/src/interface/settings.ts +++ b/packages/shared/src/interface/settings.ts @@ -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 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 537652e73..510b86a62 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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