feat(themes): flag unpublished edits and share parallax motion

Compare theme content hashes with a stored Workshop baseline so creators
can see when their local copy is not synced. Extract pointer tracking into
a shared action for the launcher and editor preview, and use the slider
component for parallax depth.
This commit is contained in:
HorizonCode committed 2026-11-04 12:04:13 +01:00
1 parent d56ed9d786
commit 323a6f18af
12 files changed
+667 -134

No files matched your search

+2
View File
@@ -1,6 +1,7 @@
import { config } from './config';
import { normalizeThemeVersion } from './themeV2';
import {
markThemeSynced,
reloadThemes,
themesDirectory,
updateInstalledThemeTags,
@@ -1008,6 +1009,7 @@ export async function downloadAndInstallCommunityTheme(
// Keep the installed manifest aligned with the workshop record.
await updateInstalledThemeTags(folderName, theme.tags);
await updateInstalledThemeWorkshopId(folderName, theme.id);
await markThemeSynced(folderName, { workshopId: theme.id, version: theme.version });
} catch (err) {
console.warn('[Workshop] Could not write workshop metadata into the installed theme:', err);
}
@@ -59,6 +59,7 @@
themeGroupContainsElement,
themeGroupInteractiveCount,
} from '$lib/themeLogic';
import { themeParallax } from '$lib/themeParallax';
import { renderThemePreview } from '$lib/themePreview';
import { themeScriptInitialVariables, themeScriptVariableNames } from '$lib/themeScript';
import {
@@ -98,6 +99,7 @@
} from '$lib/themeV2';
import {
exportThemeFolder,
markThemeSynced,
saveThemeProject,
themeAssetBase,
themesDirectory,
@@ -3545,9 +3547,13 @@
publishThemeId = result.themeId;
try {
await updateInstalledThemeWorkshopId(savedFolder, result.themeId);
await markThemeSynced(savedFolder, {
workshopId: result.themeId,
version: versionCheck.version,
});
lastSavedKey = snapshotKey(captureSnapshot());
} catch (err) {
console.warn('[Workshop] Could not store the theme ID in theme.json:', err);
console.warn('[Workshop] Could not store the theme sync metadata:', err);
}
// The launcher window owns the installed-theme list. Tell it about the
@@ -6131,26 +6137,34 @@
<div
style="width:{CANVAS_WIDTH}px;height:{CANVAS_HEIGHT}px;transform:scale({canvasScale});transform-origin:top left;"
>
<ThemeStage
{definition}
assets={assetBase}
assetOverrides={previewAssets}
{selectedIds}
{selectedGroupId}
interactive
scale={canvasScale}
variables={previewScriptVariables}
onselect={(id, additive) => selectElement(id, additive)}
onselectmany={(ids, additive) => selectMany(ids, additive)}
onselectgroup={(id) => selectGroup(id)}
onmove={moveElements}
onpatch={(id, patch) => patchElement(id, patch)}
onpatchgroup={(id, patch) => patchGroup(id, patch)}
oncontext={(id) => prepareContextMenu(id)}
oncontextgroup={(id) => prepareGroupContextMenu(id)}
ondetach={handleDetachWidget}
onbuttonaction={handleTestButtonAction}
/>
<div
class="contents"
use:themeParallax={{
enabled: definition.parallax?.enabled === true,
intensity: definition.parallax?.intensity ?? 0.25,
}}
>
<ThemeStage
{definition}
assets={assetBase}
assetOverrides={previewAssets}
{selectedIds}
{selectedGroupId}
interactive
scale={canvasScale}
variables={previewScriptVariables}
onselect={(id, additive) => selectElement(id, additive)}
onselectmany={(ids, additive) => selectMany(ids, additive)}
onselectgroup={(id) => selectGroup(id)}
onmove={moveElements}
onpatch={(id, patch) => patchElement(id, patch)}
onpatchgroup={(id, patch) => patchGroup(id, patch)}
oncontext={(id) => prepareContextMenu(id)}
oncontextgroup={(id) => prepareGroupContextMenu(id)}
ondetach={handleDetachWidget}
onbuttonaction={handleTestButtonAction}
/>
</div>
</div>
</ContextMenu.Trigger>
@@ -3,6 +3,7 @@
import Button from '$lib/components/ui/button/button.svelte';
import Input from '$lib/components/ui/input/input.svelte';
import Label from '$lib/components/ui/label/label.svelte';
import Slider from '$lib/components/ui/slider/slider.svelte';
import type { ThemeV2Transform } from '$lib/themeV2';
import { FlipHorizontal2, FlipVertical2, RotateCcw, RotateCw } from '@lucide/svelte';
@@ -267,14 +268,13 @@
<span class="text-[9px] text-muted-foreground">3D cursor perspective</span>
</div>
<div class="flex items-center gap-2">
<input
type="range"
min="-1"
max="1"
step="0.05"
<Slider
min={-1}
max={1}
step={0.05}
value={transform.parallax ?? 0}
oninput={(e) => onchange({ parallax: Number((e.target as HTMLInputElement).value) })}
class="h-1.5 w-24 cursor-pointer appearance-none rounded-lg bg-theme-800 accent-primary"
onValueChange={(value) => onchange({ parallax: value })}
class="w-24"
/>
<span class="w-8 font-mono text-[10px] text-right text-muted-foreground">
{Math.round((transform.parallax ?? 0) * 100)}%
@@ -1,6 +1,7 @@
<script lang="ts">
import { custom_theme_volume } from '$lib/global';
import { playThemeMedia, themeMediaSource, themeVideoLifecycle } from '$lib/themeMedia';
import { themeParallax } from '$lib/themeParallax';
import type { ThemeV2Definition } from '$lib/themeV2';
import { themeAssetUrl } from '$lib/themeV2';
import { reduceAnimations } from '$lib/userSettings';
@@ -20,50 +21,8 @@
} = $props();
let audioElement = $state<HTMLAudioElement | undefined>(undefined);
let mousePx = $state(0);
let mousePy = $state(0);
let targetPx = 0;
let targetPy = 0;
let animFrame: number | undefined;
function onWindowMouseMove(e: MouseEvent) {
if ($reduceAnimations || !definition.parallax?.enabled) return;
const intensity = definition.parallax.intensity ?? 0.25;
const w = window.innerWidth || 1000;
const h = window.innerHeight || 650;
targetPx = (e.clientX / w - 0.5) * 2 * intensity;
targetPy = (e.clientY / h - 0.5) * 2 * intensity;
if (animFrame === undefined) {
animFrame = requestAnimationFrame(updateParallax);
}
}
function updateParallax() {
animFrame = undefined;
mousePx += (targetPx - mousePx) * 0.12;
mousePy += (targetPy - mousePy) * 0.12;
if (Math.abs(targetPx - mousePx) > 0.001 || Math.abs(targetPy - mousePy) > 0.001) {
animFrame = requestAnimationFrame(updateParallax);
}
}
$effect(() => {
if (!definition.parallax?.enabled) {
mousePx = 0;
mousePy = 0;
targetPx = 0;
targetPy = 0;
if (animFrame !== undefined) {
cancelAnimationFrame(animFrame);
animFrame = undefined;
}
}
});
onDestroy(() => {
if (animFrame !== undefined) {
cancelAnimationFrame(animFrame);
}
if (audioElement) {
try {
audioElement.pause();
@@ -140,64 +99,68 @@
});
</script>
<svelte:window onmousemove={onWindowMouseMove} />
<div
class="theme-v2 absolute inset-0 overflow-hidden"
use:trackMedia
style="--mouse-px:{mousePx};--mouse-py:{mousePy};"
>
{#if background.type === 'color'}
<div
class="absolute inset-0"
style="background-color:{background.color};opacity:{background.opacity ?? 1}"
></div>
{:else if background.type === 'gradient'}
<div
class="absolute inset-0"
style="background-image:linear-gradient({background.angle ??
135}deg, {background.from}, {background.to});opacity:{background.opacity ?? 1}"
></div>
{:else if background.type === 'image'}
{#if background.src}
<img
class="absolute inset-0 h-full w-full"
src={assetUrl(background.src)}
alt=""
aria-hidden="true"
style="object-fit:{background.fit ?? 'cover'};opacity:{background.opacity ??
1};filter:{background.blur
? `blur(${background.blur}px)`
: 'none'};transform:{background.blur
? 'scale(1.08)'
: definition.parallax?.enabled
? 'scale(1.06)'
: 'none'} translate3d({mousePx * -18}px, {mousePy * -18}px, 0);"
/>
<div class="theme-v2 absolute inset-0 overflow-hidden" use:trackMedia>
<div
class="absolute inset-0"
use:themeParallax={{
enabled: definition.parallax?.enabled === true,
intensity: definition.parallax?.intensity ?? 0.25,
}}
style="transform:translate3d(calc(var(--mouse-px, 0) * -18px), calc(var(--mouse-py, 0) * -18px), 0);"
>
{#if background.type === 'color'}
<div
class="absolute inset-0"
style="background-color:{background.color};opacity:{background.opacity ?? 1}"
></div>
{:else if background.type === 'gradient'}
<div
class="absolute inset-0"
style="background-image:linear-gradient({background.angle ??
135}deg, {background.from}, {background.to});opacity:{background.opacity ??
1};transform:{definition.parallax?.enabled ? 'scale(1.06)' : 'none'}"
></div>
{:else if background.type === 'image'}
{#if background.src}
<img
class="absolute inset-0 h-full w-full"
src={assetUrl(background.src)}
alt=""
aria-hidden="true"
style="object-fit:{background.fit ?? 'cover'};opacity:{background.opacity ??
1};filter:{background.blur
? `blur(${background.blur}px)`
: 'none'};transform:{background.blur
? 'scale(1.08)'
: definition.parallax?.enabled
? 'scale(1.06)'
: 'none'};"
/>
{/if}
{:else if background.type === 'video'}
{#if background.src}
<video
class="absolute inset-0 h-full w-full object-cover"
use:themeMediaSource={assetUrl(background.src)}
use:themeVideoLifecycle
autoplay
loop
muted={background.muted !== false}
use:applyMuted={background.muted !== false}
playsinline
disablepictureinpicture
style="object-fit:{background.fit ?? 'cover'};opacity:{background.opacity ??
1};filter:{background.blur
? `blur(${background.blur}px)`
: 'none'};transform:{background.blur
? 'scale(1.08)'
: definition.parallax?.enabled
? 'scale(1.06)'
: 'none'};"
></video>
{/if}
{/if}
{:else if background.type === 'video'}
{#if background.src}
<video
class="absolute inset-0 h-full w-full object-cover"
use:themeMediaSource={assetUrl(background.src)}
use:themeVideoLifecycle
autoplay
loop
muted={background.muted !== false}
use:applyMuted={background.muted !== false}
playsinline
disablepictureinpicture
style="object-fit:{background.fit ?? 'cover'};opacity:{background.opacity ??
1};filter:{background.blur
? `blur(${background.blur}px)`
: 'none'};transform:{background.blur
? 'scale(1.08)'
: definition.parallax?.enabled
? 'scale(1.06)'
: 'none'} translate3d({mousePx * -18}px, {mousePy * -18}px, 0);"
></video>
{/if}
{/if}
</div>
{#if overlay && (overlay.opacity ?? 0) > 0}
<div
@@ -141,6 +141,15 @@
);
const elementFilter = (element: ThemeV2Element) =>
themeFilterCss(element.filters, ...ancestorsOf(element).map((group) => group.filters));
/** Layer depth plus every ancestor group's depth; negative follows the background. */
const elementParallaxCss = (element: ThemeV2Element) => {
const depth =
(element.parallax ?? 0) +
ancestorsOf(element).reduce((total, group) => total + (group.parallax ?? 0), 0);
if (depth === 0) return '';
const offset = depth * 30;
return ` translate3d(calc(var(--mouse-px, 0) * ${offset}px), calc(var(--mouse-py, 0) * ${offset}px), 0)`;
};
const elementClassNames = (element: ThemeV2Element) =>
themeClassNames(
[...ancestorsOf(element).map((group) => group.cssClasses), element.cssClasses]
@@ -1227,9 +1236,7 @@
element,
elements,
groups
)}{element.parallax
? ` translate3d(calc(var(--mouse-px, 0) * ${element.parallax * 30}px), calc(var(--mouse-py, 0) * ${element.parallax * 30}px), 0)`
: ''};transform-origin:0 0;touch-action:none;outline:{selected
)}{elementParallaxCss(element)};transform-origin:0 0;touch-action:none;outline:{selected
? `${selectedIds.length > 1 ? 1 : 2}px solid #ff006e`
: 'none'};outline-offset:2px;"
role={interactive || element.interactive ? 'button' : undefined}
+101
View File
@@ -0,0 +1,101 @@
import { reduceAnimations } from '$lib/userSettings';
import { get } from 'svelte/store';
export type ThemeParallaxOptions = {
enabled?: boolean;
intensity?: number;
};
const clampIntensity = (intensity: number | undefined) =>
Math.min(1, Math.max(0.05, typeof intensity === 'number' ? intensity : 0.25));
/**
* Tracks the pointer for a theme host and exposes the smoothed offset as
* `--mouse-px` / `--mouse-py`. The host must contain both the background and
* the freeform layers so those variables are inherited by every layer.
*/
export function themeParallax(node: HTMLElement, options: ThemeParallaxOptions = {}) {
let enabled = options.enabled === true;
let intensity = clampIntensity(options.intensity);
let mousePx = 0;
let mousePy = 0;
let targetPx = 0;
let targetPy = 0;
let animFrame: number | undefined;
let reduced = get(reduceAnimations);
function apply() {
node.style.setProperty('--mouse-px', mousePx.toFixed(4));
node.style.setProperty('--mouse-py', mousePy.toFixed(4));
}
function stop() {
if (animFrame !== undefined) {
cancelAnimationFrame(animFrame);
animFrame = undefined;
}
}
function reset() {
stop();
mousePx = 0;
mousePy = 0;
targetPx = 0;
targetPy = 0;
apply();
}
function updateParallax() {
animFrame = undefined;
const dx = targetPx - mousePx;
const dy = targetPy - mousePy;
if (Math.abs(dx) < 0.0005 && Math.abs(dy) < 0.0005) {
mousePx = targetPx;
mousePy = targetPy;
apply();
return;
}
mousePx += dx * 0.12;
mousePy += dy * 0.12;
apply();
animFrame = requestAnimationFrame(updateParallax);
}
function onWindowMouseMove(event: MouseEvent) {
if (!enabled || reduced) return;
const width = window.innerWidth || 1000;
const height = window.innerHeight || 650;
targetPx = (event.clientX / width - 0.5) * 2 * intensity;
targetPy = (event.clientY / height - 0.5) * 2 * intensity;
if (animFrame === undefined) {
animFrame = requestAnimationFrame(updateParallax);
}
}
const unsubscribe = reduceAnimations.subscribe((value) => {
reduced = value;
if (reduced) reset();
});
window.addEventListener('mousemove', onWindowMouseMove);
apply();
return {
update(next: ThemeParallaxOptions = {}) {
enabled = next.enabled === true;
intensity = clampIntensity(next.intensity);
if (!enabled || reduced) reset();
},
destroy() {
unsubscribe();
window.removeEventListener('mousemove', onWindowMouseMove);
stop();
node.style.removeProperty('--mouse-px');
node.style.removeProperty('--mouse-py');
},
};
}
+94
View File
@@ -27,6 +27,18 @@ export type Theme = {
status: 'installed' | 'downloading' | 'extracting' | 'deleting' | 'not-installed';
progress: number;
updateAvailable: boolean;
/** The latest Workshop version, when the theme has been published. */
workshopVersion?: string;
/** Hash of the theme files when this copy was last known to match the Workshop. */
syncedContentHash?: string;
/** Local version current when the sync baseline was written. */
syncedVersion?: string;
/** True when the local theme differs from its published Workshop package. */
isNotSynced?: boolean;
/** Modification time of the generated preview, used to migrate existing installs. */
previewModifiedAt?: number;
/** Creation time of the theme folder, used to migrate existing installs. */
folderCreatedAt?: number;
/** The version available in the repository when an update is pending. */
availableVersion?: string;
definition?: ThemeV2Definition;
@@ -95,6 +107,75 @@ const encodeThemePath = (value: string) =>
export const themesDirectory = async () =>
await path.join(await path.homeDir(), '.ezpplauncher', 'themes');
const THEME_SYNC_FILENAME = '.workshop-sync.json';
const CONTENT_HASH_PATTERN = /^[a-f0-9]{64}$/i;
export type ThemeWorkshopSync = {
contentHash: string;
version?: string;
workshopId?: string;
syncedAt?: number;
};
const readThemeWorkshopSyncFile = async (
folderPath: string
): Promise<ThemeWorkshopSync | undefined> => {
const syncPath = await path.join(folderPath, THEME_SYNC_FILENAME);
if (!(await fs.exists(syncPath))) return undefined;
try {
const parsed = JSON.parse(await fs.readTextFile(syncPath)) as Partial<ThemeWorkshopSync>;
if (!parsed || typeof parsed !== 'object') return undefined;
const contentHash =
typeof parsed.contentHash === 'string' && CONTENT_HASH_PATTERN.test(parsed.contentHash)
? parsed.contentHash.toLowerCase()
: undefined;
if (!contentHash) return undefined;
return {
contentHash,
version: typeof parsed.version === 'string' ? parsed.version : undefined,
workshopId: typeof parsed.workshopId === 'string' ? parsed.workshopId : undefined,
syncedAt: typeof parsed.syncedAt === 'number' ? parsed.syncedAt : undefined,
};
} catch {
return undefined;
}
};
export const readThemeWorkshopSync = async (folderName: string) =>
readThemeWorkshopSyncFile(await path.join(await themesDirectory(), folderName));
export const writeThemeWorkshopSync = async (
folderName: string,
sync: ThemeWorkshopSync
): Promise<void> => {
const folderPath = await path.join(await themesDirectory(), folderName);
const syncPath = await path.join(folderPath, THEME_SYNC_FILENAME);
await fs.writeFile(syncPath, new TextEncoder().encode(`${JSON.stringify(sync, null, 2)}\n`));
};
export const hashThemeContent = async (folderName: string) => {
const themeFolder = await path.join(await themesDirectory(), folderName);
return await invoke<string>('hash_theme_content', { themeFolder });
};
/** Record the current local files as the published Workshop baseline. */
export const markThemeSynced = async (
folderName: string,
options: { version?: string; workshopId?: string } = {}
): Promise<ThemeWorkshopSync> => {
const contentHash = await hashThemeContent(folderName);
const sync: ThemeWorkshopSync = {
contentHash,
version: options.version,
workshopId: options.workshopId,
syncedAt: Date.now(),
};
await writeThemeWorkshopSync(folderName, sync);
return sync;
};
/**
* Replace a theme in the store instead of mutating it. The theme list is
* rendered from a filtered derived list, and Svelte treats each item as
@@ -132,6 +213,8 @@ const themeFromFolder = async (
const definition = isV2
? normalizeThemeV2(parsed as unknown as Partial<ThemeV2Definition>)
: undefined;
const sync = await readThemeWorkshopSyncFile(folderPath);
const folderStat = await fs.stat(folderPath).catch(() => undefined);
const httpBase = await themeAssetBase();
const httpFolder = httpBase ? `${httpBase}/${encodeURIComponent(folderName)}` : '';
@@ -158,9 +241,11 @@ const themeFromFolder = async (
: convertFileSrc(await path.normalize(await path.join(folderPath, 'assets')));
const previewName = parsed.preview || (isV2 ? 'preview.png' : '');
let preview = '';
let previewModifiedAt: number | undefined;
if (previewName) {
const previewPath = await path.join(folderPath, 'assets', previewName);
if (await fs.exists(previewPath)) {
previewModifiedAt = (await fs.stat(previewPath).catch(() => undefined))?.mtime?.getTime();
// The editor rewrites preview.png on every save. A cache-busting query
// makes the WebView pick up the new file instead of its cached asset.
preview = httpFolder
@@ -190,6 +275,10 @@ const themeFromFolder = async (
status: 'installed',
progress: 0,
updateAvailable: false,
syncedContentHash: sync?.contentHash,
syncedVersion: sync?.version,
previewModifiedAt,
folderCreatedAt: folderStat?.birthtime?.getTime(),
cssStyle,
definition,
};
@@ -539,6 +628,11 @@ export const reloadThemes = async () => {
nsfw: theme.nsfw,
workshopId: theme.workshopId,
definition: theme.definition,
syncedContentHash: theme.syncedContentHash,
syncedVersion: theme.syncedVersion,
previewModifiedAt: theme.previewModifiedAt,
folderCreatedAt: theme.folderCreatedAt,
isNotSynced: versionChanged ? false : storeTheme.isNotSynced,
updateAvailable: versionChanged ? false : storeTheme.updateAvailable,
availableVersion: versionChanged ? undefined : storeTheme.availableVersion,
cssStyle: theme.cssStyle,