Files
buzz/desktop/src/shared/theme/communityThemeSync.ts
Taylor Ho 43cced308d feat(desktop): sync themes per community (#3653)
**Category:** new-feature
**User Impact:** Users can keep a distinct Appearance scheme for each
community and restore it on another desktop signed in with the same
identity.

**Problem:** A single global theme makes it harder to distinguish among
communities, and local-only preferences do not follow a user to another
device. **Solution:** Save each community's stable theme, accent, and
system-following selection as private encrypted relay state, backed by a
responsive local cache and guarded against switch races, invalid future
records, and relay failures.

<details>
<summary>File changes</summary>

**desktop/src/app/App.tsx**
Mounts the community-scoped theme controller inside the active community
lifecycle.

**desktop/src/features/settings/lib/appearanceScopeCopy.test.mjs**
Covers active-community and fallback labels used to explain Appearance
scope.

**desktop/src/features/settings/lib/appearanceScopeCopy.ts**
Builds a safe, trimmed label for the currently active community.

**desktop/src/features/settings/ui/SettingsPanels.tsx**
Clarifies which Appearance controls are per-community and which apply
globally when multiple communities exist.

**desktop/src/shared/constants/kinds.ts**
Defines the NIP-78 application-data event kind used for theme
preferences.

**desktop/src/shared/theme/CommunityThemeController.tsx**
Coordinates cached appearance, encrypted relay retrieval, live updates,
reconnect behavior, and safe community switching.

**desktop/src/shared/theme/ThemeProvider.tsx**
Exposes a single appearance application path so synchronized preferences
use the existing renderer and persistence behavior.

**desktop/src/shared/theme/communityThemePreference.test.mjs**
Covers contract validation, user/relay isolation, malformed records,
cache failures, and switch-race decisions.

**desktop/src/shared/theme/communityThemePreference.ts**
Defines the versioned stable preference contract, safe defaults, local
cache keys, and persistence guards.

**desktop/src/shared/theme/communityThemeSync.test.mjs**
Covers relay absence, unreadable records, unavailability, seeding
safety, and teardown of pending writes.

**desktop/src/shared/theme/communityThemeSync.ts**
Encrypts theme preferences to the user, publishes and retrieves NIP-78
state, and handles ordering and lifecycle safety.

</details>

### Reproduction steps

1. Join at least two communities and open **Settings → Appearance**.
2. Choose a different theme, accent, or system-following mode in each
community.
3. Switch between the communities and verify each one restores its own
scheme without overwriting the other.
4. Sign in on another desktop with the same Nostr identity, join the
same community, and verify its saved scheme is restored from that
community's relay.
5. Disconnect the relay, change Appearance, and verify the UI remains
responsive and the local fallback is retained.

### Screenshots / demos
<img width="1733" height="948" alt="image"
src="https://github.com/user-attachments/assets/5afeabaa-0def-482c-9b87-8a880ee0a467"
/>


<img width="700" height="412" alt="Screen Recording 2026-07-29 at 4 39
52 PM"
src="https://github.com/user-attachments/assets/d58da329-aec5-4324-a4b2-cbcb2702a81a"
/>

---------

Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
Signed-off-by: npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6w <52a228d6edf316ec6812ac3c9fc0d696ab59fc7954d77e7be31eedcddf91335b@buzz.block.builderlab.xyz>
Co-authored-by: npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6w <52a228d6edf316ec6812ac3c9fc0d696ab59fc7954d77e7be31eedcddf91335b@buzz.block.builderlab.xyz>
2026-08-05 13:18:48 -07:00

322 lines
9.1 KiB
TypeScript

import { relayClient } from "@/shared/api/relayClient";
import {
nip44DecryptFromSelf,
nip44EncryptToSelf,
signRelayEvent,
} from "@/shared/api/tauri";
import type { RelayEvent } from "@/shared/api/types";
import { KIND_COMMUNITY_THEME } from "@/shared/constants/kinds";
import {
parseCommunityThemePreference,
sameCommunityThemePreference,
type CommunityThemePreference,
} from "./communityThemePreference";
const D_TAG = "community-theme";
const DEBOUNCE_MS = 2_000;
const PUBLISH_RETRY_BASE_MS = 1_000;
const PUBLISH_RETRY_MAX_MS = 30_000;
export type PublishedCommunityTheme = {
preference: CommunityThemePreference;
createdAt: number;
eventId: string;
};
export type RemoteCommunityTheme = {
preference: CommunityThemePreference;
createdAt: number;
eventId: string;
};
export type RemoteCommunityThemeResult =
| { status: "valid"; remote: RemoteCommunityTheme }
| { status: "absent" | "invalid" | "unavailable" };
export function isNewerCommunityThemeCoordinate(
candidate: { createdAt: number; eventId: string },
current: { createdAt: number; eventId: string },
): boolean {
return (
candidate.createdAt > current.createdAt ||
(candidate.createdAt === current.createdAt &&
(current.eventId === "" || candidate.eventId < current.eventId))
);
}
export function shouldSeedCommunityTheme(
result: RemoteCommunityThemeResult,
): boolean {
return result.status === "absent";
}
async function decryptAndParse(
event: RelayEvent,
): Promise<RemoteCommunityTheme | null> {
try {
const plaintext = await nip44DecryptFromSelf(event.content);
const preference = parseCommunityThemePreference(JSON.parse(plaintext));
return preference
? { preference, createdAt: event.created_at, eventId: event.id }
: null;
} catch {
return null;
}
}
export class CommunityThemeSyncManager {
private readonly pubkey: string;
private debounceTimer: number | null = null;
private destroyed = false;
private lastRemoteCreatedAt = 0;
private lastRemoteEventId = "";
private lastPublished: PublishedCommunityTheme | null = null;
private pending: CommunityThemePreference | null = null;
private publishInFlight = false;
private publishRetryAttempt = 0;
private readonly remoteProcessing = new Set<Promise<unknown>>();
private readonly onPublished: (published: PublishedCommunityTheme) => void;
constructor(
pubkey: string,
onPublished: (published: PublishedCommunityTheme) => void = () => {},
) {
this.pubkey = pubkey;
this.onPublished = onPublished;
}
async fetchRemote(): Promise<RemoteCommunityThemeResult> {
try {
const events = await relayClient.fetchEvents({
kinds: [KIND_COMMUNITY_THEME],
authors: [this.pubkey],
"#d": [D_TAG],
limit: 1,
});
if (events.length === 0) return { status: "absent" };
if (events[0].pubkey !== this.pubkey) return { status: "invalid" };
const processing = decryptAndParse(events[0]);
this.trackRemoteProcessing(processing);
const remote = await processing;
if (!remote) return { status: "invalid" };
if (
isNewerCommunityThemeCoordinate(remote, {
createdAt: this.lastRemoteCreatedAt,
eventId: this.lastRemoteEventId,
})
) {
this.lastRemoteCreatedAt = remote.createdAt;
this.lastRemoteEventId = remote.eventId;
}
return { status: "valid", remote };
} catch {
return { status: "unavailable" };
}
}
publish(preference: CommunityThemePreference): void {
if (this.destroyed) return;
this.pending = preference;
this.publishRetryAttempt = 0;
this.schedulePublish(DEBOUNCE_MS);
}
private schedulePublish(delayMs: number): void {
if (this.destroyed) return;
if (this.debounceTimer !== null) {
window.clearTimeout(this.debounceTimer);
}
this.debounceTimer = window.setTimeout(() => {
this.debounceTimer = null;
this.startPublish();
}, delayMs);
}
private startPublish(): void {
if (this.destroyed || this.publishInFlight || !this.pending) return;
this.publishInFlight = true;
const preference = this.pending;
void this.doPublish(preference).finally(() => {
this.publishInFlight = false;
if (
!this.destroyed &&
this.pending &&
!sameCommunityThemePreference(this.pending, preference) &&
this.debounceTimer === null
) {
this.schedulePublish(0);
}
});
}
getPending(): CommunityThemePreference | null {
return this.pending;
}
acceptRemote(remote: RemoteCommunityTheme): void {
if (
isNewerCommunityThemeCoordinate(remote, {
createdAt: this.lastRemoteCreatedAt,
eventId: this.lastRemoteEventId,
})
) {
this.lastRemoteCreatedAt = remote.createdAt;
this.lastRemoteEventId = remote.eventId;
}
const lastPublished = this.lastPublished;
if (
lastPublished &&
(lastPublished.createdAt !== remote.createdAt ||
lastPublished.eventId !== remote.eventId)
) {
this.lastPublished = null;
}
}
cancelPendingPublish(): void {
if (this.debounceTimer !== null) {
window.clearTimeout(this.debounceTimer);
this.debounceTimer = null;
}
this.pending = null;
}
private async doPublish(preference: CommunityThemePreference): Promise<void> {
try {
const lastPublished = this.lastPublished;
if (
this.destroyed ||
(lastPublished &&
sameCommunityThemePreference(lastPublished.preference, preference))
) {
if (
this.pending &&
sameCommunityThemePreference(this.pending, preference)
) {
this.pending = null;
if (lastPublished) this.onPublished(lastPublished);
}
return;
}
const ciphertext = await nip44EncryptToSelf(JSON.stringify(preference));
if (this.destroyed) return;
const event = await signRelayEvent({
kind: KIND_COMMUNITY_THEME,
content: ciphertext,
createdAt: Math.max(
Math.floor(Date.now() / 1_000),
this.lastRemoteCreatedAt + 1,
),
tags: [
["d", D_TAG],
["t", D_TAG],
],
});
if (this.destroyed) return;
await relayClient.publishEvent(
event,
"Timed out publishing community theme.",
"Failed to publish community theme.",
);
await this.waitForDeliveredRemotes();
if (this.destroyed) return;
const published = {
preference,
createdAt: event.created_at,
eventId: event.id,
};
const eventLostToRemote = isNewerCommunityThemeCoordinate(
{
createdAt: this.lastRemoteCreatedAt,
eventId: this.lastRemoteEventId,
},
published,
);
if (eventLostToRemote) {
this.lastPublished = null;
this.publishRetryAttempt = 0;
if (
this.pending &&
sameCommunityThemePreference(this.pending, preference)
) {
this.schedulePublish(0);
}
return;
}
this.lastRemoteCreatedAt = event.created_at;
this.lastRemoteEventId = event.id;
this.lastPublished = published;
this.publishRetryAttempt = 0;
if (
this.pending &&
sameCommunityThemePreference(this.pending, preference)
) {
this.pending = null;
}
this.onPublished(published);
} catch (error) {
console.warn("[communityThemeSync] publish failed:", error);
if (
this.destroyed ||
!this.pending ||
!sameCommunityThemePreference(this.pending, preference)
) {
return;
}
const delay = Math.min(
PUBLISH_RETRY_BASE_MS * 2 ** this.publishRetryAttempt,
PUBLISH_RETRY_MAX_MS,
);
this.publishRetryAttempt += 1;
this.schedulePublish(delay);
}
}
private trackRemoteProcessing(task: Promise<unknown>): void {
this.remoteProcessing.add(task);
void task.then(
() => this.remoteProcessing.delete(task),
() => this.remoteProcessing.delete(task),
);
}
private async waitForDeliveredRemotes(): Promise<void> {
await Promise.allSettled([...this.remoteProcessing]);
}
async subscribe(
onUpdate: (remote: RemoteCommunityTheme) => void,
): Promise<() => Promise<void>> {
return relayClient.subscribeLive(
{
kinds: [KIND_COMMUNITY_THEME],
authors: [this.pubkey],
"#d": [D_TAG],
limit: 0,
},
(event: RelayEvent) => {
if (event.pubkey !== this.pubkey || this.destroyed) return;
const processing = decryptAndParse(event).then((remote) => {
if (!remote || this.destroyed) return;
if (
isNewerCommunityThemeCoordinate(remote, {
createdAt: this.lastRemoteCreatedAt,
eventId: this.lastRemoteEventId,
})
) {
this.lastRemoteCreatedAt = remote.createdAt;
this.lastRemoteEventId = remote.eventId;
}
onUpdate(remote);
});
this.trackRemoteProcessing(processing);
},
);
}
destroy(): void {
this.destroyed = true;
this.cancelPendingPublish();
}
}