Skip to content

feat(themer): leverage <ViewTransition> and <Activity> optimally - #2065

Merged
stipsan merged 1 commit into
mainfrom
themer-state-refactor
Oct 2, 2026
Merged

stipsan merged 1 commit into
mainfrom
themer-state-refactor

Conversation

@stipsan

@stipsan stipsan commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Note

Medium Risk
Touches Studio layout, theme application, and localStorage migration paths; plugin options changed (config removed) which may break integrators relying on the old API.

Overview
Refactors @sanity/themer around React 19 patterns: sidebar and split preview use <Activity> and <ViewTransition> with typed transitions via addTransitionType, lazy loads for the resizable sidebar and animated navbar icon, and startTransition/useTransition for open/close and prerender so urgent work does not fight view transitions.

State is split: a new toolReducer in ThemerProvider owns panel open/close, split-screen, prerender flags, navbar height, and the live ThemeProvider theme; the XState machine only manages theme list/edit flows and the switching tag (sidebar/open/split and layout-transition coupling are removed). Persistence moves out of the machine into PersistActorSnapshot plus valibot parsing/migration from legacy localStorage keys to full actor snapshots; themes.sync supports cross-tab theme state.

Plugin API change: themerTool({ config }) is dropped in favor of an optional title; the Studio’s configured theme is no longer passed as default options—it appears as a separate “configured theme” card (not reorderable). Mobile overlay sidebar behavior is simplified (tool stays closed on small breakpoints). View-transition CSS is reorganized into ViewTransitions.css.ts; visit-tracking and deferred-value helpers are removed.

Reviewed by Cursor Bugbot for commit a9b43a2. Bugbot is set up for automated code reviews on this repo. Configure here.

@changeset-bot

changeset-bot Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: a9b43a2

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@sanity/themer Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel

vercel Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
plugins-studio Ready Ready Preview Oct 2, 2026 4:34pm UTC
1 Skipped Deployment
Project Deployment Actions Updated
plugins-e2e-test-studio Ignored Ignored Oct 2, 2026 4:34pm UTC

Request Review

@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

✅ E2E Tests

🟢 43 passed • 🟡 1 flaky • view full report • view run

Studio: https://plugins-e2e-test-studio-3f23w8w55.sanity.dev

Datasets: pr-2065-chromium-37034749027, pr-2065-firefox-37034749027

@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Coverage Report

Status Category Percentage Covered / Total
🔵 Lines 35.65% 6506 / 18245
🔵 Statements 35.58% 6935 / 19486
🔵 Functions 31.77% 1741 / 5480
🔵 Branches 27.04% 3471 / 12836
File Coverage
File Stmts Branches Functions Lines Uncovered Lines
Changed Files
plugins/@sanity/themer/src/tool/PersistActorSnapshot.tsx 0% 0% 0% 0% 8-36
plugins/@sanity/themer/src/tool/ThemerLayout.tsx 3.57% 0% 0% 4.16% 27-237
plugins/@sanity/themer/src/tool/ThemerNavbar.tsx 2.17% 0% 0% 2.56% 22-166
plugins/@sanity/themer/src/tool/ThemerProvider.tsx 0% 0% 0% 0% 27-62
plugins/@sanity/themer/src/tool/ViewTransitions.css.ts 0% 0% 0% 0%
plugins/@sanity/themer/src/tool/addThemerTransitionType.ts 0% 0% 0% 0% 9-14
plugins/@sanity/themer/src/tool/constants.ts 100% 100% 100% 100%
plugins/@sanity/themer/src/tool/context.ts 83.33% 100% 0% 83.33% 22
plugins/@sanity/themer/src/tool/imagePalette.ts 98.63% 94.62% 100% 99.2% 316, 476
plugins/@sanity/themer/src/tool/machine.ts 98.8% 98.03% 98.41% 98.68% 376
plugins/@sanity/themer/src/tool/plugin.tsx 71.42% 100% 66.66% 71.42% 68-70
plugins/@sanity/themer/src/tool/reducer.ts 84.61% 71.42% 100% 84.61% 28, 34
plugins/@sanity/themer/src/tool/schemas.ts 100% 94.73% 100% 100%
plugins/@sanity/themer/src/tool/selectors.ts 100% 100% 100% 100%
plugins/@sanity/themer/src/tool/storage.ts 100% 95% 100% 100%
plugins/@sanity/themer/src/tool/sync.ts 84.96% 81.57% 61.53% 87.82% 75-107, 128
plugins/@sanity/themer/src/tool/themes.ts 96.55% 91.66% 100% 95.65% 143
Generated in workflow #10310 for commit a9b43a2 by the Vitest Coverage Report Action

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 7 potential issues.

Autofix Details

Bugbot Autofix prepared fixes for all 7 issues found in the latest run.

  • ✅ Fixed: Configured theme options never apply
    • themerTool reads the documented config option again and passes those BuildThemeOptions down as a stable baseOptions prop to ThemerLayout, replacing the hardcoded {config: {}}.
  • ✅ Fixed: Stock theme flashes on load
    • The tool reducer now starts with theme: null, so the first paint inherits the Studio's configured theme instead of building and applying the stock one.
  • ✅ Fixed: Body background no longer updates
    • Restored the effect that writes the applied theme's scheme background onto document.body and restores the previous value on cleanup.
  • ✅ Fixed: Wheel ignores reduced motion
    • AnimatedColorWheelIcon uses usePrefersReducedMotion() again and holds rotation at 0 when the user asked for less motion, so only the colors animate.
  • ✅ Fixed: Color wheel stories no longer animate
    • Both stories now render one navbar button that drives the icon through its imperative play() handle on hover and through the busy loop, replacing the ignored progress prop.
  • ✅ Fixed: Closing sidebar keeps split preview
    • The reducer's close action now clears split along with open, so closing the sidebar ends the split preview as documented.
  • ✅ Fixed: Mobile split uses sideways slide
    • viewTransitionClasses.splitscreen is now keyed by layout direction and ThemerLayout picks the column variant on small screens, so the stacked copy drops in from the top.

Create PR

Or push these changes by commenting:

@cursor push e945529c23
Preview (e945529c23)
diff --git a/dev/storybook/package.json b/dev/storybook/package.json
--- a/dev/storybook/package.json
+++ b/dev/storybook/package.json
@@ -31,7 +31,6 @@
     "@vanilla-extract/css": "catalog:",
     "@vitejs/plugin-react": "^6.1.1",
     "@vitest/browser-playwright": "^4.1.11",
-    "motion": "catalog:",
     "oxc-transform-react": "catalog:",
     "playwright": "^1.63.0",
     "react": "catalog:",

diff --git a/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx b/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
--- a/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
+++ b/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
@@ -1,13 +1,11 @@
 import {Button, Flex, Text} from '@sanity/ui'
 import type {Meta, StoryObj} from '@storybook/react-vite'
-import {animate, useMotionValue} from 'motion/react'
-import {useEffect} from 'react'
+import {useRef} from 'react'
 
 import AnimatedColorWheelIcon from '../../../../../plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon'
-import {ANIMATION_DURATION} from '../../../../../plugins/@sanity/themer/src/tool/colorWheel'
 
 interface WheelArgs {
-  progress: number
+  busy: boolean
 }
 
 /**
@@ -21,26 +19,23 @@
 export default meta
 type Story = StoryObj<WheelArgs>
 
-function NavbarButton() {
-  const progress = useMotionValue(0)
+function NavbarButton({busy}: WheelArgs) {
+  const icon = useRef<{play: () => void}>(null)
 
-  const play = () => {
-    // A run in progress plays out, like on the Studio navbar
-    if (progress.isAnimating()) return
-
-    animate(progress, [0, 1], {duration: ANIMATION_DURATION, ease: 'linear'})
-  }
-
   return (
     <Flex align="center" gap={3}>
       <Button
+        aria-busy={busy}
         aria-label="Themer"
-        icon={<AnimatedColorWheelIcon progress={progress} />}
+        icon={<AnimatedColorWheelIcon busy={busy} ref={icon} />}
         mode="bleed"
-        onMouseEnter={play}
+        // A run in progress plays out, like on the Studio navbar
+        // oxlint-disable-next-line storybook/context-in-play-function -- the icon's imperative handle, not another story's play function
+        onMouseEnter={() => icon.current?.play()}
+        selected={busy}
       />
       <Text muted size={1}>
-        Hover the button to play the animation
+        {busy ? 'The wheel laps until the code arrives' : 'Hover the button to play the animation'}
       </Text>
     </Flex>
   )
@@ -48,27 +43,14 @@
 
 /** The navbar toggle, which plays the animation on hover */
 export const Default: Story = {
-  render: () => <NavbarButton />,
+  args: {busy: false},
+  render: (args) => <NavbarButton busy={args.busy} />,
 }
 
-function WheelAtProgress(props: {progress: number}) {
-  const progress = useMotionValue(props.progress)
-
-  useEffect(() => {
-    progress.set(props.progress)
-  }, [progress, props.progress])
-
-  return (
-    <Text size={4}>
-      <AnimatedColorWheelIcon progress={progress} />
-    </Text>
-  )
+/** The toggle while the sidebar's code loads, where the wheel laps until it has arrived */
+export const Busy: Story = {
+  args: {busy: true},
+  argTypes: {busy: {control: {type: 'boolean'}}},
+  parameters: {controls: {include: ['busy']}},
+  render: (args) => <NavbarButton busy={args.busy} />,
 }
-
-/** The wheel at any point of the animation, from 0 to 1 */
-export const Progress: Story = {
-  args: {progress: 0.5},
-  argTypes: {progress: {control: {type: 'range', min: 0, max: 1, step: 0.01}}},
-  parameters: {controls: {include: ['progress']}},
-  render: (args) => <WheelAtProgress progress={args.progress} />,
-}

diff --git a/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx b/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
--- a/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
+++ b/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
@@ -1,3 +1,4 @@
+import {usePrefersReducedMotion} from '@sanity/ui'
 import {motion, MotionValue, useTransform, animate, useMotionValue} from 'motion/react'
 import {useEffect, useImperativeHandle} from 'react'
 
@@ -76,7 +77,10 @@
   ref: React.Ref<{play: () => void}>
 }) {
   const progress = useMotionValue(0)
-  const rotate = useTransform(progress, (value) => wheelRotation(value))
+  const prefersReducedMotion = usePrefersReducedMotion()
+  const rotate = useTransform(progress, (value) =>
+    prefersReducedMotion ? 0 : wheelRotation(value),
+  )
 
   useImperativeHandle(
     ref,

diff --git a/plugins/@sanity/themer/src/tool/ThemerLayout.tsx b/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
--- a/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
@@ -92,6 +92,8 @@
 }
 
 interface ThemerLayoutProps extends ToolReducerState {
+  /** The `buildTheme` options the Studio's configured theme was generated from */
+  baseOptions: BuildThemeOptions
   children: React.ReactNode
 }
 
@@ -124,6 +126,7 @@
  * @internal
  */
 export function ThemerLayout({
+  baseOptions,
   children,
   open,
   prerender,
@@ -131,7 +134,6 @@
   split,
   theme: currentThemeOptions,
 }: ThemerLayoutProps) {
-  const baseOptions = {config: {}}
   const [input] = useState<ThemerInput>(() => ({baseOptions, stored: readStoredState()}))
   const [snapshot, send, actorRef] = useActor(themerMachine, {input})
   const stored = useSelector(actorRef, selectStoredState, sameStoredState)
@@ -192,6 +194,21 @@
   // const scheme = useDeferredValue(useColorSchemeValue())
   const oppositeScheme: ThemeColorSchemeKey = scheme === 'dark' ? 'light' : 'dark'
 
+  useEffect(() => {
+    const background = theme?.v2?.color[scheme].default.bg
+
+    if (background === undefined) return undefined
+
+    const {style} = document.body
+    const previous = style.backgroundColor
+
+    style.backgroundColor = background
+
+    return () => {
+      style.backgroundColor = previous
+    }
+  }, [scheme, theme])
+
   // The machine releases the image of a palette as it is replaced or its
   // theme deleted; whatever it still holds goes with the layout — the actor
   // keeps its last snapshot once stopped
@@ -234,6 +251,10 @@
     ],
   )
 
+  // Side by side the split copy comes in from the side it sits on; stacked
+  // on small screens it comes in from the top
+  const splitscreen = viewTransitionClasses.splitscreen[mobile ? 'column' : 'row']
+
   // What the view transitions do this render, from what the machine says
   const classes = reduceMotion
     ? {
@@ -278,9 +299,9 @@
             <Activity mode={split && open ? 'visible' : 'hidden'}>
               <ViewTransition
                 default="none"
-                enter={viewTransitionClasses.splitscreen.enter}
-                update={viewTransitionClasses.splitscreen.update}
-                exit={viewTransitionClasses.splitscreen.exit}
+                enter={splitscreen.enter}
+                update={splitscreen.update}
+                exit={splitscreen.exit}
                 // enter={classes.copyEnter}
                 // exit={classes.copyExit}
                 // onEnter={transitioned}

diff --git a/plugins/@sanity/themer/src/tool/ViewTransitions.css.ts b/plugins/@sanity/themer/src/tool/ViewTransitions.css.ts
--- a/plugins/@sanity/themer/src/tool/ViewTransitions.css.ts
+++ b/plugins/@sanity/themer/src/tool/ViewTransitions.css.ts
@@ -120,6 +120,35 @@
   'resizeStudio',
 )
 
+/**
+ * The split copy's classes for one layout direction: it comes in from the
+ * edge it sits on — beside the Studio, or above it where the copies stack
+ */
+function createSplitscreenClasses(enterAnimation: string, exitAnimation: string, debugId: string) {
+  return {
+    enter: {
+      [viewTransitionTypes['split-creen:open']]: createViewTransitionType(
+        {new: {animationName: enterAnimation}},
+        `${debugId}In`,
+      ),
+      debug: redOutlines,
+      default: 'none',
+    },
+    update: {
+      [viewTransitionTypes.crossfade]: 'auto',
+      default: 'none',
+    },
+    exit: {
+      [viewTransitionTypes['split-creen:close']]: createViewTransitionType(
+        {old: {animationName: exitAnimation}},
+        `${debugId}Out`,
+      ),
+      debug: redOutlines,
+      default: 'none',
+    },
+  } as const satisfies Record<string, ViewTransitionClass>
+}
+
 const animationDuration = '5s'
 export const viewTransitionClasses = {
   [viewTransitionTypes.open]: createViewTransitionType({
@@ -172,27 +201,9 @@
     },
   } as const satisfies Record<string, ViewTransitionClass>,
   splitscreen: {
-    enter: {
-      [viewTransitionTypes['split-creen:open']]: createViewTransitionType(
-        {new: {animationName: slideIn}},
-        'slideIn',
-      ),
-      debug: redOutlines,
-      default: 'none',
-    },
-    update: {
-      [viewTransitionTypes.crossfade]: 'auto',
-      default: 'none',
-    },
-    exit: {
-      [viewTransitionTypes['split-creen:close']]: createViewTransitionType(
-        {old: {animationName: slideOut}},
-        'slideOut',
-      ),
-      debug: redOutlines,
-      default: 'none',
-    },
-  } as const satisfies Record<string, ViewTransitionClass>,
+    row: createSplitscreenClasses(slideIn, slideOut, 'splitSlide'),
+    column: createSplitscreenClasses(dropIn, dropOut, 'splitDrop'),
+  },
   studio: {
     enter: {
       debug: redOutlines,

diff --git a/plugins/@sanity/themer/src/tool/plugin.tsx b/plugins/@sanity/themer/src/tool/plugin.tsx
--- a/plugins/@sanity/themer/src/tool/plugin.tsx
+++ b/plugins/@sanity/themer/src/tool/plugin.tsx
@@ -23,7 +23,7 @@
  *
  * @alpha
  */
-export interface ThemerToolOptions {
+export interface ThemerToolOptions extends PluginConfig {
   /**
    * The `buildTheme` options that the Studio's configured theme was generated
    * from — the themer starts editing from these, so pass the same object that
@@ -69,10 +69,12 @@
  *
  * @alpha
  */
-export const themerTool = definePlugin<PluginConfig | void>((options) => {
-  const {title = 'Themer'} = options ?? {}
+export const themerTool = definePlugin<ThemerToolOptions | void>((options) => {
+  // No options generate the stock theme, which is what a Studio without a
+  // `theme` in its config gets
+  const {config: baseOptions = {}, title = 'Themer'} = options ?? {}
 
-  const ThemerLayoutProvider = defineThemerLayout({title})
+  const ThemerLayoutProvider = defineThemerLayout({title}, baseOptions)
 
   return {
     name: '@sanity/themer/tool',
@@ -91,18 +93,24 @@
   return index <= 2
 }
 
-function defineThemerLayout(config: Required<PluginConfig>) {
+function defineThemerLayout(config: Required<PluginConfig>, baseOptions: BuildThemeOptions) {
   return function DefinedThemerLayoutProvider(props: LayoutProps) {
     'use memo'
 
-    return <ThemerLayoutProvider config={config}>{props.renderDefault(props)}</ThemerLayoutProvider>
+    return (
+      <ThemerLayoutProvider baseOptions={baseOptions} config={config}>
+        {props.renderDefault(props)}
+      </ThemerLayoutProvider>
+    )
   }
 }
 
 function ThemerLayoutProvider({
+  baseOptions,
   children,
   config,
 }: {
+  baseOptions: BuildThemeOptions
   children: React.ReactNode
   config: Required<PluginConfig>
 }) {
@@ -112,7 +120,7 @@
     prerenderSplitScreen: false,
     open: false,
     split: false,
-    theme: undefined,
+    theme: null,
   })
 
   return (
@@ -122,6 +130,7 @@
           <ToolIsOpenContext value={state.open}>
             <BusyTransitionContext value={busy}>
               <ThemerLayout
+                baseOptions={baseOptions}
                 prerender={state.prerender}
                 prerenderSplitScreen={state.prerenderSplitScreen}
                 split={state.split}

diff --git a/plugins/@sanity/themer/src/tool/reducer.ts b/plugins/@sanity/themer/src/tool/reducer.ts
--- a/plugins/@sanity/themer/src/tool/reducer.ts
+++ b/plugins/@sanity/themer/src/tool/reducer.ts
@@ -45,11 +45,14 @@
         open: !state.open,
         prerender: true,
       }
+    // The split preview belongs to a sidebar session: closing the sidebar
+    // ends the split with it
     case 'close':
       return state.open
         ? {
             ...state,
             open: false,
+            split: false,
           }
         : state
     case 'split-screen:prerender':

diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -500,9 +500,6 @@
       '@vitest/browser-playwright':
         specifier: ^4.1.11
         version: 4.1.11([email protected])([email protected])([email protected])
-      motion:
-        specifier: 'catalog:'
-        version: 13.4.6([email protected])([email protected])
       oxc-transform-react:
         specifier: 'catalog:'
         version: 0.147.0

You can send follow-ups to the cloud agent here.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

There are 8 total unresolved issues (including 6 from previous reviews).

Autofix Details

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Split types clash on sidebar toggle
    • React joins the classes of all active transition types, so adding a split-creen:* type on sidebar open/close gave the Studio the split's blur fade on top of its resize class; the handlers now add only open/close and the split copy's enter/exit classes respond to those types as well.
  • ✅ Fixed: Themer toggle inert on small viewports
    • The navbar now leaves its toggle out below the shared SIDEBAR_MIN_MEDIA_INDEX breakpoint that the layout uses to force open off, so it can no longer be pressed where the sidebar cannot open.

Create PR

Or push these changes by commenting:

@cursor push 13417e98be
Preview (13417e98be)
diff --git a/plugins/@sanity/themer/src/tool/ThemerNavbar.tsx b/plugins/@sanity/themer/src/tool/ThemerNavbar.tsx
--- a/plugins/@sanity/themer/src/tool/ThemerNavbar.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemerNavbar.tsx
@@ -1,12 +1,17 @@
 import {ColorWheelIcon} from '@sanity/icons/ColorWheel'
-import {Box, Button, Text} from '@sanity/ui'
+import {Box, Button, Text, useMediaIndex} from '@sanity/ui'
 import {Tooltip} from '@sanity/ui/tooltip'
 import {lazy, startTransition, Suspense, use, useRef, useTransition, ViewTransition} from 'react'
 import {type NavbarProps} from 'sanity'
 import type {NavbarAction} from 'sanity/_dangerously_use_private_internals_that_do_not_follow_semver'
 
 import {addThemerTransitionType} from './addThemerTransitionType'
-import {PluginConfigContext, ToolDispatchContext, ToolIsOpenContext, ToolSplitIsOpenContext} from './context'
+import {
+  PluginConfigContext,
+  SIDEBAR_MIN_MEDIA_INDEX,
+  ToolDispatchContext,
+  ToolIsOpenContext,
+} from './context'
 
 import {viewTransitionClasses} from './ViewTransitions.css'
 
@@ -17,17 +22,17 @@
   const iconRef = useRef<{spin: () => void}>(null)
   const dispatch = use(ToolDispatchContext)
   const open = use(ToolIsOpenContext)
-  const split = use(ToolSplitIsOpenContext)
 
+  // The sidebar's own type only — a split type would also pick the Studio's
+  // blur fade out of `viewTransitionClasses.studio.update`, which belongs to
+  // toggling the split in place; the split copy comes along on these types too
   const handleOpen = () =>
     startBusyTransition(() => {
-      if(split) addThemerTransitionType('split-creen:open')
       addThemerTransitionType('open')
       dispatch({type: 'open'})
     })
   const handleClose = () =>
     startBusyTransition(() => {
-      if(split) addThemerTransitionType('split-creen:close')
       addThemerTransitionType('close')
       dispatch({type: 'close'})
     })
@@ -78,6 +83,9 @@
 
 export function ThemerNavbar(props: NavbarProps) {
   'use memo'
+  // The sidebar stays closed where there is no room for it, so the toggle
+  // stays out of the navbar there instead of doing nothing when pressed
+  const isMobile = useMediaIndex() < SIDEBAR_MIN_MEDIA_INDEX
   const button = {
     location: 'topbar',
     name: 'themer-topbar',
@@ -89,6 +97,8 @@
   } satisfies NavbarAction
   return props.renderDefault({
     ...props,
-    __internal_actions: [...(props.__internal_actions ?? []), button],
+    __internal_actions: isMobile
+      ? props.__internal_actions
+      : [...(props.__internal_actions ?? []), button],
   })
 }

diff --git a/plugins/@sanity/themer/src/tool/ThemerSidebar.tsx b/plugins/@sanity/themer/src/tool/ThemerSidebar.tsx
--- a/plugins/@sanity/themer/src/tool/ThemerSidebar.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemerSidebar.tsx
@@ -103,7 +103,6 @@
                 mode="bleed"
                 onClick={() =>
                   startTransition(() => {
-                    if(split) addThemerTransitionType('split-creen:close')
                     addThemerTransitionType('close')
                     dispatch({type: 'close'})
                   })

diff --git a/plugins/@sanity/themer/src/tool/ViewTransitions.css.ts b/plugins/@sanity/themer/src/tool/ViewTransitions.css.ts
--- a/plugins/@sanity/themer/src/tool/ViewTransitions.css.ts
+++ b/plugins/@sanity/themer/src/tool/ViewTransitions.css.ts
@@ -118,6 +118,31 @@
 
 const splitScreenFilter = 'blur(20px)'
 
+// The split copy slides in from the side and out to it — whether the split itself
+// is toggling, or the sidebar it comes and goes with is opening or closing
+const splitScreenEnterTransition = createViewTransitionType(
+  {
+    new: {
+      animationName: keyframes({
+        'from': {transform: 'translateX(-100%)', opacity: 0},
+        '10%': {opacity: 0},
+      }),
+    },
+  },
+  'slideIn',
+)
+const splitScreenExitTransition = createViewTransitionType(
+  {
+    old: {
+      animationName: keyframes({
+        'to': {transform: 'translateX(-100%)', opacity: 0},
+        '90%': {opacity: 0},
+      }),
+    },
+  },
+  'slideOut',
+)
+
 const animationDuration = '5s'
 export const viewTransitionClasses = {
   [viewTransitionTypes.open]: createViewTransitionType({
@@ -175,10 +200,8 @@
   } as const satisfies Record<string, ViewTransitionClass>,
   splitscreen: {
     enter: {
-      [viewTransitionTypes['split-creen:open']]: createViewTransitionType(
-        {new: {animationName: keyframes({from: {transform: 'translateX(-100%)', opacity: 0}, '10%': {opacity: 0}})}},
-        'slideIn',
-      ),
+      [viewTransitionTypes['split-creen:open']]: splitScreenEnterTransition,
+      [viewTransitionTypes.open]: splitScreenEnterTransition,
       debug: redOutlines,
       default: 'none',
     },
@@ -187,10 +210,8 @@
       default: 'none',
     },
     exit: {
-      [viewTransitionTypes['split-creen:close']]: createViewTransitionType(
-        {old: {animationName: keyframes({to: {transform: 'translateX(-100%)', opacity: 0}, '90%': {opacity: 0}})}},
-        'slideOut',
-      ),
+      [viewTransitionTypes['split-creen:close']]: splitScreenExitTransition,
+      [viewTransitionTypes.close]: splitScreenExitTransition,
       debug: redOutlines,
       default: 'none',
     },

diff --git a/plugins/@sanity/themer/src/tool/context.ts b/plugins/@sanity/themer/src/tool/context.ts
--- a/plugins/@sanity/themer/src/tool/context.ts
+++ b/plugins/@sanity/themer/src/tool/context.ts
@@ -62,6 +62,15 @@
   return context
 }
 
+/**
+ * The narrowest media index the sidebar shows at — themer does not support
+ * mobile yet, so below it the Studio keeps the whole width and the navbar
+ * leaves its toggle out rather than offering one that opens nothing.
+ *
+ * @internal
+ */
+export const SIDEBAR_MIN_MEDIA_INDEX = 3
+
 /** @internal */
 export const ToolIsOpenContext = createContext<boolean>(false)
 /** @internal */

diff --git a/plugins/@sanity/themer/src/tool/plugin.tsx b/plugins/@sanity/themer/src/tool/plugin.tsx
--- a/plugins/@sanity/themer/src/tool/plugin.tsx
+++ b/plugins/@sanity/themer/src/tool/plugin.tsx
@@ -7,6 +7,7 @@
   BusyTransitionContext,
   type PluginConfig,
   PluginConfigContext,
+  SIDEBAR_MIN_MEDIA_INDEX,
   StartBusyTransitionContext,
   ToolDispatchContext,
   ToolIsOpenContext,
@@ -111,7 +112,7 @@
     theme: null,
   })
   const index = useMediaIndex()
-  const isMobile = index <= 2
+  const isMobile = index < SIDEBAR_MIN_MEDIA_INDEX
   // @TODO Themer does not yet support mobile
   const open = state.open && !isMobile
   // Split screen needs some space

You can send follow-ups to the cloud agent here.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 8 total unresolved issues (including 7 from previous reviews).

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Hidden list leaves picker busy
    • Confirmed with a temporary test that a pick landing under a hidden left busy stuck, and fixed it by clearing busy in useImagePalette based only on whether the pick is still the latest one, instead of also requiring the effects to be mounted.

Create PR

Or push these changes by commenting:

@cursor push d237885b68
Preview (d237885b68)
diff --git a/plugins/@sanity/themer/src/tool/useImagePalette.ts b/plugins/@sanity/themer/src/tool/useImagePalette.ts
--- a/plugins/@sanity/themer/src/tool/useImagePalette.ts
+++ b/plugins/@sanity/themer/src/tool/useImagePalette.ts
@@ -40,9 +40,12 @@
 
       setBusy(true)
 
+      // Whether this pick is the one the busy state belongs to: a later pick
+      // takes it over
+      const isLatest = () => latestPickRef.current === pick
       // Whether this pick still matters: it is the latest one and the
       // component that asked for it is still around
-      const isCurrent = () => mountedRef.current && latestPickRef.current === pick
+      const isCurrent = () => mountedRef.current && isLatest()
 
       const extract = async () => {
         const palette = extractImagePalette(await readImagePixels(file))
@@ -61,7 +64,10 @@
           if (isCurrent()) toast.push({status: 'error', title: 'Could not read that image'})
         })
         .finally(() => {
-          if (isCurrent()) setBusy(false)
+          // Not held back by the mount: an `<Activity>` that goes hidden
+          // unmounts the effects while it keeps the state, so a pick that
+          // lands while hidden has to let go of the busy state all the same
+          if (isLatest()) setBusy(false)
         })
     },
     [toast],

You can send follow-ups to the cloud agent here.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

There are 9 total unresolved issues (including 7 from previous reviews).

Autofix Details

Bugbot Autofix prepared a fix for 1 of the 2 issues found in the latest run.

  • ✅ Fixed: Theme switch flag stays on too long
    • The effect that adds the crossfade transition type now also sends layout.transitioned, so the machine leaves switching as the cross-fade starts instead of lingering for the full 2s fallback and crossfading in-place color edits.

Create PR

Or push these changes by commenting:

@cursor push 1530b99147
Preview (1530b99147)
diff --git a/plugins/@sanity/themer/src/tool/ThemerLayout.tsx b/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
--- a/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
@@ -153,6 +153,9 @@
     startTransition(() => {
       if(switching) {
         addThemerTransitionType('crossfade')
+        // The cross-fade is under way, so the machine is no longer switching —
+        // the in-place color edits that may follow track the pointer instead
+        send({type: 'layout.transitioned'})
       }
       if (activeOptions === null) {
         dispatch({type: 'unset-theme'})
@@ -160,7 +163,7 @@
         dispatch({type: 'set-theme', theme: activeOptions})
       }
     })
-  }, [activeOptions, dispatch, switching])
+  }, [activeOptions, dispatch, send, switching])
 
   // The Studio paints the body with its configured theme from above this
   // layout, and Safari tints its chrome from the body — so the applied theme

You can send follow-ups to the cloud agent here.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 6 total unresolved issues (including 5 from previous reviews).

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Split toggle dispatches unknown action
    • The toggle reused the misspelled split-creen:* view-transition type as its reducer action, so it now dispatches the split-screen:open/split-screen:close actions toolReducer actually handles while still adding the existing transition type, which also clears the TS2322 error on that dispatch.

Create PR

Or push these changes by commenting:

@cursor push 3993b2c27c
Preview (3993b2c27c)
diff --git a/plugins/@sanity/themer/src/tool/ThemerSidebar.tsx b/plugins/@sanity/themer/src/tool/ThemerSidebar.tsx
--- a/plugins/@sanity/themer/src/tool/ThemerSidebar.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemerSidebar.tsx
@@ -77,9 +77,8 @@
                       mode="bleed"
                       onClick={() =>
                         startTransition(() => {
-                          const type = split ? 'split-creen:close' : 'split-creen:open'
-                          addThemerTransitionType(type)
-                          dispatch({type})
+                          addThemerTransitionType(split ? 'split-creen:close' : 'split-creen:open')
+                          dispatch({type: split ? 'split-screen:close' : 'split-screen:open'})
                         })
                       }
                       onMouseEnter={() =>

You can send follow-ups to the cloud agent here.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

There are 6 total unresolved issues (including 4 from previous reviews).

Autofix Details

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Config theme cannot be restored
    • The tool reducer now initializes its theme from the stored active theme so null only ever means the configured theme, and the mount-time initialOptions fallback in ThemerLayout was removed.
  • ✅ Fixed: Sidebar header height never applied
    • ResizableSidebar now takes a navbarHeight prop from ThemerLayout and forwards it to ThemerSidebar, so the header matches the measured Studio navbar height again.

Create PR

Or push these changes by commenting:

@cursor push a4dcf6c634
Preview (a4dcf6c634)
diff --git a/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx b/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
--- a/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
+++ b/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
@@ -47,9 +47,10 @@
  * @internal
  */
 export default function ResizableSidebar({
+  navbarHeight,
   overlay,
   split,
-}: {overlay: boolean} & Pick<ToolReducerState, 'split'>) {
+}: {navbarHeight: number | null; overlay: boolean} & Pick<ToolReducerState, 'split'>) {
   const [width, setWidth] = useState(readStoredWidth)
   const [dragging, setDragging] = useState(false)
   const drag = useRef<{pointerId: number; startX: number; startWidth: number} | null>(null)
@@ -126,7 +127,7 @@
           />
         )}
         <Box className={content} height="fill" overflow="hidden">
-          <ThemerSidebar split={split} />
+          <ThemerSidebar navbarHeight={navbarHeight} split={split} />
         </Box>
       </Card>
     </Layer>

diff --git a/plugins/@sanity/themer/src/tool/ThemerLayout.tsx b/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
--- a/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
@@ -144,18 +144,9 @@
     () => resolveThemes(stored, baseOptions),
     [stored, baseOptions],
   )
-  const [initialOptions] = useState(() => {
-    const {active} = resolveThemes(selectStoredState(actorRef.getSnapshot()), baseOptions)
-    return active.source === 'config' ? null : active.options
-  })
   const theme = useMemo(
-    () =>
-      currentThemeOptions !== null
-        ? buildTheme(currentThemeOptions)
-        : initialOptions !== null
-          ? buildTheme(initialOptions)
-          : null,
-    [currentThemeOptions, initialOptions],
+    () => (currentThemeOptions === null ? null : buildTheme(currentThemeOptions)),
+    [currentThemeOptions],
   )
 
   // The Studio paints the body with its configured theme from above this
@@ -242,7 +233,13 @@
                   update={viewTransitionClasses.sidebar.update}
                   exit={viewTransitionClasses.sidebar.exit}
                 >
-                  {prerender && <ResizableSidebar overlay={isMobile} split={split} />}
+                  {prerender && (
+                    <ResizableSidebar
+                      navbarHeight={navbarHeight}
+                      overlay={isMobile}
+                      split={split}
+                    />
+                  )}
                 </ViewTransition>
               </Activity>
             </Flex>

diff --git a/plugins/@sanity/themer/src/tool/plugin.tsx b/plugins/@sanity/themer/src/tool/plugin.tsx
--- a/plugins/@sanity/themer/src/tool/plugin.tsx
+++ b/plugins/@sanity/themer/src/tool/plugin.tsx
@@ -9,13 +9,33 @@
   ToolIsOpenContext,
   ToolSplitIsOpenContext,
 } from './context'
-import {toolReducer} from './reducer'
+import {toolReducer, type ToolReducerState} from './reducer'
+import {readStoredState} from './storage'
 import {ThemerLayout} from './ThemerLayout'
 import {ThemerNavbar} from './ThemerNavbar'
+import {resolveThemes} from './themes'
 import {useIsMobile} from './useIsMobile'
 import {useIsTooSmallForSplitScreen} from './useIsTooSmallForSplitScreen'
 
 /**
+ * The tool starts out with the theme the last session left applied, so that
+ * `theme: null` only ever means the Studio's configured theme — picking that
+ * one back restores it.
+ */
+function createInitialState(): ToolReducerState {
+  // The same (not yet configurable) base options the layout resolves with
+  const {active} = resolveThemes(readStoredState(), {})
+
+  return {
+    prerender: false,
+    prerenderSplitScreen: false,
+    open: false,
+    split: false,
+    theme: active.source === 'config' ? null : active.options,
+  }
+}
+
+/**
  * Options for the {@link themerTool} plugin.
  *
  * This is experimental and may change or be removed in any release without
@@ -100,13 +120,7 @@
   children: React.ReactNode
   config: Required<PluginConfig>
 }) {
-  const [state, dispatch] = useReducer(toolReducer, {
-    prerender: false,
-    prerenderSplitScreen: false,
-    open: false,
-    split: false,
-    theme: null,
-  })
+  const [state, dispatch] = useReducer(toolReducer, undefined, createInitialState)
   const isMobile = useIsMobile()
   const isTooSmallForSplitScreen = useIsTooSmallForSplitScreen()
   // @TODO Themer does not yet support mobile

You can send follow-ups to the cloud agent here.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

There are 4 total unresolved issues (including 2 from previous reviews).

Autofix Details

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Config theme never unsets
    • The crossfader now compares the resolved options against undefined (what resolveActiveThemeOptions returns for the config theme) instead of null, so unset-theme runs and buildTheme no longer replaces the Studio's configured theme with the stock one.
  • ✅ Fixed: Stale snapshot can win
    • PersistActorSnapshot now writes the persisted snapshot synchronously in the same change as the machine's persist action instead of deferring it to idle time, so a reload can never restore a snapshot older than the stored state.

Create PR

Or push these changes by commenting:

@cursor push 198cd7471d
Preview (198cd7471d)
diff --git a/plugins/@sanity/themer/src/tool/ThemerLayout.tsx b/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
--- a/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemerLayout.tsx
@@ -301,7 +301,7 @@
         if (switching) {
           addThemerTransitionType('crossfade')
         }
-        if (theme === null) {
+        if (theme === undefined) {
           dispatch({type: 'unset-theme'})
         } else {
           dispatch({type: 'set-theme', theme})
@@ -335,31 +335,17 @@
 function PersistActorSnapshot() {
   const actorRef = use(ToolActorRefContext)
 
+  // The snapshot is written in the same change as the state the machine's
+  // `persist` writes, and never later: a snapshot that lags behind is the one
+  // the actor restores from on the next load, and the machine would then
+  // persist those older themes over the newer ones that were stored
+  // @TODO use a selector or similar to only subscribe to changes that are relevant to the persisted snapshot
+  // @TODO use WebLocks and BroadcastChannel to ensure the snapshot is persisted in a consistent way cross tabs
   useEffect(() => {
-    let cancel: any
-    function cancelOrClear() {
-      if ('cancelIdleCallback' in window) {
-        cancelIdleCallback(cancel)
-      } else {
-        clearTimeout(cancel)
-      }
-    }
-
-    // @TODO use a selector or similar to only subscribe to changes that are relevant to the persisted snapshot
-    // @TODO use WebLocks and BroadcastChannel to ensure the snapshot is persisted in a consistent way cross tabs
     const subscription = actorRef.subscribe(() => {
-      cancelOrClear()
-      const callback = () => {
-        const persistedSnapshot = actorRef.getPersistedSnapshot()
-        writePersistedSnapshot(persistedSnapshot)
-      }
-      cancel =
-        'cancelIdleCallback' in window ? requestIdleCallback(callback) : setTimeout(callback, 1_000)
+      writePersistedSnapshot(actorRef.getPersistedSnapshot())
     })
-    return () => {
-      subscription.unsubscribe()
-      cancelOrClear()
-    }
+    return () => subscription.unsubscribe()
   }, [actorRef])
 
   return null

You can send follow-ups to the cloud agent here.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 3 potential issues.

There are 4 total unresolved issues (including 1 from previous review).

Autofix Details

Bugbot Autofix prepared fixes for all 3 issues found in the latest run.

  • ✅ Fixed: Theme rebuilt on every render
    • The applied theme is now built in a useMemo keyed on the reducer's state.theme options, so sidebar interactions no longer hand the Studio-wide styled-components context a new theme object.
  • ✅ Fixed: Snapshot persist can throw
    • writePersistedSnapshot now wraps its localStorage.setItem in a try/catch that swallows the failure, like every other write in the module.
  • ✅ Fixed: Body background no longer follows theme
    • A small BodyBackground component restores the removed effect, writing the applied theme's scheme background onto document.body and restoring the previous value on cleanup.

Create PR

Or push these changes by commenting:

@cursor push a05a619216
Preview (a05a619216)
diff --git a/plugins/@sanity/themer/src/tool/plugin.tsx b/plugins/@sanity/themer/src/tool/plugin.tsx
--- a/plugins/@sanity/themer/src/tool/plugin.tsx
+++ b/plugins/@sanity/themer/src/tool/plugin.tsx
@@ -1,7 +1,8 @@
 import {ThemeProvider} from '@sanity/ui'
-import {useReducer, use, useState} from 'react'
+import type {RootTheme} from '@sanity/ui/theme'
+import {use, useEffect, useMemo, useReducer, useState} from 'react'
 import {browser} from 'react-dom'
-import {definePlugin, type LayoutProps} from 'sanity'
+import {definePlugin, type LayoutProps, useColorSchemeValue} from 'sanity'
 
 import {buildTheme} from '../theme/buildTheme'
 import type {BuildThemeOptions} from '../theme/options'
@@ -119,8 +120,17 @@
   // Split screen needs some space
   const split = state.split && !isTooSmallForSplitScreen
 
+  // The theme identity must be stable between renders: it feeds the
+  // styled-components theme context for the whole Studio, and rebuilding it
+  // would re-render everything. Keying on the options, which the reducer only
+  // replaces when they change, keeps it stable across every other render.
+  const theme = useMemo(
+    () => (state.theme === null ? undefined : buildTheme(state.theme)),
+    [state.theme],
+  )
+
   return (
-    <ThemeProvider theme={(state.theme !== null ? buildTheme(state.theme) : null) ?? undefined}>
+    <ThemeProvider theme={theme}>
       <PluginConfigContext value={config}>
         <ThemerLayout
           dispatch={dispatch}
@@ -133,6 +143,33 @@
           {children}
         </ThemerLayout>
       </PluginConfigContext>
+      <BodyBackground theme={theme} />
     </ThemeProvider>
   )
 }
+
+/**
+ * The Studio paints the body with its configured theme from above this layout,
+ * and Safari tints its chrome from the body — so the applied theme has to
+ * reach the body too, in the scheme the Studio is showing.
+ */
+function BodyBackground({theme}: {theme: RootTheme | undefined}) {
+  const scheme = useColorSchemeValue()
+
+  useEffect(() => {
+    const background = theme?.v2?.color[scheme].default.bg
+
+    if (background === undefined) return undefined
+
+    const {style} = document.body
+    const previous = style.backgroundColor
+
+    style.backgroundColor = background
+
+    return () => {
+      style.backgroundColor = previous
+    }
+  }, [scheme, theme])
+
+  return null
+}

diff --git a/plugins/@sanity/themer/src/tool/storage.ts b/plugins/@sanity/themer/src/tool/storage.ts
--- a/plugins/@sanity/themer/src/tool/storage.ts
+++ b/plugins/@sanity/themer/src/tool/storage.ts
@@ -320,5 +320,9 @@
 export function writePersistedSnapshot(
   snapshot: ReturnType<ActorRefFrom<typeof themerMachine>['getPersistedSnapshot']>,
 ): void {
-  localStorage.setItem(PERSIST_SNAPSHOT_KEY, JSON.stringify(snapshot))
+  try {
+    localStorage.setItem(PERSIST_SNAPSHOT_KEY, JSON.stringify(snapshot))
+  } catch {
+    // Storage can be unavailable (e.g. private browsing) — the snapshot just won't persist
+  }
 }

You can send follow-ups to the cloud agent here.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 3 total unresolved issues (including 2 from previous reviews).

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Debug five-second transition duration
    • Confirmed the leftover debug value and changed the open/close view-transition animationDuration from 5s to 320ms so it matches the shared layout timing.

Create PR

Or push these changes by commenting:

@cursor push e15f695d3b
Preview (e15f695d3b)
diff --git a/.changeset/wide-rocks-clean.md b/.changeset/wide-rocks-clean.md
new file mode 100644
--- /dev/null
+++ b/.changeset/wide-rocks-clean.md
@@ -1,0 +1,5 @@
+---
+'@sanity/themer': minor
+---
+
+Adopt <Activity>, <ViewTransition> and React.lazy APIs according to best practice. Removes the top-level default theme config, it will be added back again later

diff --git a/dev/storybook/package.json b/dev/storybook/package.json
--- a/dev/storybook/package.json
+++ b/dev/storybook/package.json
@@ -31,7 +31,6 @@
     "@vanilla-extract/css": "catalog:",
     "@vitejs/plugin-react": "^6.1.1",
     "@vitest/browser-playwright": "^4.1.11",
-    "motion": "catalog:",
     "oxc-transform-react": "catalog:",
     "playwright": "^1.63.0",
     "react": "catalog:",

diff --git a/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx b/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
--- a/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
+++ b/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
@@ -1,13 +1,11 @@
 import {Button, Flex, Text} from '@sanity/ui'
 import type {Meta, StoryObj} from '@storybook/react-vite'
-import {animate, useMotionValue} from 'motion/react'
-import {useEffect} from 'react'
+import {useRef} from 'react'
 
-import {AnimatedColorWheelIcon} from '../../../../../plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon'
-import {ANIMATION_DURATION} from '../../../../../plugins/@sanity/themer/src/tool/colorWheel'
+import AnimatedColorWheelIcon from '../../../../../plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon'
 
 interface WheelArgs {
-  progress: number
+  busy: boolean
 }
 
 /**
@@ -21,54 +19,41 @@
 export default meta
 type Story = StoryObj<WheelArgs>
 
-function NavbarButton() {
-  const progress = useMotionValue(0)
+function NavbarButton(props: {busy: boolean}) {
+  const {busy} = props
+  const ref = useRef<{spin: () => void}>(null)
 
-  const play = () => {
-    // A run in progress plays out, like on the Studio navbar
-    if (progress.isAnimating()) return
-
-    animate(progress, [0, 1], {duration: ANIMATION_DURATION, ease: 'linear'})
-  }
-
   return (
     <Flex align="center" gap={3}>
       <Button
+        aria-busy={busy}
         aria-label="Themer"
-        icon={<AnimatedColorWheelIcon progress={progress} />}
+        icon={<AnimatedColorWheelIcon busy={busy} ref={ref} />}
         mode="bleed"
-        onMouseEnter={play}
+        onMouseEnter={() => ref.current?.spin()}
+        selected={busy}
       />
       <Text muted size={1}>
-        Hover the button to play the animation
+        {busy
+          ? 'The wheel laps while the toggle is busy'
+          : 'Hover the button to play the animation'}
       </Text>
     </Flex>
   )
 }
 
-/** The navbar toggle, which plays the animation on hover */
+/** The navbar toggle, which plays the animation once on hover */
 export const Default: Story = {
-  render: () => <NavbarButton />,
+  render: () => <NavbarButton busy={false} />,
 }
 
-function WheelAtProgress(props: {progress: number}) {
-  const progress = useMotionValue(props.progress)
-
-  useEffect(() => {
-    progress.set(props.progress)
-  }, [progress, props.progress])
-
-  return (
-    <Text size={4}>
-      <AnimatedColorWheelIcon progress={progress} />
-    </Text>
-  )
+/**
+ * The navbar toggle while the sidebar loads: the wheel laps from wherever a hover's run has got
+ * to, and the lap in progress plays out once the toggle is no longer busy
+ */
+export const Busy: Story = {
+  args: {busy: true},
+  argTypes: {busy: {control: {type: 'boolean'}}},
+  parameters: {controls: {include: ['busy']}},
+  render: (args) => <NavbarButton busy={args.busy} />,
 }
-
-/** The wheel at any point of the animation, from 0 to 1 */
-export const Progress: Story = {
-  args: {progress: 0.5},
-  argTypes: {progress: {control: {type: 'range', min: 0, max: 1, step: 0.01}}},
-  parameters: {controls: {include: ['progress']}},
-  render: (args) => <WheelAtProgress progress={args.progress} />,
-}

diff --git a/dev/test-studio/sanity.config.ts b/dev/test-studio/sanity.config.ts
--- a/dev/test-studio/sanity.config.ts
+++ b/dev/test-studio/sanity.config.ts
@@ -88,6 +88,7 @@
     name: 'home',
     title: 'Home',
     icon: HomeIcon,
+    beta: {...beta, variants: {enabled: true}},
     plugins: [
       // Order matters for the top navigation: Workspaces Home, Structure, then
       // the most-used plugin tools first.
@@ -137,10 +138,10 @@
       vercelWidgetExample(),
       contentGraphView(),
       scriptRunnerTool(),
-      themerTool(),
       debugSecrets(),
       vercelProtectionBypassTool(),
       visionTool(),
+      themerTool({title: 'Themer 2.0'}),
     ],
   }),
   // Re-registers `internationalizedArray` with async languages loaded from
@@ -148,34 +149,34 @@
   createWorkspace({
     name: 'internationalized-array-async-languages',
     title: 'internationalized-array: Async Languages',
-    plugins: [internationalizedArrayAsyncLanguages()],
+    plugins: [internationalizedArrayAsyncLanguages(), themerTool()],
   }),
   // Demos the translations tab at the internationalized-array level, with its own
   // `internationalizedArray` language set (en/de/no_nb/is) — conflicts with Home.
   createWorkspace({
     name: 'i18n-array-translation',
     title: 'sanity-translations-tab: i18n Array',
-    plugins: [i18nArrayTranslationExample()],
+    plugins: [i18nArrayTranslationExample(), themerTool()],
   }),
   // A second `documentInternationalization` registration (for docI18nLocalizedPage)
   // that cannot coexist with Home's `lesson` configuration.
   createWorkspace({
     name: 'doc-i18n-translation',
     title: 'document-internationalization: Translations',
-    plugins: [documentInternationalizationTranslationExample()],
+    plugins: [documentInternationalizationTranslationExample(), themerTool()],
   }),
   // Registers its own `internationalizedArray` (en_US/fr) and `product`/`category`
   // types (`product` collides with the workflow workspace).
   createWorkspace({
     name: 'sfcc',
     title: 'sfcc: Salesforce Commerce Cloud',
-    plugins: [sfccExample()],
+    plugins: [sfccExample(), themerTool()],
   }),
   // Defines `product`/`article`; `product` collides with the sfcc workspace.
   createWorkspace({
     name: 'workflow',
     title: 'workflow: Document Workflow',
-    plugins: [structureTool(), workflowExample()],
+    plugins: [structureTool(), workflowExample(), themerTool()],
   }),
   // Destination workspace for @sanity/cross-dataset-duplicator: uses a
   // different dataset so it can be picked as a duplication target.
@@ -186,6 +187,6 @@
     name: 'cross-dataset-duplicator-target',
     title: 'cross-dataset-duplicator: Target',
     basePath: '/cross-dataset-duplicator-target',
-    plugins: [structureTool(), crossDatasetDuplicatorExample()],
+    plugins: [structureTool(), crossDatasetDuplicatorExample(), themerTool({title: 'Not Themer'})],
   },
 ])

diff --git a/plugins/@sanity/themer/package.json b/plugins/@sanity/themer/package.json
--- a/plugins/@sanity/themer/package.json
+++ b/plugins/@sanity/themer/package.json
@@ -29,6 +29,12 @@
     "*.css"
   ],
   "types": "./dist/index.d.ts",
+  "imports": {
+    "#constants": "./src/tool/constants.ts",
+    "#context": "./src/tool/context.ts",
+    "#reducer": "./src/tool/reducer.ts",
+    "#types": "./src/tool/types.ts"
+  },
   "exports": {
     ".": "./src/index.ts",
     "./legacy": "./src/legacy/index.ts",
@@ -68,10 +74,12 @@
     "@sanity/ui": "catalog:",
     "@vanilla-extract/dynamic": "catalog:",
     "@xstate/react": "catalog:",
+    "dequal": "catalog:",
     "motion": "catalog:",
     "react-refractor": "^4.0.0",
     "refractor": "^5.0.0",
     "scroll-into-view-if-needed": "catalog:",
+    "valibot": "catalog:",
     "xstate": "catalog:"
   },
   "devDependencies": {
@@ -82,7 +90,6 @@
     "@types/react": "catalog:",
     "@types/react-dom": "catalog:",
     "@vanilla-extract/css": "catalog:",
-    "jsdom": "catalog:",
     "lightningcss": "^1.33.0",
     "oxc-transform-react": "catalog:",
     "react": "catalog:",
@@ -93,6 +100,7 @@
   },
   "peerDependencies": {
     "react": "^19.3.0",
+    "react-dom": "^19.3.0",
     "sanity": "^3 || ^4 || ^5 || ^6"
   },
   "peerDependenciesMeta": {

diff --git a/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx b/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
--- a/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
+++ b/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
@@ -1,7 +1,13 @@
-import {usePrefersReducedMotion} from '@sanity/ui'
-import {motion, MotionValue, useTransform} from 'motion/react'
+import {motion, MotionValue, useTransform, animate, useMotionValue} from 'motion/react'
+import {useEffect, useImperativeHandle} from 'react'
 
-import {isSliceFilled, SLICE_COLORS, SLICE_COUNT, wheelRotation} from './colorWheel'
+import {
+  isSliceFilled,
+  SLICE_COLORS,
+  SLICE_COUNT,
+  wheelRotation,
+  ANIMATION_DURATION,
+} from './colorWheel'
 
 /**
  * The geometry of `ColorWheelIcon` from `@sanity/icons`: a ring between two
@@ -67,13 +73,59 @@
  *
  * @internal
  */
-export function AnimatedColorWheelIcon(props: {progress: MotionValue<number>}) {
-  const {progress} = props
-  const prefersReducedMotion = usePrefersReducedMotion()
-  const rotate = useTransform(progress, (value) =>
-    prefersReducedMotion ? 0 : wheelRotation(value),
+export default function AnimatedColorWheelIcon({
+  busy,
+  ref,
+}: {
+  busy: boolean
+  ref: React.Ref<{spin: () => void}>
+}) {
+  const progress = useMotionValue(0)
+  const rotate = useTransform(progress, (value) => wheelRotation(value))
+
+  useImperativeHandle(
+    ref,
+    () => ({
+      spin: () => {
+        // A run in progress plays out — hovering again does not cut it short
+        if (progress.isAnimating()) return
+
+        animate(progress, [0, 1], {duration: ANIMATION_DURATION, ease: 'linear'})
+      },
+    }),
+    [progress],
   )
 
+  // Laps from wherever a hover's run has got to, so the wheel never jumps,
+  // and the lap in progress as the code arrives plays out: at rest, the wheel
+  // looks like the icon again
+  useEffect(() => {
+    if (!busy) return undefined
+
+    let looping = false
+    const raf = setTimeout(() => {
+      looping = true
+      const lap = (from: number) => {
+        animate(progress, [from, 1], {
+          duration: (1 - from) * ANIMATION_DURATION,
+          ease: 'linear',
+          onComplete: () => {
+            if (looping) lap(0)
+          },
+        })
+      }
+
+      lap(progress.get())
+    }, 160)
+
+    return () => {
+      clearTimeout(raf)
+      looping = false
+    }
+  }, [busy, progress])
+
+  useEffect(() => () => progress.stop(), [progress])
+
   return (
     <motion.svg
       data-sanity-icon="color-wheel"
@@ -85,7 +137,7 @@
       xmlns="http://www.w3.org/2000/svg"
     >
       {SLICE_COLORS.map((color, index) => (
-        <Slice index={index} key={color} progress={progress} />
+        <Slice key={color} index={index} progress={progress} />
       ))}
       <path d={OUTLINE} stroke="currentColor" strokeLinejoin="round" strokeWidth={1.2} />
     </motion.svg>

diff --git a/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx b/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx
--- a/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx
+++ b/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx
@@ -178,13 +178,14 @@
 
                 return (
                   <Tooltip
+                    key={key}
                     animate
                     content={
                       <Text size={1}>
                         {hex ? `${title} · ${hex}` : `No ${title.toLowerCase()} color`}
                       </Text>
                     }
-                    key={key}
+
                     placement="bottom"
                     portal
                   >
@@ -213,9 +214,9 @@
                 {variants.map(({variant, title, options: variantOptions}) => (
                   // oxlint-disable-next-line control-has-associated-label -- the title below the thumbnail is the label, deeper than the rule looks
                   <button
+                    key={variant}
                     aria-pressed={variant === current}
                     className={variantButton}
-                    key={variant}
                     onClick={() => onVariant(variant)}
                     type="button"
                   >

diff --git a/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx b/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx
--- a/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx
+++ b/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx
@@ -1,6 +1,8 @@
 import {Button, Card, Dialog, Flex, Stack, Text, TextInput} from '@sanity/ui'
 import {useState} from 'react'
 
+import type {ThemerProps} from '#types'
+
 import {useThemeCodes} from './useThemeCodes'
 
 /**
@@ -9,9 +11,9 @@
  *
  * @internal
  */
-export function PasteThemeDialog(props: {onClose: () => void}) {
-  const {onClose} = props
-  const {addThemeFromText} = useThemeCodes()
+export function PasteThemeDialog(props: {onClose: () => void} & Pick<ThemerProps, 'actorRef'>) {
+  const {actorRef, onClose} = props
+  const {addThemeFromText} = useThemeCodes({actorRef})
   const [text, setText] = useState('')
   const [invalid, setInvalid] = useState(false)
 

diff --git a/plugins/@sanity/themer/src/tool/PersistActorSnapshot.tsx b/plugins/@sanity/themer/src/tool/PersistActorSnapshot.tsx
new file mode 100644
--- /dev/null
+++ b/plugins/@sanity/themer/src/tool/PersistActorSnapshot.tsx
@@ -1,0 +1,37 @@
+import {useEffect} from 'react'
+
+import type {ThemerProps} from '#types'
+
+import {writePersistedSnapshot} from './storage'
+
+export function PersistActorSnapshot({actorRef}: Pick<ThemerProps, 'actorRef'>) {
+  useEffect(() => {
+    let cancel: any
+    function cancelOrClear() {
+      if ('cancelIdleCallback' in window) {
+        cancelIdleCallback(cancel)
+      } else {
+        clearTimeout(cancel)
+      }
+    }
+
+    // @TODO use a selector or similar to only subscribe to changes that are relevant to the persisted snapshot
+    // @TODO use WebLocks and BroadcastChannel to ensure the snapshot is persisted in a consistent way cross tabs
+    // @TODO actually only run this when the document is visible or has lock or something?
+    const subscription = actorRef.subscribe(() => {
+      cancelOrClear()
+      const callback = () => {
+        const persistedSnapshot = actorRef.getPersistedSnapshot()
+        writePersistedSnapshot(persistedSnapshot)
+      }
+      cancel =
+        'cancelIdleCallback' in window ? requestIdleCallback(callback) : setTimeout(callback, 1_000)
+    })
+    return () => {
+      subscription.unsubscribe()
+      cancelOrClear()
+    }
+  }, [actorRef])
+
+  return null
+}

diff --git a/plugins/@sanity/themer/src/tool/RemovedThemes.tsx b/plugins/@sanity/themer/src/tool/RemovedThemes.tsx
--- a/plugins/@sanity/themer/src/tool/RemovedThemes.tsx
+++ b/plugins/@sanity/themer/src/tool/RemovedThemes.tsx
@@ -1,6 +1,7 @@
 import {Box, Button, Flex, Stack, Text} from '@sanity/ui'
 
-import {useThemer} from './context'
+import type {ThemerProps} from '#types'
+
 import {ScrollArea} from './ScrollArea'
 import {displayTitle} from './themes'
 import {ThemeThumbnail} from './ThemeThumbnail'
@@ -15,14 +16,12 @@
  *
  * @internal
  */
-export function RemovedThemes() {
-  const {removed, send} = useThemer()
-
+export function RemovedThemes({actorRef, removed}: Pick<ThemerProps, 'actorRef' | 'removed'>) {
   return (
     <ScrollArea padding={3}>
       <Stack gap={5}>
         {removed.map((theme) => (
-          <Stack gap={3} key={theme.slug}>
+          <Stack key={theme.slug} gap={3}>
             <Box className={removedThumbnail}>
               <ThemeThumbnail options={theme.options} />
             </Box>
@@ -32,14 +31,14 @@
             <Flex gap={2} justify="center">
               <Button
                 mode="ghost"
-                onClick={() => send({type: 'theme.restore', slug: theme.slug})}
+                onClick={() => actorRef.send({type: 'theme.restore', slug: theme.slug})}
                 padding={2}
                 text="Restore"
               />
               {theme.source === 'custom' && (
                 <Button
                   mode="ghost"
-                  onClick={() => send({type: 'theme.delete', slug: theme.slug})}
+                  onClick={() => actorRef.send({type: 'theme.delete', slug: theme.slug})}
                   padding={2}
                   text="Delete"
                   tone="critical"

diff --git a/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts b/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts
--- a/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts
+++ b/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts
@@ -1,26 +1,10 @@
-import {createContainer, createViewTransition, style} from '@vanilla-extract/css'
+import {createContainer, style} from '@vanilla-extract/css'
 
-/**
- * The view transition group of the sidebar, which the split preview's
- * transition (see `ThemerLayout.css.ts`) leaves alone: it never animates, and
- * the Studio copies animating underneath never paint over it
- */
-export const sidebarTransition = createViewTransition()
-
 /** The sidebar's content, which the content's layout queries — as wide as the sidebar itself */
 export const sidebarContent = createContainer()
 
 export const sidebar = style({
   flex: 'none',
-  viewTransitionName: sidebarTransition,
-  selectors: {
-    // On small screens the sidebar covers the Studio instead of standing next to it
-    "&[data-overlay='true']": {
-      position: 'absolute',
-      inset: 0,
-      width: 'auto',
-    },
-  },
 })
 
 /**

diff --git a/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx b/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
--- a/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
+++ b/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
@@ -1,6 +1,9 @@
-import {Box, Card, Layer} from '@sanity/ui'
-import {useCallback, useEffect, useRef, useState} from 'react'
+import {BoundaryElementProvider, Box, Card, Layer} from '@sanity/ui'
+import {startTransition, useCallback, useEffect, useRef, useState} from 'react'
 
+import type {ThemerProps} from '#types'
+
+import {PersistActorSnapshot} from './PersistActorSnapshot'
 import {MAXIMUM_WIDTH, MINIMUM_WIDTH} from './sidebarWidth'
 import {ThemerSidebar} from './ThemerSidebar'
 
@@ -45,12 +48,17 @@
  *
  * @internal
  */
-export default function ResizableSidebar(props: {overlay: boolean}) {
-  const {overlay} = props
+export default function ResizableSidebar({
+  actorRef,
+  dispatch,
+  navbarHeight,
+  split,
+}: Pick<ThemerProps, 'actorRef' | 'dispatch' | 'navbarHeight' | 'split'>) {
   const [width, setWidth] = useState(readStoredWidth)
   const [dragging, setDragging] = useState(false)
   const drag = useRef<{pointerId: number; startX: number; startWidth: number} | null>(null)
 
+  // @TODO schedule the write to localStorage to avoid blocking the main thread
   useEffect(() => writeStoredWidth(width), [width])
 
   const handlePointerDown = useCallback(
@@ -94,15 +102,21 @@
     setWidth((current) => clampWidth(current + step))
   }, [])
 
+  const [boundaryElement, setBoundaryElement] = useState<HTMLDivElement | null>(null)
+
   return (
-    <Layer
-      className={sidebar}
-      data-overlay={overlay}
-      style={overlay ? undefined : {width}}
-      zOffset={100}
-    >
-      <Card borderLeft={!overlay} className={frame} height="fill">
-        {!overlay && (
+    <>
+      <Layer className={sidebar} style={{width}} zOffset={100}>
+        <Card
+          borderLeft
+          className={frame}
+          height="fill"
+          ref={(boundaryElement) => {
+            startTransition(() => setBoundaryElement(boundaryElement))
+            // Intentionally not unsetting the element as it would create unnecessary work when <Activity> unhides
+            return () => {}
+          }}
+        >
           <div
             aria-label="Resize the themer"
             className={resizeHandle}
@@ -121,11 +135,19 @@
             role="separator"
             tabIndex={0}
           />
-        )}
-        <Box className={content} height="fill" overflow="hidden">
-          <ThemerSidebar />
-        </Box>
-      </Card>
-    </Layer>
+          <Box className={content} height="fill" overflow="hidden">
+            <BoundaryElementProvider element={boundaryElement}>
+              <ThemerSidebar
+                split={split}
+                navbarHeight={navbarHeight}
+                actorRef={actorRef}
+                dispatch={dispatch}
+              />
+            </BoundaryElementProvider>
+          </Box>
+        </Card>
+      </Layer>
+      <PersistActorSnapshot actorRef={actorRef} />
+    </>
   )
 }

diff --git a/plugins/@sanity/themer/src/tool/ScrollArea.tsx b/plugins/@sanity/themer/src/tool/ScrollArea.tsx
--- a/plugins/@sanity/themer/src/tool/ScrollArea.tsx
+++ b/plugins/@sanity/themer/src/tool/ScrollArea.tsx
@@ -74,7 +74,7 @@
       ref={ref}
       style={{paddingRight: inset.right}}
     >
-      <ScrollAreaInsetContext.Provider value={inset}>{children}</ScrollAreaInsetContext.Provider>
+      <ScrollAreaInsetContext value={inset}>{children}</ScrollAreaInsetContext>
     </Box>
   )
 }

diff --git a/plugins/@sanity/themer/src/tool/ThemeCard.tsx b/plugins/@sanity/themer/src/tool/ThemeCard.tsx
--- a/plugins/@sanity/themer/src/tool/ThemeCard.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemeCard.tsx
@@ -12,7 +12,8 @@
 import {useRef, useState} from 'react'
 import scrollIntoView from 'scroll-into-view-if-needed'
 
-import {useThemer} from './context'
+import type {ThemerProps} from '#types'
+
 import {displayTitle, type ThemerTheme} from './themes'
 import {ThemeThumbnail} from './ThemeThumbnail'
 import {useThemeCodes} from './useThemeCodes'
@@ -37,10 +38,13 @@
  *
  * @internal
  */
-export function ThemeCard(props: {active: boolean; theme: ThemerTheme}) {
-  const {active, theme} = props
-  const {themes, send} = useThemer()
-  const {copyTheme} = useThemeCodes()
+export function ThemeCard({
+  actorRef,
+  active,
+  theme,
+  themes,
+}: {active: boolean; theme: ThemerTheme} & Pick<ThemerProps, 'actorRef' | 'themes'>) {
+  const {copyTheme} = useThemeCodes({actorRef})
   const {scheme} = useRootTheme()
   const [menuOpen, setMenuOpen] = useState(false)
   const dragControls = useDragControls()
@@ -48,12 +52,14 @@
   const dragged = useRef(false)
   const title = displayTitle(theme.title)
   const index = themes.findIndex((candidate) => candidate.slug === theme.slug)
+  // The configured theme sits ahead of the list, and does not move within it
+  const listed = index !== -1
 
   const moveTo = (to: number) => {
     const order = themes.map((candidate) => candidate.slug)
 
     order.splice(to, 0, ...order.splice(index, 1))
-    send({type: 'theme.reorder', order})
+    actorRef.send({type: 'theme.reorder', order})
   }
 
   return (
@@ -79,12 +85,12 @@
         aria-pressed={active}
         className={pickButton}
         onClick={() => {
-          if (!dragged.current) send({type: 'theme.pick', slug: theme.slug})
+          if (!dragged.current) actorRef.send({type: 'theme.pick', slug: theme.slug})
         }}
         onPointerDown={(event) => {
           // A mouse or pen drags the card off the button; a finger scrolls the
           // list instead, and moves themes from the menu
-          if (event.pointerType !== 'touch') dragControls.start(event)
+          if (listed && event.pointerType !== 'touch') dragControls.start(event)
         }}
         type="button"
       >
@@ -125,29 +131,33 @@
               id={`themer-theme-${theme.slug}`}
               menu={
                 <Menu>
-                  <MenuItem
-                    disabled={index <= 0}
-                    icon={ArrowUpIcon}
-                    onClick={() => moveTo(index - 1)}
-                    text="Move up"
-                  />
-                  <MenuItem
-                    disabled={index >= themes.length - 1}
-                    icon={ArrowDownIcon}
-                    onClick={() => moveTo(index + 1)}
-                    text="Move down"
-                  />
-                  <MenuDivider />
+                  {listed && (
+                    <>
+                      <MenuItem
+                        disabled={index <= 0}
+                        icon={ArrowUpIcon}
+                        onClick={() => moveTo(index - 1)}
+                        text="Move up"
+                      />
+                      <MenuItem
+                        disabled={index >= themes.length - 1}
+                        icon={ArrowDownIcon}
+                        onClick={() => moveTo(index + 1)}
+                        text="Move down"
+                      />
+                      <MenuDivider />
+                    </>
+                  )}
                   {theme.source === 'custom' && (
                     <MenuItem
                       icon={EditIcon}
-                      onClick={() => send({type: 'theme.edit', slug: theme.slug})}
+                      onClick={() => actorRef.send({type: 'theme.edit', slug: theme.slug})}
                       text="Edit"
                     />
                   )}
                   <MenuItem
                     icon={CopyIcon}
-                    onClick={() => send({type: 'theme.duplicate', slug: theme.slug})}
+                    onClick={() => actorRef.send({type: 'theme.duplicate', slug: theme.slug})}
                     text={theme.source === 'custom' ? 'Duplicate' : 'Duplicate to edit'}
                   />
                   <MenuItem
@@ -160,7 +170,7 @@
                       <MenuDivider />
                       <MenuItem
                         icon={TrashIcon}
-                        onClick={() => send({type: 'theme.remove', slug: theme.slug})}
+                        onClick={() => actorRef.send({type: 'theme.remove', slug: theme.slug})}
                         text="Remove"
                         tone="critical"
                       />

diff --git a/plugins/@sanity/themer/src/tool/ThemeEditor.tsx b/plugins/@sanity/themer/src/tool/ThemeEditor.tsx
--- a/plugins/@sanity/themer/src/tool/ThemeEditor.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemeEditor.tsx
@@ -2,9 +2,12 @@
 import {TrashIcon} from '@sanity/icons/Trash'
 import {Badge, Box, Button, Card, Flex, Stack, Text, TextInput} from '@sanity/ui'
 import {type ThemeColorSchemeKey} from '@sanity/ui/theme'
+import {useSelector} from '@xstate/react'
 import {useMemo} from 'react'
 import {useColorSchemeValue} from 'sanity'
 
+import type {ThemerProps} from '#types'
+
 import {buildPalette, type GeneratedColorPalette} from '../theme/buildPalette'
 import {
   type BuildThemeOptions,
@@ -13,7 +16,6 @@
   SCHEMES,
   type SchemeThemeOptions,
 } from '../theme/options'
-import {useThemer} from './context'
 import {
   applyImagePalette,
   currentImageVariant,
@@ -38,9 +40,7 @@
  * to the sidebar (or at the bottom, stacked on small screens), the other one
  * takes the far side
  */
-function splitHint(own: boolean, mobile: boolean): string {
-  if (mobile) return own ? 'Shown at the bottom' : 'Shown at the top'
-
+function splitHint(own: boolean): string {
   return own ? 'Shown on the right, next to the themer' : 'Shown on the left'
 }
 
@@ -65,9 +65,14 @@
  *
  * @internal
  */
-export function ThemeEditor(props: {focusTitle: boolean; slug: string}) {
-  const {focusTitle, slug} = props
-  const {themes, images, split, mobile, send} = useThemer()
+export function ThemeEditor({
+  actorRef,
+  focusTitle,
+  slug,
+  split,
+  themes,
+}: {focusTitle: boolean; slug: string} & Pick<ThemerProps, 'actorRef' | 'split' | 'themes'>) {
+  const images = useSelector(actorRef, (snapshot) => snapshot.context.images)
   const theme = themes.find((candidate) => candidate.slug === slug && candidate.source === 'custom')
 
   // The machine only enters the edit flow for a listed custom theme, and
@@ -77,7 +82,7 @@
   const applyVariant = (variant: ImagePaletteVariant | null) => {
     if (!theme.palette || variant === null) return
 
-    send({
+    actorRef.send({
       type: 'theme.update',
       slug,
       options: applyImagePalette(theme.options, theme.palette, variant),
... diff truncated: showing 800 of 9159 lines

You can send follow-ups to the cloud agent here.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +18 to +21
// @TODO use a selector or similar to only subscribe to changes that are relevant to the persisted snapshot
// @TODO use WebLocks and BroadcastChannel to ensure the snapshot is persisted in a consistent way cross tabs
// @TODO actually only run this when the document is visible or has lock or something?
const subscription = actorRef.subscribe(() => {
Comment on lines +41 to +42
// @TODO Themer does not yet support mobile
const open = state.open && !isMobile
</Box>
</Card>
</Layer>
<PersistActorSnapshot actorRef={actorRef} />
Comment on lines +71 to +75
theme={{
slug: CONFIG_SLUG,
title: CONFIG_TITLE,
options: {},
source: 'config',
const split = state.split && !isTooSmallForSplitScreen

return (
<ThemeProvider theme={(state.theme !== null ? buildTheme(state.theme) : null) ?? undefined}>
Comment on lines +37 to +38
case 'close':
return state.open ? {...state, open: false} : state
@@ -0,0 +1,5 @@
---
'@sanity/themer': minor
Copilot AI balanced review requested due to automatic review settings October 2, 2026 16:21
@stipsan
stipsan force-pushed the themer-state-refactor branch from 033c8c8 to 7628ccf Compare October 2, 2026 16:21
@cursor

cursor Bot commented Oct 2, 2026

Copy link
Copy Markdown

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Debug toast fires on hover
    • Removed the leftover toast.push({title: 'Hello'}) from the hover/focus handlePrerender handler along with the now-unused useToast() call and its import.
  • ✅ Fixed: Closing sidebar can drop persistence
    • Moved PersistActorSnapshot out of ResizableSidebar and into ThemerLayout beside the other actor-lifetime effects, so hiding the sidebar's Activity no longer runs its cleanup and cancels the pending idle write.

Create PR

Or push these changes by commenting:

@cursor push 46af6e5a78
Preview (46af6e5a78)
diff --git a/.changeset/wide-rocks-clean.md b/.changeset/wide-rocks-clean.md
new file mode 100644
--- /dev/null
+++ b/.changeset/wide-rocks-clean.md
@@ -1,0 +1,5 @@
+---
+'@sanity/themer': minor
+---
+
+Adopt <Activity>, <ViewTransition> and React.lazy APIs according to best practice. Removes the top-level default theme config, it will be added back again later

diff --git a/dev/storybook/package.json b/dev/storybook/package.json
--- a/dev/storybook/package.json
+++ b/dev/storybook/package.json
@@ -31,7 +31,6 @@
     "@vanilla-extract/css": "catalog:",
     "@vitejs/plugin-react": "^6.1.1",
     "@vitest/browser-playwright": "^4.1.11",
-    "motion": "catalog:",
     "oxc-transform-react": "catalog:",
     "playwright": "^1.63.0",
     "react": "catalog:",

diff --git a/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx b/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
--- a/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
+++ b/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
@@ -1,13 +1,11 @@
 import {Button, Flex, Text} from '@sanity/ui'
 import type {Meta, StoryObj} from '@storybook/react-vite'
-import {animate, useMotionValue} from 'motion/react'
-import {useEffect} from 'react'
+import {useRef} from 'react'
 
-import {AnimatedColorWheelIcon} from '../../../../../plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon'
-import {ANIMATION_DURATION} from '../../../../../plugins/@sanity/themer/src/tool/colorWheel'
+import AnimatedColorWheelIcon from '../../../../../plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon'
 
 interface WheelArgs {
-  progress: number
+  busy: boolean
 }
 
 /**
@@ -21,54 +19,41 @@
 export default meta
 type Story = StoryObj<WheelArgs>
 
-function NavbarButton() {
-  const progress = useMotionValue(0)
+function NavbarButton(props: {busy: boolean}) {
+  const {busy} = props
+  const ref = useRef<{spin: () => void}>(null)
 
-  const play = () => {
-    // A run in progress plays out, like on the Studio navbar
-    if (progress.isAnimating()) return
-
-    animate(progress, [0, 1], {duration: ANIMATION_DURATION, ease: 'linear'})
-  }
-
   return (
     <Flex align="center" gap={3}>
       <Button
+        aria-busy={busy}
         aria-label="Themer"
-        icon={<AnimatedColorWheelIcon progress={progress} />}
+        icon={<AnimatedColorWheelIcon busy={busy} ref={ref} />}
         mode="bleed"
-        onMouseEnter={play}
+        onMouseEnter={() => ref.current?.spin()}
+        selected={busy}
       />
       <Text muted size={1}>
-        Hover the button to play the animation
+        {busy
+          ? 'The wheel laps while the toggle is busy'
+          : 'Hover the button to play the animation'}
       </Text>
     </Flex>
   )
 }
 
-/** The navbar toggle, which plays the animation on hover */
+/** The navbar toggle, which plays the animation once on hover */
 export const Default: Story = {
-  render: () => <NavbarButton />,
+  render: () => <NavbarButton busy={false} />,
 }
 
-function WheelAtProgress(props: {progress: number}) {
-  const progress = useMotionValue(props.progress)
-
-  useEffect(() => {
-    progress.set(props.progress)
-  }, [progress, props.progress])
-
-  return (
-    <Text size={4}>
-      <AnimatedColorWheelIcon progress={progress} />
-    </Text>
-  )
+/**
+ * The navbar toggle while the sidebar loads: the wheel laps from wherever a hover's run has got
+ * to, and the lap in progress plays out once the toggle is no longer busy
+ */
+export const Busy: Story = {
+  args: {busy: true},
+  argTypes: {busy: {control: {type: 'boolean'}}},
+  parameters: {controls: {include: ['busy']}},
+  render: (args) => <NavbarButton busy={args.busy} />,
 }
-
-/** The wheel at any point of the animation, from 0 to 1 */
-export const Progress: Story = {
-  args: {progress: 0.5},
-  argTypes: {progress: {control: {type: 'range', min: 0, max: 1, step: 0.01}}},
-  parameters: {controls: {include: ['progress']}},
-  render: (args) => <WheelAtProgress progress={args.progress} />,
-}

diff --git a/dev/test-studio/sanity.config.ts b/dev/test-studio/sanity.config.ts
--- a/dev/test-studio/sanity.config.ts
+++ b/dev/test-studio/sanity.config.ts
@@ -88,6 +88,7 @@
     name: 'home',
     title: 'Home',
     icon: HomeIcon,
+    beta: {...beta, variants: {enabled: true}},
     plugins: [
       // Order matters for the top navigation: Workspaces Home, Structure, then
       // the most-used plugin tools first.
@@ -137,10 +138,10 @@
       vercelWidgetExample(),
       contentGraphView(),
       scriptRunnerTool(),
-      themerTool(),
       debugSecrets(),
       vercelProtectionBypassTool(),
       visionTool(),
+      themerTool({title: 'Themer 2.0'}),
     ],
   }),
   // Re-registers `internationalizedArray` with async languages loaded from
@@ -148,34 +149,34 @@
   createWorkspace({
     name: 'internationalized-array-async-languages',
     title: 'internationalized-array: Async Languages',
-    plugins: [internationalizedArrayAsyncLanguages()],
+    plugins: [internationalizedArrayAsyncLanguages(), themerTool()],
   }),
   // Demos the translations tab at the internationalized-array level, with its own
   // `internationalizedArray` language set (en/de/no_nb/is) — conflicts with Home.
   createWorkspace({
     name: 'i18n-array-translation',
     title: 'sanity-translations-tab: i18n Array',
-    plugins: [i18nArrayTranslationExample()],
+    plugins: [i18nArrayTranslationExample(), themerTool()],
   }),
   // A second `documentInternationalization` registration (for docI18nLocalizedPage)
   // that cannot coexist with Home's `lesson` configuration.
   createWorkspace({
     name: 'doc-i18n-translation',
     title: 'document-internationalization: Translations',
-    plugins: [documentInternationalizationTranslationExample()],
+    plugins: [documentInternationalizationTranslationExample(), themerTool()],
   }),
   // Registers its own `internationalizedArray` (en_US/fr) and `product`/`category`
   // types (`product` collides with the workflow workspace).
   createWorkspace({
     name: 'sfcc',
     title: 'sfcc: Salesforce Commerce Cloud',
-    plugins: [sfccExample()],
+    plugins: [sfccExample(), themerTool()],
   }),
   // Defines `product`/`article`; `product` collides with the sfcc workspace.
   createWorkspace({
     name: 'workflow',
     title: 'workflow: Document Workflow',
-    plugins: [structureTool(), workflowExample()],
+    plugins: [structureTool(), workflowExample(), themerTool()],
   }),
   // Destination workspace for @sanity/cross-dataset-duplicator: uses a
   // different dataset so it can be picked as a duplication target.
@@ -186,6 +187,6 @@
     name: 'cross-dataset-duplicator-target',
     title: 'cross-dataset-duplicator: Target',
     basePath: '/cross-dataset-duplicator-target',
-    plugins: [structureTool(), crossDatasetDuplicatorExample()],
+    plugins: [structureTool(), crossDatasetDuplicatorExample(), themerTool({title: 'Not Themer'})],
   },
 ])

diff --git a/plugins/@sanity/themer/package.json b/plugins/@sanity/themer/package.json
--- a/plugins/@sanity/themer/package.json
+++ b/plugins/@sanity/themer/package.json
@@ -29,6 +29,12 @@
     "*.css"
   ],
   "types": "./dist/index.d.ts",
+  "imports": {
+    "#constants": "./src/tool/constants.ts",
+    "#context": "./src/tool/context.ts",
+    "#reducer": "./src/tool/reducer.ts",
+    "#types": "./src/tool/types.ts"
+  },
   "exports": {
     ".": "./src/index.ts",
     "./legacy": "./src/legacy/index.ts",
@@ -68,10 +74,12 @@
     "@sanity/ui": "catalog:",
     "@vanilla-extract/dynamic": "catalog:",
     "@xstate/react": "catalog:",
+    "dequal": "catalog:",
     "motion": "catalog:",
     "react-refractor": "^4.0.0",
     "refractor": "^5.0.0",
     "scroll-into-view-if-needed": "catalog:",
+    "valibot": "catalog:",
     "xstate": "catalog:"
   },
   "devDependencies": {
@@ -82,7 +90,6 @@
     "@types/react": "catalog:",
     "@types/react-dom": "catalog:",
     "@vanilla-extract/css": "catalog:",
-    "jsdom": "catalog:",
     "lightningcss": "^1.33.0",
     "oxc-transform-react": "catalog:",
     "react": "catalog:",
@@ -93,6 +100,7 @@
   },
   "peerDependencies": {
     "react": "^19.3.0",
+    "react-dom": "^19.3.0",
     "sanity": "^3 || ^4 || ^5 || ^6"
   },
   "peerDependenciesMeta": {

diff --git a/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx b/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
--- a/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
+++ b/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
@@ -1,7 +1,13 @@
-import {usePrefersReducedMotion} from '@sanity/ui'
-import {motion, MotionValue, useTransform} from 'motion/react'
+import {motion, MotionValue, useTransform, animate, useMotionValue} from 'motion/react'
+import {useEffect, useImperativeHandle} from 'react'
 
-import {isSliceFilled, SLICE_COLORS, SLICE_COUNT, wheelRotation} from './colorWheel'
+import {
+  isSliceFilled,
+  SLICE_COLORS,
+  SLICE_COUNT,
+  wheelRotation,
+  ANIMATION_DURATION,
+} from './colorWheel'
 
 /**
  * The geometry of `ColorWheelIcon` from `@sanity/icons`: a ring between two
@@ -67,13 +73,59 @@
  *
  * @internal
  */
-export function AnimatedColorWheelIcon(props: {progress: MotionValue<number>}) {
-  const {progress} = props
-  const prefersReducedMotion = usePrefersReducedMotion()
-  const rotate = useTransform(progress, (value) =>
-    prefersReducedMotion ? 0 : wheelRotation(value),
+export default function AnimatedColorWheelIcon({
+  busy,
+  ref,
+}: {
+  busy: boolean
+  ref: React.Ref<{spin: () => void}>
+}) {
+  const progress = useMotionValue(0)
+  const rotate = useTransform(progress, (value) => wheelRotation(value))
+
+  useImperativeHandle(
+    ref,
+    () => ({
+      spin: () => {
+        // A run in progress plays out — hovering again does not cut it short
+        if (progress.isAnimating()) return
+
+        animate(progress, [0, 1], {duration: ANIMATION_DURATION, ease: 'linear'})
+      },
+    }),
+    [progress],
   )
 
+  // Laps from wherever a hover's run has got to, so the wheel never jumps,
+  // and the lap in progress as the code arrives plays out: at rest, the wheel
+  // looks like the icon again
+  useEffect(() => {
+    if (!busy) return undefined
+
+    let looping = false
+    const raf = setTimeout(() => {
+      looping = true
+      const lap = (from: number) => {
+        animate(progress, [from, 1], {
+          duration: (1 - from) * ANIMATION_DURATION,
+          ease: 'linear',
+          onComplete: () => {
+            if (looping) lap(0)
+          },
+        })
+      }
+
+      lap(progress.get())
+    }, 160)
+
+    return () => {
+      clearTimeout(raf)
+      looping = false
+    }
+  }, [busy, progress])
+
+  useEffect(() => () => progress.stop(), [progress])
+
   return (
     <motion.svg
       data-sanity-icon="color-wheel"
@@ -85,7 +137,7 @@
       xmlns="http://www.w3.org/2000/svg"
     >
       {SLICE_COLORS.map((color, index) => (
-        <Slice index={index} key={color} progress={progress} />
+        <Slice key={color} index={index} progress={progress} />
       ))}
       <path d={OUTLINE} stroke="currentColor" strokeLinejoin="round" strokeWidth={1.2} />
     </motion.svg>

diff --git a/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx b/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx
--- a/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx
+++ b/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx
@@ -178,13 +178,14 @@
 
                 return (
                   <Tooltip
+                    key={key}
                     animate
                     content={
                       <Text size={1}>
                         {hex ? `${title} · ${hex}` : `No ${title.toLowerCase()} color`}
                       </Text>
                     }
-                    key={key}
+
                     placement="bottom"
                     portal
                   >
@@ -213,9 +214,9 @@
                 {variants.map(({variant, title, options: variantOptions}) => (
                   // oxlint-disable-next-line control-has-associated-label -- the title below the thumbnail is the label, deeper than the rule looks
                   <button
+                    key={variant}
                     aria-pressed={variant === current}
                     className={variantButton}
-                    key={variant}
                     onClick={() => onVariant(variant)}
                     type="button"
                   >

diff --git a/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx b/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx
--- a/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx
+++ b/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx
@@ -1,6 +1,8 @@
 import {Button, Card, Dialog, Flex, Stack, Text, TextInput} from '@sanity/ui'
 import {useState} from 'react'
 
+import type {ThemerProps} from '#types'
+
 import {useThemeCodes} from './useThemeCodes'
 
 /**
@@ -9,9 +11,9 @@
  *
  * @internal
  */
-export function PasteThemeDialog(props: {onClose: () => void}) {
-  const {onClose} = props
-  const {addThemeFromText} = useThemeCodes()
+export function PasteThemeDialog(props: {onClose: () => void} & Pick<ThemerProps, 'actorRef'>) {
+  const {actorRef, onClose} = props
+  const {addThemeFromText} = useThemeCodes({actorRef})
   const [text, setText] = useState('')
   const [invalid, setInvalid] = useState(false)
 

diff --git a/plugins/@sanity/themer/src/tool/PersistActorSnapshot.tsx b/plugins/@sanity/themer/src/tool/PersistActorSnapshot.tsx
new file mode 100644
--- /dev/null
+++ b/plugins/@sanity/themer/src/tool/PersistActorSnapshot.tsx
@@ -1,0 +1,37 @@
+import {useEffect} from 'react'
+
+import type {ThemerProps} from '#types'
+
+import {writePersistedSnapshot} from './storage'
+
+export function PersistActorSnapshot({actorRef}: Pick<ThemerProps, 'actorRef'>) {
+  useEffect(() => {
+    let cancel: any
+    function cancelOrClear() {
+      if ('cancelIdleCallback' in window) {
+        cancelIdleCallback(cancel)
+      } else {
+        clearTimeout(cancel)
+      }
+    }
+
+    // @TODO use a selector or similar to only subscribe to changes that are relevant to the persisted snapshot
+    // @TODO use WebLocks and BroadcastChannel to ensure the snapshot is persisted in a consistent way cross tabs
+    // @TODO actually only run this when the document is visible or has lock or something?
+    const subscription = actorRef.subscribe(() => {
+      cancelOrClear()
+      const callback = () => {
+        const persistedSnapshot = actorRef.getPersistedSnapshot()
+        writePersistedSnapshot(persistedSnapshot)
+      }
+      cancel =
+        'cancelIdleCallback' in window ? requestIdleCallback(callback) : setTimeout(callback, 1_000)
+    })
+    return () => {
+      subscription.unsubscribe()
+      cancelOrClear()
+    }
+  }, [actorRef])
+
+  return null
+}

diff --git a/plugins/@sanity/themer/src/tool/RemovedThemes.tsx b/plugins/@sanity/themer/src/tool/RemovedThemes.tsx
--- a/plugins/@sanity/themer/src/tool/RemovedThemes.tsx
+++ b/plugins/@sanity/themer/src/tool/RemovedThemes.tsx
@@ -1,6 +1,7 @@
 import {Box, Button, Flex, Stack, Text} from '@sanity/ui'
 
-import {useThemer} from './context'
+import type {ThemerProps} from '#types'
+
 import {ScrollArea} from './ScrollArea'
 import {displayTitle} from './themes'
 import {ThemeThumbnail} from './ThemeThumbnail'
@@ -15,14 +16,12 @@
  *
  * @internal
  */
-export function RemovedThemes() {
-  const {removed, send} = useThemer()
-
+export function RemovedThemes({actorRef, removed}: Pick<ThemerProps, 'actorRef' | 'removed'>) {
   return (
     <ScrollArea padding={3}>
       <Stack gap={5}>
         {removed.map((theme) => (
-          <Stack gap={3} key={theme.slug}>
+          <Stack key={theme.slug} gap={3}>
             <Box className={removedThumbnail}>
               <ThemeThumbnail options={theme.options} />
             </Box>
@@ -32,14 +31,14 @@
             <Flex gap={2} justify="center">
               <Button
                 mode="ghost"
-                onClick={() => send({type: 'theme.restore', slug: theme.slug})}
+                onClick={() => actorRef.send({type: 'theme.restore', slug: theme.slug})}
                 padding={2}
                 text="Restore"
               />
               {theme.source === 'custom' && (
                 <Button
                   mode="ghost"
-                  onClick={() => send({type: 'theme.delete', slug: theme.slug})}
+                  onClick={() => actorRef.send({type: 'theme.delete', slug: theme.slug})}
                   padding={2}
                   text="Delete"
                   tone="critical"

diff --git a/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts b/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts
--- a/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts
+++ b/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts
@@ -1,26 +1,10 @@
-import {createContainer, createViewTransition, style} from '@vanilla-extract/css'
+import {createContainer, style} from '@vanilla-extract/css'
 
-/**
- * The view transition group of the sidebar, which the split preview's
- * transition (see `ThemerLayout.css.ts`) leaves alone: it never animates, and
- * the Studio copies animating underneath never paint over it
- */
-export const sidebarTransition = createViewTransition()
-
 /** The sidebar's content, which the content's layout queries — as wide as the sidebar itself */
 export const sidebarContent = createContainer()
 
 export const sidebar = style({
   flex: 'none',
-  viewTransitionName: sidebarTransition,
-  selectors: {
-    // On small screens the sidebar covers the Studio instead of standing next to it
-    "&[data-overlay='true']": {
-      position: 'absolute',
-      inset: 0,
-      width: 'auto',
-    },
-  },
 })
 
 /**

diff --git a/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx b/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
--- a/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
+++ b/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
@@ -1,6 +1,8 @@
-import {Box, Card, Layer} from '@sanity/ui'
-import {useCallback, useEffect, useRef, useState} from 'react'
+import {BoundaryElementProvider, Box, Card, Layer} from '@sanity/ui'
+import {startTransition, useCallback, useEffect, useRef, useState} from 'react'
 
+import type {ThemerProps} from '#types'
+
 import {MAXIMUM_WIDTH, MINIMUM_WIDTH} from './sidebarWidth'
 import {ThemerSidebar} from './ThemerSidebar'
 
@@ -45,12 +47,17 @@
  *
  * @internal
  */
-export default function ResizableSidebar(props: {overlay: boolean}) {
-  const {overlay} = props
+export default function ResizableSidebar({
+  actorRef,
+  dispatch,
+  navbarHeight,
+  split,
+}: Pick<ThemerProps, 'actorRef' | 'dispatch' | 'navbarHeight' | 'split'>) {
   const [width, setWidth] = useState(readStoredWidth)
   const [dragging, setDragging] = useState(false)
   const drag = useRef<{pointerId: number; startX: number; startWidth: number} | null>(null)
 
+  // @TODO schedule the write to localStorage to avoid blocking the main thread
   useEffect(() => writeStoredWidth(width), [width])
 
   const handlePointerDown = useCallback(
@@ -94,36 +101,47 @@
     setWidth((current) => clampWidth(current + step))
   }, [])
 
+  const [boundaryElement, setBoundaryElement] = useState<HTMLDivElement | null>(null)
+
   return (
-    <Layer
-      className={sidebar}
-      data-overlay={overlay}
-      style={overlay ? undefined : {width}}
-      zOffset={100}
-    >
-      <Card borderLeft={!overlay} className={frame} height="fill">
-        {!overlay && (
-          <div
-            aria-label="Resize the themer"
-            className={resizeHandle}
-            aria-orientation="vertical"
-            aria-valuemax={MAXIMUM_WIDTH}
-            aria-valuemin={MINIMUM_WIDTH}
-            aria-valuenow={width}
-            data-dragging={dragging}
-            onDoubleClick={() => setWidth(MINIMUM_WIDTH)}
-            onKeyDown={handleKeyDown}
-            onPointerCancel={handlePointerUp}
-            onPointerDown={handlePointerDown}
-            onPointerMove={handlePointerMove}
-            onPointerUp={handlePointerUp}
-            // oxlint-disable-next-line prefer-tag-over-role -- a window splitter is a focusable, draggable separator, which an hr is not
-            role="separator"
-            tabIndex={0}
-          />
-        )}
+    <Layer className={sidebar} style={{width}} zOffset={100}>
+      <Card
+        borderLeft
+        className={frame}
+        height="fill"
+        ref={(boundaryElement) => {
+          startTransition(() => setBoundaryElement(boundaryElement))
+          // Intentionally not unsetting the element as it would create unnecessary work when <Activity> unhides
+          return () => {}
+        }}
+      >
+        <div
+          aria-label="Resize the themer"
+          className={resizeHandle}
+          aria-orientation="vertical"
+          aria-valuemax={MAXIMUM_WIDTH}
+          aria-valuemin={MINIMUM_WIDTH}
+          aria-valuenow={width}
+          data-dragging={dragging}
+          onDoubleClick={() => setWidth(MINIMUM_WIDTH)}
+          onKeyDown={handleKeyDown}
+          onPointerCancel={handlePointerUp}
+          onPointerDown={handlePointerDown}
+          onPointerMove={handlePointerMove}
+          onPointerUp={handlePointerUp}
+          // oxlint-disable-next-line prefer-tag-over-role -- a window splitter is a focusable, draggable separator, which an hr is not
+          role="separator"
+          tabIndex={0}
+        />
         <Box className={content} height="fill" overflow="hidden">
-          <ThemerSidebar />
+          <BoundaryElementProvider element={boundaryElement}>
+            <ThemerSidebar
+              split={split}
+              navbarHeight={navbarHeight}
+              actorRef={actorRef}
+              dispatch={dispatch}
+            />
+          </BoundaryElementProvider>
         </Box>
       </Card>
     </Layer>

diff --git a/plugins/@sanity/themer/src/tool/ScrollArea.tsx b/plugins/@sanity/themer/src/tool/ScrollArea.tsx
--- a/plugins/@sanity/themer/src/tool/ScrollArea.tsx
+++ b/plugins/@sanity/themer/src/tool/ScrollArea.tsx
@@ -74,7 +74,7 @@
       ref={ref}
       style={{paddingRight: inset.right}}
     >
-      <ScrollAreaInsetContext.Provider value={inset}>{children}</ScrollAreaInsetContext.Provider>
+      <ScrollAreaInsetContext value={inset}>{children}</ScrollAreaInsetContext>
     </Box>
   )
 }

diff --git a/plugins/@sanity/themer/src/tool/ThemeCard.tsx b/plugins/@sanity/themer/src/tool/ThemeCard.tsx
--- a/plugins/@sanity/themer/src/tool/ThemeCard.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemeCard.tsx
@@ -12,7 +12,8 @@
 import {useRef, useState} from 'react'
 import scrollIntoView from 'scroll-into-view-if-needed'
 
-import {useThemer} from './context'
+import type {ThemerProps} from '#types'
+
 import {displayTitle, type ThemerTheme} from './themes'
 import {ThemeThumbnail} from './ThemeThumbnail'
 import {useThemeCodes} from './useThemeCodes'
@@ -37,10 +38,13 @@
  *
  * @internal
  */
-export function ThemeCard(props: {active: boolean; theme: ThemerTheme}) {
-  const {active, theme} = props
-  const {themes, send} = useThemer()
-  const {copyTheme} = useThemeCodes()
+export function ThemeCard({
+  actorRef,
+  active,
+  theme,
+  themes,
+}: {active: boolean; theme: ThemerTheme} & Pick<ThemerProps, 'actorRef' | 'themes'>) {
+  const {copyTheme} = useThemeCodes({actorRef})
   const {scheme} = useRootTheme()
   const [menuOpen, setMenuOpen] = useState(false)
   const dragControls = useDragControls()
@@ -53,7 +57,7 @@
     const order = themes.map((candidate) => candidate.slug)
 
     order.splice(to, 0, ...order.splice(index, 1))
-    send({type: 'theme.reorder', order})
+    actorRef.send({type: 'theme.reorder', order})
   }
 
   return (
@@ -79,7 +83,7 @@
         aria-pressed={active}
         className={pickButton}
         onClick={() => {
-          if (!dragged.current) send({type: 'theme.pick', slug: theme.slug})
+          if (!dragged.current) actorRef.send({type: 'theme.pick', slug: theme.slug})
         }}
         onPointerDown={(event) => {
           // A mouse or pen drags the card off the button; a finger scrolls the
@@ -141,13 +145,13 @@
                   {theme.source === 'custom' && (
                     <MenuItem
                       icon={EditIcon}
-                      onClick={() => send({type: 'theme.edit', slug: theme.slug})}
+                      onClick={() => actorRef.send({type: 'theme.edit', slug: theme.slug})}
                       text="Edit"
                     />
                   )}
                   <MenuItem
                     icon={CopyIcon}
-                    onClick={() => send({type: 'theme.duplicate', slug: theme.slug})}
+                    onClick={() => actorRef.send({type: 'theme.duplicate', slug: theme.slug})}
                     text={theme.source === 'custom' ? 'Duplicate' : 'Duplicate to edit'}
                   />
                   <MenuItem
@@ -160,7 +164,7 @@
                       <MenuDivider />
                       <MenuItem
                         icon={TrashIcon}
-                        onClick={() => send({type: 'theme.remove', slug: theme.slug})}
+                        onClick={() => actorRef.send({type: 'theme.remove', slug: theme.slug})}
                         text="Remove"
                         tone="critical"
                       />

diff --git a/plugins/@sanity/themer/src/tool/ThemeEditor.tsx b/plugins/@sanity/themer/src/tool/ThemeEditor.tsx
--- a/plugins/@sanity/themer/src/tool/ThemeEditor.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemeEditor.tsx
@@ -2,9 +2,12 @@
 import {TrashIcon} from '@sanity/icons/Trash'
 import {Badge, Box, Button, Card, Flex, Stack, Text, TextInput} from '@sanity/ui'
 import {type ThemeColorSchemeKey} from '@sanity/ui/theme'
+import {useSelector} from '@xstate/react'
 import {useMemo} from 'react'
 import {useColorSchemeValue} from 'sanity'
 
+import type {ThemerProps} from '#types'
+
 import {buildPalette, type GeneratedColorPalette} from '../theme/buildPalette'
 import {
   type BuildThemeOptions,
@@ -13,7 +16,6 @@
   SCHEMES,
   type SchemeThemeOptions,
 } from '../theme/options'
-import {useThemer} from './context'
 import {
   applyImagePalette,
   currentImageVariant,
@@ -38,9 +40,7 @@
  * to the sidebar (or at the bottom, stacked on small screens), the other one
  * takes the far side
  */
-function splitHint(own: boolean, mobile: boolean): string {
-  if (mobile) return own ? 'Shown at the bottom' : 'Shown at the top'
-
+function splitHint(own: boolean): string {
   return own ? 'Shown on the right, next to the themer' : 'Shown on the left'
 }
 
@@ -65,9 +65,14 @@
  *
  * @internal
  */
-export function ThemeEditor(props: {focusTitle: boolean; slug: string}) {
-  const {focusTitle, slug} = props
-  const {themes, images, split, mobile, send} = useThemer()
+export function ThemeEditor({
+  actorRef,
+  focusTitle,
+  slug,
+  split,
+  themes,
+}: {focusTitle: boolean; slug: string} & Pick<ThemerProps, 'actorRef' | 'split' | 'themes'>) {
+  const images = useSelector(actorRef, (snapshot) => snapshot.context.images)
   const theme = themes.find((candidate) => candidate.slug === slug && candidate.source === 'custom')
 
   // The machine only enters the edit flow for a listed custom theme, and
@@ -77,7 +82,7 @@
   const applyVariant = (variant: ImagePaletteVariant | null) => {
     if (!theme.palette || variant === null) return
 
-    send({
+    actorRef.send({
       type: 'theme.update',
       slug,
       options: applyImagePalette(theme.options, theme.palette, variant),
@@ -88,7 +93,7 @@
     <ThemeEditorForm
       focusTitle={focusTitle}
       imageUrl={images[slug]}
-      onDone={() => send({type: 'flow.list'})}
+      onDone={() => actorRef.send({type: 'flow.list'})}
       onLucky={() => {
         if (!theme.palette) return
 
@@ -98,9 +103,9 @@
           }),
         )
       }}
-      onOptionsChange={(options) => send({type: 'theme.update', slug, options})}
+      onOptionsChange={(options) => actorRef.send({type: 'theme.update', slug, options})}
       onPalette={(palette, file) =>
-        send({
+        actorRef.send({
           type: 'theme.update',
           slug,
           options: applyImagePalette(theme.options, palette),
@@ -108,13 +113,12 @@
           imageUrl: URL.createObjectURL(file),
         })
       }
-      onRemove={() => send({type: 'theme.remove', slug})}
-      onTitleChange={(title) => send({type: 'theme.update', slug, title})}
... diff truncated: showing 800 of 8109 lines

You can send follow-ups to the cloud agent here.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Comment on lines +47 to +50
<ThemeProvider theme={(state.theme !== null ? buildTheme(state.theme) : null) ?? undefined}>
<ThemerLayout
config={config}
backgroundColor={state.theme?.[scheme]?.background}
Copilot AI balanced review requested due to automatic review settings October 2, 2026 16:26

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 3 total unresolved issues (including 2 from previous reviews).

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Applied theme background is incomplete
    • The layout now receives the built theme's v2.color[scheme].default.bg instead of the frequently-unset raw background option, and ThemerLayout again paints document.body with it so chrome, overscroll and layout gaps follow the applied theme.

Create PR

Or push these changes by commenting:

@cursor push fd2147f400
Preview (fd2147f400)
diff --git a/.changeset/wide-rocks-clean.md b/.changeset/wide-rocks-clean.md
new file mode 100644
--- /dev/null
+++ b/.changeset/wide-rocks-clean.md
@@ -1,0 +1,5 @@
+---
+'@sanity/themer': minor
+---
+
+Adopt <Activity>, <ViewTransition> and React.lazy APIs according to best practice. Removes the top-level default theme config, it will be added back again later

diff --git a/dev/storybook/package.json b/dev/storybook/package.json
--- a/dev/storybook/package.json
+++ b/dev/storybook/package.json
@@ -31,7 +31,6 @@
     "@vanilla-extract/css": "catalog:",
     "@vitejs/plugin-react": "^6.1.1",
     "@vitest/browser-playwright": "^4.1.11",
-    "motion": "catalog:",
     "oxc-transform-react": "catalog:",
     "playwright": "^1.63.0",
     "react": "catalog:",

diff --git a/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx b/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
--- a/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
+++ b/dev/storybook/stories/themer/tool/AnimatedColorWheelIcon.stories.tsx
@@ -1,13 +1,11 @@
 import {Button, Flex, Text} from '@sanity/ui'
 import type {Meta, StoryObj} from '@storybook/react-vite'
-import {animate, useMotionValue} from 'motion/react'
-import {useEffect} from 'react'
+import {useRef} from 'react'
 
-import {AnimatedColorWheelIcon} from '../../../../../plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon'
-import {ANIMATION_DURATION} from '../../../../../plugins/@sanity/themer/src/tool/colorWheel'
+import AnimatedColorWheelIcon from '../../../../../plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon'
 
 interface WheelArgs {
-  progress: number
+  busy: boolean
 }
 
 /**
@@ -21,54 +19,41 @@
 export default meta
 type Story = StoryObj<WheelArgs>
 
-function NavbarButton() {
-  const progress = useMotionValue(0)
+function NavbarButton(props: {busy: boolean}) {
+  const {busy} = props
+  const ref = useRef<{spin: () => void}>(null)
 
-  const play = () => {
-    // A run in progress plays out, like on the Studio navbar
-    if (progress.isAnimating()) return
-
-    animate(progress, [0, 1], {duration: ANIMATION_DURATION, ease: 'linear'})
-  }
-
   return (
     <Flex align="center" gap={3}>
       <Button
+        aria-busy={busy}
         aria-label="Themer"
-        icon={<AnimatedColorWheelIcon progress={progress} />}
+        icon={<AnimatedColorWheelIcon busy={busy} ref={ref} />}
         mode="bleed"
-        onMouseEnter={play}
+        onMouseEnter={() => ref.current?.spin()}
+        selected={busy}
       />
       <Text muted size={1}>
-        Hover the button to play the animation
+        {busy
+          ? 'The wheel laps while the toggle is busy'
+          : 'Hover the button to play the animation'}
       </Text>
     </Flex>
   )
 }
 
-/** The navbar toggle, which plays the animation on hover */
+/** The navbar toggle, which plays the animation once on hover */
 export const Default: Story = {
-  render: () => <NavbarButton />,
+  render: () => <NavbarButton busy={false} />,
 }
 
-function WheelAtProgress(props: {progress: number}) {
-  const progress = useMotionValue(props.progress)
-
-  useEffect(() => {
-    progress.set(props.progress)
-  }, [progress, props.progress])
-
-  return (
-    <Text size={4}>
-      <AnimatedColorWheelIcon progress={progress} />
-    </Text>
-  )
+/**
+ * The navbar toggle while the sidebar loads: the wheel laps from wherever a hover's run has got
+ * to, and the lap in progress plays out once the toggle is no longer busy
+ */
+export const Busy: Story = {
+  args: {busy: true},
+  argTypes: {busy: {control: {type: 'boolean'}}},
+  parameters: {controls: {include: ['busy']}},
+  render: (args) => <NavbarButton busy={args.busy} />,
 }
-
-/** The wheel at any point of the animation, from 0 to 1 */
-export const Progress: Story = {
-  args: {progress: 0.5},
-  argTypes: {progress: {control: {type: 'range', min: 0, max: 1, step: 0.01}}},
-  parameters: {controls: {include: ['progress']}},
-  render: (args) => <WheelAtProgress progress={args.progress} />,
-}

diff --git a/dev/test-studio/sanity.config.ts b/dev/test-studio/sanity.config.ts
--- a/dev/test-studio/sanity.config.ts
+++ b/dev/test-studio/sanity.config.ts
@@ -88,6 +88,7 @@
     name: 'home',
     title: 'Home',
     icon: HomeIcon,
+    beta: {...beta, variants: {enabled: true}},
     plugins: [
       // Order matters for the top navigation: Workspaces Home, Structure, then
       // the most-used plugin tools first.
@@ -137,10 +138,10 @@
       vercelWidgetExample(),
       contentGraphView(),
       scriptRunnerTool(),
-      themerTool(),
       debugSecrets(),
       vercelProtectionBypassTool(),
       visionTool(),
+      themerTool({title: 'Themer 2.0'}),
     ],
   }),
   // Re-registers `internationalizedArray` with async languages loaded from
@@ -148,34 +149,34 @@
   createWorkspace({
     name: 'internationalized-array-async-languages',
     title: 'internationalized-array: Async Languages',
-    plugins: [internationalizedArrayAsyncLanguages()],
+    plugins: [internationalizedArrayAsyncLanguages(), themerTool()],
   }),
   // Demos the translations tab at the internationalized-array level, with its own
   // `internationalizedArray` language set (en/de/no_nb/is) — conflicts with Home.
   createWorkspace({
     name: 'i18n-array-translation',
     title: 'sanity-translations-tab: i18n Array',
-    plugins: [i18nArrayTranslationExample()],
+    plugins: [i18nArrayTranslationExample(), themerTool()],
   }),
   // A second `documentInternationalization` registration (for docI18nLocalizedPage)
   // that cannot coexist with Home's `lesson` configuration.
   createWorkspace({
     name: 'doc-i18n-translation',
     title: 'document-internationalization: Translations',
-    plugins: [documentInternationalizationTranslationExample()],
+    plugins: [documentInternationalizationTranslationExample(), themerTool()],
   }),
   // Registers its own `internationalizedArray` (en_US/fr) and `product`/`category`
   // types (`product` collides with the workflow workspace).
   createWorkspace({
     name: 'sfcc',
     title: 'sfcc: Salesforce Commerce Cloud',
-    plugins: [sfccExample()],
+    plugins: [sfccExample(), themerTool()],
   }),
   // Defines `product`/`article`; `product` collides with the sfcc workspace.
   createWorkspace({
     name: 'workflow',
     title: 'workflow: Document Workflow',
-    plugins: [structureTool(), workflowExample()],
+    plugins: [structureTool(), workflowExample(), themerTool()],
   }),
   // Destination workspace for @sanity/cross-dataset-duplicator: uses a
   // different dataset so it can be picked as a duplication target.
@@ -186,6 +187,6 @@
     name: 'cross-dataset-duplicator-target',
     title: 'cross-dataset-duplicator: Target',
     basePath: '/cross-dataset-duplicator-target',
-    plugins: [structureTool(), crossDatasetDuplicatorExample()],
+    plugins: [structureTool(), crossDatasetDuplicatorExample(), themerTool({title: 'Not Themer'})],
   },
 ])

diff --git a/plugins/@sanity/themer/package.json b/plugins/@sanity/themer/package.json
--- a/plugins/@sanity/themer/package.json
+++ b/plugins/@sanity/themer/package.json
@@ -29,6 +29,12 @@
     "*.css"
   ],
   "types": "./dist/index.d.ts",
+  "imports": {
+    "#constants": "./src/tool/constants.ts",
+    "#context": "./src/tool/context.ts",
+    "#reducer": "./src/tool/reducer.ts",
+    "#types": "./src/tool/types.ts"
+  },
   "exports": {
     ".": "./src/index.ts",
     "./legacy": "./src/legacy/index.ts",
@@ -68,10 +74,12 @@
     "@sanity/ui": "catalog:",
     "@vanilla-extract/dynamic": "catalog:",
     "@xstate/react": "catalog:",
+    "dequal": "catalog:",
     "motion": "catalog:",
     "react-refractor": "^4.0.0",
     "refractor": "^5.0.0",
     "scroll-into-view-if-needed": "catalog:",
+    "valibot": "catalog:",
     "xstate": "catalog:"
   },
   "devDependencies": {
@@ -82,7 +90,6 @@
     "@types/react": "catalog:",
     "@types/react-dom": "catalog:",
     "@vanilla-extract/css": "catalog:",
-    "jsdom": "catalog:",
     "lightningcss": "^1.33.0",
     "oxc-transform-react": "catalog:",
     "react": "catalog:",
@@ -93,6 +100,7 @@
   },
   "peerDependencies": {
     "react": "^19.3.0",
+    "react-dom": "^19.3.0",
     "sanity": "^3 || ^4 || ^5 || ^6"
   },
   "peerDependenciesMeta": {

diff --git a/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx b/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
--- a/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
+++ b/plugins/@sanity/themer/src/tool/AnimatedColorWheelIcon.tsx
@@ -1,7 +1,13 @@
-import {usePrefersReducedMotion} from '@sanity/ui'
-import {motion, MotionValue, useTransform} from 'motion/react'
+import {motion, MotionValue, useTransform, animate, useMotionValue} from 'motion/react'
+import {useEffect, useImperativeHandle} from 'react'
 
-import {isSliceFilled, SLICE_COLORS, SLICE_COUNT, wheelRotation} from './colorWheel'
+import {
+  isSliceFilled,
+  SLICE_COLORS,
+  SLICE_COUNT,
+  wheelRotation,
+  ANIMATION_DURATION,
+} from './colorWheel'
 
 /**
  * The geometry of `ColorWheelIcon` from `@sanity/icons`: a ring between two
@@ -67,13 +73,59 @@
  *
  * @internal
  */
-export function AnimatedColorWheelIcon(props: {progress: MotionValue<number>}) {
-  const {progress} = props
-  const prefersReducedMotion = usePrefersReducedMotion()
-  const rotate = useTransform(progress, (value) =>
-    prefersReducedMotion ? 0 : wheelRotation(value),
+export default function AnimatedColorWheelIcon({
+  busy,
+  ref,
+}: {
+  busy: boolean
+  ref: React.Ref<{spin: () => void}>
+}) {
+  const progress = useMotionValue(0)
+  const rotate = useTransform(progress, (value) => wheelRotation(value))
+
+  useImperativeHandle(
+    ref,
+    () => ({
+      spin: () => {
+        // A run in progress plays out — hovering again does not cut it short
+        if (progress.isAnimating()) return
+
+        animate(progress, [0, 1], {duration: ANIMATION_DURATION, ease: 'linear'})
+      },
+    }),
+    [progress],
   )
 
+  // Laps from wherever a hover's run has got to, so the wheel never jumps,
+  // and the lap in progress as the code arrives plays out: at rest, the wheel
+  // looks like the icon again
+  useEffect(() => {
+    if (!busy) return undefined
+
+    let looping = false
+    const raf = setTimeout(() => {
+      looping = true
+      const lap = (from: number) => {
+        animate(progress, [from, 1], {
+          duration: (1 - from) * ANIMATION_DURATION,
+          ease: 'linear',
+          onComplete: () => {
+            if (looping) lap(0)
+          },
+        })
+      }
+
+      lap(progress.get())
+    }, 160)
+
+    return () => {
+      clearTimeout(raf)
+      looping = false
+    }
+  }, [busy, progress])
+
+  useEffect(() => () => progress.stop(), [progress])
+
   return (
     <motion.svg
       data-sanity-icon="color-wheel"
@@ -85,7 +137,7 @@
       xmlns="http://www.w3.org/2000/svg"
     >
       {SLICE_COLORS.map((color, index) => (
-        <Slice index={index} key={color} progress={progress} />
+        <Slice key={color} index={index} progress={progress} />
       ))}
       <path d={OUTLINE} stroke="currentColor" strokeLinejoin="round" strokeWidth={1.2} />
     </motion.svg>

diff --git a/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx b/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx
--- a/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx
+++ b/plugins/@sanity/themer/src/tool/ImagePaletteSection.tsx
@@ -178,13 +178,14 @@
 
                 return (
                   <Tooltip
+                    key={key}
                     animate
                     content={
                       <Text size={1}>
                         {hex ? `${title} · ${hex}` : `No ${title.toLowerCase()} color`}
                       </Text>
                     }
-                    key={key}
+
                     placement="bottom"
                     portal
                   >
@@ -213,9 +214,9 @@
                 {variants.map(({variant, title, options: variantOptions}) => (
                   // oxlint-disable-next-line control-has-associated-label -- the title below the thumbnail is the label, deeper than the rule looks
                   <button
+                    key={variant}
                     aria-pressed={variant === current}
                     className={variantButton}
-                    key={variant}
                     onClick={() => onVariant(variant)}
                     type="button"
                   >

diff --git a/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx b/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx
--- a/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx
+++ b/plugins/@sanity/themer/src/tool/PasteThemeDialog.tsx
@@ -1,6 +1,8 @@
 import {Button, Card, Dialog, Flex, Stack, Text, TextInput} from '@sanity/ui'
 import {useState} from 'react'
 
+import type {ThemerProps} from '#types'
+
 import {useThemeCodes} from './useThemeCodes'
 
 /**
@@ -9,9 +11,9 @@
  *
  * @internal
  */
-export function PasteThemeDialog(props: {onClose: () => void}) {
-  const {onClose} = props
-  const {addThemeFromText} = useThemeCodes()
+export function PasteThemeDialog(props: {onClose: () => void} & Pick<ThemerProps, 'actorRef'>) {
+  const {actorRef, onClose} = props
+  const {addThemeFromText} = useThemeCodes({actorRef})
   const [text, setText] = useState('')
   const [invalid, setInvalid] = useState(false)
 

diff --git a/plugins/@sanity/themer/src/tool/PersistActorSnapshot.tsx b/plugins/@sanity/themer/src/tool/PersistActorSnapshot.tsx
new file mode 100644
--- /dev/null
+++ b/plugins/@sanity/themer/src/tool/PersistActorSnapshot.tsx
@@ -1,0 +1,37 @@
+import {useEffect} from 'react'
+
+import type {ThemerProps} from '#types'
+
+import {writePersistedSnapshot} from './storage'
+
+export function PersistActorSnapshot({actorRef}: Pick<ThemerProps, 'actorRef'>) {
+  useEffect(() => {
+    let cancel: any
+    function cancelOrClear() {
+      if ('cancelIdleCallback' in window) {
+        cancelIdleCallback(cancel)
+      } else {
+        clearTimeout(cancel)
+      }
+    }
+
+    // @TODO use a selector or similar to only subscribe to changes that are relevant to the persisted snapshot
+    // @TODO use WebLocks and BroadcastChannel to ensure the snapshot is persisted in a consistent way cross tabs
+    // @TODO actually only run this when the document is visible or has lock or something?
+    const subscription = actorRef.subscribe(() => {
+      cancelOrClear()
+      const callback = () => {
+        const persistedSnapshot = actorRef.getPersistedSnapshot()
+        writePersistedSnapshot(persistedSnapshot)
+      }
+      cancel =
+        'cancelIdleCallback' in window ? requestIdleCallback(callback) : setTimeout(callback, 1_000)
+    })
+    return () => {
+      subscription.unsubscribe()
+      cancelOrClear()
+    }
+  }, [actorRef])
+
+  return null
+}

diff --git a/plugins/@sanity/themer/src/tool/RemovedThemes.tsx b/plugins/@sanity/themer/src/tool/RemovedThemes.tsx
--- a/plugins/@sanity/themer/src/tool/RemovedThemes.tsx
+++ b/plugins/@sanity/themer/src/tool/RemovedThemes.tsx
@@ -1,6 +1,7 @@
 import {Box, Button, Flex, Stack, Text} from '@sanity/ui'
 
-import {useThemer} from './context'
+import type {ThemerProps} from '#types'
+
 import {ScrollArea} from './ScrollArea'
 import {displayTitle} from './themes'
 import {ThemeThumbnail} from './ThemeThumbnail'
@@ -15,14 +16,12 @@
  *
  * @internal
  */
-export function RemovedThemes() {
-  const {removed, send} = useThemer()
-
+export function RemovedThemes({actorRef, removed}: Pick<ThemerProps, 'actorRef' | 'removed'>) {
   return (
     <ScrollArea padding={3}>
       <Stack gap={5}>
         {removed.map((theme) => (
-          <Stack gap={3} key={theme.slug}>
+          <Stack key={theme.slug} gap={3}>
             <Box className={removedThumbnail}>
               <ThemeThumbnail options={theme.options} />
             </Box>
@@ -32,14 +31,14 @@
             <Flex gap={2} justify="center">
               <Button
                 mode="ghost"
-                onClick={() => send({type: 'theme.restore', slug: theme.slug})}
+                onClick={() => actorRef.send({type: 'theme.restore', slug: theme.slug})}
                 padding={2}
                 text="Restore"
               />
               {theme.source === 'custom' && (
                 <Button
                   mode="ghost"
-                  onClick={() => send({type: 'theme.delete', slug: theme.slug})}
+                  onClick={() => actorRef.send({type: 'theme.delete', slug: theme.slug})}
                   padding={2}
                   text="Delete"
                   tone="critical"

diff --git a/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts b/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts
--- a/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts
+++ b/plugins/@sanity/themer/src/tool/ResizableSidebar.css.ts
@@ -1,26 +1,10 @@
-import {createContainer, createViewTransition, style} from '@vanilla-extract/css'
+import {createContainer, style} from '@vanilla-extract/css'
 
-/**
- * The view transition group of the sidebar, which the split preview's
- * transition (see `ThemerLayout.css.ts`) leaves alone: it never animates, and
- * the Studio copies animating underneath never paint over it
- */
-export const sidebarTransition = createViewTransition()
-
 /** The sidebar's content, which the content's layout queries — as wide as the sidebar itself */
 export const sidebarContent = createContainer()
 
 export const sidebar = style({
   flex: 'none',
-  viewTransitionName: sidebarTransition,
-  selectors: {
-    // On small screens the sidebar covers the Studio instead of standing next to it
-    "&[data-overlay='true']": {
-      position: 'absolute',
-      inset: 0,
-      width: 'auto',
-    },
-  },
 })
 
 /**

diff --git a/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx b/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
--- a/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
+++ b/plugins/@sanity/themer/src/tool/ResizableSidebar.tsx
@@ -1,6 +1,8 @@
-import {Box, Card, Layer} from '@sanity/ui'
-import {useCallback, useEffect, useRef, useState} from 'react'
+import {BoundaryElementProvider, Box, Card, Layer} from '@sanity/ui'
+import {startTransition, useCallback, useEffect, useRef, useState} from 'react'
 
+import type {ThemerProps} from '#types'
+
 import {MAXIMUM_WIDTH, MINIMUM_WIDTH} from './sidebarWidth'
 import {ThemerSidebar} from './ThemerSidebar'
 
@@ -45,12 +47,17 @@
  *
  * @internal
  */
-export default function ResizableSidebar(props: {overlay: boolean}) {
-  const {overlay} = props
+export default function ResizableSidebar({
+  actorRef,
+  dispatch,
+  navbarHeight,
+  split,
+}: Pick<ThemerProps, 'actorRef' | 'dispatch' | 'navbarHeight' | 'split'>) {
   const [width, setWidth] = useState(readStoredWidth)
   const [dragging, setDragging] = useState(false)
   const drag = useRef<{pointerId: number; startX: number; startWidth: number} | null>(null)
 
+  // @TODO schedule the write to localStorage to avoid blocking the main thread
   useEffect(() => writeStoredWidth(width), [width])
 
   const handlePointerDown = useCallback(
@@ -94,36 +101,47 @@
     setWidth((current) => clampWidth(current + step))
   }, [])
 
+  const [boundaryElement, setBoundaryElement] = useState<HTMLDivElement | null>(null)
+
   return (
-    <Layer
-      className={sidebar}
-      data-overlay={overlay}
-      style={overlay ? undefined : {width}}
-      zOffset={100}
-    >
-      <Card borderLeft={!overlay} className={frame} height="fill">
-        {!overlay && (
-          <div
-            aria-label="Resize the themer"
-            className={resizeHandle}
-            aria-orientation="vertical"
-            aria-valuemax={MAXIMUM_WIDTH}
-            aria-valuemin={MINIMUM_WIDTH}
-            aria-valuenow={width}
-            data-dragging={dragging}
-            onDoubleClick={() => setWidth(MINIMUM_WIDTH)}
-            onKeyDown={handleKeyDown}
-            onPointerCancel={handlePointerUp}
-            onPointerDown={handlePointerDown}
-            onPointerMove={handlePointerMove}
-            onPointerUp={handlePointerUp}
-            // oxlint-disable-next-line prefer-tag-over-role -- a window splitter is a focusable, draggable separator, which an hr is not
-            role="separator"
-            tabIndex={0}
-          />
-        )}
+    <Layer className={sidebar} style={{width}} zOffset={100}>
+      <Card
+        borderLeft
+        className={frame}
+        height="fill"
+        ref={(boundaryElement) => {
+          startTransition(() => setBoundaryElement(boundaryElement))
+          // Intentionally not unsetting the element as it would create unnecessary work when <Activity> unhides
+          return () => {}
+        }}
+      >
+        <div
+          aria-label="Resize the themer"
+          className={resizeHandle}
+          aria-orientation="vertical"
+          aria-valuemax={MAXIMUM_WIDTH}
+          aria-valuemin={MINIMUM_WIDTH}
+          aria-valuenow={width}
+          data-dragging={dragging}
+          onDoubleClick={() => setWidth(MINIMUM_WIDTH)}
+          onKeyDown={handleKeyDown}
+          onPointerCancel={handlePointerUp}
+          onPointerDown={handlePointerDown}
+          onPointerMove={handlePointerMove}
+          onPointerUp={handlePointerUp}
+          // oxlint-disable-next-line prefer-tag-over-role -- a window splitter is a focusable, draggable separator, which an hr is not
+          role="separator"
+          tabIndex={0}
+        />
         <Box className={content} height="fill" overflow="hidden">
-          <ThemerSidebar />
+          <BoundaryElementProvider element={boundaryElement}>
+            <ThemerSidebar
+              split={split}
+              navbarHeight={navbarHeight}
+              actorRef={actorRef}
+              dispatch={dispatch}
+            />
+          </BoundaryElementProvider>
         </Box>
       </Card>
     </Layer>

diff --git a/plugins/@sanity/themer/src/tool/ScrollArea.tsx b/plugins/@sanity/themer/src/tool/ScrollArea.tsx
--- a/plugins/@sanity/themer/src/tool/ScrollArea.tsx
+++ b/plugins/@sanity/themer/src/tool/ScrollArea.tsx
@@ -74,7 +74,7 @@
       ref={ref}
       style={{paddingRight: inset.right}}
     >
-      <ScrollAreaInsetContext.Provider value={inset}>{children}</ScrollAreaInsetContext.Provider>
+      <ScrollAreaInsetContext value={inset}>{children}</ScrollAreaInsetContext>
     </Box>
   )
 }

diff --git a/plugins/@sanity/themer/src/tool/ThemeCard.tsx b/plugins/@sanity/themer/src/tool/ThemeCard.tsx
--- a/plugins/@sanity/themer/src/tool/ThemeCard.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemeCard.tsx
@@ -12,7 +12,8 @@
 import {useRef, useState} from 'react'
 import scrollIntoView from 'scroll-into-view-if-needed'
 
-import {useThemer} from './context'
+import type {ThemerProps} from '#types'
+
 import {displayTitle, type ThemerTheme} from './themes'
 import {ThemeThumbnail} from './ThemeThumbnail'
 import {useThemeCodes} from './useThemeCodes'
@@ -37,10 +38,13 @@
  *
  * @internal
  */
-export function ThemeCard(props: {active: boolean; theme: ThemerTheme}) {
-  const {active, theme} = props
-  const {themes, send} = useThemer()
-  const {copyTheme} = useThemeCodes()
+export function ThemeCard({
+  actorRef,
+  active,
+  theme,
+  themes,
+}: {active: boolean; theme: ThemerTheme} & Pick<ThemerProps, 'actorRef' | 'themes'>) {
+  const {copyTheme} = useThemeCodes({actorRef})
   const {scheme} = useRootTheme()
   const [menuOpen, setMenuOpen] = useState(false)
   const dragControls = useDragControls()
@@ -48,12 +52,14 @@
   const dragged = useRef(false)
   const title = displayTitle(theme.title)
   const index = themes.findIndex((candidate) => candidate.slug === theme.slug)
+  // The configured theme sits ahead of the list, and does not move within it
+  const listed = index !== -1
 
   const moveTo = (to: number) => {
     const order = themes.map((candidate) => candidate.slug)
 
     order.splice(to, 0, ...order.splice(index, 1))
-    send({type: 'theme.reorder', order})
+    actorRef.send({type: 'theme.reorder', order})
   }
 
   return (
@@ -79,12 +85,12 @@
         aria-pressed={active}
         className={pickButton}
         onClick={() => {
-          if (!dragged.current) send({type: 'theme.pick', slug: theme.slug})
+          if (!dragged.current) actorRef.send({type: 'theme.pick', slug: theme.slug})
         }}
         onPointerDown={(event) => {
           // A mouse or pen drags the card off the button; a finger scrolls the
           // list instead, and moves themes from the menu
-          if (event.pointerType !== 'touch') dragControls.start(event)
+          if (listed && event.pointerType !== 'touch') dragControls.start(event)
         }}
         type="button"
       >
@@ -125,29 +131,33 @@
               id={`themer-theme-${theme.slug}`}
               menu={
                 <Menu>
-                  <MenuItem
-                    disabled={index <= 0}
-                    icon={ArrowUpIcon}
-                    onClick={() => moveTo(index - 1)}
-                    text="Move up"
-                  />
-                  <MenuItem
-                    disabled={index >= themes.length - 1}
-                    icon={ArrowDownIcon}
-                    onClick={() => moveTo(index + 1)}
-                    text="Move down"
-                  />
-                  <MenuDivider />
+                  {listed && (
+                    <>
+                      <MenuItem
+                        disabled={index <= 0}
+                        icon={ArrowUpIcon}
+                        onClick={() => moveTo(index - 1)}
+                        text="Move up"
+                      />
+                      <MenuItem
+                        disabled={index >= themes.length - 1}
+                        icon={ArrowDownIcon}
+                        onClick={() => moveTo(index + 1)}
+                        text="Move down"
+                      />
+                      <MenuDivider />
+                    </>
+                  )}
                   {theme.source === 'custom' && (
                     <MenuItem
                       icon={EditIcon}
-                      onClick={() => send({type: 'theme.edit', slug: theme.slug})}
+                      onClick={() => actorRef.send({type: 'theme.edit', slug: theme.slug})}
                       text="Edit"
                     />
                   )}
                   <MenuItem
                     icon={CopyIcon}
-                    onClick={() => send({type: 'theme.duplicate', slug: theme.slug})}
+                    onClick={() => actorRef.send({type: 'theme.duplicate', slug: theme.slug})}
                     text={theme.source === 'custom' ? 'Duplicate' : 'Duplicate to edit'}
                   />
                   <MenuItem
@@ -160,7 +170,7 @@
                       <MenuDivider />
                       <MenuItem
                         icon={TrashIcon}
-                        onClick={() => send({type: 'theme.remove', slug: theme.slug})}
+                        onClick={() => actorRef.send({type: 'theme.remove', slug: theme.slug})}
                         text="Remove"
                         tone="critical"
                       />

diff --git a/plugins/@sanity/themer/src/tool/ThemeEditor.tsx b/plugins/@sanity/themer/src/tool/ThemeEditor.tsx
--- a/plugins/@sanity/themer/src/tool/ThemeEditor.tsx
+++ b/plugins/@sanity/themer/src/tool/ThemeEditor.tsx
@@ -2,9 +2,12 @@
 import {TrashIcon} from '@sanity/icons/Trash'
 import {Badge, Box, Button, Card, Flex, Stack, Text, TextInput} from '@sanity/ui'
 import {type ThemeColorSchemeKey} from '@sanity/ui/theme'
+import {useSelector} from '@xstate/react'
 import {useMemo} from 'react'
 import {useColorSchemeValue} from 'sanity'
 
+import type {ThemerProps} from '#types'
+
 import {buildPalette, type GeneratedColorPalette} from '../theme/buildPalette'
 import {
   type BuildThemeOptions,
@@ -13,7 +16,6 @@
   SCHEMES,
   type SchemeThemeOptions,
 } from '../theme/options'
-import {useThemer} from './context'
 import {
   applyImagePalette,
   currentImageVariant,
@@ -38,9 +40,7 @@
  * to the sidebar (or at the bottom, stacked on small screens), the other one
  * takes the far side
  */
-function splitHint(own: boolean, mobile: boolean): string {
-  if (mobile) return own ? 'Shown at the bottom' : 'Shown at the top'
-
+function splitHint(own: boolean): string {
   return own ? 'Shown on the right, next to the themer' : 'Shown on the left'
 }
 
@@ -65,9 +65,14 @@
  *
  * @internal
  */
-export function ThemeEditor(props: {focusTitle: boolean; slug: string}) {
-  const {focusTitle, slug} = props
-  const {themes, images, split, mobile, send} = useThemer()
+export function ThemeEditor({
... diff truncated: showing 800 of 9210 lines

You can send follow-ups to the cloud agent here.

Reviewed by Cursor Bugbot for commit 3b2c35b. Configure here.

<ThemeProvider theme={(state.theme !== null ? buildTheme(state.theme) : null) ?? undefined}>
<ThemerLayout
config={config}
backgroundColor={state.theme?.[scheme]?.background}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied theme background is incomplete

Medium Severity

The layout uses state.theme?.[scheme]?.background, the raw option, and no longer paints document.body with the built theme. Presets that only set an accent leave chrome, overscroll, and layout gaps on the previous color.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3b2c35b. Configure here.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Comment on lines +99 to +104
icon={
// The animated wheel needs `motion/react`, which is heavy, so it
// loads lazily — behind the plain icon it reimplements
<Suspense fallback={<ColorWheelIcon />}>
<AnimatedColorWheelIcon busy={busy} ref={iconRef} />
</Suspense>
Copilot AI balanced review requested due to automatic review settings October 2, 2026 16:33
@stipsan
stipsan force-pushed the themer-state-refactor branch from 3b2c35b to a9b43a2 Compare October 2, 2026 16:33
@stipsan
stipsan merged commit e1c357b into main Oct 2, 2026
26 checks passed
@stipsan
stipsan deleted the themer-state-refactor branch October 2, 2026 16:38

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

'@sanity/themer': minor
---

Adopt <Activity>, <ViewTransition> and React.lazy APIs according to best practice. Removes the top-level default theme config, it will be added back again later
direction={'row'}
height="fill"
sizing="border"
style={{backgroundColor}}
@squiggler-app squiggler-app Bot mentioned this pull request Oct 2, 2026
stipsan pushed a commit that referenced this pull request Oct 2, 2026
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and the packages will
be published to npm automatically. If you're not ready to do a release
yet, that's fine, whenever you add more changesets to main, this PR will
be updated.


# Releases
## @sanity/[email protected]

### Minor Changes

- [#2065](#2065)
[`e1c357b`](e1c357b)
Thanks [@stipsan](https://github.com/stipsan)! - Adopt <Activity>,
<ViewTransition> and React.lazy APIs according to best practice. Removes
the top-level default theme config, it will be added back again later
## @sanity/[email protected]

### Patch Changes

- [#2047](#2047)
[`89bbaf7`](89bbaf7)
Thanks [@stipsan](https://github.com/stipsan)! - Update the optional
`oxfmt` peer dependency to ^0.71.0

- [#2047](#2047)
[`89bbaf7`](89bbaf7)
Thanks [@stipsan](https://github.com/stipsan)! - The
`@sanity/plugin-kit/oxfmt` preset no longer formats `.changeset/*.md`
files with double quotes, so their frontmatter gets single quotes like
the rest of your code. Changesets 3 formats the changesets it writes
with oxfmt when it finds your `oxfmt.config.ts`, or when
`.changeset/config.json` sets `"format": "oxfmt"`, so they come out the
same way.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Themer’s minor release documents a breaking-adjacent removal of
default theme config; plugin-kit is tooling-only but may change how
changeset files format in repos using the oxfmt preset.
> 
> **Overview**
> This is a **Changesets release** PR that publishes two npm packages by
bumping versions, folding pending changesets into each package’s
`CHANGELOG.md`, and deleting the consumed `.changeset/*.md` files.
> 
> **`@sanity/[email protected]`** (patch): release notes record a bump
of the optional `oxfmt` peer to `^0.71.0` and a tweak to the
`@sanity/plugin-kit/oxfmt` preset so `.changeset/*.md` frontmatter uses
single quotes, aligning with Changesets 3 when oxfmt is enabled.
> 
> **`@sanity/[email protected]`** (minor): release notes cover adopting React
`<Activity>`, `<ViewTransition>`, and `React.lazy` patterns, and
**removing the top-level default theme config** (called out as temporary
until it returns).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7b2b0b2. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: squiggler-app[bot] <265501495+squiggler-app[bot]@users.noreply.github.com>
stipsan added a commit that referenced this pull request Oct 5, 2026
…nd review follow-ups to #2065 (#2066)

<!-- CURSOR_AGENT_PR_BODY_BEGIN -->
Follow-up to #2065, now that it has landed on `main` (this PR was
stacked on it and GitHub retargeted it to `main` when the branch went).
Sixteen commits, each a delta `main` lacks.

## What it does

**Cross-tab sync actually runs.** `main` ships `sync.ts`
(BroadcastChannel + a Web Lock electing the one tab that persists) but
nothing calls it: `PersistActorSnapshot` still writes on
`requestIdleCallback`. It now runs `syncThemer(actorRef, {persist:
writePersistedSnapshot})`, so themes picked, edited, added or removed in
one tab show in the others, writes are idle-deferred and flushed on
`pagehide`, and knip stops flagging `sync.ts`.

**Sidebar footers follow the Studio's document footer** (one main
action, the rest behind a `…` menu — see screenshots):
- Header: only the split preview toggle and the close button (the code
button and the back arrow are gone).
- List footer: **`Edit`** when the applied theme is one of the user's
own, **`Duplicate & Edit`** for a preset or the configured theme; the
menu holds `Add theme`, `Add from image`, `Add from code` and — for a
listed applied theme — `Show theme code` (the snippet dialog, moved here
from the header). The image picker's hidden input is now its own
`ImageFileInput`, which the menu item clicks; the menu button shows
`loading` while an image's palette is read.
- Editor footer: **`Done`**, with `Remove` in the menu.
- Removed themes: a **`Done`** footer back to the list, in place of the
header's back arrow.
- Buttons are the Studio's own size (`padding: 2`, `gap: 2`, font size
1, as `DEFAULT_BUTTON_PROPS` in sanity's `Button`), in `ghost` mode, and
the main actions carry an icon: `Edit` a pencil, `Duplicate & Edit` a
copy, `Done` a checkmark. The footer menus animate like the cards' do.
- The list's two dialogs are states of the machine's list flow (`idle` /
`pasting` / `snippet`; events `dialog.paste`, `dialog.snippet` — guarded
on an applied listed theme, left when it goes away — and
`dialog.close`), so leaving the list closes them, and the
persisted-snapshot schema restores a dialog-open snapshot to the plain
list.
- The cards' own `…` menus are untouched. Labels are short on purpose:
your `BoundaryElementProvider` confines the menu to the sidebar, which
can be narrow.
- Every element id (menus, dialogs, the paste dialog's error) comes from
`useId()`; no hardcoded ids remain under `src/`.

[The Studio document footer (Publish and the more menu) next to the
themer footer (Duplicate &amp; Edit and the more menu), the buttons the
same
height](https://cursor.com/agents/bc-5f1ecba9-2792-59bb-99f3-e7db7346d6e5/artifacts?path=%2Fopt%2Fcursor%2Fartifacts%2Fthemer-footer-vs-studio-footer.png)
[Themer list footer: Duplicate &amp; Edit plus the menu with Add theme,
Add from image, Add from code, Show theme
code](https://cursor.com/agents/bc-5f1ecba9-2792-59bb-99f3-e7db7346d6e5/artifacts?path=%2Fopt%2Fcursor%2Fartifacts%2Fthemer-list-footer-menu.png)
[Themer editor footer: Done plus the menu with
Remove](https://cursor.com/agents/bc-5f1ecba9-2792-59bb-99f3-e7db7346d6e5/artifacts?path=%2Fopt%2Fcursor%2Fartifacts%2Fthemer-editor-footer-menu.png)

**Safari: the Studio scaled wrongly while it resized with the split
copy.** Safari (WebKit, as of Technology Preview 253) paints a
view-transition snapshot that has a `filter` animating on it as raw
layer contents, losing the `object-fit` stretch of `resizeStudioRules` —
remove the blur and it animates like Chrome. The blur now sits on the
`::view-transition-image-pair`, which holds both snapshots and is a
plain box, as one blur peaking at the cross-over (6px, what the two 12px
blurs on the snapshots crossfaded into at that point), while the
snapshots keep the stretch and only fade. Verified in Chromium and
WebKit on the real Studio that the pair carries the blur and the
snapshots keep their sizing rules. A reduced case for Safari (variant A
= snapshots, variant B = image pair) is attached as an artifact:
`safari-snapshot-filter-repro.html`.

**Review comments on #2065 that still applied, fixed here:**
- *Hidden list leaves picker busy* (Bugbot) — `useImagePalette` guarded
`setBusy(false)` with a mounted flag that goes false when the list's
`Activity` hides on `theme.add`, so the image button stayed loading. The
list's state survives being hidden; only the pick number guards the
result now.
- *Wheel ignores reduced motion* (Bugbot, Copilot) — the navbar renders
the plain `ColorWheelIcon` under `prefers-reduced-motion: reduce`
(`usePrefersReducedMotion` from `@sanity/ui`), so
`AnimatedColorWheelIcon` and `motion/react` are not even loaded then.
- *Themer toggle inert on small viewports* — per review, left to the
toolbar's own breakpoints; `ThemerProvider` reads the sidebar threshold
from `MIN_MEDIA_INDEX_FOR_SIDEBAR` (2).
- *Applied theme background is incomplete* — reverted per review, for a
follow-up PR.

**Also:** the commented-out crossfade experiment in
`ViewTransitions.css.ts` (it refers to keyframes that are gone), docs
for the layout (no more `panel`/`split`/`moving` tags or
`ThemerLayout.css.ts`), the reducer and `ThemerProps` (minus
`images`/`view`, which nothing picks), the README's `title` option in
place of the removed `config`, a `minor` changeset, and the `AGENTS.md`
note about Turbo's `pnpm run` re-resolving the lockfile locally.

## Review comments on #2065 I did not act on

- *Split types clash on sidebar toggle* — opening the sidebar with the
split on adds both `open` and `split-screen:open`, so the Studio gets
the resize and the blur-fade together. Looks deliberate (the split copy
needs its type to slide in); your call.
- *Lazy `AnimatedColorWheelIcon` imports `motion/react` at navbar mount*
(Copilot) — a startup-cost question, not a bug; the hover spin needs the
icon ready.
- *Closing the sidebar keeps the split* — you marked it intentional.
*Theme rebuilt on every render* — React Compiler, as you said. *Config
card shows the stock theme* — by design until `config` returns.
*Changeset should be major* — `minor`, 0.x.

## Verification

- Manual, in the test studio (video below): footer buttons measured at
24.98px, the same as the document footer's `Publish`, with
`copy`/`checkmark` icons; header buttons, both footers and their menus,
`Duplicate & Edit` → editor → `Remove` → `Show removed (1)` → `Delete` →
back in the list, `Show theme code` present for a preset and absent for
the configured theme; no console errors.
- Dialogs, on the built studio (Playwright): `Add from code` opens the
paste dialog (clipboard unavailable), a bad code shows the error, Escape
closes it; `Show theme code` opens the snippet dialog for a preset and
does not return after a reload; the configured theme's menu has no
snippet item.
- Split transition probed in Chromium and WebKit (Playwright) on the
built Studio: `::view-transition-image-pair` gets the 6px blur, the
snapshots our fades plus the stretch rules, the split copy its slide,
all at 480ms.
- `oxfmt --check` clean; `oxlint --disable-nested-config` (whole repo,
type-aware) 0 errors; `CI=1 knip` clean
- `@sanity/themer` tsdown build (publint clean) and the Storybook static
build
- `vitest run --project @sanity/themer`: 13 files, 143 tests
- Storybook browser tests (headless Chromium): 4 files, 7 stories
- `pnpm install --frozen-lockfile` passes


[themer-sidebar-footer-actions.mp4](https://cursor.com/agents/bc-5f1ecba9-2792-59bb-99f3-e7db7346d6e5/artifacts?path=%2Fopt%2Fcursor%2Fartifacts%2Fthemer-sidebar-footer-actions.mp4)

<sub>To show artifacts inline, <a
href="https://cursor.com/dashboard/cloud-agents#team-pull-requests">enable</a>
in settings.</sub>
<!-- CURSOR_AGENT_PR_BODY_END -->

<div><a
href="https://cursor.com/agents/bc-5f1ecba9-2792-59bb-99f3-e7db7346d6e5?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-web-light.png"><img
alt="Open in Web" width="114" height="28"
src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a>&nbsp;<a
href="https://cursor.com/background-agent?bcId=bc-5f1ecba9-2792-59bb-99f3-e7db7346d6e5&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img
alt="Open in Cursor" width="131" height="28"
src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a>&nbsp;</div>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Cody Olsen <[email protected]>

This branch was successfully deployed

1 active deployment
Preview – plugins-studio — a9b43a23 Deployed Oct 2, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants