Files
raucao d846735b1e 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.
2026-11-10 15:18:13 +04:00

595 lines
15 KiB
JavaScript

import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import {
DEFAULT_ENABLED_FEED_IDS,
DEFAULT_ROTATION,
FALLBACK_WALLPAPER_URL,
NATURE_FEED_ID,
PHOTO_CONFIG_KEY,
PHOTO_PREFERENCES_NAMESPACE,
PHOTO_PREFETCH_ORIGINAL_COUNT,
PHOTO_STORAGE_NAMESPACE,
ROTATION_MODES,
ROTATION_VERSION,
WELCOME_WALLPAPER_URL,
} from '../config/nostr';
import { parseFeedEvents, parsePhotoEvents } from '../utils/nostr-photo-events';
import { nextRotationStart, rotationIndex, shuffle } from '../utils/rotation';
function normalizeRotation(mode) {
return ROTATION_MODES.includes(mode) ? mode : DEFAULT_ROTATION;
}
// Owns the read-only photo feed state, the selected wallpaper, and the
// prefetch/cache policy. The protocol is documented in doc/nostr-photo-feeds.md.
export default class PhotosService extends Service {
@service storage;
@service nostr;
@service photoCache;
@tracked feeds = [];
@tracked photos = [];
@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;
@tracked rotation = DEFAULT_ROTATION;
@tracked rotationPeriodIndex = null;
@tracked rotationQueue = [];
ready = null;
refreshPromise = null;
prefetchPromise = null;
displayToken = 0;
random = Math.random;
rotationTimer = null;
get welcomePhoto() {
return {
url: WELCOME_WALLPAPER_URL,
displayUrl: WELCOME_WALLPAPER_URL,
alt: '',
};
}
get fallbackPhoto() {
return {
url: FALLBACK_WALLPAPER_URL,
displayUrl: FALLBACK_WALLPAPER_URL,
alt: '',
};
}
get enabledFeeds() {
return this.feeds.filter((feed) => this.enabledFeedIds.includes(feed.id));
}
get rotationPool() {
return this.visiblePhotos;
}
get isRotating() {
return this.rotation !== 'off';
}
get defaultFeed() {
return (
this.enabledFeeds.find((feed) => feed.id === NATURE_FEED_ID) ??
this.enabledFeeds[0] ??
null
);
}
get defaultPhoto() {
const feed = this.defaultFeed;
if (!feed) {
return null;
}
return this.photosForFeed(feed.id)[0] ?? null;
}
get currentPhoto() {
const selected = this.currentPhotoId
? this.photoById(this.currentPhotoId)
: null;
if (selected?.attributed) {
return selected;
}
return this.defaultPhoto;
}
get currentWallpaper() {
const photo = this.currentPhoto;
if (!photo) {
return null;
}
return {
...photo,
displayUrl: this.displayUrl,
};
}
get currentCredit() {
const creator = this.currentPhoto?.creator;
if (!creator?.name) {
return null;
}
const url = creator.profile ?? creator.source;
if (!url) {
return null;
}
return {
name: creator.name,
url,
platform: creator.platform,
};
}
get visiblePhotos() {
const seen = new Set();
const photos = [];
for (const feed of this.enabledFeeds) {
for (const photo of this.photosForFeed(feed.id)) {
if (!seen.has(photo.id)) {
seen.add(photo.id);
photos.push(photo);
}
}
}
return photos;
}
photoById(id) {
return this.photos.find((photo) => photo.id === id) ?? null;
}
photosForFeed(feedId) {
const feed = this.feeds.find((candidate) => candidate.id === feedId);
if (!feed) {
return [];
}
return feed.photoIds
.map((id) => this.photoById(id))
.filter((photo) => photo?.attributed);
}
isFeedEnabled(feedId) {
return this.enabledFeedIds.includes(feedId);
}
loadCached() {
if (!this.ready) {
this.ready = this.doLoadCached();
}
return this.ready;
}
async doLoadCached() {
try {
const config = await this.storage.get(
PHOTO_PREFERENCES_NAMESPACE,
PHOTO_CONFIG_KEY
);
if (config) {
if (Array.isArray(config.enabledFeedIds)) {
this.enabledFeedIds = config.enabledFeedIds;
}
if (config.currentPhotoId) {
this.currentPhotoId = config.currentPhotoId;
}
// Rotation was never exposed before version 2, so any legacy config
// migrates to the new weekly default instead of remaining off.
if (config.rotationVersion === ROTATION_VERSION) {
this.rotation = normalizeRotation(config.rotation);
this.rotationPeriodIndex = Number.isInteger(
config.rotationPeriodIndex
)
? config.rotationPeriodIndex
: null;
this.rotationQueue = Array.isArray(config.rotationQueue)
? config.rotationQueue
: [];
} else {
this.rotation = DEFAULT_ROTATION;
this.rotationPeriodIndex = null;
this.rotationQueue = [];
}
}
if (this.rotation === 'off') {
this.rotationPeriodIndex = null;
this.rotationQueue = [];
}
const keys = await this.storage.keys(PHOTO_STORAGE_NAMESPACE);
const feedEvents = [];
const photoEvents = [];
for (const key of keys) {
const event = await this.storage.get(PHOTO_STORAGE_NAMESPACE, key);
if (!event) {
continue;
}
if (event.kind === 30006) {
feedEvents.push(event);
} else if (event.kind === 20) {
photoEvents.push(event);
}
}
this.applyEvents(feedEvents, photoEvents);
this.syncRotationPool();
await this.rotateIfDue();
await this.resolveCurrentWallpaper();
} catch (error) {
console.error('Error loading cached photos:', error);
} finally {
this.initialized = true;
this.scheduleRotation();
}
}
applyEvents(feedEvents, photoEvents) {
this.feeds = parseFeedEvents(feedEvents);
this.photos = parsePhotoEvents(photoEvents);
}
refreshInBackground() {
this.refresh().catch((error) => {
console.error('Error refreshing photo feeds:', error);
});
}
refresh({ prefetch = true } = {}) {
if (!this.refreshPromise) {
this.refreshPromise = this.doRefresh({ prefetch }).finally(() => {
this.refreshPromise = null;
});
}
return this.refreshPromise;
}
async doRefresh({ prefetch }) {
await this.loadCached();
this.refreshing = true;
this.error = null;
try {
const feedEvents = await this.nostr.queryFeedEvents();
const feeds = parseFeedEvents(feedEvents);
if (feeds.length > 0) {
this.feeds = feeds;
}
const ids = this.enabledFeeds.flatMap((feed) => feed.photoIds);
const photoEvents = ids.length ? await this.nostr.queryPhotos(ids) : [];
const freshPhotos = parsePhotoEvents(photoEvents);
// Keep cached photos for feeds that were not refreshed, but prefer the
// freshly relayed copy when the same event id comes back.
const byId = new Map(this.photos.map((photo) => [photo.id, photo]));
for (const photo of freshPhotos) {
byId.set(photo.id, photo);
}
this.photos = [...byId.values()];
await this.cacheEvents(this.feeds, freshPhotos);
this.syncRotationPool();
await this.rotateIfDue();
await this.resolveCurrentWallpaper();
if (prefetch) {
this.prefetchAssets();
}
} catch (error) {
console.error('Error refreshing photo feeds:', error);
this.error = error?.message ?? 'Unable to refresh photo feeds';
} finally {
this.refreshing = false;
this.scheduleRotation();
}
}
async cacheEvents(feeds, photos) {
try {
for (const feed of feeds) {
await this.storage.set(
PHOTO_STORAGE_NAMESPACE,
`feed:${feed.id}`,
feed.event
);
}
for (const photo of photos) {
await this.storage.set(
PHOTO_STORAGE_NAMESPACE,
`photo:${photo.id}`,
photo.event
);
}
} catch (error) {
console.error('Error caching photo events:', error);
}
}
prefetchAssets() {
const photos = this.enabledFeeds.flatMap((feed) =>
this.photosForFeed(feed.id)
);
const originals = photos.slice(0, PHOTO_PREFETCH_ORIGINAL_COUNT);
const tasks = [
...photos.map((photo) =>
this.photoCache.prefetchThumb(photo).catch(() => null)
),
...originals.map((photo) =>
this.photoCache.prefetchOriginal(photo).catch(() => null)
),
];
return Promise.allSettled(tasks).catch(() => null);
}
prefetchForWelcome() {
if (!this.prefetchPromise) {
this.prefetchPromise = (async () => {
await this.loadCached();
await this.refresh({ prefetch: true });
})()
.catch((error) => {
console.error('Error prefetching welcome photos:', error);
})
.finally(() => {
this.prefetchPromise = null;
});
}
return this.prefetchPromise;
}
async resolveCurrentWallpaper() {
const photo = this.currentPhoto;
const token = (this.displayToken += 1);
if (!photo) {
this.displayUrl = null;
return;
}
try {
const cached = await this.photoCache.originalUrl(photo);
if (token !== this.displayToken) {
return;
}
if (cached) {
this.displayUrl = cached;
return;
}
// 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);
}
}
syncRotationPool() {
if (this.rotation === 'off') {
this.rotationQueue = [];
return;
}
const poolIds = this.rotationPool.map((photo) => photo.id);
const currentId = this.currentPhoto?.id;
const queue = this.rotationQueue.filter(
(id) => poolIds.includes(id) && id !== currentId
);
const queued = new Set(queue);
const additions = shuffle(
poolIds.filter((id) => id !== currentId && !queued.has(id)),
this.random
);
this.rotationQueue = [...queue, ...additions];
}
async rotateIfDue(now = Date.now()) {
if (this.rotation === 'off') {
return false;
}
const period = rotationIndex(now, this.rotation);
if (period === null) {
return false;
}
if (this.rotationPeriodIndex === null) {
this.rotationPeriodIndex = period;
this.syncRotationPool();
await this.persistConfig();
return false;
}
if (this.rotationPeriodIndex > period) {
this.rotationPeriodIndex = period;
await this.persistConfig();
return false;
}
if (this.rotationPeriodIndex === period) {
return false;
}
const pool = this.rotationPool;
if (pool.length === 0) {
this.rotationPeriodIndex = period;
await this.persistConfig();
return false;
}
this.syncRotationPool();
const currentId = this.currentPhoto?.id;
let nextId = this.rotationQueue[0];
if (!nextId || nextId === currentId) {
const poolIds = pool.map((photo) => photo.id);
const candidates = poolIds.filter((id) => id !== currentId);
this.rotationQueue = shuffle(
candidates.length > 0 ? candidates : poolIds,
this.random
);
nextId = this.rotationQueue[0];
}
this.rotationQueue = this.rotationQueue.slice(1);
if (nextId) {
this.currentPhotoId = nextId;
}
this.rotationPeriodIndex = period;
await this.persistConfig();
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) {
return;
}
this.rotation = next;
if (next === 'off') {
this.rotationPeriodIndex = null;
this.rotationQueue = [];
} else {
this.rotationPeriodIndex = rotationIndex(Date.now(), next);
this.syncRotationPool();
}
this.scheduleRotation();
await this.persistConfig();
}
async setCurrentPhoto(id) {
const photo = this.photoById(id);
if (!photo?.attributed) {
return;
}
this.currentPhotoId = id;
if (this.rotation !== 'off') {
this.rotationQueue = this.rotationQueue.filter(
(queuedId) => queuedId !== id
);
}
await this.persistConfig();
await this.resolveCurrentWallpaper();
}
async setFeedEnabled(id, enabled) {
const ids = new Set(this.enabledFeedIds);
if (enabled) {
ids.add(id);
} else {
ids.delete(id);
}
this.enabledFeedIds = [...ids];
this.syncRotationPool();
await this.persistConfig();
if (enabled) {
await this.refresh();
}
}
async persistConfig() {
try {
await this.storage.set(PHOTO_PREFERENCES_NAMESPACE, PHOTO_CONFIG_KEY, {
enabledFeedIds: [...this.enabledFeedIds],
currentPhotoId: this.currentPhotoId,
rotation: this.rotation,
rotationVersion: ROTATION_VERSION,
rotationPeriodIndex: this.rotationPeriodIndex,
rotationQueue: [...this.rotationQueue],
});
} catch (error) {
console.error('Error saving photo settings:', error);
}
}
willDestroy() {
clearTimeout(this.rotationTimer);
super.willDestroy(...arguments);
}
}