From 2ee7e0f83205517ce37ee65d986471ebac95264d Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 20 Oct 2024 20:02:46 -0400 Subject: [PATCH] Use view transition API to smoothly transition between light/dark theme --- app/stores/UiStore.ts | 8 +++++++- app/utils/viewTransition.ts | 13 +++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 app/utils/viewTransition.ts diff --git a/app/stores/UiStore.ts b/app/stores/UiStore.ts index 84c59675a0..ecbeb68c77 100644 --- a/app/stores/UiStore.ts +++ b/app/stores/UiStore.ts @@ -1,8 +1,10 @@ import { action, autorun, computed, observable } from "mobx"; +import { flushSync } from "react-dom"; import { light as defaultTheme } from "@shared/styles/theme"; import Storage from "@shared/utils/Storage"; import Document from "~/models/Document"; import type { ConnectionStatus } from "~/scenes/Document/components/MultiplayerEditor"; +import { startViewTransition } from "~/utils/viewTransition"; import type RootStore from "./RootStore"; const UI_STORE = "UI_STORE"; @@ -140,7 +142,11 @@ class UiStore { @action setTheme = (theme: Theme) => { - this.theme = theme; + startViewTransition(() => { + flushSync(() => { + this.theme = theme; + }); + }); Storage.set("theme", this.theme); }; diff --git a/app/utils/viewTransition.ts b/app/utils/viewTransition.ts new file mode 100644 index 0000000000..95dcef9461 --- /dev/null +++ b/app/utils/viewTransition.ts @@ -0,0 +1,13 @@ +/** + * A simple wrapper around the startViewTransition API, if it exists. Otherwise + * it will just call the callback immediately. + * + * @param callback The callback to call inside the view transition. + */ +export const startViewTransition = (callback: UpdateCallback) => { + if (self.document.startViewTransition) { + self.document.startViewTransition(callback); + } else { + callback(); + } +};