From dc3b77f82b7b80be6ca9249899c450f9a422b6ac Mon Sep 17 00:00:00 2001 From: StroepWafel Date: Wed, 26 Aug 2026 21:11:53 +0930 Subject: [PATCH] fix(settings): issues with new themes systems --- .../components/themes/ThemeSelector.svelte | 239 +++++++++++------- src/interface/pages/communityThemes.svelte | 6 +- src/interface/pages/themeCreator.svelte | 12 +- src/interface/utils/themeListFilters.test.ts | 94 ++++++- src/interface/utils/themeListFilters.ts | 34 ++- src/plugins/built-in/themes/theme-manager.ts | 16 +- src/seqta/ui/colors/Manager.ts | 5 +- .../syncTransparencyEffectsClass.test.ts | 20 ++ .../ui/colors/syncTransparencyEffectsClass.ts | 10 + .../utils/Closers/closeExtensionPopup.ts | 46 +++- src/seqta/utils/listeners/StorageChanges.ts | 8 +- .../utils/settingsPopupTransition.test.ts | 30 +++ src/seqta/utils/settingsPopupTransition.ts | 43 ++++ src/seqta/utils/setupSettingsButton.ts | 61 +++-- 14 files changed, 477 insertions(+), 147 deletions(-) create mode 100644 src/seqta/ui/colors/syncTransparencyEffectsClass.test.ts create mode 100644 src/seqta/ui/colors/syncTransparencyEffectsClass.ts create mode 100644 src/seqta/utils/settingsPopupTransition.test.ts create mode 100644 src/seqta/utils/settingsPopupTransition.ts diff --git a/src/interface/components/themes/ThemeSelector.svelte b/src/interface/components/themes/ThemeSelector.svelte index 0dd6535a..0e278354 100644 --- a/src/interface/components/themes/ThemeSelector.svelte +++ b/src/interface/components/themes/ThemeSelector.svelte @@ -3,12 +3,12 @@ import { onDestroy, onMount } from 'svelte' import browser from 'webextension-polyfill' import { themeUpdates } from '@/interface/hooks/ThemeUpdates' - import { closeExtensionPopup } from '@/seqta/utils/Closers/closeExtensionPopup' import { ThemeManager } from '@/plugins/built-in/themes/theme-manager' import { cloudAuth } from '@/seqta/utils/CloudAuth' import SignInToFavoriteModal from '@/interface/components/SignInToFavoriteModal.svelte' import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte' - import { filterThemesByMode, type ThemeListMode } from '@/interface/utils/themeListFilters' + import { filterThemesByMode, isLocalCustomTheme, type ThemeListMode } from '@/interface/utils/themeListFilters' + import { closeExtensionPopup, SettingsClicked } from '@/seqta/utils/Closers/closeExtensionPopup' const themeManager = ThemeManager.getInstance(); @@ -19,7 +19,9 @@ listMode?: ThemeListMode; }>(); let isDragging = $state(false); + let dragDepth = $state(0); let tempTheme = $state(null); + let fileInput = $state(null); let favoriteStatus = $state>({}); let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn); let prevLoggedIn = $state(false); @@ -72,21 +74,33 @@ } } - const handleDragOver = (e: DragEvent) => { + const allowsFileImport = $derived(listMode === 'custom'); + + const handleDragEnter = (e: DragEvent) => { + if (!allowsFileImport) return; e.preventDefault(); + dragDepth += 1; isDragging = true; } - const handleDragLeave = () => { - isDragging = false; + const handleDragOver = (e: DragEvent) => { + if (!allowsFileImport) return; + e.preventDefault(); + if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'; + isDragging = true; } - const handleDrop = async (e: DragEvent) => { + const handleDragLeave = (e: DragEvent) => { + if (!allowsFileImport) return; e.preventDefault(); - isDragging = false; - const file = e.dataTransfer?.files[0]; - if (!file) return; + dragDepth -= 1; + if (dragDepth <= 0) { + dragDepth = 0; + isDragging = false; + } + } + async function importThemeFromFile(file: File) { const reader = new FileReader(); reader.onload = async (event: ProgressEvent) => { try { @@ -103,6 +117,27 @@ reader.readAsText(file); } + const handleDrop = async (e: DragEvent) => { + if (!allowsFileImport) return; + e.preventDefault(); + dragDepth = 0; + isDragging = false; + const file = e.dataTransfer?.files[0]; + if (!file) return; + await importThemeFromFile(file); + } + + const handleFileInputChange = async (e: Event) => { + const input = e.currentTarget as HTMLInputElement; + const file = input.files?.[0]; + if (file) await importThemeFromFile(file); + input.value = ''; + } + + const triggerFileUpload = () => { + fileInput?.click(); + } + const fetchThemes = async () => { themes = { themes: await themeManager.getAvailableThemes(), @@ -139,20 +174,30 @@ const openThemeCreator = async (themeId?: string) => { const { OpenThemeCreator } = await import('@/plugins/built-in/themes/ThemeCreator') OpenThemeCreator(themeId) - closeExtensionPopup() + if (!SettingsClicked) closeExtensionPopup() } const openCommunitySubmit = async () => { + if (SettingsClicked) { + const [{ requestSettingsDestination }, { requestOpenCommunityThemeSubmit }] = + await Promise.all([ + import('@/seqta/utils/settingsNavigation'), + import('@/seqta/utils/openCommunityThemeSubmit'), + ]) + requestOpenCommunityThemeSubmit() + requestSettingsDestination({ page: 'themes', view: 'community' }) + return + } + const { openCommunityThemeSubmit } = await import('@/seqta/utils/openCommunityThemeSubmit') await openCommunityThemeSubmit() closeExtensionPopup() } const customThemeActionClass = - 'flex items-center justify-center gap-2 w-full rounded-xl transition bg-zinc-100 text-xl dark:bg-zinc-900 dark:text-white hover:bg-zinc-200 dark:hover:bg-zinc-800' + 'flex h-12 items-center justify-center gap-2 w-full rounded-xl transition bg-zinc-100 text-xl dark:bg-zinc-900 dark:text-white hover:bg-zinc-200 dark:hover:bg-zinc-800' - const customThemeActionCompactClass = - `${customThemeActionClass} h-full min-h-0` + const customThemeActionCompactClass = customThemeActionClass const handleToggleFavorite = async (theme: CustomTheme, e: MouseEvent) => { e.stopPropagation(); @@ -187,29 +232,51 @@ const useTwoColumnLayout = $derived(listMode === 'downloaded' || listMode === 'custom'); +{#snippet customThemeUploadZone()} + +{/snippet} +
-
-
-
-
- - - - - - - Import Theme -
+ {#if allowsFileImport} + void handleFileInputChange(e)} + /> + {/if} + + {#if allowsFileImport && isDragging} +
+
+ + Drop theme file to import
-
+ {/if} +
{#if themes} {#each visibleThemes as theme (theme.id)} @@ -230,38 +297,45 @@ {/if} {#if !isEditMode} -
handleToggleFavorite(theme, event)} - onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleToggleFavorite(theme, event as any) }} - role="button" - tabindex="-1" - title={cloudLoggedIn ? ((favoriteStatus[theme.id] ?? false) ? 'Remove from favorites' : 'Add to favorites') : 'Sign in to favorite themes'} - > - - - -
- {#if theme.isEditable} +
+ {#if !isLocalCustomTheme(theme)} +
handleToggleFavorite(theme, event)} + onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleToggleFavorite(theme, event as any) }} + role="button" + tabindex="-1" + title={cloudLoggedIn ? ((favoriteStatus[theme.id] ?? false) ? 'Remove from favorites' : 'Add to favorites') : 'Sign in to favorite themes'} + > + + + +
+ {/if} +
{ event.stopPropagation(); void openThemeCreator(theme.id) }} - onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void openThemeCreator(theme.id) }} + class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-white/80" + onclick={(event) => { event.stopPropagation(); handleShareTheme(theme) }} + onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleShareTheme(theme) }} role="button" tabindex="-1" + title="Export theme" > - +
- {/if} -
{ event.stopPropagation(); handleShareTheme(theme) }} - onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleShareTheme(theme) }} - role="button" - tabindex="-1" - > - + {#if isLocalCustomTheme(theme)} +
{ event.stopPropagation(); void openThemeCreator(theme.id) }} + onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void openThemeCreator(theme.id) }} + role="button" + tabindex="-1" + title="Edit theme" + > + +
+ {/if}
{/if} @@ -297,17 +371,10 @@ No custom themes yet

- Create your own theme or follow our guide to get started. + Create your own theme, or follow our guide to get started.

-
- +
+ {@render customThemeUploadZone()}
{:else if listMode === 'downloaded'}

@@ -355,36 +422,38 @@

{/if} - {#if themes && ((showNavigation && visibleThemes.length > 0) || (listMode === 'custom' && visibleThemes.length > 0) || (listMode === 'downloaded' && visibleThemes.length > 0))} + {#if allowsFileImport && themes && visibleThemes.length > 0 && !tempTheme} + {@render customThemeUploadZone()} + {/if} + + {#if themes && (listMode === 'custom' || (showNavigation && visibleThemes.length > 0) || (listMode === 'downloaded' && visibleThemes.length > 0))}
{#if listMode === 'custom'} -
-
- +
+ - - - View docs - -
+ + + View docs + +
@@ -424,11 +430,5 @@ ] as SettingItem[] as setting} {@render settingItem(setting)} {/each} - -
\ No newline at end of file diff --git a/src/interface/utils/themeListFilters.test.ts b/src/interface/utils/themeListFilters.test.ts index 7cd6b603..e53cfc56 100644 --- a/src/interface/utils/themeListFilters.test.ts +++ b/src/interface/utils/themeListFilters.test.ts @@ -3,7 +3,10 @@ import type { Theme } from '@/interface/types/Theme'; import { filterThemesByMode, getThemeApplyButtonStyles, + isDownloadedTheme, + isLocalCustomTheme, isStoreThemeInstalled, + resolveLocalThemeInstallId, resolveStoreVariantAccentColor, } from './themeListFilters'; @@ -30,20 +33,97 @@ function makeStoreTheme(overrides: Partial & Pick): }; } +describe('isLocalCustomTheme', () => { + it('returns true for file imports and theme creator saves', () => { + expect(isLocalCustomTheme(makeCustomTheme({ id: 'a', name: 'A' }))).toBe(true); + expect( + isLocalCustomTheme( + makeCustomTheme({ id: 'b', name: 'B', installedFromStore: false }), + ), + ).toBe(true); + }); + + it('returns false for store and community installs', () => { + expect( + isLocalCustomTheme( + makeCustomTheme({ id: 's', name: 'S', installedFromStore: true }), + ), + ).toBe(false); + expect( + isLocalCustomTheme( + makeCustomTheme({ id: 'c', name: 'C', installedFromCommunity: true }), + ), + ).toBe(false); + }); +}); + +describe('resolveLocalThemeInstallId', () => { + it('keeps the id for store installs', () => { + expect(resolveLocalThemeInstallId('theme-1', null, true, false)).toBe('theme-1'); + }); + + it('generates a new id when a local import collides with a store copy', () => { + const nextId = resolveLocalThemeInstallId( + 'theme-1', + makeCustomTheme({ id: 'theme-1', name: 'Store', installedFromStore: true }), + false, + false, + ); + expect(nextId).not.toBe('theme-1'); + }); + + it('keeps the id when replacing an existing local copy', () => { + expect( + resolveLocalThemeInstallId( + 'theme-1', + makeCustomTheme({ id: 'theme-1', name: 'Local' }), + false, + false, + ), + ).toBe('theme-1'); + }); +}); + describe('filterThemesByMode', () => { - const downloaded = makeCustomTheme({ id: 'store-1', name: 'Store Theme', isEditable: false }); - const custom = makeCustomTheme({ id: 'custom-1', name: 'Custom Theme', isEditable: true }); + const storeTheme = makeCustomTheme({ + id: 'store-1', + name: 'Store Theme', + installedFromStore: true, + }); + const communityTheme = makeCustomTheme({ + id: 'community-1', + name: 'Community Theme', + installedFromCommunity: true, + }); + const localTheme = makeCustomTheme({ id: 'local-1', name: 'Local Theme' }); + const fileImport = makeCustomTheme({ + id: 'file-1', + name: 'Imported Theme', + installedFromStore: false, + isEditable: false, + }); it('returns all themes in all mode', () => { - expect(filterThemesByMode([downloaded, custom], 'all')).toEqual([downloaded, custom]); + expect(filterThemesByMode([storeTheme, localTheme], 'all')).toEqual([storeTheme, localTheme]); }); - it('returns only non-editable themes in downloaded mode', () => { - expect(filterThemesByMode([downloaded, custom], 'downloaded')).toEqual([downloaded]); + it('returns store and community themes in downloaded mode', () => { + expect( + filterThemesByMode([storeTheme, communityTheme, localTheme, fileImport], 'downloaded'), + ).toEqual([storeTheme, communityTheme]); }); - it('returns only editable themes in custom mode', () => { - expect(filterThemesByMode([downloaded, custom], 'custom')).toEqual([custom]); + it('returns local/file themes in custom mode', () => { + expect( + filterThemesByMode([storeTheme, communityTheme, localTheme, fileImport], 'custom'), + ).toEqual([localTheme, fileImport]); + }); + + it('isDownloadedTheme is the inverse of isLocalCustomTheme for known sources', () => { + expect(isDownloadedTheme(storeTheme)).toBe(true); + expect(isLocalCustomTheme(storeTheme)).toBe(false); + expect(isDownloadedTheme(localTheme)).toBe(false); + expect(isLocalCustomTheme(localTheme)).toBe(true); }); }); diff --git a/src/interface/utils/themeListFilters.ts b/src/interface/utils/themeListFilters.ts index 41e54e10..66666730 100644 --- a/src/interface/utils/themeListFilters.ts +++ b/src/interface/utils/themeListFilters.ts @@ -6,10 +6,40 @@ export type ThemeListMode = 'downloaded' | 'custom' | 'all'; const DEFAULT_THEME_ACCENT = 'rgba(0, 123, 255, 1)'; +/** Local themes: created in the editor or imported from a file (not store/community). */ +export function isLocalCustomTheme(theme: CustomTheme): boolean { + return theme.installedFromStore !== true && theme.installedFromCommunity !== true; +} + +/** Themes installed from the official store or community API. */ +export function isDownloadedTheme(theme: CustomTheme): boolean { + return theme.installedFromStore === true || theme.installedFromCommunity === true; +} + +/** + * When importing a local copy of a theme whose id already belongs to a store/community + * install, use a new id so both copies can coexist. + */ +export function resolveLocalThemeInstallId( + themeId: string, + existing: Pick | null, + fromStore: boolean, + fromCommunity: boolean, +): string { + if (fromStore || fromCommunity) return themeId; + if ( + existing && + (existing.installedFromStore === true || existing.installedFromCommunity === true) + ) { + return crypto.randomUUID(); + } + return themeId; +} + export function filterThemesByMode(themes: CustomTheme[], mode: ThemeListMode): CustomTheme[] { if (mode === 'all') return themes; - if (mode === 'custom') return themes.filter((theme) => theme.isEditable === true); - return themes.filter((theme) => theme.isEditable !== true); + if (mode === 'custom') return themes.filter(isLocalCustomTheme); + return themes.filter(isDownloadedTheme); } export function isStoreThemeInstalled(theme: Theme, installedIds: string[]): boolean { diff --git a/src/plugins/built-in/themes/theme-manager.ts b/src/plugins/built-in/themes/theme-manager.ts index ef25a197..a5c1a0c8 100644 --- a/src/plugins/built-in/themes/theme-manager.ts +++ b/src/plugins/built-in/themes/theme-manager.ts @@ -23,6 +23,7 @@ import { type ThemePageSyncInput, } from "@/seqta/utils/patchThemeImagesPageContext"; import { verboseDebug, verboseInfo } from "@/utils/verboseLog"; +import { resolveLocalThemeInstallId } from "@/interface/utils/themeListFilters"; import { clearThemeRuntime, injectThemeDom, @@ -704,6 +705,15 @@ export class ThemeManager { const fromStore = meta?.fromStore ?? false; const fromCommunity = meta?.fromCommunity ?? false; const serverUpdatedAtSec = meta?.serverUpdatedAtSec; + const isLocalInstall = !fromStore && !fromCommunity; + + const existingTheme = (await localforage.getItem(themeData.id)) as CustomTheme | null; + const themeId = resolveLocalThemeInstallId( + themeData.id, + existingTheme, + fromStore, + fromCommunity, + ); // Handle cover image (optional) let coverImageBlob = null; @@ -740,17 +750,17 @@ export class ThemeManager { .filter((img) => img !== null) ?? []; const theme: LoadedCustomTheme = { - id: themeData.id, + id: themeId, name: themeData.name, description: themeData.description || "", - webURL: themeData.id, + webURL: themeId, coverImage: coverImageBlob, CustomImages: images, CustomCSS: themeData.CustomCSS || "", defaultColour: themeData.defaultColour || "rgba(0, 123, 255, 1)", CanChangeColour: themeData.CanChangeColour ?? true, allowBackgrounds: true, - isEditable: false, + isEditable: isLocalInstall, hideThemeName: themeData.hideThemeName ?? false, forceDark: themeData.forceDark, installedFromStore: fromStore, diff --git a/src/seqta/ui/colors/Manager.ts b/src/seqta/ui/colors/Manager.ts index bb55220c..f0f1fbc0 100644 --- a/src/seqta/ui/colors/Manager.ts +++ b/src/seqta/ui/colors/Manager.ts @@ -6,6 +6,7 @@ import ColorLuminance from "./ColorLuminance"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { getAdaptiveColour } from "@/seqta/utils/adaptiveThemeColour"; import { getCustomThemeAdaptiveCssVariableBindings } from "@/seqta/ui/colors/customThemeAdaptiveBindings"; +import { syncTransparencyEffectsClass } from "@/seqta/ui/colors/syncTransparencyEffectsClass"; import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl"; import darkLogo from "@/resources/icons/betterseqta-light-full.png"; @@ -126,9 +127,7 @@ function getRepresentativeRgbChannels(s: string): { r: number; g: number; b: num } function applyColorsWith(selectedColor: string) { - if (settingsState.transparencyEffects) { - document.documentElement.classList.add("transparencyEffects"); - } + syncTransparencyEffectsClass(settingsState.transparencyEffects === true); // Common properties, always applied const commonProps = { diff --git a/src/seqta/ui/colors/syncTransparencyEffectsClass.test.ts b/src/seqta/ui/colors/syncTransparencyEffectsClass.test.ts new file mode 100644 index 00000000..fd8dd926 --- /dev/null +++ b/src/seqta/ui/colors/syncTransparencyEffectsClass.test.ts @@ -0,0 +1,20 @@ +/** @jest-environment jsdom */ + +import { syncTransparencyEffectsClass } from "./syncTransparencyEffectsClass"; + +describe("syncTransparencyEffectsClass", () => { + beforeEach(() => { + document.documentElement.classList.remove("transparencyEffects"); + }); + + it("adds the transparency class when enabled", () => { + syncTransparencyEffectsClass(true); + expect(document.documentElement.classList.contains("transparencyEffects")).toBe(true); + }); + + it("removes the transparency class when disabled", () => { + document.documentElement.classList.add("transparencyEffects"); + syncTransparencyEffectsClass(false); + expect(document.documentElement.classList.contains("transparencyEffects")).toBe(false); + }); +}); diff --git a/src/seqta/ui/colors/syncTransparencyEffectsClass.ts b/src/seqta/ui/colors/syncTransparencyEffectsClass.ts new file mode 100644 index 00000000..cf7c7138 --- /dev/null +++ b/src/seqta/ui/colors/syncTransparencyEffectsClass.ts @@ -0,0 +1,10 @@ +export function syncTransparencyEffectsClass( + enabled: boolean, + root: HTMLElement = document.documentElement, +): void { + if (enabled) { + root.classList.add("transparencyEffects"); + } else { + root.classList.remove("transparencyEffects"); + } +} diff --git a/src/seqta/utils/Closers/closeExtensionPopup.ts b/src/seqta/utils/Closers/closeExtensionPopup.ts index 20d67f22..d71e06f6 100644 --- a/src/seqta/utils/Closers/closeExtensionPopup.ts +++ b/src/seqta/utils/Closers/closeExtensionPopup.ts @@ -2,30 +2,48 @@ import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { animate } from "motion"; import { settingsPopup } from "@/seqta/utils/settingsPopup"; +import { + beginSettingsPopupTransition, + isCurrentSettingsPopupTransition, + resetSettingsPopupVisualState, + trackSettingsPopupAnimation, +} from "@/seqta/utils/settingsPopupTransition"; export let SettingsClicked = false; export const closeExtensionPopup = (extensionPopup?: HTMLElement) => { - if (!extensionPopup) - extensionPopup = document.getElementById("ExtensionPopup")!; + const generation = beginSettingsPopupTransition(); + changeSettingsClicked(false); + + if (!extensionPopup) { + extensionPopup = document.getElementById("ExtensionPopup") ?? undefined; + } + if (!extensionPopup) return false; extensionPopup.classList.add("hide"); + resetSettingsPopupVisualState(extensionPopup); + if (settingsState.animations) { const panel = extensionPopup.shadowRoot?.querySelector( "[data-settings-panel]", ); - animate(1, 0, { - onUpdate: (progress) => { - extensionPopup.style.opacity = Math.max(0, progress).toString(); - }, - duration: 0.18, - ease: "easeIn", - }); + trackSettingsPopupAnimation( + animate(1, 0, { + onUpdate: (progress) => { + if (!isCurrentSettingsPopupTransition(generation)) return; + extensionPopup.style.opacity = Math.max(0, progress).toString(); + }, + duration: 0.18, + ease: "easeIn", + }), + ); if (panel) { - animate( - panel, - { scale: [1, 0], opacity: [1, 0] }, - { duration: 0.18, ease: "easeIn" }, + trackSettingsPopupAnimation( + animate( + panel, + { scale: [1, 0], opacity: [1, 0] }, + { duration: 0.18, ease: "easeIn" }, + ), ); } } else { @@ -33,7 +51,7 @@ export const closeExtensionPopup = (extensionPopup?: HTMLElement) => { } settingsPopup.triggerClose(); - return (SettingsClicked = false); + return false; }; export function changeSettingsClicked(newVal: boolean) { diff --git a/src/seqta/utils/listeners/StorageChanges.ts b/src/seqta/utils/listeners/StorageChanges.ts index 720601ff..7064632a 100644 --- a/src/seqta/utils/listeners/StorageChanges.ts +++ b/src/seqta/utils/listeners/StorageChanges.ts @@ -1,6 +1,6 @@ import { settingsState } from "./SettingsState"; import { updateAllColors } from "@/seqta/ui/colors/Manager"; -import { applySelectedFont } from "@/seqta/ui/fonts/Manager"; +import { syncTransparencyEffectsClass } from "@/seqta/ui/colors/syncTransparencyEffectsClass"; // Shortcuts rendering import { renderShortcuts } from "@/seqta/utils/Render/renderShortcuts"; @@ -85,10 +85,6 @@ export class StorageChangeHandler { } private handleTransparencyEffectsChange(newValue: boolean) { - if (newValue) { - document.documentElement.classList.add("transparencyEffects"); - } else { - document.documentElement.classList.remove("transparencyEffects"); - } + syncTransparencyEffectsClass(newValue === true); } } diff --git a/src/seqta/utils/settingsPopupTransition.test.ts b/src/seqta/utils/settingsPopupTransition.test.ts new file mode 100644 index 00000000..ae4dbaaf --- /dev/null +++ b/src/seqta/utils/settingsPopupTransition.test.ts @@ -0,0 +1,30 @@ +/** @jest-environment jsdom */ + +import { + beginSettingsPopupTransition, + isCurrentSettingsPopupTransition, + stopSettingsPopupAnimations, + trackSettingsPopupAnimation, +} from "./settingsPopupTransition"; + +describe("settingsPopupTransition", () => { + it("invalidates prior transitions when a new one begins", () => { + const first = beginSettingsPopupTransition(); + expect(isCurrentSettingsPopupTransition(first)).toBe(true); + + const second = beginSettingsPopupTransition(); + expect(isCurrentSettingsPopupTransition(first)).toBe(false); + expect(isCurrentSettingsPopupTransition(second)).toBe(true); + }); + + it("clears tracked animations when a new transition begins", () => { + const stop = jest.fn(); + stopSettingsPopupAnimations(); + + beginSettingsPopupTransition(); + trackSettingsPopupAnimation({ stop } as never); + + beginSettingsPopupTransition(); + expect(stop).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/seqta/utils/settingsPopupTransition.ts b/src/seqta/utils/settingsPopupTransition.ts new file mode 100644 index 00000000..b22bc07d --- /dev/null +++ b/src/seqta/utils/settingsPopupTransition.ts @@ -0,0 +1,43 @@ +import type { AnimationPlaybackControls } from "motion"; + +let popupTransitionGeneration = 0; +let activePopupAnimations: AnimationPlaybackControls[] = []; + +export function beginSettingsPopupTransition(): number { + popupTransitionGeneration += 1; + stopSettingsPopupAnimations(); + return popupTransitionGeneration; +} + +export function isCurrentSettingsPopupTransition(generation: number): boolean { + return generation === popupTransitionGeneration; +} + +export function trackSettingsPopupAnimation( + controls: AnimationPlaybackControls, +): void { + activePopupAnimations.push(controls); +} + +export function stopSettingsPopupAnimations(): void { + for (const animation of activePopupAnimations) { + try { + animation.stop(); + } catch { + /* ignore */ + } + } + activePopupAnimations = []; +} + +export function resetSettingsPopupVisualState(extensionPopup: HTMLElement): void { + extensionPopup.style.removeProperty("opacity"); + extensionPopup.style.removeProperty("transition"); + const panel = extensionPopup.shadowRoot?.querySelector( + "[data-settings-panel]", + ); + if (panel) { + panel.style.removeProperty("opacity"); + panel.style.removeProperty("scale"); + } +} diff --git a/src/seqta/utils/setupSettingsButton.ts b/src/seqta/utils/setupSettingsButton.ts index 0cabfee0..ca478f7d 100644 --- a/src/seqta/utils/setupSettingsButton.ts +++ b/src/seqta/utils/setupSettingsButton.ts @@ -7,6 +7,11 @@ import { animate } from "motion"; import { settingsState } from "./listeners/SettingsState"; import { renderSettingsIfNeeded } from "./Adders/AddExtensionSettings"; import { delay } from "./delay"; +import { + beginSettingsPopupTransition, + isCurrentSettingsPopupTransition, + trackSettingsPopupAnimation, +} from "./settingsPopupTransition"; export function setupSettingsButton() { const AddedSettings = document.getElementById("AddedSettings"); @@ -26,38 +31,60 @@ export function setupSettingsButton() { } export async function openSettingsPopup(): Promise { - if (SettingsClicked && document.getElementById("ExtensionPopup")) return; - - // Re-query each time — Engage SPA navigations can recreate the host. let extensionPopup = document.getElementById("ExtensionPopup"); + if ( + SettingsClicked && + extensionPopup && + !extensionPopup.classList.contains("hide") + ) { + return; + } + + const generation = beginSettingsPopupTransition(); + changeSettingsClicked(true); + if (!extensionPopup) { const { addExtensionSettings } = await import("./Adders/AddExtensionSettings"); addExtensionSettings(); extensionPopup = document.getElementById("ExtensionPopup"); } - if (!extensionPopup) return; + if (!extensionPopup) { + changeSettingsClicked(false); + return; + } await renderSettingsIfNeeded(); + if (!isCurrentSettingsPopupTransition(generation)) return; + await delay(30); + if (!isCurrentSettingsPopupTransition(generation)) return; extensionPopup.style.transform = "none"; + extensionPopup.classList.remove("hide"); + const panel = extensionPopup.shadowRoot?.querySelector( "[data-settings-panel]", ); if (settingsState.animations) { - animate(0, 1, { - onUpdate: (progress) => { - extensionPopup.style.opacity = progress.toString(); - }, - type: "spring", - stiffness: 280, - damping: 20, - }); + extensionPopup.style.opacity = "0"; + trackSettingsPopupAnimation( + animate(0, 1, { + onUpdate: (progress) => { + if (!isCurrentSettingsPopupTransition(generation)) return; + extensionPopup.style.opacity = progress.toString(); + }, + type: "spring", + stiffness: 280, + damping: 20, + }), + ); if (panel) { - animate( - panel, - { scale: [0, 1], opacity: [0, 1] }, - { type: "spring", stiffness: 330, damping: 30 }, + trackSettingsPopupAnimation( + animate( + panel, + { scale: [0, 1], opacity: [0, 1] }, + { type: "spring", stiffness: 330, damping: 30 }, + ), ); } } else { @@ -68,6 +95,4 @@ export async function openSettingsPopup(): Promise { panel.style.opacity = "1"; } } - extensionPopup.classList.remove("hide"); - changeSettingsClicked(true); }