feat: add spotlight settings across desktop and mobile

This commit is contained in:
DIYgod
2026-04-09 13:45:05 +08:00
parent e8619436c7
commit f6cdb64186
18 changed files with 476 additions and 73 deletions
@@ -0,0 +1,18 @@
import { createSettingAtom } from "@follow/atoms/helper/setting.js"
import type { SpotlightSettings } from "@follow/shared/spotlight"
import { defaultSpotlightSettings } from "@follow/shared/spotlight"
export const createDefaultSpotlightSettings = (): SpotlightSettings => ({
...defaultSpotlightSettings,
})
export const {
useSettingKey: useSpotlightSettingKey,
useSettingSelector: useSpotlightSettingSelector,
setSetting: setSpotlightSetting,
getSettings: getSpotlightSettings,
initializeDefaultSettings: initializeDefaultSpotlightSettings,
settingAtom: __spotlightSettingAtom,
} = createSettingAtom("spotlight", createDefaultSpotlightSettings)
export const spotlightServerSyncWhiteListKeys: (keyof SpotlightSettings)[] = ["spotlights"]
@@ -187,7 +187,7 @@ const SpotlightRuleEditor = ({
</div>
<div className="flex flex-wrap justify-end gap-2">
<Button size="sm" variant="outline" className="text-red" onClick={onDelete}>
<Button size="sm" variant="outline" onClick={onDelete}>
{t("words.delete", { ns: "common" })}
</Button>
<Button disabled={isFirst} size="sm" variant="outline" onClick={() => onMove(-1)}>
@@ -119,7 +119,7 @@ export const createSettingAtom = <T extends object>(
const updated = Date.now()
EventBus.dispatch("SETTING_CHANGE_EVENT", {
key: settingKey as "general" | "ui",
key: settingKey as "general" | "ui" | "spotlight",
payload: {
[key]: value,
},
@@ -0,0 +1,22 @@
import type { SpotlightSettings } from "@follow/shared/spotlight"
import { defaultSpotlightSettings } from "@follow/shared/spotlight"
import { createSettingAtom } from "./internal/helper"
export const createDefaultSpotlightSettings = (): SpotlightSettings => ({
...defaultSpotlightSettings,
})
export const {
useSettingKey: useSpotlightSettingKey,
useSettingSelector: useSpotlightSettingSelector,
useSettingKeys: useSpotlightSettingKeys,
setSetting: setSpotlightSetting,
clearSettings: clearSpotlightSettings,
initializeDefaultSettings: initializeDefaultSpotlightSettings,
getSettings: getSpotlightSettings,
useSettingValue: useSpotlightSettingValue,
settingAtom: __spotlightSettingAtom,
} = createSettingAtom("spotlight", createDefaultSpotlightSettings)
export const spotlightServerSyncWhiteListKeys: (keyof SpotlightSettings)[] = ["spotlights"]
@@ -4,6 +4,7 @@ import { useEffect, useMemo, useRef, useState } from "react"
import { PixelRatio } from "react-native"
import { useActionLanguage } from "@/src/atoms/settings/general"
import { useSpotlightSettingKey } from "@/src/atoms/settings/spotlight"
import { useUISettingKey } from "@/src/atoms/settings/ui"
import { prepareEntryRenderWebView } from "./index"
@@ -59,6 +60,7 @@ export function useWebViewEntry({
const codeThemeLight = useUISettingKey("codeHighlightThemeLight")
const codeThemeDark = useUISettingKey("codeHighlightThemeDark")
const readerRenderInlineStyle = useUISettingKey("readerRenderInlineStyle")
const spotlightRules = useSpotlightSettingKey("spotlights")
const useSystemFontScaling = useUISettingKey("useSystemFontScaling")
const customFontScale = useUISettingKey("fontScale")
const useDifferentFontSizeForContent = useUISettingKey("useDifferentFontSizeForContent")
@@ -93,11 +95,13 @@ export function useWebViewEntry({
return {
...entry,
content,
spotlightRules,
}
}, [
entry,
showReadability,
showTranslation,
spotlightRules,
translation?.content,
translation?.readabilityContent,
])
@@ -115,6 +119,10 @@ export function useWebViewEntry({
WebViewManager.setCodeTheme(codeThemeLight, codeThemeDark)
}, [codeThemeLight, codeThemeDark])
useEffect(() => {
WebViewManager.setSpotlights(spotlightRules)
}, [spotlightRules])
useEffect(() => {
WebViewManager.setEntry(entryInWebview)
}, [entryInWebview])
@@ -1,7 +1,12 @@
import type { SpotlightRule } from "@follow/shared/spotlight"
import type { EntryModel } from "@follow/store/entry/types"
import { SharedWebViewModule } from "./index"
type WebViewEntryPayload = EntryModel & {
spotlightRules?: SpotlightRule[]
}
/**
* WebView JavaScript bridge manager
* Provides a centralized way to execute JavaScript functions in the WebView
@@ -17,12 +22,19 @@ export const WebViewManager = {
/**
* Set the current entry data in WebView
*/
setEntry(entry?: EntryModel | null): void {
setEntry(entry?: WebViewEntryPayload | null): void {
if (!entry) return
const json = JSON.stringify(entry)
SharedWebViewModule.dispatch?.("setEntry", json)
},
/**
* Set spotlight rules for rich content highlighting in WebView
*/
setSpotlights(spotlights: SpotlightRule[]): void {
SharedWebViewModule.dispatch?.("setSpotlights", JSON.stringify(spotlights))
},
/**
* Set root font size for the WebView
*/
@@ -3,7 +3,7 @@ import { SymbolView } from "expo-symbols"
import type { FC, PropsWithChildren } from "react"
import * as React from "react"
import { Fragment } from "react"
import type { PressableProps, ViewProps } from "react-native"
import type { PressableProps, ViewProps, ViewStyle } from "react-native"
import { Pressable, StyleSheet, View } from "react-native"
import Animated, { FadeIn, FadeOut } from "react-native-reanimated"
import type { SFSymbol } from "sf-symbols-typescript"
@@ -26,6 +26,11 @@ import {
import { GroupedInsetListCardItemStyle } from "./GroupedInsetListCardItemStyle"
const GROUPED_TABLET_MAX_WIDTH = 760
const GROUPED_TABLET_CARD_STYLE: ViewStyle = {
width: "100%",
maxWidth: GROUPED_TABLET_MAX_WIDTH,
alignSelf: "center",
}
interface GroupedInsetListCardProps {
showSeparator?: boolean
@@ -57,9 +62,7 @@ export const GroupedInsetListCard: FC<
return normalizedChildren.filter(Boolean)
}, [children])
const isTablet = useIsTabletLayout()
const tabletCardStyle = isTablet
? { width: "100%", maxWidth: GROUPED_TABLET_MAX_WIDTH, alignSelf: "center" as const }
: undefined
const tabletCardStyle = isTablet ? GROUPED_TABLET_CARD_STYLE : undefined
return (
<View
{...props}
@@ -115,10 +118,10 @@ export const GroupedInsetListSectionHeader: FC<{
marginSize?: "normal" | "small"
}> = ({ label, marginSize = "normal" }) => {
const isTablet = useIsTabletLayout()
const sectionStyle = {
const sectionStyle: ViewStyle = {
width: isTablet ? "100%" : undefined,
maxWidth: isTablet ? GROUPED_TABLET_MAX_WIDTH : undefined,
alignSelf: isTablet ? ("center" as const) : undefined,
alignSelf: isTablet ? "center" : undefined,
paddingHorizontal: GROUPED_LIST_ITEM_PADDING,
marginHorizontal: GROUPED_LIST_MARGIN,
marginTop:
+2
View File
@@ -2,6 +2,7 @@ import { persistQueryClient } from "@tanstack/react-query-persist-client"
import { initializeDefaultDataSettings } from "../atoms/settings/data"
import { initializeDefaultGeneralSettings } from "../atoms/settings/general"
import { initializeDefaultSpotlightSettings } from "../atoms/settings/spotlight"
import { initializeDefaultUISettings } from "../atoms/settings/ui"
import { kvStoragePersister, queryClient } from "../lib/query-client"
@@ -17,6 +18,7 @@ export const hydrateSettings = () => {
initializeDefaultUISettings()
initializeDefaultGeneralSettings()
initializeDefaultDataSettings()
initializeDefaultSpotlightSettings()
}
export const hydrateQueryClient = () => {
persistQueryClient({
+215 -62
View File
@@ -1,4 +1,10 @@
import type { GeneralSettings, UISettings } from "@follow/shared/settings/interface"
import type { SpotlightSettings } from "@follow/shared/spotlight"
import {
mergeAppearancePayloadWithSpotlightSettings,
pickSpotlightPayloadFromRemoteAppearance,
toAppearanceSpotlightPayload,
} from "@follow/shared/spotlight"
import { whoami } from "@follow/store/user/getters"
import { tracker } from "@follow/tracker"
import { isEmptyObject, jotaiStore, sleep } from "@follow/utils"
@@ -12,6 +18,11 @@ import {
generalServerSyncWhiteListKeys,
getGeneralSettings,
} from "@/src/atoms/settings/general"
import {
__spotlightSettingAtom,
getSpotlightSettings,
spotlightServerSyncWhiteListKeys,
} from "@/src/atoms/settings/spotlight"
import { __uiSettingAtom, getUISettings, uiServerSyncWhiteListKeys } from "@/src/atoms/settings/ui"
import { followClient } from "@/src/lib/api-client"
import { kv } from "@/src/lib/kv"
@@ -19,7 +30,10 @@ import { kv } from "@/src/lib/kv"
type SettingMapping = {
appearance: UISettings
general: GeneralSettings
spotlight: SpotlightSettings
}
type SettingDomain = keyof SettingMapping
type RemoteSettingsTab = "appearance" | "general"
const pickSyncPayload = <T extends object>(payload: T, keys: readonly (keyof T | string)[]) => {
const nextPayload = {} as Partial<T>
@@ -37,6 +51,7 @@ const pickSyncPayload = <T extends object>(payload: T, keys: readonly (keyof T |
const localSettingGetterMap = {
appearance: () => getUISettings(),
general: () => getGeneralSettings(),
spotlight: () => getSpotlightSettings(),
}
const createInternalSetter =
@@ -49,15 +64,111 @@ const createInternalSetter =
const localSettingSetterMap = {
appearance: createInternalSetter(__uiSettingAtom),
general: createInternalSetter(__generalSettingAtom),
spotlight: createInternalSetter(__spotlightSettingAtom),
}
const settingWhiteListMap = {
appearance: uiServerSyncWhiteListKeys,
general: generalServerSyncWhiteListKeys,
spotlight: spotlightServerSyncWhiteListKeys,
}
const bizSettingKeyToTabMapping = {
const remoteTabMap: Record<SettingDomain, RemoteSettingsTab> = {
appearance: "appearance",
general: "general",
spotlight: "appearance",
}
const remoteTabToDomainMap: Record<RemoteSettingsTab, SettingDomain[]> = {
appearance: ["appearance", "spotlight"],
general: ["general"],
}
const bizSettingKeyToDomainMapping = {
ui: "appearance",
general: "general",
spotlight: "spotlight",
} as const
const getSettingUpdated = (payload: Record<string, unknown>) =>
typeof payload.updated === "number" ? payload.updated : undefined
const getLocalAppearancePayload = () =>
pickSyncPayload(localSettingGetterMap.appearance(), settingWhiteListMap.appearance)
const getLocalSpotlightSnapshot = () =>
localSettingGetterMap.spotlight() as SpotlightSettings & { updated?: number }
const payloadForRemote = (
domain: SettingDomain,
payload: Record<string, unknown>,
): Record<string, unknown> =>
domain === "spotlight"
? toAppearanceSpotlightPayload(
payload as unknown as SpotlightSettings,
getSettingUpdated(payload),
)
: pickSyncPayload(payload, settingWhiteListMap[domain])
const buildFullLocalAppearancePayload = () => {
const spotlightSettings = getLocalSpotlightSnapshot()
return mergeAppearancePayloadWithSpotlightSettings(
getLocalAppearancePayload(),
spotlightSettings,
getSettingUpdated(spotlightSettings as unknown as Record<string, unknown>),
)
}
const mergeAppearancePayloadWithLocalChanges = (
basePayload: Record<string, unknown>,
options: {
appearancePayload?: Record<string, unknown>
spotlightSettings?: (SpotlightSettings & { updated?: number }) | null
},
) => {
let nextPayload = { ...basePayload }
if (options.appearancePayload) {
nextPayload = {
...nextPayload,
...options.appearancePayload,
}
}
if (options.spotlightSettings) {
nextPayload = mergeAppearancePayloadWithSpotlightSettings(
nextPayload,
options.spotlightSettings,
getSettingUpdated(options.spotlightSettings as unknown as Record<string, unknown>),
)
}
return nextPayload
}
const getLocalPayloadForRemoteTab = (remoteTab: Exclude<RemoteSettingsTab, "appearance">) =>
payloadForRemote(
remoteTab,
localSettingGetterMap[remoteTab]() as unknown as Record<string, unknown>,
)
const payloadFromRemote = (
domain: SettingDomain,
payload: Record<string, unknown>,
updated: number,
): Record<string, unknown> | null => {
if (domain === "spotlight") {
return pickSpotlightPayloadFromRemoteAppearance(payload, updated)
}
const nextPayload = pickSyncPayload(payload, settingWhiteListMap[domain])
if (isEmptyObject(nextPayload)) {
return null
}
return {
...nextPayload,
updated,
}
}
const isUnauthorizedError = (error: unknown) => {
@@ -72,7 +183,7 @@ const isUnauthorizedError = (error: unknown) => {
return false
}
export type SettingSyncTab = keyof SettingMapping
export type SettingSyncTab = SettingDomain
export interface SettingSyncQueueItem<T extends SettingSyncTab = SettingSyncTab> {
tab: T
payload: Partial<SettingMapping[T]>
@@ -87,7 +198,7 @@ interface PersistedSettingSyncQueue {
declare module "@follow/utils/event-bus" {
interface CustomEvent {
SETTING_CHANGE_EVENT: {
key: keyof typeof bizSettingKeyToTabMapping
key: keyof typeof bizSettingKeyToDomainMapping
payload: any
}
}
@@ -138,12 +249,12 @@ class SettingSyncQueue {
this.bindQueueOwner(currentUserId)
const tab = bizSettingKeyToTabMapping[data.key] as SettingSyncTab
if (!tab) return
const domain = bizSettingKeyToDomainMapping[data.key] as SettingSyncTab
if (!domain) return
const nextPayload = pickSyncPayload(data.payload, settingWhiteListMap[tab])
const nextPayload = pickSyncPayload(data.payload, settingWhiteListMap[domain])
if (isEmptyObject(nextPayload)) return
this.enqueue(tab, nextPayload)
this.enqueue(domain, nextPayload)
void this.persist()
})
@@ -228,6 +339,15 @@ class SettingSyncQueue {
private threshold = 1000
private flushScheduled = false
private async fetchRemoteAppearancePayload() {
const remoteSettings = await this.fetchSettingRemote()
const remoteAppearancePayload = remoteSettings.settings?.appearance
return remoteAppearancePayload && typeof remoteAppearancePayload === "object"
? { ...(remoteAppearancePayload as Record<string, unknown>) }
: {}
}
async enqueue<T extends SettingSyncTab>(tab: T, payload: Partial<SettingMapping[T]>) {
const currentUserId = this.getCurrentUserId()
if (!currentUserId) {
@@ -274,42 +394,67 @@ class SettingSyncQueue {
return
}
const groupedTab = {} as Record<SettingSyncTab, any>
const referenceMap = {} as Record<SettingSyncTab, Set<SettingSyncQueueItem>>
const changedDomainsByRemoteTab = {} as Partial<Record<RemoteSettingsTab, Set<SettingDomain>>>
const domainOverrides = {} as Partial<Record<SettingDomain, Record<string, unknown>>>
const referenceMap = {} as Partial<Record<RemoteSettingsTab, Set<SettingSyncQueueItem>>>
for (const item of this.queue) {
if (!groupedTab[item.tab]) {
groupedTab[item.tab] = {}
const remoteTab = remoteTabMap[item.tab]
changedDomainsByRemoteTab[remoteTab] ||= new Set()
changedDomainsByRemoteTab[remoteTab].add(item.tab)
referenceMap[remoteTab] ||= new Set()
referenceMap[remoteTab].add(item)
domainOverrides[item.tab] = {
...domainOverrides[item.tab],
...payloadForRemote(item.tab, item.payload as unknown as Record<string, unknown>),
}
}
referenceMap[item.tab] ||= new Set()
referenceMap[item.tab].add(item)
let remoteAppearancePayload = {} as Record<string, unknown>
if (changedDomainsByRemoteTab.appearance?.size) {
try {
remoteAppearancePayload = await this.fetchRemoteAppearancePayload()
} catch (error) {
if (isUnauthorizedError(error)) {
await this.clearQueueAndPersist(currentUserId)
return
}
groupedTab[item.tab] = {
...groupedTab[item.tab],
...item.payload,
this.reportSyncError("flush", error)
return
}
}
const promises = [] as Promise<any>[]
for (const tab in groupedTab) {
const json = pickSyncPayload(
groupedTab[tab as SettingSyncTab],
settingWhiteListMap[tab as SettingSyncTab],
)
for (const tab in changedDomainsByRemoteTab) {
const remoteTab = tab as RemoteSettingsTab
const changedDomains = changedDomainsByRemoteTab[remoteTab]
const json =
remoteTab === "appearance"
? // Preserve remote untouched appearance fields so spotlight-only syncs do not clobber them.
mergeAppearancePayloadWithLocalChanges(remoteAppearancePayload, {
appearancePayload: changedDomains?.has("appearance")
? domainOverrides.appearance
: undefined,
spotlightSettings: changedDomains?.has("spotlight")
? getLocalSpotlightSnapshot()
: undefined,
})
: domainOverrides[remoteTab]
if (isEmptyObject(json)) {
if (!json || isEmptyObject(json)) {
continue
}
const promise = followClient.api.settings
.update({
tab: tab as SettingsTab,
tab: remoteTab as SettingsTab,
...json,
})
.then(() => {
// remove from queue
for (const item of referenceMap[tab as SettingSyncTab]) {
for (const item of referenceMap[remoteTab] ?? []) {
const index = this.queue.indexOf(item)
if (index !== -1) {
this.queue.splice(index, 1)
@@ -341,31 +486,35 @@ class SettingSyncQueue {
this.bindQueueOwner(currentUserId)
if (!tab) {
const promises = [] as Promise<any>[]
for (const tab in localSettingGetterMap) {
const payload = pickSyncPayload(
localSettingGetterMap[tab as SettingSyncTab](),
settingWhiteListMap[tab as SettingSyncTab],
)
const groupedPayloads = {} as Partial<Record<RemoteSettingsTab, Record<string, unknown>>>
groupedPayloads.appearance = buildFullLocalAppearancePayload()
groupedPayloads.general = getLocalPayloadForRemoteTab("general")
const promise = followClient.api.settings.update({
tab: tab as SettingsTab,
const promises = Object.entries(groupedPayloads).map(([remoteTab, payload]) =>
followClient.api.settings.update({
tab: remoteTab as SettingsTab,
...payload,
})
promises.push(promise)
}
}),
)
this.chain = this.chain.finally(() => Promise.all(promises))
return this.chain
} else {
const payload = pickSyncPayload(localSettingGetterMap[tab](), settingWhiteListMap[tab])
this.chain = this.chain.finally(async () => {
const remoteTab = remoteTabMap[tab]
const payload =
remoteTab === "appearance"
? mergeAppearancePayloadWithLocalChanges(await this.fetchRemoteAppearancePayload(), {
appearancePayload: tab === "appearance" ? getLocalAppearancePayload() : undefined,
spotlightSettings: tab === "spotlight" ? getLocalSpotlightSnapshot() : undefined,
})
: getLocalPayloadForRemoteTab(remoteTab)
this.chain = this.chain.finally(() =>
followClient.api.settings.update({
tab: tab as SettingsTab,
return followClient.api.settings.update({
tab: remoteTab as SettingsTab,
...payload,
}),
)
})
})
return this.chain
}
@@ -415,36 +564,40 @@ class SettingSyncQueue {
if (isEmptyObject(remoteSettings.settings)) return
for (const tab in remoteSettings.settings) {
const settingTab = tab as SettingSyncTab
const remoteSettingPayload = remoteSettings.settings[tab as SettingsTab]
const updated = remoteSettings.updated[tab as SettingsTab]
const remoteTab = tab as RemoteSettingsTab
const remoteSettingPayload = remoteSettings.settings[remoteTab as SettingsTab]
const updated = remoteSettings.updated[remoteTab as SettingsTab]
if (!updated) {
if (!updated || !remoteSettingPayload || typeof remoteSettingPayload !== "object") {
continue
}
const remoteUpdatedDate = new Date(updated).getTime()
const localSettings = localSettingGetterMap[settingTab]()
const localSettingsUpdated =
"updated" in localSettings && typeof localSettings.updated === "number"
? localSettings.updated
: undefined
if (!localSettingsUpdated || remoteUpdatedDate > localSettingsUpdated) {
// Use remote and update local
const nextPayload = pickSyncPayload(remoteSettingPayload, settingWhiteListMap[settingTab])
if (isEmptyObject(nextPayload)) {
for (const settingDomain of remoteTabToDomainMap[remoteTab] ?? []) {
const nextPayload = payloadFromRemote(
settingDomain,
remoteSettingPayload as Record<string, unknown>,
remoteUpdatedDate,
)
if (!nextPayload || isEmptyObject(nextPayload)) {
continue
}
const setter = localSettingSetterMap[settingTab]
const nextUpdated =
typeof nextPayload.updated === "number" ? nextPayload.updated : remoteUpdatedDate
const localSettings = localSettingGetterMap[settingDomain]()
const localSettingsUpdated =
"updated" in localSettings && typeof localSettings.updated === "number"
? localSettings.updated
: undefined
setter({
...nextPayload,
updated: remoteUpdatedDate,
} as Partial<SettingMapping[typeof settingTab]>)
if (localSettingsUpdated && nextUpdated <= localSettingsUpdated) {
continue
}
const setter = localSettingSetterMap[settingDomain]
setter(nextPayload as Partial<SettingMapping[typeof settingDomain]>)
}
}
}
@@ -0,0 +1,7 @@
import type { SpotlightRule } from "@follow/shared/spotlight"
import { buildHighlightSegments, compileSpotlightRules } from "@follow/utils/spotlight"
export const getHighlightedTextSegments = (
text: string | null | undefined,
rules: SpotlightRule[],
) => buildHighlightSegments(text ?? "", compileSpotlightRules(rules))
@@ -1,8 +1,9 @@
import { atom } from "jotai"
import type { EntryModel } from "../../types"
import type { EntryModel, SpotlightState } from "../../types"
export const entryAtom = atom<EntryModel | null>(null)
export const spotlightAtom = atom<SpotlightState["spotlights"]>([])
export const codeThemeLightAtom = atom<string | null>(null)
export const codeThemeDarkAtom = atom<string | null>(null)
@@ -1,10 +1,11 @@
import type { EntryModel } from "../../types"
import type { EntryModel, SpotlightState } from "../../types"
import {
codeThemeDarkAtom,
codeThemeLightAtom,
entryAtom,
noMediaAtom,
readerRenderInlineStyleAtom,
spotlightAtom,
} from "../atoms"
type Store = ReturnType<typeof import("jotai").createStore>
@@ -25,6 +26,14 @@ export class WebViewBridgeManager {
*/
setEntry = (entry: EntryModel) => {
this.store.set(entryAtom, entry)
if (Array.isArray(entry.spotlightRules)) {
this.store.set(spotlightAtom, entry.spotlightRules)
}
bridge.measure()
}
setSpotlights = (spotlights: SpotlightState["spotlights"]) => {
this.store.set(spotlightAtom, spotlights)
bridge.measure()
}
@@ -74,6 +83,7 @@ export class WebViewBridgeManager {
if (!window.__FO_BRIDGE__) {
const handlers = {
setEntry: this.setEntry,
setSpotlights: this.setSpotlights,
setCodeTheme: this.setCodeTheme,
setReaderRenderInlineStyle: this.setReaderRenderInlineStyle,
setNoMedia: this.setNoMedia,
@@ -1,3 +1,5 @@
import type { SpotlightRule } from "@follow/shared/spotlight"
export interface MediaModel {
url: string
type: "photo" | "video"
@@ -11,4 +13,9 @@ export interface EntryModel {
content?: string
title?: string
media?: MediaModel[]
spotlightRules?: SpotlightRule[]
}
export interface SpotlightState {
spotlights: SpotlightRule[]
}
+12
View File
@@ -750,6 +750,17 @@
"rsshub.useModal.purchase_expires_at": "You have purchased this Instance, and your purchase expires at",
"rsshub.useModal.title": "RSSHub Instance",
"rsshub.useModal.useWith": "Use with {{amount}} <Power />",
"spotlight.add_rule": "Add rule",
"spotlight.case_sensitive": "Case sensitive",
"spotlight.color": "Color",
"spotlight.enabled": "Enabled",
"spotlight.invalid_regex": "Invalid regex: {{error}}",
"spotlight.keyword": "Keyword",
"spotlight.move_down": "Move down",
"spotlight.move_up": "Move up",
"spotlight.pattern": "Pattern",
"spotlight.regex": "Regex",
"spotlight.type": "Type",
"subscription.actions.comingSoon": "Coming soon",
"subscription.actions.current": "Current plan",
"subscription.actions.manage_error": "Something went wrong while opening subscription management.",
@@ -797,6 +808,7 @@
"titles.referral.short": "Invite & Earn",
"titles.shortcuts": "Shortcuts",
"titles.sign_out": "Sign Out",
"titles.spotlight": "Spotlight",
"titles.subscription.long": "Manage your subscription",
"titles.subscription.short": "Subscription",
"titles.token_usage": "AI Credits Usage",
+12
View File
@@ -746,6 +746,17 @@
"rsshub.useModal.purchase_expires_at": "このインスタンスを購入しました、利用期限は",
"rsshub.useModal.title": "RSSHub インスタンス",
"rsshub.useModal.useWith": "使用する {{amount}} <Power />",
"spotlight.add_rule": "ルールを追加",
"spotlight.case_sensitive": "大文字と小文字を区別",
"spotlight.color": "色",
"spotlight.enabled": "有効",
"spotlight.invalid_regex": "無効な正規表現: {{error}}",
"spotlight.keyword": "キーワード",
"spotlight.move_down": "下へ移動",
"spotlight.move_up": "上へ移動",
"spotlight.pattern": "パターン",
"spotlight.regex": "正規表現",
"spotlight.type": "種類",
"subscription.actions.comingSoon": "近日公開",
"subscription.actions.current": "現在のプラン",
"subscription.actions.manage_error": "サブスクリプション管理を開けませんでした。",
@@ -793,6 +804,7 @@
"titles.referral.short": "招待 & 収益",
"titles.shortcuts": "ショートカット",
"titles.sign_out": "サインアウト",
"titles.spotlight": "Spotlight",
"titles.subscription.long": "サブスクリプション管理",
"titles.subscription.short": "サブスクリプション",
"titles.token_usage": "トークン使用状況",
+12
View File
@@ -750,6 +750,17 @@
"rsshub.useModal.purchase_expires_at": "你已购买此实例,到期时间为",
"rsshub.useModal.title": "RSSHub 实例",
"rsshub.useModal.useWith": "使用 {{amount}} <Power />",
"spotlight.add_rule": "添加规则",
"spotlight.case_sensitive": "区分大小写",
"spotlight.color": "颜色",
"spotlight.enabled": "启用",
"spotlight.invalid_regex": "无效的正则表达式:{{error}}",
"spotlight.keyword": "关键词",
"spotlight.move_down": "下移",
"spotlight.move_up": "上移",
"spotlight.pattern": "模式",
"spotlight.regex": "正则",
"spotlight.type": "类型",
"subscription.actions.comingSoon": "即将推出",
"subscription.actions.current": "当前计划",
"subscription.actions.manage_error": "打开订阅管理时出现问题。",
@@ -797,6 +808,7 @@
"titles.referral.short": "邀请并赚取",
"titles.shortcuts": "快捷键",
"titles.sign_out": "登出",
"titles.spotlight": "Spotlight",
"titles.subscription.long": "管理订阅",
"titles.subscription.short": "订阅",
"titles.token_usage": "AI 积分使用情况",
+1
View File
@@ -10,5 +10,6 @@ export * from "./noop"
export * from "./path-parser"
export * from "./react"
export * from "./resize"
export * from "./spotlight"
export * from "./url-for-video"
export * from "./utils"
+123
View File
@@ -0,0 +1,123 @@
import type { SpotlightRule } from "@follow/shared/spotlight"
const escapeRegExp = (value: string) => value.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")
export interface CompiledSpotlightRule {
id: string
color: string
regex: RegExp
}
export interface SpotlightPatternValidationResult {
valid: true
error?: never
}
export interface SpotlightPatternValidationError {
valid: false
error: string
}
export type SpotlightPatternValidation =
| SpotlightPatternValidationResult
| SpotlightPatternValidationError
export interface HighlightSegment {
text: string
highlight: null | {
ruleId: string
color: string
}
}
export const validateSpotlightPattern = (
pattern: string,
patternType: SpotlightRule["patternType"],
): SpotlightPatternValidation => {
if (!pattern.trim()) {
return { valid: false, error: "Pattern is required." }
}
if (patternType === "regex") {
try {
new RegExp(pattern)
} catch (error) {
return {
valid: false,
error:
error instanceof Error
? `Invalid regular expression: ${error.message}`
: "Invalid regular expression.",
}
}
}
return { valid: true }
}
export const compileSpotlightRules = (rules: SpotlightRule[]): CompiledSpotlightRule[] =>
rules
.filter((rule) => rule.enabled)
.flatMap((rule) => {
const validation = validateSpotlightPattern(rule.pattern, rule.patternType)
if (!validation.valid) return []
const source = rule.patternType === "keyword" ? escapeRegExp(rule.pattern) : rule.pattern
const flags = rule.caseSensitive ? "g" : "gi"
return [{ id: rule.id, color: rule.color, regex: new RegExp(source, flags) }]
})
export const buildHighlightSegments = (
text: string,
rules: CompiledSpotlightRule[],
): HighlightSegment[] => {
if (!text || rules.length === 0) return [{ text, highlight: null }]
const claimed = Array.from({ length: text.length }, () => false)
const segments: Array<{ start: number; end: number; ruleId: string; color: string }> = []
for (const rule of rules) {
const regex = new RegExp(rule.regex.source, rule.regex.flags)
for (const match of text.matchAll(regex)) {
const start = match.index ?? -1
const value = match[0] ?? ""
const end = start + value.length
if (start < 0 || !value) continue
if (claimed.slice(start, end).some(Boolean)) continue
for (let index = start; index < end; index += 1) {
claimed[index] = true
}
segments.push({ start, end, ruleId: rule.id, color: rule.color })
}
}
if (segments.length === 0) return [{ text, highlight: null }]
segments.sort((left, right) => left.start - right.start)
const output: HighlightSegment[] = []
let cursor = 0
for (const segment of segments) {
if (cursor < segment.start) {
output.push({ text: text.slice(cursor, segment.start), highlight: null })
}
output.push({
text: text.slice(segment.start, segment.end),
highlight: { ruleId: segment.ruleId, color: segment.color },
})
cursor = segment.end
}
if (cursor < text.length) {
output.push({ text: text.slice(cursor), highlight: null })
}
return output
}