Refactors admin page design to move each 'facet' of admin into its own component.

This commit is contained in:
2026-07-10 01:14:30 -07:00
parent a4093e86b1
commit c02c0cdde9
30 changed files with 1970 additions and 1757 deletions
+56 -592
View File
@@ -1,30 +1,23 @@
import { Component, inject, signal, OnInit } from '@angular/core';
import { CommonModule, AsyncPipe } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { BehaviorSubject, firstValueFrom } from 'rxjs';
import { Component, inject, OnInit, signal, ViewEncapsulation } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Show } from '../interfaces/show';
import { Event as StationEvent } from '../interfaces/event';
import { StationConfig } from '../interfaces/station-config';
import { HistoryEntry } from '../interfaces/history-entry';
import { TeamMember } from '../interfaces/team-member';
import { CommunityHighlight } from '../interfaces/community-highlight';
import { Underwriter } from '../interfaces/underwriter';
import {
MobileBuildArtifact,
MobileBuildDefaults,
MobileBuildRequest,
ThemeStatus,
} from '../interfaces/mobile-build';
import { ShowService } from '../services/show.service';
import { EventService } from '../services/event.service';
import { StationConfig } from '../interfaces/station-config';
import { StationConfigService } from '../services/station-config.service';
import { ThemeService } from '../services/theme.service';
import { HistoryEntryService } from '../services/history-entry.service';
import { TeamMemberService } from '../services/team-member.service';
import { CommunityHighlightService } from '../services/community-highlight.service';
import { UnderwriterService } from '../services/underwriter.service';
import { MobileBuildService } from '../services/mobile-build.service';
import { AdminShowsTabComponent } from './admin-shows-tab.component';
import { AdminEventsTabComponent } from './admin-events-tab.component';
import { AdminHistoryTabComponent } from './admin-history-tab.component';
import { AdminTeamTabComponent } from './admin-team-tab.component';
import { AdminCommunityTabComponent } from './admin-community-tab.component';
import { AdminStationTabComponent } from './admin-station-tab.component';
import { AdminThemeTabComponent } from './admin-theme-tab.component';
import { AdminUnderwritersTabComponent } from './admin-underwriters-tab.component';
import { AdminMobileBuildsTabComponent } from './admin-mobile-builds-tab.component';
import { AdminShowFormComponent } from './admin-show-form.component';
import { AdminEventFormComponent } from './admin-event-form.component';
import { AdminStationFormComponent } from './admin-station-form.component';
@@ -33,50 +26,35 @@ import { AdminTeamFormComponent } from './admin-team-form.component';
import { AdminCommunityFormComponent } from './admin-community-form.component';
import { AdminUnderwriterFormComponent } from './admin-underwriter-form.component';
import { AdminStatsDashboardComponent } from './admin-stats-dashboard.component';
import {
COLOR_ROLES,
HARMONY_RULE_LABELS,
detectHarmonyRule,
validatePalette,
autoFixPalette,
generateLight,
generateDark,
generateMuted,
HarmonyRule,
ColorValidation,
} from '../utils/color-harmony';
import { getAppConfig } from '../services/app-config.service';
type TabKey = 'shows' | 'events' | 'station' | 'theme' | 'history' | 'team' | 'community' | 'underwriters' | 'mobile-builds' | 'stats';
interface ThemeColorState {
color_primary: string;
color_primary_light: string;
color_primary_dark: string;
color_primary_muted: string;
color_accent: string;
color_accent_light: string;
color_accent_dark: string;
color_accent_muted: string;
color_background: string;
color_text: string;
color_success: string;
color_danger: string;
color_info: string;
color_white: string;
color_light: string;
color_medium: string;
color_black: string;
[key: string]: string;
}
type TabKey =
| 'shows'
| 'events'
| 'history'
| 'team'
| 'community'
| 'station'
| 'theme'
| 'underwriters'
| 'mobile-builds'
| 'stats';
@Component({
selector: 'app-admin',
standalone: true,
encapsulation: ViewEncapsulation.None,
imports: [
CommonModule,
AsyncPipe,
FormsModule,
AdminShowsTabComponent,
AdminEventsTabComponent,
AdminHistoryTabComponent,
AdminTeamTabComponent,
AdminCommunityTabComponent,
AdminStationTabComponent,
AdminThemeTabComponent,
AdminUnderwritersTabComponent,
AdminMobileBuildsTabComponent,
AdminStatsDashboardComponent,
AdminShowFormComponent,
AdminEventFormComponent,
AdminStationFormComponent,
@@ -84,109 +62,25 @@ interface ThemeColorState {
AdminTeamFormComponent,
AdminCommunityFormComponent,
AdminUnderwriterFormComponent,
AdminStatsDashboardComponent,
],
templateUrl: './admin.component.html',
styleUrl: './admin.component.scss',
})
export class AdminComponent implements OnInit {
private showService = inject(ShowService);
private eventService = inject(EventService);
private stationConfigService = inject(StationConfigService);
private themeService = inject(ThemeService);
private historyEntryService = inject(HistoryEntryService);
private teamMemberService = inject(TeamMemberService);
private communityHighlightService = inject(CommunityHighlightService);
private underwriterService = inject(UnderwriterService);
private mobileBuildService = inject(MobileBuildService);
activeTab = signal<TabKey>('shows');
/** Item currently being edited (set by editXxx, cleared on save/close). */
editingShow: Show | null = null;
editingEvent: StationEvent | null = null;
editingHistory: HistoryEntry | null = null;
editingTeam: TeamMember | null = null;
editingCommunity: CommunityHighlight | null = null;
editingUnderwriter: Underwriter | null = null;
/** Station config for the station form modal. */
stationConfig: StationConfig | null = null;
/** BehaviorSubjects guarantee change detection via the async pipe — start empty, populated on load. */
readonly shows$ = new BehaviorSubject<Show[]>([]);
readonly events$ = new BehaviorSubject<StationEvent[]>([]);
readonly stationConfig$ = new BehaviorSubject<StationConfig | null>(null);
readonly historyEntries$ = new BehaviorSubject<HistoryEntry[]>([]);
readonly teamMembers$ = new BehaviorSubject<TeamMember[]>([]);
readonly communityHighlights$ = new BehaviorSubject<CommunityHighlight[]>([]);
readonly underwriters$ = new BehaviorSubject<Underwriter[]>([]);
readonly mobileBuilds$ = new BehaviorSubject<MobileBuildRequest[]>([]);
mobileBuildDefaults: MobileBuildDefaults | null = null;
selectedMobileBuildId: number | null = null;
selectedMobileBuild: MobileBuildRequest | null = null;
mobileBuildStatusMessage = '';
mobileBuildErrorMessage = '';
mobileBuildPreflightIssues: string[] = [];
mobileBuildBusy = false;
// ── Theme JSON status (mobile build tab) ────────────────────
readonly themeJsonStatus$ = new BehaviorSubject<ThemeStatus | null>(null);
readonly themeJsonLoading$ = new BehaviorSubject<boolean>(false);
buildAndroid = true;
buildIos = true;
androidApplicationId = '';
iosBundleId = '';
buildVersionName = '1.0.0';
buildNumber = '1';
buildReleaseProfile = 'release';
androidKeystoreFile: File | null = null;
androidDescriptorFile: File | null = null;
iosCertificateFile: File | null = null;
iosProfileFile: File | null = null;
// ── Theme tab state ──────────────────────────────────────────
/** Local editable color palette (copied from StationConfig on tab open). */
themeColors: ThemeColorState = {} as ThemeColorState;
/** Current harmony rule detected from the palette. */
themeHarmonyRule: HarmonyRule = 'none';
/** Validation results per color field. */
themeValidation: { [key: string]: ColorValidation } = {};
/** Whether auto-generate variants is enabled. */
themeAutoVariants = true;
/** Saving state for theme tab. */
themeSaving = false;
themeSaveSuccess = '';
themeSaveError = '';
/** Color role definitions for the template. */
readonly colorRoles = COLOR_ROLES;
/** Default palette for reset. */
readonly themeDefaults: ThemeColorState = {
color_primary: '#1a3a5c',
color_primary_light: '#2a5a8c',
color_primary_dark: '#0e2440',
color_primary_muted: '#3a6a9c',
color_accent: '#e87a2e',
color_accent_light: '#f09a4e',
color_accent_dark: '#c85a1e',
color_accent_muted: '#f0a86a',
color_background: '#faf6f0',
color_text: '#3a3632',
color_success: '#4a9e4f',
color_danger: '#c83030',
color_info: '#3a8abf',
color_white: '#ffffff',
color_light: '#f0ebe3',
color_medium: '#8a8580',
color_black: '#1a1816',
};
ngOnInit(): void {
this.stationConfigService.load().then(() => {
this.stationConfig = this.stationConfigService.config();
});
}
// ── Form modal state ──────────────────────────────────────
showShowForm = false;
showEventForm = false;
showStationForm = false;
@@ -195,286 +89,14 @@ export class AdminComponent implements OnInit {
showCommunityForm = false;
showUnderwriterForm = false;
ngOnInit(): void {
this.loadAll();
}
async reloadShows(): Promise<void> {
const data = await firstValueFrom(this.showService.getShows());
this.shows$.next(data);
}
async reloadEvents(): Promise<void> {
const data = await firstValueFrom(this.eventService.getEvents());
this.events$.next(data);
}
async reloadStationConfig(): Promise<void> {
await this.stationConfigService.load();
this.stationConfig$.next(this.stationConfigService.config());
}
async reloadHistoryEntries(): Promise<void> {
const data = await firstValueFrom(this.historyEntryService.getHistoryEntries());
this.historyEntries$.next(data);
}
async reloadTeamMembers(): Promise<void> {
const data = await firstValueFrom(this.teamMemberService.getTeamMembers());
this.teamMembers$.next(data);
}
async reloadCommunityHighlights(): Promise<void> {
const data = await firstValueFrom(this.communityHighlightService.getCommunityHighlights());
this.communityHighlights$.next(data);
}
async reloadUnderwriters(): Promise<void> {
const data = await firstValueFrom(this.underwriterService.getUnderwriters());
this.underwriters$.next(data);
}
async loadAll(): Promise<void> {
await Promise.all([
this.reloadShows(),
this.reloadEvents(),
this.reloadStationConfig(),
this.reloadHistoryEntries(),
this.reloadTeamMembers(),
this.reloadCommunityHighlights(),
this.reloadUnderwriters(),
this.reloadMobileBuildDefaults(),
this.reloadMobileBuilds(),
]);
}
async reloadMobileBuildDefaults(): Promise<void> {
try {
this.mobileBuildDefaults = await firstValueFrom(this.mobileBuildService.getDefaults());
} catch {
this.mobileBuildDefaults = null;
}
}
async reloadMobileBuilds(): Promise<void> {
const data = await firstValueFrom(this.mobileBuildService.listRequests());
this.mobileBuilds$.next(data);
if (this.selectedMobileBuildId !== null) {
const selected = data.find((item) => item.id === this.selectedMobileBuildId) ?? null;
this.selectedMobileBuild = selected;
if (!selected) {
this.selectedMobileBuildId = null;
}
}
}
onMobileBuildSelected(buildId: number): void {
this.selectedMobileBuildId = buildId;
const selected = this.mobileBuilds$.value.find((item) => item.id === buildId) ?? null;
this.selectedMobileBuild = selected;
this.mobileBuildPreflightIssues = selected?.preflight_report
? selected.preflight_report.split('\n').filter((line) => line.trim().length > 0)
: [];
}
onFileChosen(event: Event, target: 'android-keystore' | 'android-descriptor' | 'ios-certificate' | 'ios-profile'): void {
const input = event.target as HTMLInputElement;
const file = input.files && input.files.length > 0 ? input.files[0] : null;
if (target === 'android-keystore') this.androidKeystoreFile = file;
if (target === 'android-descriptor') this.androidDescriptorFile = file;
if (target === 'ios-certificate') this.iosCertificateFile = file;
if (target === 'ios-profile') this.iosProfileFile = file;
}
private getErrorMessage(err: unknown, fallback: string): string {
if (typeof err === 'object' && err !== null) {
const maybeErr = err as { error?: { detail?: string | string[]; message?: string }; message?: string };
const detail = maybeErr.error?.detail;
if (typeof detail === 'string') return detail;
if (Array.isArray(detail)) return detail.join(' | ');
if (typeof maybeErr.error?.message === 'string') return maybeErr.error.message;
if (typeof maybeErr.message === 'string') return maybeErr.message;
}
return fallback;
}
private resetMobileBuildMessages(): void {
this.mobileBuildStatusMessage = '';
this.mobileBuildErrorMessage = '';
}
private validateBuildInputs(): string | null {
if (!this.buildAndroid && !this.buildIos) {
return 'Select at least one platform.';
}
if (this.buildAndroid && !this.androidApplicationId.trim()) {
return 'Android application ID is required.';
}
if (this.buildIos && !this.iosBundleId.trim()) {
return 'iOS bundle ID is required.';
}
if (!this.buildVersionName.trim() || !this.buildNumber.trim()) {
return 'Version name and build number are required.';
}
if (this.buildAndroid && (!this.androidKeystoreFile || !this.androidDescriptorFile)) {
return 'Android requires both keystore and descriptor files.';
}
if (this.buildIos && (!this.iosCertificateFile || !this.iosProfileFile)) {
return 'iOS requires both certificate and provisioning profile files.';
}
return null;
}
async createAndUploadMobileBuildRequest(): Promise<void> {
this.resetMobileBuildMessages();
this.mobileBuildPreflightIssues = [];
const inputError = this.validateBuildInputs();
if (inputError) {
this.mobileBuildErrorMessage = inputError;
return;
}
this.mobileBuildBusy = true;
try {
const request = await firstValueFrom(this.mobileBuildService.createRequest({
platform_android: this.buildAndroid,
platform_ios: this.buildIos,
android_application_id: this.androidApplicationId.trim() || undefined,
ios_bundle_id: this.iosBundleId.trim() || undefined,
version_name: this.buildVersionName.trim(),
build_number: this.buildNumber.trim(),
release_profile: this.buildReleaseProfile.trim() || 'release',
}));
if (this.buildAndroid && this.androidKeystoreFile && this.androidDescriptorFile) {
await firstValueFrom(this.mobileBuildService.uploadFile(request.id, 'android', 'keystore', this.androidKeystoreFile));
await firstValueFrom(this.mobileBuildService.uploadFile(request.id, 'android', 'descriptor', this.androidDescriptorFile));
}
if (this.buildIos && this.iosCertificateFile && this.iosProfileFile) {
await firstValueFrom(this.mobileBuildService.uploadFile(request.id, 'ios', 'certificate', this.iosCertificateFile));
await firstValueFrom(this.mobileBuildService.uploadFile(request.id, 'ios', 'profile', this.iosProfileFile));
}
this.mobileBuildStatusMessage = `Draft build request #${request.id} created and files uploaded.`;
await this.reloadMobileBuilds();
this.onMobileBuildSelected(request.id);
} catch (err) {
this.mobileBuildErrorMessage = this.getErrorMessage(err, 'Failed to create build request.');
} finally {
this.mobileBuildBusy = false;
}
}
async runPreflightForSelectedBuild(): Promise<void> {
if (!this.selectedMobileBuildId) return;
this.resetMobileBuildMessages();
this.mobileBuildBusy = true;
try {
const result = await firstValueFrom(this.mobileBuildService.preflight(this.selectedMobileBuildId));
this.mobileBuildPreflightIssues = result.issues;
this.mobileBuildStatusMessage = result.passed
? 'Preflight passed. Build can be triggered.'
: 'Preflight failed. Resolve the listed issues.';
await this.reloadMobileBuilds();
this.onMobileBuildSelected(this.selectedMobileBuildId);
} catch (err) {
this.mobileBuildErrorMessage = this.getErrorMessage(err, 'Preflight failed to run.');
} finally {
this.mobileBuildBusy = false;
}
}
async triggerSelectedBuild(): Promise<void> {
if (!this.selectedMobileBuildId) return;
this.resetMobileBuildMessages();
this.mobileBuildBusy = true;
try {
const request = await firstValueFrom(this.mobileBuildService.trigger(this.selectedMobileBuildId));
this.mobileBuildStatusMessage = `Build #${request.id} queued.`;
await this.reloadMobileBuilds();
this.onMobileBuildSelected(this.selectedMobileBuildId);
} catch (err) {
this.mobileBuildErrorMessage = this.getErrorMessage(err, 'Failed to trigger build.');
} finally {
this.mobileBuildBusy = false;
}
}
async refreshSelectedBuild(): Promise<void> {
if (!this.selectedMobileBuildId) return;
await this.reloadMobileBuilds();
this.onMobileBuildSelected(this.selectedMobileBuildId);
}
// ── Theme JSON status ──────────────────────────────────────
async loadThemeJsonStatus(): Promise<void> {
try {
this.themeJsonLoading$.next(true);
this.themeJsonStatus$.next(await firstValueFrom(
this.mobileBuildService.getThemeStatus(),
));
} catch {
this.themeJsonStatus$.next(null);
} finally {
this.themeJsonLoading$.next(false);
}
}
async regenerateThemeJson(): Promise<void> {
try {
this.themeJsonLoading$.next(true);
await firstValueFrom(this.mobileBuildService.regenerateTheme());
await this.loadThemeJsonStatus();
} catch (err) {
this.mobileBuildErrorMessage = this.getErrorMessage(
err,
'Failed to regenerate theme.json.',
);
} finally {
this.themeJsonLoading$.next(false);
}
}
getArtifactDownloadHref(path: string): string {
return `${getAppConfig().apiBaseUrl}${path}`;
}
formatFileSize(bytes: number): string {
if (bytes === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
const size = bytes / Math.pow(1024, i);
return `${size.toFixed(size < 10 ? 1 : 0)} ${units[i]}`;
}
downloadArtifact(artifact: MobileBuildArtifact): void {
this.mobileBuildService
.getDownloadUrl(artifact.id)
.subscribe({
next: (res) => {
// Trigger native browser download with the signed URL
window.open(res.download_url, '_blank');
},
error: (err) => {
console.error('Failed to get download URL:', err);
},
});
}
// ── Show CRUD ───────────────────────────────────────────
editingShow: Show | null = null;
editingEvent: StationEvent | null = null;
editingHistory: HistoryEntry | null = null;
editingTeam: TeamMember | null = null;
editingCommunity: CommunityHighlight | null = null;
editingUnderwriter: Underwriter | null = null;
// ── Show form ─────────────────────────────────────────────
openShowForm(): void {
this.editingShow = null;
this.showShowForm = true;
@@ -486,7 +108,6 @@ export class AdminComponent implements OnInit {
}
onShowSaved(): void {
this.reloadShows();
this.showShowForm = false;
this.editingShow = null;
}
@@ -496,14 +117,7 @@ export class AdminComponent implements OnInit {
this.editingShow = null;
}
async deleteShow(id: number): Promise<void> {
if (!confirm('Delete this show?')) return;
await firstValueFrom(this.showService.deleteShow(id));
await this.reloadShows();
}
// ── Event CRUD ──────────────────────────────────────────
// ── Event form ────────────────────────────────────────────
openEventForm(): void {
this.editingEvent = null;
this.showEventForm = true;
@@ -515,7 +129,6 @@ export class AdminComponent implements OnInit {
}
onEventSaved(): void {
this.reloadEvents();
this.showEventForm = false;
this.editingEvent = null;
}
@@ -525,20 +138,13 @@ export class AdminComponent implements OnInit {
this.editingEvent = null;
}
async deleteEvent(id: number): Promise<void> {
if (!confirm('Delete this event?')) return;
await firstValueFrom(this.eventService.deleteEvent(id));
await this.reloadEvents();
}
// ── Station Config ──────────────────────────────────────
// ── Station form ──────────────────────────────────────────
openStationForm(): void {
this.showStationForm = true;
}
onStationSaved(): void {
this.reloadStationConfig();
this.stationConfig = this.stationConfigService.config();
this.showStationForm = false;
}
@@ -546,8 +152,7 @@ export class AdminComponent implements OnInit {
this.showStationForm = false;
}
// ── History CRUD ────────────────────────────────────────
// ── History form ──────────────────────────────────────────
openHistoryForm(): void {
this.editingHistory = null;
this.showHistoryForm = true;
@@ -559,7 +164,6 @@ export class AdminComponent implements OnInit {
}
onHistorySaved(): void {
this.reloadHistoryEntries();
this.showHistoryForm = false;
this.editingHistory = null;
}
@@ -569,14 +173,7 @@ export class AdminComponent implements OnInit {
this.editingHistory = null;
}
async deleteHistory(id: number): Promise<void> {
if (!confirm('Delete this history entry?')) return;
await firstValueFrom(this.historyEntryService.deleteHistoryEntry(id));
await this.reloadHistoryEntries();
}
// ── Team CRUD ───────────────────────────────────────────
// ── Team form ─────────────────────────────────────────────
openTeamForm(): void {
this.editingTeam = null;
this.showTeamForm = true;
@@ -588,7 +185,6 @@ export class AdminComponent implements OnInit {
}
onTeamSaved(): void {
this.reloadTeamMembers();
this.showTeamForm = false;
this.editingTeam = null;
}
@@ -598,14 +194,7 @@ export class AdminComponent implements OnInit {
this.editingTeam = null;
}
async deleteTeam(id: number): Promise<void> {
if (!confirm('Delete this team member?')) return;
await firstValueFrom(this.teamMemberService.deleteTeamMember(id));
await this.reloadTeamMembers();
}
// ── Community CRUD ──────────────────────────────────────
// ── Community form ────────────────────────────────────────
openCommunityForm(): void {
this.editingCommunity = null;
this.showCommunityForm = true;
@@ -617,7 +206,6 @@ export class AdminComponent implements OnInit {
}
onCommunitySaved(): void {
this.reloadCommunityHighlights();
this.showCommunityForm = false;
this.editingCommunity = null;
}
@@ -627,14 +215,7 @@ export class AdminComponent implements OnInit {
this.editingCommunity = null;
}
async deleteCommunity(id: number): Promise<void> {
if (!confirm('Delete this community highlight?')) return;
await firstValueFrom(this.communityHighlightService.deleteCommunityHighlight(id));
await this.reloadCommunityHighlights();
}
// ── Underwriter CRUD ────────────────────────────────────
// ── Underwriter form ──────────────────────────────────────
openUnderwriterForm(): void {
this.editingUnderwriter = null;
this.showUnderwriterForm = true;
@@ -646,7 +227,6 @@ export class AdminComponent implements OnInit {
}
onUnderwriterSaved(): void {
this.reloadUnderwriters();
this.showUnderwriterForm = false;
this.editingUnderwriter = null;
}
@@ -655,120 +235,4 @@ export class AdminComponent implements OnInit {
this.showUnderwriterForm = false;
this.editingUnderwriter = null;
}
async deleteUnderwriter(id: number): Promise<void> {
if (!confirm('Delete this underwriter?')) return;
await firstValueFrom(this.underwriterService.deleteUnderwriter(id));
await this.reloadUnderwriters();
}
// ── Theme tab ────────────────────────────────────────────
onTabChanged(): void {
if (this.activeTab() === 'theme') {
this.loadThemeColors();
}
}
loadThemeColors(): void {
const config = this.stationConfigService.config();
this.themeColors = {
color_primary: config.color_primary || this.themeDefaults.color_primary,
color_primary_light: config.color_primary_light || this.themeDefaults.color_primary_light,
color_primary_dark: config.color_primary_dark || this.themeDefaults.color_primary_dark,
color_primary_muted: config.color_primary_muted || this.themeDefaults.color_primary_muted,
color_accent: config.color_accent || this.themeDefaults.color_accent,
color_accent_light: config.color_accent_light || this.themeDefaults.color_accent_light,
color_accent_dark: config.color_accent_dark || this.themeDefaults.color_accent_dark,
color_accent_muted: config.color_accent_muted || this.themeDefaults.color_accent_muted,
color_background: config.color_background || this.themeDefaults.color_background,
color_text: config.color_text || this.themeDefaults.color_text,
color_success: config.color_success || this.themeDefaults.color_success,
color_danger: config.color_danger || this.themeDefaults.color_danger,
color_info: config.color_info || this.themeDefaults.color_info,
color_white: config.color_white || this.themeDefaults.color_white,
color_light: config.color_light || this.themeDefaults.color_light,
color_medium: config.color_medium || this.themeDefaults.color_medium,
color_black: config.color_black || this.themeDefaults.color_black,
};
this.themeSaveSuccess = '';
this.themeSaveError = '';
this.revalidateTheme();
}
/** Re-run harmony detection + validation on the current palette. */
revalidateTheme(): void {
const primary = this.themeColors.color_primary;
const accent = this.themeColors.color_accent;
this.themeHarmonyRule = detectHarmonyRule(primary, accent);
this.themeValidation = validatePalette(this.themeColors, this.themeHarmonyRule);
}
/** Handle color change from the picker. */
onThemeColorChange(field: string, value: string): void {
this.themeColors[field] = value;
// Auto-generate variants for primary/accent bases
if (this.themeAutoVariants) {
if (field === 'color_primary') {
this.themeColors.color_primary_light = generateLight(value);
this.themeColors.color_primary_dark = generateDark(value);
this.themeColors.color_primary_muted = generateMuted(value);
} else if (field === 'color_accent') {
this.themeColors.color_accent_light = generateLight(value);
this.themeColors.color_accent_dark = generateDark(value);
this.themeColors.color_accent_muted = generateMuted(value);
}
}
// Live-apply to DOM for instant preview
this.themeService.apply(this.themeColors as any);
this.revalidateTheme();
}
/** Auto-fix all non-harmonious colors. */
autoFixTheme(): void {
const fixed = autoFixPalette(this.themeColors, this.themeHarmonyRule);
for (const key of Object.keys(fixed) as (keyof ThemeColorState)[]) {
(this.themeColors as any)[key] = fixed[key];
}
this.themeService.apply(this.themeColors as any);
this.revalidateTheme();
}
/** Reset to default palette. */
resetTheme(): void {
for (const key of Object.keys(this.themeDefaults) as (keyof ThemeColorState)[]) {
(this.themeColors as any)[key] = this.themeDefaults[key];
}
this.themeService.apply(this.themeColors as any);
this.revalidateTheme();
}
/** Save theme colors to the database. */
async saveTheme(): Promise<void> {
this.themeSaving = true;
this.themeSaveError = '';
this.themeSaveSuccess = '';
try {
await this.stationConfigService.updateConfig(this.themeColors);
this.themeSaveSuccess = 'Theme saved successfully!';
} catch (err: any) {
this.themeSaveError = err?.error?.detail || 'Failed to save theme.';
} finally {
this.themeSaving = false;
}
}
/** Get harmony rule label for display. */
getHarmonyLabel(): string {
return HARMONY_RULE_LABELS[this.themeHarmonyRule];
}
/** Check if a color field has a harmony issue. */
hasHarmonyIssue(field: string): boolean {
const v = this.themeValidation[field];
return v ? !v.isHarmonious : false;
}
}