Add weekly and daily wallpaper rotation

Rotate through photos from enabled feeds with a persisted shuffle-bag queue. Weekly changes at local Monday midnight and daily at local midnight; Off keeps the selected photo. Legacy configs migrate to the weekly default, and Rotation now sits above Feeds in the Photos settings.
This commit is contained in:
raucao committed 2026-11-08 22:25:59 +04:00
1 parent 5fd916886e
commit 2cb54813b9
11 files changed
+731 -28

No files matched your search

@@ -2,6 +2,8 @@ import Component from '@glimmer/component';
import { action } from '@ember/object';
import { service } from '@ember/service';
import PhotoFeed from './photo-feed.gjs';
import RotationSettings from './rotation-settings.gjs';
import { nextRotationStart } from '../../../../utils/rotation';
// The Photos settings section: enable feeds and pick the current wallpaper.
// Creator attribution intentionally lives on the dashboard, next to Settings.
@@ -12,6 +14,22 @@ export default class SettingsPhotosSection extends Component {
return this.photos.feeds;
}
get nextChangeLabel() {
if (!this.photos.isRotating) {
return null;
}
const date = new Date(nextRotationStart(Date.now(), this.photos.rotation));
return new Intl.DateTimeFormat(undefined, {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(date);
}
@action
async toggleFeed(feedId, event) {
await this.photos.setFeedEnabled(feedId, event.target.checked);
@@ -21,8 +39,8 @@ export default class SettingsPhotosSection extends Component {
<div class="min-h-0 flex-1 overflow-y-auto px-6 py-6">
<div class="flex items-center gap-3">
<p class="max-w-prose text-sm text-gray-500">
Choose which photo feeds are available and pick the wallpaper shown on
your dashboard.
Choose the wallpapers shown on your dashboard, and if or when they
change.
</p>
{{#if this.photos.refreshing}}
<span class="text-xs text-gray-400">Refreshing...</span>
@@ -35,23 +53,34 @@ export default class SettingsPhotosSection extends Component {
</p>
{{/if}}
{{#if this.feeds.length}}
<div class="mt-6 space-y-4">
{{#each this.feeds as |feed|}}
<PhotoFeed @feed={{feed}} @onToggle={{this.toggleFeed}} />
{{/each}}
</div>
<RotationSettings />
<p class="mt-8 text-xs text-gray-400">
Weekly rotation is planned for a later update.
</p>
{{else if this.photos.refreshing}}
<p class="mt-6 text-sm text-gray-400">Loading photo feeds...</p>
{{else}}
<p
class="mt-6 rounded-xl bg-gray-50 p-6 text-center text-sm text-gray-500"
>
No photo feeds loaded yet.
<div class="mt-8 border-t border-gray-200 pt-6">
<h4 class="text-sm font-semibold text-gray-900" data-test-feeds-header>
Feeds
</h4>
{{#if this.feeds.length}}
<div class="mt-4 space-y-4">
{{#each this.feeds as |feed|}}
<PhotoFeed @feed={{feed}} @onToggle={{this.toggleFeed}} />
{{/each}}
</div>
{{else if this.photos.refreshing}}
<p class="mt-4 text-sm text-gray-400">Loading photo feeds...</p>
{{else}}
<p
class="mt-4 rounded-xl bg-gray-50 p-6 text-center text-sm text-gray-500"
>
No photo feeds loaded yet.
</p>
{{/if}}
</div>
{{#if this.photos.isRotating}}
<p class="mt-6 text-xs text-gray-400" data-test-rotation-next>
Selecting a photo keeps it until the next change. Next change:
{{this.nextChangeLabel}}.
</p>
{{/if}}
</div>
@@ -0,0 +1,69 @@
import Component from '@glimmer/component';
import { fn } from '@ember/helper';
import { on } from '@ember/modifier';
import { service } from '@ember/service';
const ROTATION_OPTIONS = [
{ value: 'weekly', label: 'Weekly' },
{ value: 'daily', label: 'Daily' },
{ value: 'off', label: 'Off' },
];
// Rotation mode controls for the Photos settings section.
export default class SettingsRotationSettingsComponent extends Component {
@service photos;
rotationOptions = ROTATION_OPTIONS;
isRotation = (mode) => this.photos.rotation === mode;
setRotation = async (mode) => {
await this.photos.setRotation(mode);
};
get rotationDescription() {
switch (this.photos.rotation) {
case 'daily':
return 'Every day at local midnight.';
case 'weekly':
return 'Every Monday at local midnight.';
default:
return 'Keep the selected photo.';
}
}
<template>
<fieldset class="mt-6" data-test-rotation>
<legend class="text-sm font-semibold text-gray-900">Rotation</legend>
<p class="mt-1 text-sm text-gray-500">
How often the wallpaper changes.
</p>
<div class="mt-3 grid grid-cols-3 gap-2">
{{#each this.rotationOptions as |option|}}
<label
class="cursor-pointer rounded-md border px-3 py-2 text-center text-sm font-medium transition-colors
{{if
(this.isRotation option.value)
'border-indigo-600 bg-indigo-50 text-indigo-700'
'border-gray-200 text-gray-600 hover:bg-gray-50'
}}"
>
<input
type="radio"
name="photo-rotation"
value={{option.value}}
checked={{this.isRotation option.value}}
data-test-rotation-option={{option.value}}
{{on "change" (fn this.setRotation option.value)}}
class="sr-only"
/>
{{option.label}}
</label>
{{/each}}
</div>
<p class="mt-2 text-xs text-gray-400">{{this.rotationDescription}}</p>
</fieldset>
</template>
}
+5 -4
View File
@@ -40,7 +40,8 @@ export const NOSTR_QUERY_TIMEOUT = 10_000;
export const PHOTO_ID_CHUNK_SIZE = 300;
export const PHOTO_PREFETCH_ORIGINAL_COUNT = 3;
// Rotation is intentionally out of this phase; the persisted config keeps the
// field so the next phase can add it without a storage migration.
export const DEFAULT_ROTATION = 'off';
export const ROTATION_MODES = ['off', 'weekly'];
// Rotation defaults to weekly. Bump ROTATION_VERSION when the persisted shape
// changes so legacy configs can be migrated intentionally.
export const DEFAULT_ROTATION = 'weekly';
export const ROTATION_MODES = ['weekly', 'daily', 'off'];
export const ROTATION_VERSION = 2;
+156 -1
View File
@@ -9,9 +9,16 @@ import {
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 { 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.
@@ -28,11 +35,15 @@ export default class PhotosService extends Service {
@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;
get welcomePhoto() {
return {
@@ -54,6 +65,14 @@ export default class PhotosService extends Service {
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) ??
@@ -170,6 +189,29 @@ export default class PhotosService extends Service {
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);
@@ -190,6 +232,8 @@ export default class PhotosService extends Service {
}
this.applyEvents(feedEvents, photoEvents);
this.syncRotationPool();
await this.rotateIfDue();
await this.resolveCurrentWallpaper();
} catch (error) {
console.error('Error loading cached photos:', error);
@@ -246,6 +290,8 @@ export default class PhotosService extends Service {
this.photos = [...byId.values()];
await this.cacheEvents(this.feeds, freshPhotos);
this.syncRotationPool();
await this.rotateIfDue();
await this.resolveCurrentWallpaper();
if (prefetch) {
@@ -348,6 +394,104 @@ export default class PhotosService extends Service {
}
}
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);
}
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();
}
await this.persistConfig();
}
async setCurrentPhoto(id) {
const photo = this.photoById(id);
if (!photo?.attributed) {
@@ -355,6 +499,13 @@ export default class PhotosService extends Service {
}
this.currentPhotoId = id;
if (this.rotation !== 'off') {
this.rotationQueue = this.rotationQueue.filter(
(queuedId) => queuedId !== id
);
}
await this.persistConfig();
await this.resolveCurrentWallpaper();
}
@@ -368,6 +519,7 @@ export default class PhotosService extends Service {
}
this.enabledFeedIds = [...ids];
this.syncRotationPool();
await this.persistConfig();
if (enabled) {
@@ -380,7 +532,10 @@ export default class PhotosService extends Service {
await this.storage.set(PHOTO_PREFERENCES_NAMESPACE, PHOTO_CONFIG_KEY, {
enabledFeedIds: [...this.enabledFeedIds],
currentPhotoId: this.currentPhotoId,
rotation: DEFAULT_ROTATION, // TODO: next phase
rotation: this.rotation,
rotationVersion: ROTATION_VERSION,
rotationPeriodIndex: this.rotationPeriodIndex,
rotationQueue: [...this.rotationQueue],
});
} catch (error) {
console.error('Error saving photo settings:', error);
+62
View File
@@ -0,0 +1,62 @@
export const DAY_MS = 24 * 60 * 60 * 1000;
// Local calendar day index. Using the local Y/M/D components keeps the index
// stable across DST transitions and makes it change at local midnight.
function localDayIndex(date) {
return Math.floor(
Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / DAY_MS
);
}
// Weekly periods start on Monday at local midnight. 1970-01-05 was a Monday,
// which is day 4 in this day-index scheme.
export function rotationIndex(now, mode) {
const date = new Date(now);
if (mode === 'weekly') {
return Math.floor((localDayIndex(date) - 4) / 7);
}
if (mode === 'daily') {
return localDayIndex(date);
}
return null;
}
export function nextRotationStart(now, mode) {
const date = new Date(now);
if (mode === 'weekly') {
const daysUntilMonday = (8 - date.getDay()) % 7 || 7;
const next = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() + daysUntilMonday,
0,
0,
0,
0
);
return next.getTime();
}
if (mode === 'daily') {
const next = new Date(date);
next.setHours(24, 0, 0, 0);
return next.getTime();
}
return null;
}
export function shuffle(items, random = Math.random) {
const result = [...items];
for (let index = result.length - 1; index > 0; index -= 1) {
const swapIndex = Math.floor(random() * (index + 1));
[result[index], result[swapIndex]] = [result[swapIndex], result[index]];
}
return result;
}
+25 -5
View File
@@ -112,14 +112,34 @@ Rules:
background.
- 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 next to the Settings button; Settings itself shows no
creator credit link sits in the bottom-right corner; Settings itself shows no
attribution text.
- Tests use the published events in `tests/fixtures/nostr/`; all relay,
Blossom, and image connections are stubbed.
## Rotation
Weekly rotation is intentionally out of the current phase. The persisted
`photos.config` keeps a `rotation` field (`off`) so it can be added without a
storage migration. The next phase will use a UTC-Monday week index and a
persisted shuffle-bag queue.
Rotation defaults to **Weekly**:
- **Weekly** changes at local Monday midnight.
- **Daily** changes at local midnight.
- **Off** keeps the selected photo.
The pool is all attributed photos from enabled feeds. A persisted shuffle-bag
queue avoids repeats until the pool is exhausted. Selecting a photo manually
keeps it until the next scheduled change and removes it from the queue.
Persisted fields:
```json
{
"rotation": "weekly",
"rotationVersion": 2,
"rotationPeriodIndex": 1789,
"rotationQueue": ["...", "..."]
}
```
Configs written before `rotationVersion: 2` migrate to the weekly default.
`rotationPeriodIndex` uses the UTC week index for weekly mode and the local
calendar day index for daily mode.
+13
View File
@@ -10,6 +10,9 @@ export default class FakePhotos {
@tracked error = null;
@tracked currentWallpaper = null;
@tracked currentCredit = null;
@tracked rotation = 'weekly';
@tracked rotationPeriodIndex = null;
@tracked rotationQueue = [];
fallbackPhoto = {
url: '/img/wallpapers/fallback.jpg',
@@ -20,8 +23,13 @@ export default class FakePhotos {
calls = {
setFeedEnabled: [],
setCurrentPhoto: [],
setRotation: [],
};
get isRotating() {
return this.rotation !== 'off';
}
get currentPhoto() {
const photos = this.feeds.flatMap((feed) => feed.photos ?? []);
return (
@@ -52,4 +60,9 @@ export default class FakePhotos {
this.calls.setCurrentPhoto.push(photoId);
this.currentPhotoId = photoId;
}
async setRotation(mode) {
this.calls.setRotation.push(mode);
this.rotation = mode;
}
}
@@ -85,6 +85,19 @@ module('Integration | Component | settings/photos', function (hooks) {
await render(<template><SettingsPhotosSection /></template>);
assert.dom('[data-test-rotation]').exists();
assert.dom('[data-test-feeds-header]').hasText('Feeds');
const rotation = this.element.querySelector('[data-test-rotation]');
const feedsHeader = this.element.querySelector('[data-test-feeds-header]');
assert.true(
Boolean(
rotation.compareDocumentPosition(feedsHeader) &
Node.DOCUMENT_POSITION_FOLLOWING
),
'Rotation appears before Feeds'
);
assert.dom('[data-test-photo-feed="dt:nature"]').exists();
assert.dom('[data-test-photo-feed="dt:city-nights"]').exists();
assert.dom('[data-test-photo-feed-toggle="dt:nature"]').isChecked();
@@ -97,6 +110,36 @@ module('Integration | Component | settings/photos', function (hooks) {
...this.element.querySelectorAll('[data-test-photo-feed]'),
].map((element) => element.getAttribute('data-test-photo-feed'));
assert.deepEqual(feedOrder, ['dt:nature', 'dt:city-nights']);
assert.dom('[data-test-rotation-next]').exists();
const rotationNext = this.element.querySelector(
'[data-test-rotation-next]'
);
assert.true(
Boolean(
feedsHeader.compareDocumentPosition(rotationNext) &
Node.DOCUMENT_POSITION_FOLLOWING
),
'next-change line appears after the Feeds header'
);
assert.true(
Boolean(
this.element
.querySelector('[data-test-photo-feed="dt:city-nights"]')
.compareDocumentPosition(rotationNext) &
Node.DOCUMENT_POSITION_FOLLOWING
),
'next-change line appears at the bottom of the section'
);
});
test('hides the next-change line when rotation is off', async function (assert) {
const photos = setup(this);
photos.rotation = 'off';
await render(<template><SettingsPhotosSection /></template>);
assert.dom('[data-test-rotation-next]').doesNotExist();
});
test('does not render attribution text in Settings', async function (assert) {
@@ -0,0 +1,61 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, click } from '@ember/test-helpers';
import RotationSettings from 'dashtab/components/settings/global-settings/sections/rotation-settings';
import FakePhotos from 'dashtab/tests/helpers/fake-photos';
module(
'Integration | Component | settings/rotation-settings',
function (hooks) {
setupRenderingTest(hooks);
function setup(context) {
const photos = new FakePhotos();
context.owner.register('service:photos', photos, {
instantiate: false,
});
return photos;
}
test('defaults to Weekly', async function (assert) {
setup(this);
await render(<template><RotationSettings /></template>);
assert.dom('legend').hasText('Rotation');
assert.dom('[data-test-rotation-option="weekly"]').isChecked();
assert.dom('[data-test-rotation-option="daily"]').isNotChecked();
assert.dom('[data-test-rotation-option="off"]').isNotChecked();
assert
.dom('[data-test-rotation]')
.includesText('Every Monday at local midnight.');
});
test('switching to Daily updates the mode and copy', async function (assert) {
const photos = setup(this);
await render(<template><RotationSettings /></template>);
await click('[data-test-rotation-option="daily"]');
assert.deepEqual(photos.calls.setRotation, ['daily']);
assert.strictEqual(photos.rotation, 'daily');
assert.dom('[data-test-rotation-option="daily"]').isChecked();
assert
.dom('[data-test-rotation]')
.includesText('Every day at local midnight.');
});
test('Off shows the keep-selected copy', async function (assert) {
const photos = setup(this);
await render(<template><RotationSettings /></template>);
await click('[data-test-rotation-option="off"]');
assert.deepEqual(photos.calls.setRotation, ['off']);
assert.strictEqual(photos.rotation, 'off');
assert
.dom('[data-test-rotation]')
.includesText('Keep the selected photo.');
});
}
);
+192
View File
@@ -1,5 +1,6 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
import { rotationIndex } from 'dashtab/utils/rotation';
import photoEvents from '../../fixtures/nostr/photo-events.json';
import feedEvents from '../../fixtures/nostr/feed-events.json';
@@ -108,6 +109,9 @@ module('Unit | Service | photos', function (hooks) {
assert.deepEqual(photos.feeds, []);
assert.deepEqual(photos.photos, []);
assert.strictEqual(photos.currentPhoto, null);
assert.strictEqual(photos.rotation, 'weekly');
assert.strictEqual(typeof photos.rotationPeriodIndex, 'number');
assert.deepEqual(photos.rotationQueue, []);
assert.true(photos.initialized);
});
@@ -278,4 +282,192 @@ module('Unit | Service | photos', function (hooks) {
const config = await storage.get('preferences', 'photos.config');
assert.strictEqual(config.currentPhotoId, alexander.id);
});
test('migrates a legacy off config to weekly', async function (assert) {
const { photos, storage } = setup(this);
await storage.set('preferences', 'photos.config', {
enabledFeedIds: ['dt:nature'],
currentPhotoId: null,
rotation: 'off',
});
await photos.loadCached();
assert.strictEqual(photos.rotation, 'weekly');
assert.strictEqual(typeof photos.rotationPeriodIndex, 'number');
const config = await storage.get('preferences', 'photos.config');
assert.strictEqual(config.rotation, 'weekly');
assert.strictEqual(config.rotationVersion, 2);
});
test('honors an explicit off mode in a versioned config', async function (assert) {
const { photos, storage } = setup(this);
await storage.set('preferences', 'photos.config', {
enabledFeedIds: ['dt:nature'],
currentPhotoId: null,
rotation: 'off',
rotationVersion: 2,
rotationPeriodIndex: 42,
rotationQueue: ['stale'],
});
await photos.loadCached();
assert.strictEqual(photos.rotation, 'off');
assert.strictEqual(photos.rotationPeriodIndex, null);
assert.deepEqual(photos.rotationQueue, []);
});
test('rotates daily when the local day changes', 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;
const changed = await photos.rotateIfDue(now);
assert.true(changed);
assert.strictEqual(photos.currentPhotoId, nextId);
assert.strictEqual(photos.rotationPeriodIndex, rotationIndex(now, 'daily'));
assert.notOk(photos.rotationQueue.includes(nextId));
});
test('rotates weekly when the UTC week changes', async function (assert) {
const { photos } = setup(this);
const now = Date.now();
const nextId = photoByTitle('Rolling sand dunes').id;
await photos.refresh();
photos.rotation = 'weekly';
photos.rotationPeriodIndex = rotationIndex(now, 'weekly') - 1;
photos.rotationQueue = [nextId];
photos.random = () => 0;
const changed = await photos.rotateIfDue(now);
assert.true(changed);
assert.strictEqual(photos.currentPhotoId, nextId);
assert.strictEqual(
photos.rotationPeriodIndex,
rotationIndex(now, 'weekly')
);
});
test('does not rotate twice in the same period', async function (assert) {
const { photos } = setup(this);
const now = Date.now();
await photos.refresh();
const currentId = photos.currentPhoto.id;
photos.rotation = 'daily';
photos.rotationPeriodIndex = rotationIndex(now, 'daily');
photos.currentPhotoId = currentId;
photos.rotationQueue = [photoByTitle('Awakening trees').id];
const changed = await photos.rotateIfDue(now);
assert.false(changed);
assert.strictEqual(photos.currentPhotoId, currentId);
assert.deepEqual(photos.rotationQueue, [
photoByTitle('Awakening trees').id,
]);
});
test('refills the queue without repeating the current photo', async function (assert) {
const { photos } = setup(this);
const now = Date.now();
await photos.refresh();
const currentId = photos.currentPhoto.id;
photos.rotation = 'daily';
photos.rotationPeriodIndex = rotationIndex(now, 'daily') - 1;
photos.currentPhotoId = currentId;
photos.rotationQueue = [];
photos.random = () => 0;
const changed = await photos.rotateIfDue(now);
assert.true(changed);
assert.notStrictEqual(photos.currentPhotoId, currentId);
assert.true(
photos.rotationPool
.map((photo) => photo.id)
.includes(photos.currentPhotoId)
);
});
test('keeps a single-photo pool', async function (assert) {
const { photos } = setup(this);
const now = Date.now();
const adrian = photoByTitle('Winding road through autumn forest');
await photos.refresh();
photos.photos = photos.photos.filter((photo) => photo.id === adrian.id);
photos.rotation = 'daily';
photos.rotationPeriodIndex = rotationIndex(now, 'daily') - 1;
photos.currentPhotoId = adrian.id;
photos.rotationQueue = [];
photos.random = () => 0;
const changed = await photos.rotateIfDue(now);
assert.false(changed);
assert.strictEqual(photos.currentPhotoId, adrian.id);
});
test('switching modes keeps the current photo and resets rotation state', async function (assert) {
const { photos } = setup(this);
await photos.refresh();
const currentId = photos.currentPhoto.id;
await photos.setRotation('daily');
assert.strictEqual(photos.rotation, 'daily');
assert.strictEqual(typeof photos.rotationPeriodIndex, 'number');
assert.strictEqual(photos.currentPhoto.id, currentId);
await photos.setRotation('off');
assert.strictEqual(photos.rotation, 'off');
assert.strictEqual(photos.rotationPeriodIndex, null);
assert.deepEqual(photos.rotationQueue, []);
});
test('manual selection removes the photo from the rotation queue', async function (assert) {
const { photos } = setup(this);
const selectedId = photoByTitle('Awakening trees').id;
await photos.refresh();
photos.rotation = 'weekly';
photos.rotationQueue = [selectedId, photoByTitle('Rolling sand dunes').id];
await photos.setCurrentPhoto(selectedId);
assert.strictEqual(photos.currentPhotoId, selectedId);
assert.notOk(photos.rotationQueue.includes(selectedId));
});
test('new feed photos enter the rotation queue', async function (assert) {
const { photos } = setup(this);
const cityId = photoByTitle('Train at night').id;
await photos.refresh();
photos.currentPhotoId = photoByTitle(
'Winding road through autumn forest'
).id;
photos.syncRotationPool();
assert.notOk(photos.rotationQueue.includes(cityId));
await photos.setFeedEnabled('dt:city-nights', true);
assert.ok(photos.rotationQueue.includes(cityId));
});
});
+58
View File
@@ -0,0 +1,58 @@
import { module, test } from 'qunit';
import {
nextRotationStart,
rotationIndex,
shuffle,
} from 'dashtab/utils/rotation';
module('Unit | Utility | rotation', function () {
test('weekly periods change at local Monday midnight', function (assert) {
const sunday = new Date(2026, 10, 8, 23, 59, 59).getTime();
const monday = new Date(2026, 10, 9, 0, 0, 0).getTime();
assert.strictEqual(
rotationIndex(monday, 'weekly'),
rotationIndex(sunday, 'weekly') + 1
);
const next = new Date(nextRotationStart(sunday, 'weekly'));
assert.strictEqual(next.getFullYear(), 2026);
assert.strictEqual(next.getMonth(), 10);
assert.strictEqual(next.getDate(), 9);
assert.strictEqual(next.getHours(), 0);
assert.strictEqual(next.getMinutes(), 0);
assert.strictEqual(next.getSeconds(), 0);
});
test('daily periods change at local midnight', function (assert) {
const before = new Date(2026, 10, 8, 23, 59, 59).getTime();
const after = new Date(2026, 10, 9, 0, 0, 0).getTime();
assert.strictEqual(
rotationIndex(after, 'daily'),
rotationIndex(before, 'daily') + 1
);
const next = new Date(nextRotationStart(before, 'daily'));
assert.strictEqual(next.getFullYear(), 2026);
assert.strictEqual(next.getMonth(), 10);
assert.strictEqual(next.getDate(), 9);
assert.strictEqual(next.getHours(), 0);
assert.strictEqual(next.getMinutes(), 0);
assert.strictEqual(next.getSeconds(), 0);
});
test('off has no rotation period', function (assert) {
assert.strictEqual(rotationIndex(Date.now(), 'off'), null);
assert.strictEqual(nextRotationStart(Date.now(), 'off'), null);
});
test('shuffle is deterministic with an injected random source', function (assert) {
assert.deepEqual(
shuffle([1, 2, 3], () => 0),
[2, 3, 1]
);
});
});