Crossfade the wallpaper only on intentional changes

Use a new bundled image for both the welcome screen and the dashboard
fallback, and crossfade into the first feed photo only when arriving from
the welcome screen or when the wallpaper changes after the first paint (a
live rotation or a manual pick). A plain open shows the resolved photo
outright, with no transition.

- wallpaper.gjs: three layers (bundled base, last settled photo, current
  photo). The current photo fades in on load and the previous one stays
  beneath for a crossfade; the photo layer renders only from the cached
  displayUrl, so a change fades instead of flashing the bundled base.
  Reduced motion settles instantly.
- photos.js: keep the last-known-good wallpaper on a cache miss or fetch
  error; add a one-shot timer that rotates at the day/week boundary while
  the dashboard stays open; expose animateEntry for the welcome entry.
- routes/index.js: set photos.animateEntry from the transition origin. A
  strict-mode route template's `this` is not the controller, so a
  controller property never reached the component.
- config/nostr.js: alias the welcome and fallback URLs to one image.

Tests and docs updated.
This commit is contained in:
raucao committed 2026-11-10 15:18:13 +04:00
1 parent 66e58c49da
commit d846735b1e
9 files changed
+389 -24

No files matched your search

+80 -4
View File
@@ -1,24 +1,83 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { on } from '@ember/modifier';
import { service } from '@ember/service';
function prefersReducedMotion() {
return (
typeof window !== 'undefined' &&
typeof window.matchMedia === 'function' &&
window.matchMedia('(prefers-reduced-motion: reduce)').matches
);
}
// Full-bleed wallpaper. Pass @photo for route-specific images (the welcome
// screen); otherwise the selected feed photo is used. A bundled fallback sits
// behind the current image so a failed/remote load never leaves a blank page.
// screen); otherwise the selected feed photo is used.
//
// Three stacked layers, bottom to top: a bundled base that is always painted so
// a failed or slow load never leaves a blank page, the last settled photo
// (shown only while a photo is selected), and the current photo. The current
// photo only crossfades for an intentional change — arriving from the welcome
// screen (photos.animateEntry) or any change after the first paint (a rotation
// or a manual pick). The initial paint on a plain open is shown outright, with
// no transition.
//
// `displayUrl` is only ever a cached object URL, so a fade runs once the photo
// is cached rather than mid-fetch. Keeping the previous photo as a layer lets
// consecutive photos crossfade instead of flashing the bundled base.
export default class WallpaperComponent extends Component {
@service photos;
// The src of the last photo that finished fading in. It stays visible beneath
// the incoming photo for the crossfade.
@tracked baseSrc = null;
// The src whose image has finished loading and is currently fading in.
@tracked loadedSrc = null;
get photo() {
return this.args.photo ?? this.photos.currentWallpaper;
}
get src() {
return this.photo?.displayUrl ?? this.photo?.url ?? null;
return this.photo?.displayUrl ?? null;
}
get fallbackSrc() {
return this.photos.fallbackPhoto.displayUrl;
}
// Animate only intentional changes: the welcome -> dashboard entry
// (photos.animateEntry) and any change after the first photo is on screen.
// The initial paint is shown outright.
get shouldAnimate() {
return this.photos.animateEntry || this.baseSrc !== null;
}
get isLoaded() {
return this.src !== null && this.loadedSrc === this.src;
}
@action
handleLoad() {
this.loadedSrc = this.src;
// Settle immediately when there is nothing to transition — the initial
// paint, or reduced motion — so the base is ready for the next change and
// no transitionend is awaited.
if (!this.shouldAnimate || prefersReducedMotion()) {
this.baseSrc = this.src;
}
}
@action
handleTransitionEnd(event) {
if (event.propertyName === 'opacity' && this.isLoaded) {
this.baseSrc = this.src;
}
}
<template>
<div
class="pointer-events-none fixed inset-0 -z-10 overflow-hidden bg-gray-900"
@@ -32,13 +91,30 @@ export default class WallpaperComponent extends Component {
class="absolute inset-0 h-full w-full object-cover"
/>
{{#if this.src}}
{{#if this.baseSrc}}
<img
src={{this.baseSrc}}
alt=""
aria-hidden="true"
draggable="false"
data-test-wallpaper-base
class="absolute inset-0 h-full w-full object-cover"
/>
{{/if}}
<img
src={{this.src}}
alt=""
aria-hidden="true"
draggable="false"
data-test-wallpaper
class="absolute inset-0 h-full w-full object-cover"
{{on "load" this.handleLoad}}
{{on "transitionend" this.handleTransitionEnd}}
class="absolute inset-0 h-full w-full object-cover transition-opacity duration-700 ease-in-out motion-reduce:transition-none
{{if
(or this.isLoaded (not this.shouldAnimate))
'opacity-100'
'opacity-0'
}}"
/>
{{/if}}
</div>
+10 -7
View File
@@ -19,14 +19,17 @@ export const CITY_NIGHTS_FEED_ID = 'dt:city-nights';
// Nature is the default feed. City Nights is available but opt-in.
export const DEFAULT_ENABLED_FEED_IDS = [NATURE_FEED_ID];
// The welcome screen uses a separate bundled image while the first feed photos
// are being prefetched. Replace this when the real welcome photo is added.
export const WELCOME_WALLPAPER_URL =
'/img/wallpapers/meiying-ng-iB7gjOsLrEQ-unsplash.jpg';
// Bundled image shared by the welcome screen and the dashboard fallback, shown
// while the first feed photo is fetched and cached. The welcome -> dashboard
// crossfade fades from this image, so the two must stay identical.
const BUNDLED_WALLPAPER_URL =
'/img/wallpapers/manu-schwendener-DSwBHyWKiVw-unsplash.jpg';
// Shown on the dashboard until a cached/remote feed original is available.
export const FALLBACK_WALLPAPER_URL =
'/img/wallpapers/aleksandr-popov-ez4pqCpEfuI-unsplash.jpg';
export const WELCOME_WALLPAPER_URL = BUNDLED_WALLPAPER_URL;
// Shown on the dashboard until a cached feed original is available; the
// wallpaper crossfades from it into the first photo once that is cached.
export const FALLBACK_WALLPAPER_URL = BUNDLED_WALLPAPER_URL;
// Storage.
export const PHOTO_STORAGE_NAMESPACE = 'photos';
+7 -1
View File
@@ -8,7 +8,13 @@ export default class IndexRoute extends Route {
@service router;
@service photos;
async beforeModel() {
async beforeModel(transition) {
// Arriving from onboarding, the wallpaper crossfades from the welcome image
// into the first photo; a plain open shows the photo outright. Set on the
// service because a strict-mode route template's `this` is not the
// controller, so a controller property would not reach the component.
this.photos.animateEntry = transition.from?.name === 'welcome';
await this.user.ready;
if (!this.user.hasName) {
+55 -5
View File
@@ -14,7 +14,7 @@ import {
WELCOME_WALLPAPER_URL,
} from '../config/nostr';
import { parseFeedEvents, parsePhotoEvents } from '../utils/nostr-photo-events';
import { rotationIndex, shuffle } from '../utils/rotation';
import { nextRotationStart, rotationIndex, shuffle } from '../utils/rotation';
function normalizeRotation(mode) {
return ROTATION_MODES.includes(mode) ? mode : DEFAULT_ROTATION;
@@ -32,6 +32,10 @@ export default class PhotosService extends Service {
@tracked enabledFeedIds = [...DEFAULT_ENABLED_FEED_IDS];
@tracked currentPhotoId = null;
@tracked displayUrl = null;
// Set when the dashboard is entered from the welcome screen so the first
// wallpaper crossfades in; a plain open leaves it false and shows the photo
// outright. Read by the wallpaper component.
@tracked animateEntry = false;
@tracked refreshing = false;
@tracked error = null;
@tracked initialized = false;
@@ -44,6 +48,7 @@ export default class PhotosService extends Service {
prefetchPromise = null;
displayToken = 0;
random = Math.random;
rotationTimer = null;
get welcomePhoto() {
return {
@@ -239,6 +244,7 @@ export default class PhotosService extends Service {
console.error('Error loading cached photos:', error);
} finally {
this.initialized = true;
this.scheduleRotation();
}
}
@@ -302,6 +308,7 @@ export default class PhotosService extends Service {
this.error = error?.message ?? 'Unable to refresh photo feeds';
} finally {
this.refreshing = false;
this.scheduleRotation();
}
}
@@ -381,16 +388,16 @@ export default class PhotosService extends Service {
return;
}
this.displayUrl = null;
// Keep the previous photo on screen while the new one is fetched, so a
// change crossfades instead of flashing the bundled fallback.
const url = await this.photoCache.prefetchOriginal(photo);
if (token === this.displayToken) {
this.displayUrl = url;
}
} catch (error) {
// Leave the last-known-good photo in place. A fetch error can persist, so
// the credit may not match the image until the next successful resolve.
console.error('Error resolving the wallpaper:', error);
if (token === this.displayToken) {
this.displayUrl = null;
}
}
}
@@ -473,6 +480,43 @@ export default class PhotosService extends Service {
return Boolean(nextId && nextId !== currentId);
}
// Rotation is only evaluated on load/refresh, so arm a one-shot timer for the
// next day/week boundary to rotate a dashboard that stays open. Hidden tabs
// throttle timers and laptops sleep, but rotateIfDue(now) recomputes from the
// clock, so a late fire self-corrects.
scheduleRotation() {
clearTimeout(this.rotationTimer);
this.rotationTimer = null;
if (this.rotation === 'off') {
return;
}
const now = Date.now();
const next = nextRotationStart(now, this.rotation);
if (next === null) {
return;
}
this.rotationTimer = setTimeout(
() => this.runScheduledRotation(),
Math.max(next - now, 0)
);
}
// Injectable so it can be driven without real timers.
async runScheduledRotation(now = Date.now()) {
try {
if (await this.rotateIfDue(now)) {
await this.resolveCurrentWallpaper();
}
} catch (error) {
console.error('Error rotating the wallpaper:', error);
} finally {
this.scheduleRotation();
}
}
async setRotation(mode) {
const next = normalizeRotation(mode);
if (next === this.rotation) {
@@ -489,6 +533,7 @@ export default class PhotosService extends Service {
this.syncRotationPool();
}
this.scheduleRotation();
await this.persistConfig();
}
@@ -541,4 +586,9 @@ export default class PhotosService extends Service {
console.error('Error saving photo settings:', error);
}
}
willDestroy() {
clearTimeout(this.rotationTimer);
super.willDestroy(...arguments);
}
}
+5 -2
View File
@@ -102,14 +102,17 @@ Rules:
- Originals: cached on demand for the current wallpaper and the first three
photos of enabled feeds; LRU budget 30 originals / 250 MB.
- Wallpaper: cached original or bundled fallback with zero network on first
paint; never a thumbnail.
paint; never a thumbnail. The initial paint is shown outright; the wallpaper
only crossfades for an intentional change — arriving from the welcome screen,
or a rotation (live at the day/week boundary, or a manual pick).
## App behavior
- The welcome screen shows a bundled placeholder wallpaper while
`photos.prefetchForWelcome()` fetches the feed definitions, Nature's photo
events, all enabled thumbnails, and the first three originals in the
background.
background. The dashboard then crossfades from that placeholder into the
first cached photo.
- Nature is enabled by default. City Nights is available as an opt-in toggle.
- The dashboard wallpaper uses the original, never the thumbnail. A discreet
creator credit link sits in the bottom-right corner; Settings itself shows no
Binary file not shown.

After

Width:  |  Height:  |  Size: 412 KiB

+1
View File
@@ -6,6 +6,7 @@ export default class FakePhotos {
@tracked feeds = [];
@tracked enabledFeedIds = [];
@tracked currentPhotoId = null;
@tracked animateEntry = false;
@tracked refreshing = false;
@tracked error = null;
@tracked currentWallpaper = null;
+102 -5
View File
@@ -1,6 +1,6 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render } from '@ember/test-helpers';
import { render, settled, triggerEvent } from '@ember/test-helpers';
import Wallpaper from 'dashtab/components/wallpaper';
import FakePhotos from 'dashtab/tests/helpers/fake-photos';
@@ -37,7 +37,7 @@ module('Integration | Component | wallpaper', function (hooks) {
assert.dom('[data-test-wallpaper-container]').exists();
});
test('falls back to the remote original while the cache warms', async function (assert) {
test('shows only the bundled fallback while the cache warms', async function (assert) {
registerPhotos(this, {
currentWallpaper: {
url: 'https://blossom.example/full.jpg',
@@ -48,9 +48,9 @@ module('Integration | Component | wallpaper', function (hooks) {
await render(<template><Wallpaper /></template>);
assert
.dom('[data-test-wallpaper]')
.hasAttribute('src', 'https://blossom.example/full.jpg');
assert.dom('[data-test-wallpaper]').doesNotExist();
assert.dom('[data-test-wallpaper-base]').doesNotExist();
assert.dom('[data-test-wallpaper-container] img').exists({ count: 1 });
});
test('accepts a route-specific photo for the welcome screen', async function (assert) {
@@ -78,4 +78,101 @@ module('Integration | Component | wallpaper', function (hooks) {
assert.dom('[data-test-wallpaper]').doesNotExist();
assert.dom('[data-test-wallpaper-container] img').exists({ count: 1 });
});
test('shows the first photo outright on a plain open', async function (assert) {
registerPhotos(this, {
currentWallpaper: {
url: 'https://blossom.example/full.jpg',
displayUrl: 'blob:cached-full',
},
});
await render(<template><Wallpaper /></template>);
assert.dom('[data-test-wallpaper]').hasClass('opacity-100');
assert.dom('[data-test-wallpaper-base]').doesNotExist();
await triggerEvent('[data-test-wallpaper]', 'load');
assert
.dom('[data-test-wallpaper-base]')
.hasAttribute('src', 'blob:cached-full');
});
test('crossfades the first photo in when arriving from the welcome screen', async function (assert) {
registerPhotos(this, {
animateEntry: true,
currentWallpaper: {
url: 'https://blossom.example/full.jpg',
displayUrl: 'blob:cached-full',
},
});
await render(<template><Wallpaper /></template>);
assert.dom('[data-test-wallpaper]').hasClass('opacity-0');
await triggerEvent('[data-test-wallpaper]', 'load');
assert.dom('[data-test-wallpaper]').hasClass('opacity-100');
});
test('fades in a photo that resolves after mount when arriving from welcome', async function (assert) {
const photos = registerPhotos(this, {
animateEntry: true,
currentWallpaper: null,
});
await render(<template><Wallpaper /></template>);
assert.dom('[data-test-wallpaper]').doesNotExist();
photos.currentWallpaper = {
url: 'https://blossom.example/full.jpg',
displayUrl: 'blob:cached-full',
};
await settled();
assert.dom('[data-test-wallpaper]').hasClass('opacity-0');
await triggerEvent('[data-test-wallpaper]', 'load');
assert.dom('[data-test-wallpaper]').hasClass('opacity-100');
});
test('crossfades between photos, keeping the previous one beneath', async function (assert) {
const photos = registerPhotos(this, {
currentWallpaper: {
url: 'https://blossom.example/a.jpg',
displayUrl: 'blob:a',
},
});
await render(<template><Wallpaper /></template>);
await triggerEvent('[data-test-wallpaper]', 'load');
await triggerEvent('[data-test-wallpaper]', 'transitionend', {
propertyName: 'opacity',
});
assert.dom('[data-test-wallpaper-base]').hasAttribute('src', 'blob:a');
photos.currentWallpaper = {
url: 'https://blossom.example/b.jpg',
displayUrl: 'blob:b',
};
await settled();
assert.dom('[data-test-wallpaper]').hasAttribute('src', 'blob:b');
assert.dom('[data-test-wallpaper]').hasClass('opacity-0');
assert.dom('[data-test-wallpaper-base]').hasAttribute('src', 'blob:a');
await triggerEvent('[data-test-wallpaper]', 'load');
await triggerEvent('[data-test-wallpaper]', 'transitionend', {
propertyName: 'opacity',
});
assert.dom('[data-test-wallpaper]').hasClass('opacity-100');
assert.dom('[data-test-wallpaper-base]').hasAttribute('src', 'blob:b');
});
});
+129
View File
@@ -46,13 +46,42 @@ class FakeNostr {
class FakePhotoCache {
cached = new Map();
calls = [];
deferred = new Map();
failing = new Set();
// Gate `prefetchOriginal` for this id behind a promise the test resolves.
defer(photoId) {
let resolve;
const promise = new Promise((settle) => {
resolve = settle;
});
this.deferred.set(photoId, { promise, resolve });
return { promise, resolve };
}
fail(photoId) {
this.failing.add(photoId);
}
async originalUrl(photo) {
this.calls.push(['originalUrl', photo.id]);
return this.cached.get(photo.id) ?? null;
}
async prefetchOriginal(photo) {
this.calls.push(['original', photo.id]);
if (this.failing.has(photo.id)) {
throw new Error('prefetch failed');
}
const gate = this.deferred.get(photo.id);
if (gate) {
const url = await gate.promise;
this.cached.set(photo.id, url);
return url;
}
const url = `blob:original:${photo.id}`;
this.cached.set(photo.id, url);
return url;
@@ -70,6 +99,10 @@ class FakePhotoCache {
}
}
function flush() {
return new Promise((resolve) => setTimeout(resolve, 0));
}
function photoByTitle(title) {
return photoEvents.find((event) =>
event.tags.some((tag) => tag[0] === 'title' && tag[1] === title)
@@ -470,4 +503,100 @@ module('Unit | Service | photos', function (hooks) {
assert.ok(photos.rotationQueue.includes(cityId));
});
test('keeps the previous wallpaper while an uncached photo resolves', async function (assert) {
const { photos, photoCache } = setup(this);
await photos.refresh({ prefetch: false });
const previous = photos.displayUrl;
assert.ok(previous, 'a wallpaper is displayed');
const next = photos.photos.find(
(photo) => !photoCache.cached.has(photo.id)
);
assert.ok(next, 'there is an uncached photo');
const gate = photoCache.defer(next.id);
photos.currentPhotoId = next.id;
const pending = photos.resolveCurrentWallpaper();
await flush();
assert.strictEqual(
photos.displayUrl,
previous,
'the previous wallpaper stays while the new one is fetched'
);
gate.resolve(`blob:original:${next.id}`);
await pending;
assert.strictEqual(photos.displayUrl, `blob:original:${next.id}`);
});
test('keeps the last wallpaper when a fetch fails', async function (assert) {
const { photos, photoCache } = setup(this);
await photos.refresh({ prefetch: false });
const previous = photos.displayUrl;
const next = photos.photos.find(
(photo) => !photoCache.cached.has(photo.id)
);
photoCache.fail(next.id);
photos.currentPhotoId = next.id;
const originalError = console.error;
console.error = () => {};
try {
await photos.resolveCurrentWallpaper();
} finally {
console.error = originalError;
}
assert.strictEqual(photos.displayUrl, previous);
});
test('a scheduled rotation switches the wallpaper', async function (assert) {
const { photos } = setup(this);
const now = Date.now();
const nextId = photoByTitle('Awakening trees').id;
await photos.refresh();
photos.rotation = 'daily';
photos.rotationPeriodIndex = rotationIndex(now, 'daily') - 1;
photos.rotationQueue = [nextId];
photos.random = () => 0;
let rearmed = 0;
photos.scheduleRotation = () => {
rearmed += 1;
};
await photos.runScheduledRotation(now);
assert.strictEqual(photos.currentPhotoId, nextId);
assert.strictEqual(photos.displayUrl, `blob:original:${nextId}`);
assert.strictEqual(rearmed, 1, 're-arms the timer');
});
test('a scheduled rotation with nothing due leaves the wallpaper', async function (assert) {
const { photos, photoCache } = setup(this);
const now = Date.now();
await photos.refresh({ prefetch: false });
const currentId = photos.currentPhoto.id;
const url = photos.displayUrl;
const calls = photoCache.calls.length;
photos.scheduleRotation = () => {};
await photos.runScheduledRotation(now);
assert.strictEqual(photos.currentPhoto.id, currentId);
assert.strictEqual(photos.displayUrl, url);
assert.strictEqual(
photoCache.calls.length,
calls,
'does not resolve the wallpaper when nothing is due'
);
});
});