fix(actions): stabilize rule editor state

This commit is contained in:
DIYgod
2026-05-29 14:00:19 +08:00
parent 69202876ed
commit df8b8d0670
8 changed files with 234 additions and 14 deletions
@@ -0,0 +1,84 @@
import { useActionStore } from "@follow/store/action/store"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import * as React from "react"
import { act } from "react"
import type { Root } from "react-dom/client"
import { createRoot } from "react-dom/client"
import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest"
import { RuleCard } from "./rule-card"
vi.mock("react-i18next", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-i18next")>()
return {
...actual,
["useTranslation"]: () => ({
t: (key: string, options?: Record<string, unknown>) => {
if (typeof options?.count === "number") {
return `${key}:${options.count}`
}
return key
},
}),
}
})
vi.mock("~/components/ui/modal/stacked/hooks", () => ({
["useDialog"]: () => ({
ask: vi.fn(),
}),
}))
vi.mock("../settings/modal/useSettingModal", () => ({
["useSettingModal"]: () => vi.fn(),
}))
describe("RuleCard", () => {
let root: Root | null = null
let container: HTMLElement | null = null
beforeAll(() => {
;(globalThis as typeof globalThis & { React: typeof React }).React = React
;(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
).IS_REACT_ACT_ENVIRONMENT = true
window.removeEventListener ??= () => {}
})
beforeEach(() => {
useActionStore.setState({
rules: [],
isDirty: false,
})
})
afterEach(async () => {
if (root) {
await act(async () => {
root?.unmount()
})
}
container?.remove()
root = null
container = null
})
test("does not crash while a deleted rule card is still mounted", async () => {
container = document.createElement("div")
document.body.append(container)
root = createRoot(container)
const queryClient = new QueryClient()
await expect(
act(async () => {
root!.render(
<QueryClientProvider client={queryClient}>
<RuleCard index={0} />
</QueryClientProvider>,
)
}),
).resolves.toBeUndefined()
})
})
@@ -28,6 +28,12 @@ export const RuleCard = ({
defaultOpen = false,
onOpenChange,
}: RuleCardProps) => {
const ruleExists = useActionRules((rules) => Boolean(rules[index]))
if (!ruleExists) {
return null
}
if (mode === "compact") {
return <CompactRuleCard index={index} defaultOpen={defaultOpen} onOpenChange={onOpenChange} />
}
@@ -73,6 +79,10 @@ const CompactRuleCard = ({
setOpen(defaultOpen)
}, [defaultOpen])
if (!rule) {
return null
}
const toggle = () => {
setOpen((prev) => {
const next = !prev
@@ -123,12 +133,20 @@ const CompactRuleCard = ({
const RuleCardToolbar = ({ index }: { index: number }) => {
const { t } = useTranslation("settings")
const name = useActionRule(index, (a) => a.name)
const disabled = useActionRule(index, (a) => a.result.disabled)
const rule = useActionRule(index)
const ruleCount = useActionRules((s) => s.length)
const mutation = useUpdateActionsMutation()
const { ask } = useDialog()
if (!rule) {
return null
}
const {
name,
result: { disabled },
} = rule
const handleDelete = () => {
if (ruleCount === 1) {
ask({
@@ -0,0 +1,68 @@
import { SegmentGroup, SegmentItem } from "@follow/components/ui/segment/index.js"
import * as React from "react"
import { act } from "react"
import type { Root } from "react-dom/client"
import { createRoot } from "react-dom/client"
import { afterEach, beforeAll, describe, expect, test } from "vitest"
const ControlledSegment = ({ value }: { value: string }) => (
<SegmentGroup value={value}>
<SegmentItem value="all" label="All" />
<SegmentItem value="filter" label="Custom Filters" />
</SegmentGroup>
)
const getTab = (container: HTMLElement, name: string) => {
const tab = Array.from(container.querySelectorAll<HTMLButtonElement>("[role=tab]")).find(
(element) => element.textContent?.trim() === name,
)
if (!tab) {
throw new Error(`Tab not found: ${name}`)
}
return tab
}
describe("SegmentGroup", () => {
let root: Root | null = null
let container: HTMLElement | null = null
beforeAll(() => {
;(globalThis as typeof globalThis & { React: typeof React }).React = React
;(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
).IS_REACT_ACT_ENVIRONMENT = true
})
afterEach(async () => {
if (root) {
await act(async () => {
root?.unmount()
})
}
container?.remove()
root = null
container = null
})
test("updates the active item when the controlled value changes", async () => {
container = document.createElement("div")
document.body.append(container)
root = createRoot(container)
await act(async () => {
root!.render(<ControlledSegment value="filter" />)
})
expect(getTab(container, "Custom Filters").dataset.state).toBe("active")
await act(async () => {
root!.render(<ControlledSegment value="all" />)
})
expect(getTab(container, "All").dataset.state).toBe("active")
expect(getTab(container, "Custom Filters").dataset.state).toBe("inactive")
})
})
@@ -206,9 +206,14 @@ export const ThenSection = ({ index, variant: _variant = "detail" }: ThenSection
return (
<section className="flex flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<span className="text-xs font-semibold uppercase tracking-wide text-text-secondary">
{t("actions.action_card.then_do")}
</span>
<div className="flex items-center gap-2">
<span className="flex size-5 items-center justify-center rounded-full bg-orange text-[11px] font-bold text-white shadow-sm">
2
</span>
<span className="text-sm font-bold uppercase tracking-wide text-text">
{t("actions.action_card.then_do")}
</span>
</div>
{enabledActions.length > 0 && (
<span className="text-xs text-text-secondary">
{t("actions.action_card.summary.action_count", { count: enabledActions.length })}
@@ -26,7 +26,7 @@ export const WhenSection = ({ index }: WhenSectionProps) => {
const { t } = useTranslation("settings")
const disabled = useActionRule(index, (a) => a.result.disabled)
const condition = useActionRule(index, (a) => a.condition)
const condition = useActionRule(index, (a) => a.condition) ?? []
const mode = condition.length > 0 ? "filter" : "all"
@@ -43,9 +43,14 @@ export const WhenSection = ({ index }: WhenSectionProps) => {
return (
<section className="flex flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<span className="text-xs font-semibold uppercase tracking-wide text-text-secondary">
{t("actions.action_card.when_feeds_match")}
</span>
<div className="flex items-center gap-2">
<span className="flex size-5 items-center justify-center rounded-full bg-orange text-[11px] font-bold text-white shadow-sm">
1
</span>
<span className="text-sm font-bold uppercase tracking-wide text-text">
{t("actions.action_card.when_feeds_match")}
</span>
</div>
<SegmentGroup
value={mode}
onValueChanged={(value) => handleModeChange(value as "all" | "filter")}
@@ -14,7 +14,9 @@ interface SegmentGroupProps {
export const SegmentGroup = (props: ComponentType<SegmentGroupProps>) => {
const { onValueChanged, value, className } = props
const [currentValue, setCurrentValue] = useState(value || "")
const isControlled = value !== undefined
const [uncontrolledValue, setUncontrolledValue] = useState(value || "")
const currentValue = isControlled ? value : uncontrolledValue
const componentId = useId()
return (
@@ -23,13 +25,15 @@ export const SegmentGroup = (props: ComponentType<SegmentGroupProps>) => {
value={useMemo(
() => ({
value: currentValue,
setValue: (value) => {
setCurrentValue(value)
onValueChanged?.(value)
setValue: (nextValue) => {
if (!isControlled) {
setUncontrolledValue(nextValue)
}
onValueChanged?.(nextValue)
},
componentId,
}),
[componentId, currentValue, onValueChanged],
[componentId, currentValue, isControlled, onValueChanged],
)}
>
<div
@@ -0,0 +1,33 @@
import { beforeEach, describe, expect, test } from "vitest"
import { actionActions, useActionStore } from "./store"
describe("actionActions", () => {
beforeEach(() => {
useActionStore.setState({
rules: [],
isDirty: false,
})
})
test("creates new rules that match all feeds by default", () => {
actionActions.addRule((index) => `Action ${index}`)
expect(useActionStore.getState().rules[0]).toMatchObject({
name: "Action 1",
condition: [],
index: 0,
result: {},
})
})
test("keeps rule indexes stable after deleting and adding rules", () => {
actionActions.addRule((index) => `Action ${index}`)
actionActions.addRule((index) => `Action ${index}`)
actionActions.deleteRule(0)
actionActions.addRule((index) => `Action ${index}`)
expect(useActionStore.getState().rules.map((rule) => rule.index)).toEqual([0, 1])
})
})
@@ -160,6 +160,9 @@ class ActionActions {
deleteRule(index: number) {
immerSet((state) => {
state.rules.splice(index, 1)
state.rules.forEach((rule, ruleIndex) => {
rule.index = ruleIndex
})
state.isDirty = true
})
}