Files
buzz/desktop/src/shared/theme/communityThemePreference.ts
Taylor Ho 83ca595ada fix(desktop): preserve theme when opening communities (#5266)
**Category:** fix
**User Impact:** Previously selected community themes are preserved when
opening a relay through onboarding, while first-time theme migration
still completes for communities with no saved theme.

**Problem:** During community initialization, desktop queried theme
history before establishing live delivery. If a replacement event
arrived while an empty history query was in flight, the client could
incorrectly treat the theme as absent and publish the default over the
user's saved selection.

**Solution:** Subscribe before fetching history, expose whether live
readiness reached EOSE, flush buffered live events before resolving
EOSE, and retain the newest delivered replacement through hydration.
Seed the inherited/default theme only when both live and history
snapshots reach EOSE with no valid or unreadable event; subscription
failures, CLOSED, readiness timeout, relay failure, and unreadable
events fail closed without publishing.

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

**desktop/src/shared/api/relayClientSession.ts / relayClientShared.ts /
relayClosedRecovery.ts**
Distinguish EOSE from CLOSED/timeout readiness and flush buffered events
before resolving an EOSE fence.

**desktop/src/shared/theme/CommunityThemeController.tsx**
Seed and complete first-community migration only for confirmed absence;
uncertain hydration remains non-publishing.

**desktop/src/shared/theme/communityThemePreference.ts**
Keep the inherited appearance for the first migrated community and the
stable default for later empty communities.

**desktop/src/shared/theme/communityThemeSync.ts**
Arbitrate live and history results into valid, confirmed-absent,
invalid, or unavailable hydration outcomes.

**Tests**
Cover EOSE/CLOSED readiness, subscription failure, timeout, unreadable
and live-racing events, no-op initialization, and first-to-later
community fallback isolation.

</details>

## Reproduction steps

1. Save a non-default appearance for a community relay.
2. Remove the community locally, then open the same relay again through
onboarding.
3. Arrange for the saved replacement event to arrive live while the
initial history query returns empty.
4. Confirm the saved appearance remains selected and the client does not
publish the default theme over it.
5. On an account with no theme records, open a first empty community and
confirm its inherited appearance is migrated; open a later empty
community and confirm it starts from the stable default.

## Validation

- Pre-push desktop checks, typecheck, and full desktop tests: passed at
`f79556b0e`
- Focused theme/relay readiness tests: 38 passed
- Desktop file-size ratchet and diff check: passed

---------

Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
Signed-off-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@buzz.block.builderlab.xyz>
Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@buzz.block.builderlab.xyz>
2026-08-11 08:21:34 -07:00

210 lines
5.6 KiB
TypeScript

import { normalizeRelayUrl } from "@/features/profile/lib/selfProfileStorage";
import { ACCENT_COLORS } from "./ThemeProvider";
import { SYNTAX_THEMES, type SyntaxThemeName } from "./theme-loader";
const STORAGE_KEY_PREFIX = "buzz-community-theme.v1";
const OUTBOX_KEY_PREFIX = "buzz-community-theme-outbox.v1";
const MIGRATION_KEY_PREFIX = "buzz-community-theme-migrated.v1";
export type CommunityThemePreference = {
version: 1;
theme: SyntaxThemeName;
accent: string;
followSystem: boolean;
};
export const DEFAULT_COMMUNITY_THEME: CommunityThemePreference = Object.freeze({
version: 1,
theme: "buzz",
accent: "#3b82f6",
followSystem: true,
});
const THEME_NAMES = new Set<string>(SYNTAX_THEMES);
const ACCENTS = new Set<string>(ACCENT_COLORS.map(({ value }) => value));
export function communityThemeStorageKey(
pubkey: string,
relayUrl: string,
): string {
return `${STORAGE_KEY_PREFIX}:${pubkey}:${encodeURIComponent(normalizeRelayUrl(relayUrl))}`;
}
export function communityThemeOutboxKey(
pubkey: string,
relayUrl: string,
): string {
return `${OUTBOX_KEY_PREFIX}:${pubkey}:${encodeURIComponent(normalizeRelayUrl(relayUrl))}`;
}
export function parseCommunityThemePreference(
value: unknown,
): CommunityThemePreference | null {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return null;
}
const candidate = value as Record<string, unknown>;
if (
candidate.version !== 1 ||
typeof candidate.theme !== "string" ||
!THEME_NAMES.has(candidate.theme) ||
typeof candidate.accent !== "string" ||
!ACCENTS.has(candidate.accent) ||
typeof candidate.followSystem !== "boolean"
) {
return null;
}
return {
version: 1,
theme: candidate.theme as SyntaxThemeName,
accent: candidate.accent,
followSystem: candidate.followSystem,
};
}
export function readCommunityThemePreference(
pubkey: string,
relayUrl: string,
): CommunityThemePreference | null {
try {
const raw = window.localStorage.getItem(
communityThemeStorageKey(pubkey, relayUrl),
);
return raw ? parseCommunityThemePreference(JSON.parse(raw)) : null;
} catch {
return null;
}
}
export function readCommunityThemeOutbox(
pubkey: string,
relayUrl: string,
): CommunityThemePreference | null {
try {
const raw = window.localStorage.getItem(
communityThemeOutboxKey(pubkey, relayUrl),
);
return raw ? parseCommunityThemePreference(JSON.parse(raw)) : null;
} catch {
return null;
}
}
export function writeCommunityThemeOutbox(
pubkey: string,
relayUrl: string,
preference: CommunityThemePreference,
): boolean {
try {
window.localStorage.setItem(
communityThemeOutboxKey(pubkey, relayUrl),
JSON.stringify(preference),
);
return true;
} catch {
return false;
}
}
export function clearCommunityThemeOutbox(
pubkey: string,
relayUrl: string,
acknowledged: CommunityThemePreference,
): void {
const pending = readCommunityThemeOutbox(pubkey, relayUrl);
if (!pending || !sameCommunityThemePreference(pending, acknowledged)) return;
try {
window.localStorage.removeItem(communityThemeOutboxKey(pubkey, relayUrl));
} catch {
// A later retry can safely publish the same replaceable event again.
}
}
export function hasMigratedCommunityTheme(pubkey: string): boolean {
try {
return (
window.localStorage.getItem(`${MIGRATION_KEY_PREFIX}:${pubkey}`) ===
"true"
);
} catch {
return false;
}
}
export function markCommunityThemeMigrated(pubkey: string): void {
try {
window.localStorage.setItem(`${MIGRATION_KEY_PREFIX}:${pubkey}`, "true");
} catch {
// The preference itself remains usable in memory when storage is full.
}
}
export function writeCommunityThemePreference(
pubkey: string,
relayUrl: string,
preference: CommunityThemePreference,
): boolean {
try {
window.localStorage.setItem(
communityThemeStorageKey(pubkey, relayUrl),
JSON.stringify(preference),
);
return true;
} catch {
return false;
}
}
export function cacheAndApplyCommunityTheme(
pubkey: string,
relayUrl: string,
preference: CommunityThemePreference,
apply: (preference: CommunityThemePreference) => void,
): void {
writeCommunityThemePreference(pubkey, relayUrl, preference);
apply(preference);
}
export function communityThemeScopeFallback(
migrated: boolean,
inherited: CommunityThemePreference,
): CommunityThemePreference {
return migrated ? DEFAULT_COMMUNITY_THEME : inherited;
}
export function sameCommunityThemePreference(
left: CommunityThemePreference,
right: CommunityThemePreference,
): boolean {
return (
left.theme === right.theme &&
left.accent === right.accent &&
left.followSystem === right.followSystem
);
}
export function communityThemeApplyExpectation(
preference: CommunityThemePreference,
current: CommunityThemePreference,
preserveNoop = false,
): CommunityThemePreference | null {
return preserveNoop || !sameCommunityThemePreference(preference, current)
? preference
: null;
}
/**
* Decide whether the current context value is safe to persist for this scope.
* Applying a scoped preference updates the outer ThemeProvider asynchronously,
* so renders that still expose the previous scope must be deferred.
*/
export function communityThemePersistenceAction(
expectedApplied: CommunityThemePreference | null,
current: CommunityThemePreference,
): "persist" | "defer" | "acknowledge" {
if (!expectedApplied) return "persist";
return sameCommunityThemePreference(expectedApplied, current)
? "acknowledge"
: "defer";
}