Skip to content

An open-source, self-hosted system for apps built with web technologies.

Add coherent desktop theme transitions

zohayrslilehfc6e77a687e2
diff --git a/source/client/view/appearance/appearance.css b/source/client/view/appearance/appearance.css
index 1f9d805..713fe60 100644
--- a/source/client/view/appearance/appearance.css
+++ b/source/client/view/appearance/appearance.css
@@ -3,6 +3,77 @@
@import "@fontsource/roboto";
+html[data-phreshos-theme-capture] * {
+
+ transition-delay: 0ms !important;
+
+ transition-duration: 0ms !important;
+
+}
+
+html[data-phreshos-theme-transition]::view-transition-old(root),
+html[data-phreshos-theme-transition]::view-transition-new(root) {
+
+ animation-duration: var(--phreshos-theme-transition-duration);
+
+ animation-fill-mode: both;
+
+ animation-timing-function: var(--phreshos-theme-transition-easing);
+
+}
+
+html[data-phreshos-theme-transition]::view-transition-old(root) {
+
+ animation-name: phreshos-theme-leave;
+
+}
+
+html[data-phreshos-theme-transition]::view-transition-new(root) {
+
+ animation-name: phreshos-theme-enter;
+
+}
+
+@keyframes phreshos-theme-leave {
+
+ from {
+
+ opacity: 1;
+
+ scale: 1;
+
+ }
+
+ to {
+
+ opacity: 0;
+
+ scale: 1.05;
+
+ }
+
+}
+
+@keyframes phreshos-theme-enter {
+
+ from {
+
+ opacity: 0;
+
+ scale: 1.05;
+
+ }
+
+ to {
+
+ opacity: 1;
+
+ scale: 1;
+
+ }
+
+}
+
@theme {
--font-roboto: "Roboto", sans-serif;
diff --git a/source/client/view/appearance/desktop-preferences.tsx b/source/client/view/appearance/desktop-preferences.tsx
index 992eea1..24b940f 100644
--- a/source/client/view/appearance/desktop-preferences.tsx
+++ b/source/client/view/appearance/desktop-preferences.tsx
@@ -1,10 +1,13 @@
import useStorage from "@libs/storage-hook"
import {
+ defaultAppearance,
+ type AppearanceTransaction,
type DesktopPreferences,
type DesktopPreferencesUpdate,
type Theme
} from "@phreshos/core"
-import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useSyncExternalStore, type ReactNode } from "react"
+import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react"
+import { transitionTheme } from "./theme-transition"
const themeQuery = "(prefers-color-scheme: dark)"
const reducedMotionQuery = "(prefers-reduced-motion: reduce)"
@@ -19,9 +22,14 @@ export default function DesktopPreferencesProvider({ children }: Readonly<{ chil
const storedAnimations = useStorage(animationsKey)
const nativeDark = useMediaPreference(themeQuery)
const nativeReducedMotion = useMediaPreference(reducedMotionQuery)
- const theme = selectedTheme(storedTheme.value, nativeDark)
- const animations = selectedAnimations(storedAnimations.value, nativeReducedMotion)
- const preferences = useMemo<DesktopPreferences>(() => ({ theme, animations }), [animations, theme])
+ const desiredTheme = selectedTheme(storedTheme.value, nativeDark)
+ const desiredAnimations = selectedAnimations(storedAnimations.value, nativeReducedMotion)
+ const desired = useMemo<DesktopPreferences>(() => ({ theme: desiredTheme, animations: desiredAnimations }), [desiredAnimations, desiredTheme])
+ const [preferences, setPreferences] = useState(desired)
+ const current = useRef(preferences)
+ const pending = useRef<PendingCommit | null>(null)
+ const revision = useRef(0)
+ const transaction = useRef<AppearanceTransaction>(defaultAppearance.transaction)
const update = useCallback(function (change: DesktopPreferencesUpdate) {
if (change.theme !== undefined) {
@@ -35,16 +43,57 @@ export default function DesktopPreferencesProvider({ children }: Readonly<{ chil
}
}, [storedAnimations.remove, storedAnimations.update, storedTheme.remove, storedTheme.update])
+ const setTransaction = useCallback(function (value: AppearanceTransaction) {
+ transaction.current = value
+ }, [])
+
+ useEffect(() => {
+ if (samePreferences(current.current, desired)) return
+
+ pending.current?.resolve()
+ pending.current = null
+
+ const change = ++revision.current
+ const themeChanged = current.current.theme !== desired.theme
+
+ if (!themeChanged) {
+ setPreferences(desired)
+ return
+ }
+
+ void transitionTheme(document, transaction.current, desired.animations, async () => {
+ if (revision.current !== change) return
+
+ await new Promise<void>(resolve => {
+ pending.current = { preferences: desired, resolve }
+ setPreferences(desired)
+ })
+ })
+ }, [desired])
+
useLayoutEffect(() => {
const root = document.documentElement
const previous = root.style.colorScheme
+ current.current = preferences
root.style.colorScheme = preferences.theme
+ const commit = pending.current
+
+ if (commit && samePreferences(commit.preferences, preferences)) {
+ pending.current = null
+ queueMicrotask(commit.resolve)
+ }
+
return () => { root.style.colorScheme = previous }
- }, [preferences.theme])
+ }, [preferences])
- const owner = useMemo(() => ({ preferences, update }), [preferences, update])
+ useEffect(() => () => {
+ pending.current?.resolve()
+ pending.current = null
+ }, [])
+
+ const owner = useMemo(() => ({ preferences, update, setTransaction }), [preferences, update, setTransaction])
return <DesktopPreferencesContext.Provider value={owner}>{children}</DesktopPreferencesContext.Provider>
}
@@ -56,6 +105,15 @@ export function useDesktopPreferences() {
return owner
}
+/** Supplies the active Appearance timing to the Desktop-owned theme transition. */
+export function useDesktopThemeTransaction(transaction: AppearanceTransaction) {
+ const owner = useDesktopPreferences()
+
+ useLayoutEffect(() => {
+ owner.setTransaction(transaction)
+ }, [owner, transaction])
+}
+
function selectedTheme(value: string | null, nativeDark: boolean): Theme {
return value === "light" || value === "dark" ? value : nativeDark ? "dark" : "light"
}
@@ -81,4 +139,14 @@ function useMediaPreference(query: string) {
interface DesktopPreferencesOwner {
readonly preferences: DesktopPreferences
readonly update: (change: DesktopPreferencesUpdate) => void
+ readonly setTransaction: (transaction: AppearanceTransaction) => void
+}
+
+interface PendingCommit {
+ readonly preferences: DesktopPreferences
+ readonly resolve: () => void
+}
+
+function samePreferences(first: DesktopPreferences, second: DesktopPreferences) {
+ return first.theme === second.theme && first.animations === second.animations
}
diff --git a/source/client/view/appearance/theme-transition.ts b/source/client/view/appearance/theme-transition.ts
new file mode 100644
index 0000000..42e6b30
--- /dev/null
+++ b/source/client/view/appearance/theme-transition.ts
@@ -0,0 +1,94 @@
+import type { AppearanceTransaction } from "@phreshos/core"
+import { cssEasing } from "./motion"
+
+const durationProperty = "--phreshos-theme-transition-duration"
+const easingProperty = "--phreshos-theme-transition-easing"
+
+type NativeViewTransition = Readonly<{
+ ready: Promise<unknown>
+ finished: Promise<unknown>
+ skipTransition: () => void
+}>
+
+type ViewTransitionDocument = Document & Readonly<{
+ startViewTransition?: (update: () => Promise<void>) => NativeViewTransition
+}>
+
+type ActiveTransition = Readonly<{
+ revision: number
+ transition: NativeViewTransition
+}>
+
+const active = new WeakMap<Document, ActiveTransition>()
+const revisions = new WeakMap<Document, number>()
+
+/** Applies one theme state change through the document's old and new rendered views. */
+export function transitionTheme(
+ document: Document,
+ transaction: AppearanceTransaction,
+ animated: boolean,
+ update: () => Promise<void>
+) {
+ const target = document as ViewTransitionDocument
+ const revision = (revisions.get(document) ?? 0) + 1
+ const previous = active.get(document)
+
+ revisions.set(document, revision)
+
+ if (!animated || !target.startViewTransition) {
+ previous?.transition.skipTransition()
+ active.delete(document)
+ clearTransition(document)
+ return update()
+ }
+
+ const root = document.documentElement
+ root.dataset.phreshosThemeTransition = ""
+ root.style.setProperty(durationProperty, `${transaction.duration}ms`)
+ root.style.setProperty(easingProperty, cssEasing(transaction.easing))
+
+ let view: NativeViewTransition
+
+ try {
+ view = target.startViewTransition(async () => {
+ if (revisions.get(document) !== revision) return
+
+ root.dataset.phreshosThemeCapture = ""
+ await update()
+ })
+ }
+ catch {
+ previous?.transition.skipTransition()
+ active.delete(document)
+ clearTransition(document)
+ return update()
+ }
+
+ active.set(document, { revision, transition: view })
+
+ settle(view.ready, () => {
+ if (revisions.get(document) === revision) delete root.dataset.phreshosThemeCapture
+ })
+
+ settle(view.finished, () => {
+ if (active.get(document)?.revision !== revision) return
+
+ active.delete(document)
+ clearTransition(document)
+ })
+
+ return view.finished.then(() => undefined, () => undefined)
+}
+
+function settle(promise: Promise<unknown>, complete: () => void) {
+ void promise.then(complete, complete)
+}
+
+function clearTransition(document: Document) {
+ const root = document.documentElement
+
+ delete root.dataset.phreshosThemeCapture
+ delete root.dataset.phreshosThemeTransition
+ root.style.removeProperty(durationProperty)
+ root.style.removeProperty(easingProperty)
+}
diff --git a/source/client/view/structure/structure.tsx b/source/client/view/structure/structure.tsx
index f981717..3c06aa6 100644
--- a/source/client/view/structure/structure.tsx
+++ b/source/client/view/structure/structure.tsx
@@ -7,7 +7,7 @@ import Loading from "../components/loading"
import Alert from "../components/alert"
import { ApplicationContext, LinkManagerContext } from "../contexts"
import usePromise from "@libs/react-promise"
-import { useDesktopPreferences } from "../appearance/desktop-preferences"
+import { useDesktopPreferences, useDesktopThemeTransaction } from "../appearance/desktop-preferences"
import Authentication from "./authentication/authentication"
import { useCallback, useEffect, useState } from "react"
import Readiness, { useReady } from "@libs/readiness"
@@ -115,6 +115,8 @@ function ConnectedDesktop({ linkManager }: { linkManager: LinkManager }) {
const appearance = useProperty(linkManager.appearance)
+ useDesktopThemeTransaction(appearance.transaction)
+
useEffect(function () {
void linkManager.updateDesktopPreferences(preferences)
}, [linkManager, preferences])
diff --git a/tests/theme-transition.test.ts b/tests/theme-transition.test.ts
new file mode 100644
index 0000000..f0bf46a
--- /dev/null
+++ b/tests/theme-transition.test.ts
@@ -0,0 +1,120 @@
+import assert from "node:assert/strict"
+import type { AppearanceTransaction } from "@phreshos/core"
+import { transitionTheme } from "@client/view/appearance/theme-transition"
+import { test } from "vitest"
+
+const transaction = { duration: 180, easing: [0.2, 0.4, 0.6, 0.8] } satisfies AppearanceTransaction
+
+test("theme transitions capture one complete old and new document state", async () => {
+ const ready = deferred()
+ const finished = deferred()
+ const commit = deferred()
+ const document = fakeDocument()
+ let update: (() => Promise<void>) | undefined
+ let changes = 0
+
+ document.startViewTransition = callback => {
+ update = callback
+ return {
+ ready: ready.promise,
+ finished: finished.promise,
+ skipTransition() {}
+ }
+ }
+
+ const complete = transitionTheme(document as unknown as Document, transaction, true, async () => {
+ changes += 1
+ await commit.promise
+ })
+
+ assert.equal(changes, 0)
+ assert.equal(document.documentElement.dataset.phreshosThemeTransition, "")
+ assert.equal(document.documentElement.style.values.get("--phreshos-theme-transition-duration"), "180ms")
+ assert.equal(document.documentElement.style.values.get("--phreshos-theme-transition-easing"), "cubic-bezier(0.2, 0.4, 0.6, 0.8)")
+
+ const updated = update!()
+
+ assert.equal(changes, 1)
+ assert.equal(document.documentElement.dataset.phreshosThemeCapture, "")
+
+ commit.resolve()
+ await updated
+
+ ready.resolve()
+ await ready.promise
+ await Promise.resolve()
+
+ assert.equal(document.documentElement.dataset.phreshosThemeCapture, undefined)
+ assert.equal(document.documentElement.dataset.phreshosThemeTransition, "")
+
+ finished.resolve()
+ await complete
+ await Promise.resolve()
+
+ assert.equal(document.documentElement.dataset.phreshosThemeTransition, undefined)
+ assert.equal(document.documentElement.style.values.size, 0)
+})
+
+test("theme changes remain functional without animation support", async () => {
+ const document = fakeDocument()
+ let changes = 0
+
+ await transitionTheme(document as unknown as Document, transaction, true, async () => {
+ changes += 1
+ })
+
+ assert.equal(changes, 1)
+ assert.deepEqual(document.documentElement.dataset, {})
+ assert.equal(document.documentElement.style.values.size, 0)
+})
+
+test("disabling animations interrupts an active theme transition", async () => {
+ const firstReady = deferred()
+ const firstFinished = deferred()
+ const document = fakeDocument()
+ let skipped = false
+
+ document.startViewTransition = () => ({
+ ready: firstReady.promise,
+ finished: firstFinished.promise,
+ skipTransition() { skipped = true }
+ })
+
+ void transitionTheme(document as unknown as Document, transaction, true, async () => {})
+ await transitionTheme(document as unknown as Document, transaction, false, async () => {})
+
+ assert.equal(skipped, true)
+ assert.deepEqual(document.documentElement.dataset, {})
+ assert.equal(document.documentElement.style.values.size, 0)
+
+ firstReady.resolve()
+ firstFinished.resolve()
+})
+
+function deferred() {
+ let resolve!: () => void
+ const promise = new Promise<void>(accept => { resolve = accept })
+
+ return { promise, resolve }
+}
+
+function fakeDocument() {
+ const dataset: Record<string, string | undefined> = {}
+ const values = new Map<string, string>()
+
+ return {
+ documentElement: {
+ dataset,
+ style: {
+ values,
+ setProperty(name: string, value: string) { values.set(name, value) },
+ removeProperty(name: string) { values.delete(name) }
+ }
+ },
+ startViewTransition: undefined as undefined | ((update: () => Promise<void>) => {
+ ready: Promise<unknown>
+ finished: Promise<unknown>
+ skipTransition(): void
+ })
+ }
+}