diff --git a/apps/backend/src/features/overlays/assets/overlay-assets.service.ts b/apps/backend/src/features/overlays/assets/overlay-assets.service.ts index 3c6c0c1..bdeca0b 100644 --- a/apps/backend/src/features/overlays/assets/overlay-assets.service.ts +++ b/apps/backend/src/features/overlays/assets/overlay-assets.service.ts @@ -214,7 +214,7 @@ export class OverlayAssetsService implements OnModuleInit, OnModuleDestroy { } if (!overlay || !asset) throw new NotFoundException("Medium nicht gefunden.") const isReferenced = overlay.widgets.some( - (widget) => widget.type === asset.kind && (widget.params as {assetId?: string} | null)?.assetId === asset.id + (widget) => widget.type === "MEDIA" && (widget.params as {assetId?: string} | null)?.assetId === asset.id ) if (!isReferenced) throw new NotFoundException("Medium nicht gefunden.") const hasValidSignature = timingSafeEqual( diff --git a/apps/backend/src/features/overlays/services/overlay.service.ts b/apps/backend/src/features/overlays/services/overlay.service.ts index 63dab82..9973533 100644 --- a/apps/backend/src/features/overlays/services/overlay.service.ts +++ b/apps/backend/src/features/overlays/services/overlay.service.ts @@ -11,21 +11,19 @@ import {BotLoggerService, errorDetails, frontendUrl, TokenEncryptionService, typ import { overlayPreset, OVERLAY_THEME_COLORS, - isWidgetDesignId, OVERLAY_WIDTH, OVERLAY_HEIGHT, - TWITCH_CHAT_DEFAULTS, + WIDGET_SPECS, + isWidgetType, + normalizeAppearance, twitchChatUrl, - type SpotifyWidgetParams, - type ChatWidgetParams, - type WindowWidgetParams, - type MediaWidgetParams, type GuildOverlay, type OverlayChat, type OverlayLink, type OverlaySnapshot, type OverlayTheme, type OverlayScene, + type OverlayLayout, type EditorWidget } from "@streamcat/interfaces" import {overlayGuides, validateOverlayLayout} from "../settings/overlay-layout" @@ -48,12 +46,14 @@ function sceneName(value: unknown): string { return value.trim() } -function storedDesignColors(value: unknown): Record<`--${string}`, string> | undefined { +function storedThemeColors(value: unknown): OverlayLayout["themeColors"] { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined - const entries = Object.entries(value) - if (!entries.length || entries.length > 20) return undefined - if (entries.some(([key, color]) => !/^--[a-z0-9-]{1,60}$/.test(key) || typeof color !== "string")) return undefined - return Object.fromEntries(entries) as Record<`--${string}`, string> + const data = value as Record + const colors: NonNullable = {} + for (const key of ["primary", "secondary", "surface", "window", "text"] as const) { + if (typeof data[key] === "string") colors[key] = data[key] + } + return Object.keys(colors).length ? colors : undefined } @Injectable() @@ -104,8 +104,10 @@ export class OverlayService { const scene = data.scene === undefined ? "intermission" : data.scene if (!["intermission", "starting_soon", "stream_ending", "widgets"].includes(scene as string)) throw new BadRequestException("Unbekannte Overlay-Szene.") + const theme = data.theme === undefined ? "default" : data.theme + if (!Object.hasOwn(OVERLAY_THEME_COLORS, theme as string)) throw new BadRequestException("Unbekanntes Theme.") const token = randomBytes(32).toString("base64url") - const layout = overlayPreset(scene as OverlayScene, [randomUUID(), randomUUID()]) + const layout = overlayPreset(scene as OverlayScene, [randomUUID(), randomUUID()], theme as OverlayTheme) const browserToken = await this.tokenEncryption.encrypt(token) const overlay = await this.repository.createScene(guildId, name, hashToken(token), layout, browserToken) if (!overlay) throw new ConflictException("Maximal 20 Szenen pro Server sind erlaubt.") @@ -119,7 +121,7 @@ export class OverlayService { const saved = await this.repository.saveLayout(guildId, overlayId, layout) if (!saved) throw new BadRequestException( - "Das gewählte Medium gehört nicht zu diesem Server, wurde gelöscht oder hat den falschen Typ." + "Das gewählte Medium gehört nicht zu diesem Server oder wurde gelöscht." ) this.logger.info( `Overlay scene layout saved guild=${guildId} overlay=${overlayId} widgets=${saved.widgets.length}` @@ -188,13 +190,6 @@ export class OverlayService { const scene = ["intermission", "starting_soon", "stream_ending"].includes(settings?.scene as string) ? (settings!.scene as OverlayScene) : "widgets" - const socialSettings = - settings?.socials && typeof settings.socials === "object" && !Array.isArray(settings.socials) - ? (settings.socials as Record) - : {} - const socials: {twitch?: string; twitter?: string; discord?: string} = {} - for (const key of ["twitch", "twitter", "discord"] as const) - if (typeof socialSettings[key] === "string") socials[key] = socialSettings[key].slice(0, 100) return { id: overlay.id, guildId: overlay.guildId, @@ -203,86 +198,36 @@ export class OverlayService { width: OVERLAY_WIDTH, height: OVERLAY_HEIGHT, theme, + themeColors: storedThemeColors(settings?.themeColors), scene, font: settings?.font === "jersey10" ? "jersey10" : "tiny5", - socials, guides: overlayGuides(settings?.guides), - widgets: overlay.widgets.map((widget) => this.toEditorWidget(widget, theme)) + widgets: overlay.widgets + .map((widget) => this.toEditorWidget(widget)) + .filter((widget): widget is EditorWidget => widget !== null) } } } - private toEditorWidget(widget: OverlayWidgetRecord, theme: OverlayTheme): EditorWidget { + private toEditorWidget(widget: OverlayWidgetRecord): EditorWidget | null { + if (!isWidgetType(widget.type)) { + this.logger.warn(`Skipping unknown overlay widget type=${widget.type} overlay=${widget.overlayId}`) + return null + } const geometry = { id: widget.id, x: widget.x, y: widget.y, width: widget.width, height: widget.height, - zIndex: widget.zIndex + zIndex: widget.zIndex, + label: widget.label ?? undefined, + hidden: widget.hidden ? true : undefined } const storedParams = widget.params as Record | null - const design = - typeof storedParams?.design === "string" && isWidgetDesignId(storedParams.design) - ? storedParams.design - : theme - const designColors = storedDesignColors(storedParams?.designColors) - const appearance = { - design, - color: typeof storedParams?.color === "string" ? storedParams.color : "#ffffff", - backgroundColor: - typeof storedParams?.backgroundColor === "string" ? storedParams.backgroundColor : "#18181b", - ...(designColors ? {designColors} : {}) - } - switch (widget.type) { - case "WINDOW": { - const params = storedParams as Partial | null - return { - ...geometry, - type: "WINDOW", - params: { - ...appearance, - title: params?.title ?? "Fenster", - lockContentAspectRatio: params?.lockContentAspectRatio === true, - greenScreen: params?.greenScreen === true - } - } - } - case "SPOTIFY_NOW_PLAYING": { - const params = storedParams as Partial | null - return { - ...geometry, - type: "SPOTIFY_NOW_PLAYING", - params: { - ...appearance, - spectralizer: params?.spectralizer === true, - spectrumMode: params?.spectrumMode === "simulated" ? "simulated" : "audio", - audioDeviceName: params?.audioDeviceName ?? "" - } - } - } - case "TWITCH_CHAT": { - const params = storedParams as Partial | null - return { - ...geometry, - type: "TWITCH_CHAT", - params: {...TWITCH_CHAT_DEFAULTS, ...params, ...appearance} - } - } - case "IMAGE": - case "VIDEO": { - const params = storedParams as Partial | null - return { - ...geometry, - type: widget.type, - params: { - ...appearance, - assetId: params?.assetId ?? "", - fit: params?.fit === "cover" ? "cover" : "contain" - } - } - } - } + const appearance = normalizeAppearance(storedParams, "default") + const params = WIDGET_SPECS[widget.type].normalize(storedParams, appearance) + return {...geometry, type: widget.type, params} as EditorWidget } private browserSourceUrl(token: string): string { diff --git a/apps/backend/src/features/overlays/settings/overlay-layout.ts b/apps/backend/src/features/overlays/settings/overlay-layout.ts index 1cefe01..f869946 100644 --- a/apps/backend/src/features/overlays/settings/overlay-layout.ts +++ b/apps/backend/src/features/overlays/settings/overlay-layout.ts @@ -1,23 +1,21 @@ import {BadRequestException} from "@nestjs/common" import { + WIDGET_SPECS, OVERLAY_THEME_COLORS, - isWidgetDesignId, - TWITCH_CHAT_DEFAULTS, - TWITCH_CHAT_FONTS, - MAX_OVERLAY_WIDGETS, MAX_OVERLAY_GUIDES, - OVERLAY_WIDTH, - OVERLAY_HEIGHT, - MIN_WIDGET_WIDTH, + MAX_OVERLAY_WIDGETS, MIN_WIDGET_HEIGHT, - windowHeight, + MIN_WIDGET_WIDTH, + OVERLAY_HEIGHT, + OVERLAY_WIDTH, + WidgetParamError, + isWidgetType, + parseAppearance, type EditorWidget, - type ChatWidgetParams, + type OverlayFont, type OverlayLayout, - type OverlayTheme, type OverlayScene, - type OverlayFont, - type WidgetDesignId + type OverlayTheme } from "@streamcat/interfaces" function object(value: unknown): Record { @@ -26,7 +24,6 @@ function object(value: unknown): Record { return value as Record } -// Fractional 16:9 sizes can exceed a scene edge by a rounding error. const GEOMETRY_ROUNDING_TOLERANCE = 1e-9 function readGeometryValue(value: unknown, min: number, max: number): number { @@ -49,19 +46,6 @@ function color(value: unknown): string { return value } -function designColors(value: unknown): Record<`--${string}`, string> | undefined { - if (value === undefined) return undefined - const data = object(value) - const entries = Object.entries(data) - if (entries.length > 20) throw new BadRequestException("Zu viele Design-Farben.") - const colors: Record = {} - for (const [key, entry] of entries) { - if (!/^--[a-z0-9-]{1,60}$/.test(key)) throw new BadRequestException("Ungültiger Design-Farbname.") - colors[key] = color(entry) - } - return Object.keys(colors).length ? (colors as Record<`--${string}`, string>) : undefined -} - function themeColors(value: unknown): OverlayLayout["themeColors"] { if (value === undefined) return undefined const data = object(value) @@ -74,12 +58,6 @@ function themeColors(value: unknown): OverlayLayout["themeColors"] { return Object.keys(colors).length ? colors : undefined } -function widgetDesign(value: unknown, fallback: WidgetDesignId): WidgetDesignId { - if (value === undefined) return fallback - if (isWidgetDesignId(value)) return value - throw new BadRequestException("Ungültiges Widget-Design.") -} - export function overlayGuides(input: unknown): NonNullable { const data = input === undefined ? {} : object(input) const guides: NonNullable = {vertical: [], horizontal: []} @@ -102,50 +80,6 @@ export function overlayGuides(input: unknown): NonNullable= 0 && value < TWITCH_CHAT_FONTS.length) - return value - if (typeof value === "string") { - const name = value.trim() - if (!name) return TWITCH_CHAT_DEFAULTS.chatFont - if (name.length <= 100 && /^[a-z0-9][a-z0-9 -]*$/i.test(name) && /[a-z]/i.test(name)) return name - } - throw new BadRequestException("Ungültige Chat-Schrift. Gib einen Schriftnamen ein, z. B. Tiny5.") -} - -function chatSettings(params: Record): Partial { - const channel = params.chatChannel ?? "" - if (typeof channel !== "string" || (channel.trim() && !/^[a-zA-Z0-9_]{1,25}$/.test(channel.trim()))) - throw new BadRequestException("Ungültiger Twitch-Kanal.") - const settings = { - ...TWITCH_CHAT_DEFAULTS, - title: "Stream Chat", - chatChannel: channel.trim(), - chatFont: chatFont(params.chatFont ?? TWITCH_CHAT_DEFAULTS.chatFont) - } - for (const [key, max] of [ - ["chatSize", 3], - ["chatFade", 3600] - ] as const) { - if (params[key] === undefined) continue - const value = params[key] - if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > max) - throw new BadRequestException("Ungültige Chat-Einstellung.") - settings[key] = value - } - for (const key of ["chatAnimate", "chatBots", "chatHideCommands", "chatHideBadges"] as const) { - if (params[key] === undefined) continue - if (typeof params[key] !== "boolean") throw new BadRequestException("Ungültige Chat-Einstellung.") - settings[key] = params[key] - } - if (params.title !== undefined) { - if (typeof params.title !== "string" || params.title.length > 80) - throw new BadRequestException("Der Fenstertitel darf maximal 80 Zeichen enthalten.") - settings.title = params.title.trim() || "Stream Chat" - } - return settings -} - export function validateOverlayLayout(input: unknown): OverlayLayout { const data = object(input) if ( @@ -161,14 +95,6 @@ export function validateOverlayLayout(input: unknown): OverlayLayout { throw new BadRequestException("Unbekannte Overlay-Szene.") const font = data.font ?? "tiny5" if (font !== "tiny5" && font !== "jersey10") throw new BadRequestException("Unbekannte Overlay-Schrift.") - const socialInput = data.socials === undefined ? {} : object(data.socials) - const socials: NonNullable = {} - for (const key of ["twitch", "twitter", "discord"] as const) { - if (socialInput[key] === undefined) continue - if (typeof socialInput[key] !== "string" || socialInput[key].length > 100) - throw new BadRequestException("Social-Handles dürfen maximal 100 Zeichen enthalten.") - socials[key] = socialInput[key].trim() - } if (!Array.isArray(data.widgets) || data.widgets.length > MAX_OVERLAY_WIDGETS) throw new BadRequestException(`Maximal ${MAX_OVERLAY_WIDGETS} Widgets sind erlaubt.`) const ids = new Set() @@ -177,8 +103,7 @@ export function validateOverlayLayout(input: unknown): OverlayLayout { if (typeof widget.id !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(widget.id) || ids.has(widget.id)) throw new BadRequestException("Jedes Widget benötigt eine eindeutige ID.") ids.add(widget.id) - if (!["SPOTIFY_NOW_PLAYING", "TWITCH_CHAT", "IMAGE", "VIDEO", "WINDOW"].includes(widget.type as string)) - throw new BadRequestException("Unbekannter Widget-Typ.") + if (!isWidgetType(widget.type)) throw new BadRequestException("Unbekannter Widget-Typ.") const x = readGeometryValue(widget.x, 0, OVERLAY_WIDTH - MIN_WIDGET_WIDTH) const y = readGeometryValue(widget.y, 0, OVERLAY_HEIGHT - MIN_WIDGET_HEIGHT) const width = readGeometryValue(widget.width, MIN_WIDGET_WIDTH, OVERLAY_WIDTH - x) @@ -187,82 +112,17 @@ export function validateOverlayLayout(input: unknown): OverlayLayout { if (typeof zIndex !== "number" || !Number.isInteger(zIndex) || zIndex < 0 || zIndex > 1000) throw new BadRequestException("Die Widget-Reihenfolge muss eine ganze Zahl zwischen 0 und 1000 sein.") const params = object(widget.params) - if (params.spectralizer !== undefined && typeof params.spectralizer !== "boolean") - throw new BadRequestException("Ungültige Spektrum-Einstellung.") - if ( - params.audioDeviceName !== undefined && - (typeof params.audioDeviceName !== "string" || params.audioDeviceName.length > 200) - ) - throw new BadRequestException("Ungültiger Audioeingang.") const label = typeof widget.label === "string" && widget.label.trim() ? widget.label.trim().slice(0, 80) : undefined const hidden = widget.hidden === true ? true : undefined const geometry = {id: widget.id, x, y, width, height, zIndex, label, hidden} - const colors = designColors(params.designColors) - const appearance = { - design: widgetDesign(params.design, theme), - color: color(params.color), - backgroundColor: color(params.backgroundColor), - ...(colors ? {designColors: colors} : {}) - } - switch (widget.type) { - case "WINDOW": - if (params.title !== undefined && (typeof params.title !== "string" || params.title.length > 80)) - throw new BadRequestException("Der Fenstertitel darf maximal 80 Zeichen enthalten.") - if (params.lockContentAspectRatio !== undefined && typeof params.lockContentAspectRatio !== "boolean") - throw new BadRequestException("Ungültige 16:9-Einstellung.") - if (params.greenScreen !== undefined && typeof params.greenScreen !== "boolean") - throw new BadRequestException("Ungültige Greenscreen-Einstellung.") - if (params.lockContentAspectRatio === true && Math.abs(height - windowHeight(width)) > 0.01) - throw new BadRequestException( - "Die gesperrte Content-Fläche muss 16:9 sein; der Header zählt nicht dazu." - ) - return { - ...geometry, - type: "WINDOW", - params: { - ...appearance, - title: (params.title ?? "Fenster") as string, - lockContentAspectRatio: params.lockContentAspectRatio === true, - greenScreen: params.greenScreen === true - } - } - case "SPOTIFY_NOW_PLAYING": - if ( - params.spectrumMode !== undefined && - params.spectrumMode !== "audio" && - params.spectrumMode !== "simulated" - ) - throw new BadRequestException("Unbekannter Spektrum-Modus.") - return { - ...geometry, - type: "SPOTIFY_NOW_PLAYING", - params: { - ...appearance, - spectralizer: params.spectralizer === true, - spectrumMode: (params.spectrumMode ?? "audio") as "audio" | "simulated", - audioDeviceName: (params.audioDeviceName as string | undefined) ?? "" - } - } - case "TWITCH_CHAT": - return {...geometry, type: "TWITCH_CHAT", params: {...appearance, ...chatSettings(params)}} - case "IMAGE": - case "VIDEO": - if (typeof params.assetId !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(params.assetId)) - throw new BadRequestException("Wähle ein hochgeladenes Medium für dieses Widget.") - if (params.fit !== undefined && params.fit !== "contain" && params.fit !== "cover") - throw new BadRequestException("Ungültige Medien-Skalierung.") - return { - ...geometry, - type: widget.type, - params: { - ...appearance, - assetId: params.assetId as string, - fit: (params.fit ?? "contain") as "contain" | "cover" - } - } - default: - throw new BadRequestException("Unbekannter Widget-Typ.") + try { + const appearance = parseAppearance(params, "default") + const parsed = WIDGET_SPECS[widget.type].parse(params, {appearance, width, height}) + return {...geometry, type: widget.type, params: parsed} as EditorWidget + } catch (error) { + if (error instanceof WidgetParamError) throw new BadRequestException(error.message) + throw error } }) return { @@ -272,7 +132,6 @@ export function validateOverlayLayout(input: unknown): OverlayLayout { themeColors: themeColors(data.themeColors), scene: scene as OverlayScene, font: font as OverlayFont, - socials, guides: overlayGuides(data.guides), widgets } diff --git a/apps/backend/tests/overlay-assets-security.test.ts b/apps/backend/tests/overlay-assets-security.test.ts index e9bd593..658b8d7 100644 --- a/apps/backend/tests/overlay-assets-security.test.ts +++ b/apps/backend/tests/overlay-assets-security.test.ts @@ -19,7 +19,7 @@ const overlay = { id: "scene-audit", guildId: asset.guildId, tokenHash: "ab".repeat(32), - widgets: [{type: "IMAGE", params: {assetId: asset.id}}] + widgets: [{type: "MEDIA", params: {assetId: asset.id}}] } const previousSecret = process.env.AUTH_SECRET beforeEach(() => { diff --git a/apps/backend/tests/overlay-design-colors.test.ts b/apps/backend/tests/overlay-design-colors.test.ts index 5467258..cab5c61 100644 --- a/apps/backend/tests/overlay-design-colors.test.ts +++ b/apps/backend/tests/overlay-design-colors.test.ts @@ -9,11 +9,8 @@ const overlay = { name: "Scene", tokenHash: "a".repeat(64), browserToken: "encrypted-token", - type: "STATIC" as const, backgroundAssetId: null, - settings: {theme: "default", font: "tiny5"}, - customHtml: null, - customCss: null, + settings: {theme: "default", font: "tiny5", themeColors: {primary: "#123456"}}, updatedAt: date, widgets: [ { @@ -25,6 +22,8 @@ const overlay = { width: 640, height: 300, zIndex: 1, + label: "Spotify", + hidden: true, params: { design: "default", color: "#ffffff", @@ -53,6 +52,9 @@ const service = new OverlayService( test("stored design color overrides survive the dashboard mapping", async () => { const [scene] = await service.scenes("guild") expect(scene?.layout.widgets[0]?.params.designColors).toEqual({"--progress-color": "#ff0000"}) + expect(scene?.layout.themeColors).toEqual({primary: "#123456"}) + expect(scene?.layout.widgets[0]?.label).toBe("Spotify") + expect(scene?.layout.widgets[0]?.hidden).toBe(true) }) test("stored browser tokens are returned as scene links", async () => { diff --git a/apps/backend/tests/overlay-widget-specs.test.ts b/apps/backend/tests/overlay-widget-specs.test.ts new file mode 100644 index 0000000..f039033 --- /dev/null +++ b/apps/backend/tests/overlay-widget-specs.test.ts @@ -0,0 +1,57 @@ +import "reflect-metadata" +import {expect, test} from "bun:test" +import {OVERLAY_HEIGHT, OVERLAY_WIDTH, WIDGET_SPECS, type EditorWidget, type WidgetType} from "@streamcat/interfaces" +import {validateOverlayLayout} from "../src/features/overlays/settings/overlay-layout" + +const appearance = {design: "default", color: "#ffffff", backgroundColor: "transparent"} + +function widget(type: WidgetType, index: number): EditorWidget { + const spec = WIDGET_SPECS[type] + const params = spec.defaults(appearance) + if (type === "MEDIA") params.assetId = "asset-1" + return { + id: `widget-${index}`, + type, + x: 0, + y: 0, + width: spec.width, + height: type === "WINDOW" ? 300 : spec.height, + zIndex: index, + params + } as EditorWidget +} + +test("every widget spec validates through the layout parser", () => { + const types = Object.keys(WIDGET_SPECS) as WidgetType[] + const layout = validateOverlayLayout({ + width: OVERLAY_WIDTH, + height: OVERLAY_HEIGHT, + theme: "default", + scene: "widgets", + font: "tiny5", + widgets: types.map(widget) + }) + expect(layout.widgets).toHaveLength(types.length) + expect(layout.widgets.map((item) => item.type)).toEqual(types) +}) + +test("scene widget specs reject invalid values", () => { + const base = widget("TEXT", 0) + expect(() => + validateOverlayLayout({ + width: OVERLAY_WIDTH, + height: OVERLAY_HEIGHT, + theme: "default", + widgets: [{...base, params: {...base.params, fontSize: 1000}}] + }) + ).toThrow("Ungültige Text-Einstellung.") + const clock = widget("CLOCK", 1) + expect(() => + validateOverlayLayout({ + width: OVERLAY_WIDTH, + height: OVERLAY_HEIGHT, + theme: "default", + widgets: [{...clock, params: {...clock.params, timeZone: "Not/AZone"}}] + }) + ).toThrow("Ungültige Zeitzone.") +}) diff --git a/apps/demo/src/mock/seed.ts b/apps/demo/src/mock/seed.ts index 4fb3e9b..cbd5eae 100644 --- a/apps/demo/src/mock/seed.ts +++ b/apps/demo/src/mock/seed.ts @@ -32,8 +32,18 @@ const SEEDS: Seed[] = [ function tuneLayout(layout: OverlayLayout): OverlayLayout { return { ...layout, - socials: {twitch: "streamcatdemo", twitter: "streamcatdemo", discord: "streamcatdemo"}, widgets: layout.widgets.map((widget) => { + if (widget.type === "SOCIALS") { + return { + ...widget, + params: { + ...widget.params, + twitch: "streamcatdemo", + twitter: "streamcatdemo", + discord: "streamcatdemo" + } + } + } if (widget.type === "SPOTIFY_NOW_PLAYING") { return { ...widget, diff --git a/apps/demo/src/mock/storage.ts b/apps/demo/src/mock/storage.ts index 27d57aa..aa6c69d 100644 --- a/apps/demo/src/mock/storage.ts +++ b/apps/demo/src/mock/storage.ts @@ -1,7 +1,8 @@ -import type {GuildOverlay} from "@streamcat/interfaces" +import type {GuildOverlay, OverlayAsset} from "@streamcat/interfaces" import {seedScenes} from "./seed" -const STORAGE_KEY = "streamcat-demo-scenes-v1" +const STORAGE_KEY = "streamcat-demo-scenes-v2" +const ASSETS_KEY = "streamcat-demo-assets-v2" export function loadScenes(): GuildOverlay[] { try { @@ -23,9 +24,29 @@ export function persistScenes(scenes: GuildOverlay[]): void { } } +export function loadAssets(): OverlayAsset[] { + try { + const stored = localStorage.getItem(ASSETS_KEY) + if (!stored) return [] + const parsed = JSON.parse(stored) as unknown + return Array.isArray(parsed) ? (parsed as OverlayAsset[]) : [] + } catch { + return [] + } +} + +export function persistAssets(assets: OverlayAsset[]): void { + try { + localStorage.setItem(ASSETS_KEY, JSON.stringify(assets)) + } catch { + console.warn("[Demo] Demo-Assets konnten nicht im Browser gespeichert werden.") + } +} + export function clearDemoScenes(): void { try { localStorage.removeItem(STORAGE_KEY) + localStorage.removeItem(ASSETS_KEY) } catch { // Storage can be unavailable in private mode. } diff --git a/apps/demo/src/mock/transport.ts b/apps/demo/src/mock/transport.ts index 481a9fd..445bab2 100644 --- a/apps/demo/src/mock/transport.ts +++ b/apps/demo/src/mock/transport.ts @@ -1,11 +1,18 @@ -import type {GuildOverlay, OverlayAsset, OverlayChat, OverlayLayout, OverlayScene} from "@streamcat/interfaces" +import type { + GuildOverlay, + OverlayAsset, + OverlayChat, + OverlayLayout, + OverlayScene, + OverlayTheme +} from "@streamcat/interfaces" import type {OverlayRequest} from "@streamcat/overlay-engine" import {DEMO_ASSETS, DEMO_BASE_PATH, createDemoOverlay, demoPlayback} from "./seed" -import {loadScenes, persistScenes} from "./storage" +import {loadAssets, loadScenes, persistAssets, persistScenes} from "./storage" const LATENCY_MS = 120 let scenes = loadScenes() -let sessionAssets: OverlayAsset[] = [] +let sessionAssets: OverlayAsset[] = loadAssets() function clone(value: T): T { return JSON.parse(JSON.stringify(value)) as T @@ -35,7 +42,16 @@ function chatPreview(): OverlayChat { return {channel: "streamcatdemo", url: null, previewUrl} } -function assetUpload(body: BodyInit | null | undefined): OverlayAsset { +function readFile(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader() + reader.onload = () => resolve(String(reader.result)) + reader.onerror = () => reject(new Error("Demo-Upload konnte die Datei nicht lesen.")) + reader.readAsDataURL(file) + }) +} + +async function assetUpload(body: BodyInit | null | undefined): Promise { if (!(body instanceof File)) throw new Error("Demo-Upload konnte die Datei nicht lesen.") if (!body.type.startsWith("image/") && !body.type.startsWith("video/")) { throw new Error("Die Demo unterstützt nur Bilder und Videos.") @@ -46,9 +62,10 @@ function assetUpload(body: BodyInit | null | undefined): OverlayAsset { fileName: body.name, mimeType: body.type, sizeBytes: body.size, - url: URL.createObjectURL(body) + url: await readFile(body) } sessionAssets = [asset, ...sessionAssets] + persistAssets(sessionAssets) return asset } @@ -82,10 +99,14 @@ export const demoRequest: OverlayRequest = async (path: string, options: Requ } if (method === "POST" && parts.length === 1 && parts[0] === "scenes") { - const body = jsonBody<{name?: unknown; scene?: unknown}>(options.body) + const body = jsonBody<{name?: unknown; scene?: unknown; theme?: unknown}>(options.body) if (typeof body.name !== "string" || !body.name.trim()) throw new Error("Bitte gib der Szene einen Namen.") const scene = body.scene as OverlayScene - const overlay = createDemoOverlay(scene, body.name.trim(), `demo-${crypto.randomUUID()}`) + const theme = + body.theme === "autumn" || body.theme === "winter" || body.theme === "default" + ? (body.theme as OverlayTheme) + : "default" + const overlay = createDemoOverlay(scene, body.name.trim(), `demo-${crypto.randomUUID()}`, theme) persist([...scenes, overlay]) return clone({overlay, browserSourceUrl: ""}) as T } @@ -122,7 +143,7 @@ export const demoRequest: OverlayRequest = async (path: string, options: Requ } if (method === "POST" && parts.length === 1 && parts[0] === "assets") { - return clone(assetUpload(options.body)) as T + return clone(await assetUpload(options.body)) as T } if (method === "DELETE" && parts.length === 2 && parts[0] === "assets") { @@ -130,6 +151,7 @@ export const demoRequest: OverlayRequest = async (path: string, options: Requ if (!sessionAssets.some((asset) => asset.id === id)) throw new Error("Demo-Assets bleiben erhalten. Lade eigene Dateien hoch, um sie zu löschen.") sessionAssets = sessionAssets.filter((asset) => asset.id !== id) + persistAssets(sessionAssets) return {success: true} as T } diff --git a/apps/web/tests/overlay-engine.test.tsx b/apps/web/tests/overlay-engine.test.tsx index 7508e35..7b6ec4a 100644 --- a/apps/web/tests/overlay-engine.test.tsx +++ b/apps/web/tests/overlay-engine.test.tsx @@ -7,7 +7,20 @@ import { OverlayRenderer, type OverlayRequest } from "@streamcat/overlay-engine" -import {OVERLAY_HEIGHT, OVERLAY_WIDTH, type EditorWidget, type OverlayLayout} from "@streamcat/interfaces" +import {WIDGET_MODULES} from "../../../packages/ui/overlay-engine/src/widgets/registry" +import { + formatClockDate, + formatClockTime +} from "../../../packages/ui/overlay-engine/src/widgets/clock/logic/clock-format" +import { + OVERLAY_HEIGHT, + OVERLAY_WIDTH, + overlayPreset, + type ClockWidgetParams, + type EditorWidget, + type OverlayLayout, + type OverlayScene +} from "@streamcat/interfaces" const layout: OverlayLayout = { width: OVERLAY_WIDTH, @@ -79,7 +92,7 @@ const windowWidget: EditorWidget = { const windowLayout: OverlayLayout = {...layout, widgets: [windowWidget]} const mediaWidget: EditorWidget = { id: "media", - type: "IMAGE", + type: "MEDIA", x: 0, y: 0, width: 480, @@ -88,6 +101,156 @@ const mediaWidget: EditorWidget = { params: {design: "default", color: "#ffffff", backgroundColor: "#000000", assetId: "missing"} } const mediaLayout: OverlayLayout = {...layout, widgets: [mediaWidget]} +const sceneWidgets: EditorWidget[] = [ + { + id: "background", + type: "BACKGROUND", + x: 0, + y: 0, + width: OVERLAY_WIDTH, + height: OVERLAY_HEIGHT, + zIndex: 0, + params: { + design: "animated", + color: "#ffffff", + backgroundColor: "transparent", + speedSeconds: 15, + blur: 0, + dim: 0 + } + }, + { + id: "text", + type: "TEXT", + x: 96, + y: 54, + width: 1100, + height: 180, + zIndex: 1, + params: { + design: "headline", + color: "#ffffff", + backgroundColor: "transparent", + text: "STARTING SOON", + fontSize: 134.4, + fontWeight: "bold", + align: "left", + animation: "bounce", + animationSeconds: 1.4, + letterSpacing: 0 + } + }, + { + id: "clock", + type: "CLOCK", + x: 1600, + y: 1026, + width: 300, + height: 54, + zIndex: 2, + params: { + design: "stacked", + color: "#ffffff", + backgroundColor: "transparent", + timeZone: "", + dateStyle: "dmy-dot", + hour12: false, + showSeconds: false, + showDate: true + } + }, + { + id: "socials", + type: "SOCIALS", + x: 20, + y: 1026, + width: 700, + height: 54, + zIndex: 2, + params: { + design: "inline", + color: "#ffffff", + backgroundColor: "transparent", + twitch: "demo", + twitter: "@demo", + discord: "demo", + direction: "row", + showLabels: true, + showIcons: true + } + }, + { + id: "shape", + type: "SHAPE", + x: 0, + y: 1026, + width: OVERLAY_WIDTH, + height: 54, + zIndex: 1, + params: { + design: "rect", + color: "#ffffff", + backgroundColor: "transparent", + radius: 0, + opacity: 1 + } + }, + { + id: "countdown", + type: "COUNTDOWN", + x: 700, + y: 900, + width: 520, + height: 140, + zIndex: 2, + params: { + design: "stacked", + color: "#ffffff", + backgroundColor: "transparent", + target: "", + label: "Countdown", + completeText: "Jetzt!", + format: "dhms" + } + }, + { + id: "ticker", + type: "TICKER", + x: 0, + y: 900, + width: 1200, + height: 60, + zIndex: 2, + params: { + design: "marquee", + color: "#ffffff", + backgroundColor: "transparent", + text: "Willkommen", + separator: " • ", + speedSeconds: 20, + direction: "left" + } + }, + { + id: "progress", + type: "PROGRESS", + x: 0, + y: 800, + width: 600, + height: 90, + zIndex: 2, + params: { + design: "bar", + color: "#ffffff", + backgroundColor: "transparent", + label: "Ziel", + current: 40, + target: 100, + showValue: true + } + } +] +const sceneLayout: OverlayLayout = {...layout, widgets: sceneWidgets} test("overlay renderer is available outside the web app", () => { const html = renderToStaticMarkup() @@ -96,7 +259,8 @@ test("overlay renderer is available outside the web app", () => { test("overlay renderer falls back to a widget module default design", () => { const html = renderToStaticMarkup() - expect(html).toContain('data-design="default"') + expect(html).toContain('data-design="artwork"') + expect(html).toContain('data-widget-type="SPOTIFY_NOW_PLAYING"') expect(html).toContain("overlay-window") }) @@ -140,6 +304,26 @@ test("window and media modules render their design components", () => { expect(mediaHtml).toContain("Asset nicht verfügbar") }) +test("scene widgets render as normal overlay widgets", () => { + const html = renderToStaticMarkup() + expect(html).toContain("overlay-background-gradient") + expect(html).toContain("overlay-text-headline") + expect(html).toContain("overlay-clock-stacked") + expect(html).toContain("overlay-socials") + expect(html).toContain("overlay-shape") + expect(html).toContain("overlay-countdown") + expect(html).toContain("overlay-ticker") + expect(html).toContain("overlay-progress-widget") + expect(html).toContain('data-widget-type="BACKGROUND"') + expect(html).toContain('data-widget-type="TEXT"') + expect(html).toContain('data-widget-type="CLOCK"') + expect(html).toContain('data-widget-type="SOCIALS"') + expect(html).toContain('data-widget-type="SHAPE"') + expect(html).toContain('data-widget-type="COUNTDOWN"') + expect(html).toContain('data-widget-type="TICKER"') + expect(html).toContain('data-widget-type="PROGRESS"') +}) + test("overlay editor renders from the ui package", () => { const html = renderToStaticMarkup( @@ -153,3 +337,68 @@ test("overlay player renders its loading state", () => { expect(html).toContain("obs-overlay") expect(html).toContain("Overlay wird geladen") }) + +test("every widget module has metadata, a default design and editable colors", () => { + const modules = Object.values(WIDGET_MODULES) + for (const definition of modules) { + expect(definition.label.length).toBeGreaterThan(0) + expect(definition.description.length).toBeGreaterThan(0) + expect(definition.sectionLabel.length).toBeGreaterThan(0) + expect(definition.designs[definition.defaultDesign]).toBeDefined() + const designs = Object.values(definition.designs) + for (const design of designs) { + const keys = design.colorControls.map((control) => control.key) + expect(keys.length).toBeGreaterThan(0) + expect(new Set(keys).size).toBe(keys.length) + } + } +}) + +test("clock formatting honors date style, 12h mode and seconds", () => { + const now = new Date("2026-11-21T15:04:05Z") + const params: ClockWidgetParams = { + design: "stacked", + color: "#ffffff", + backgroundColor: "transparent", + timeZone: "Europe/Berlin", + dateStyle: "dmy-dot", + hour12: false, + showSeconds: true, + showDate: true + } + expect(formatClockTime(now, params)).toBe("16:04:05") + expect(formatClockTime(now, {...params, hour12: true})).toContain("04:04:05") + expect(formatClockDate(now, params)).toBe("21.11.2026") + expect(formatClockDate(now, {...params, dateStyle: "ymd-dash"})).toBe("2026-11-21") +}) + +test("starter presets contain widgetized scene elements", () => { + const expectations: Record, number> = { + intermission: 8, + starting_soon: 8, + stream_ending: 8 + } + for (const [scene, count] of Object.entries(expectations) as [Exclude, number][]) { + const layout = overlayPreset(scene, [`${scene}-chat`, `${scene}-spotify`]) + expect(layout.widgets).toHaveLength(count) + const types = new Set(layout.widgets.map((widget) => widget.type)) + expect(types.has("BACKGROUND")).toBe(true) + expect(types.has("SHAPE")).toBe(true) + expect(types.has("SOCIALS")).toBe(true) + expect(types.has("CLOCK")).toBe(true) + expect(types.has("TWITCH_CHAT")).toBe(true) + expect(types.has("SPOTIFY_NOW_PLAYING")).toBe(true) + expect(types.has("TEXT")).toBe(scene !== "intermission") + const background = layout.widgets.find((widget) => widget.type === "BACKGROUND") + expect(background).toMatchObject({x: 0, y: 0, width: OVERLAY_WIDTH, height: OVERLAY_HEIGHT, zIndex: 0}) + const taskbar = layout.widgets.find((widget) => widget.id.endsWith("-taskbar")) + expect(taskbar).toMatchObject({x: 0, y: 1026, width: OVERLAY_WIDTH, height: 54, zIndex: 5}) + const socials = layout.widgets.find((widget) => widget.type === "SOCIALS") + expect(socials).toMatchObject({x: 20, y: 1026, width: 700, height: 54, zIndex: 6}) + const clock = layout.widgets.find((widget) => widget.type === "CLOCK") + expect(clock).toMatchObject({x: 1600, y: 1026, width: 300, height: 54, zIndex: 6}) + for (const widget of layout.widgets) { + expect(WIDGET_MODULES[widget.type].designs[widget.params.design]).toBeDefined() + } + } +}) diff --git a/packages/db/prisma/migrations/20260925131412_notification_template_defaults/migration.sql b/packages/db/prisma/migrations/20260925131412_notification_template_defaults/migration.sql deleted file mode 100644 index 27c2e06..0000000 --- a/packages/db/prisma/migrations/20260925131412_notification_template_defaults/migration.sql +++ /dev/null @@ -1,11 +0,0 @@ --- AlterTable -ALTER TABLE "NotificationConfig" ALTER COLUMN "mainStreamNotification" SET DEFAULT 'Hey @everyone! {Username} is now live!', -ALTER COLUMN "partnerStreamNotification" SET DEFAULT 'Hey @here! {Username} is now live!'; - --- Backfill -UPDATE "NotificationConfig" SET "mainStreamNotification" = 'Hey @everyone! {Username} is now live!' WHERE "mainStreamNotification" IS NULL; -UPDATE "NotificationConfig" SET "partnerStreamNotification" = 'Hey @here! {Username} is now live!' WHERE "partnerStreamNotification" IS NULL; - --- AlterTable -ALTER TABLE "NotificationConfig" ALTER COLUMN "mainStreamNotification" SET NOT NULL, -ALTER COLUMN "partnerStreamNotification" SET NOT NULL; diff --git a/packages/db/prisma/migrations/20260925133715_log_channel_not_null/migration.sql b/packages/db/prisma/migrations/20260925133715_log_channel_not_null/migration.sql deleted file mode 100644 index 60f704a..0000000 --- a/packages/db/prisma/migrations/20260925133715_log_channel_not_null/migration.sql +++ /dev/null @@ -1,8 +0,0 @@ -/* - Warnings: - - - Made the column `logChannel` on table `GuildConfig` required. This step will fail if there are existing NULL values in that column. - -*/ --- AlterTable -ALTER TABLE "GuildConfig" ALTER COLUMN "logChannel" SET NOT NULL; diff --git a/packages/db/prisma/migrations/20260925144853_notification_backfill_updated_at/migration.sql b/packages/db/prisma/migrations/20260925144853_notification_backfill_updated_at/migration.sql deleted file mode 100644 index 8fb62b6..0000000 --- a/packages/db/prisma/migrations/20260925144853_notification_backfill_updated_at/migration.sql +++ /dev/null @@ -1,5 +0,0 @@ --- Run before the existing channel migration; keep applied migration checksums unchanged. -INSERT INTO "NotificationConfig" ("guildId", "liveChannel", "partnerChannel", "updatedAt") -SELECT gc."guildId", gc."logChannel", gc."logChannel", CURRENT_TIMESTAMP -FROM "GuildConfig" gc -ON CONFLICT ("guildId") DO NOTHING; diff --git a/packages/db/prisma/migrations/20260925144854_notification_channels_required/migration.sql b/packages/db/prisma/migrations/20260925144854_notification_channels_required/migration.sql deleted file mode 100644 index 66b95d5..0000000 --- a/packages/db/prisma/migrations/20260925144854_notification_channels_required/migration.sql +++ /dev/null @@ -1,19 +0,0 @@ --- Backfill: create NotificationConfig for guilds that have none (channels default to the guild's log channel) -INSERT INTO "NotificationConfig" ("guildId", "liveChannel", "partnerChannel") -SELECT gc."guildId", gc."logChannel", gc."logChannel" -FROM "GuildConfig" gc -WHERE NOT EXISTS (SELECT 1 FROM "NotificationConfig" nc WHERE nc."guildId" = gc."guildId"); - --- Backfill: fill NULL channels (live falls back to log channel, partner falls back to resolved live channel) -UPDATE "NotificationConfig" nc -SET "liveChannel" = COALESCE(nc."liveChannel", gc."logChannel") -FROM "GuildConfig" gc -WHERE gc."guildId" = nc."guildId" AND nc."liveChannel" IS NULL; - -UPDATE "NotificationConfig" nc -SET "partnerChannel" = COALESCE(nc."partnerChannel", nc."liveChannel") -WHERE nc."partnerChannel" IS NULL; - --- AlterTable -ALTER TABLE "NotificationConfig" ALTER COLUMN "liveChannel" SET NOT NULL, -ALTER COLUMN "partnerChannel" SET NOT NULL; diff --git a/packages/db/prisma/migrations/20261002183644_twitch_reward_routing/migration.sql b/packages/db/prisma/migrations/20261002183644_twitch_reward_routing/migration.sql deleted file mode 100644 index 2d58135..0000000 --- a/packages/db/prisma/migrations/20261002183644_twitch_reward_routing/migration.sql +++ /dev/null @@ -1,44 +0,0 @@ --- Dedicated reward-mapping table for Twitch channel-point redemptions. --- Replaces the single-purpose TwitchConfig.spotifySr column so N reward kinds --- can be mapped per guild without further schema changes. TwitchReward is a --- pure mapping: titles are always resolved live (redemption event / Twitch API) --- and never stored. --- NOTE: applied manually in the original environment (see below) because that --- database had drifted ahead of the migration history and `migrate dev` --- demands a reset. This squashed file is the single migration to deploy --- elsewhere (`migrate deploy`). - --- CreateEnum -CREATE TYPE "TwitchRewardKind" AS ENUM ('SPOTIFY_SR'); - --- CreateTable -CREATE TABLE "TwitchReward" ( - "id" SERIAL NOT NULL, - "guildId" TEXT NOT NULL, - "rewardId" TEXT NOT NULL, - "kind" "TwitchRewardKind" NOT NULL, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "TwitchReward_pkey" PRIMARY KEY ("id") -); - --- CreateIndex -CREATE UNIQUE INDEX "TwitchReward_guildId_rewardId_key" ON "TwitchReward"("guildId", "rewardId"); - --- CreateIndex -CREATE INDEX "TwitchReward_guildId_idx" ON "TwitchReward"("guildId"); - --- AddForeignKey -ALTER TABLE "TwitchReward" ADD CONSTRAINT "TwitchReward_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "GuildConfig"("guildId") ON DELETE CASCADE ON UPDATE CASCADE; - --- Backfill: carry any existing song-request mappings into the new table --- before the old column goes away. No-op when there are none. -INSERT INTO "TwitchReward" ("guildId", "rewardId", "kind", "createdAt", "updatedAt") -SELECT "guildId", "spotifySr", 'SPOTIFY_SR', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP -FROM "TwitchConfig" -WHERE "spotifySr" IS NOT NULL -ON CONFLICT ("guildId", "rewardId") DO NOTHING; - --- AlterTable -ALTER TABLE "TwitchConfig" DROP COLUMN "spotifySr"; diff --git a/packages/db/prisma/migrations/20261006090000_web_sessions/migration.sql b/packages/db/prisma/migrations/20261006090000_web_sessions/migration.sql deleted file mode 100644 index 8862d4b..0000000 --- a/packages/db/prisma/migrations/20261006090000_web_sessions/migration.sql +++ /dev/null @@ -1,13 +0,0 @@ -CREATE TABLE "WebSession" ( - "id" TEXT NOT NULL, - "userId" TEXT NOT NULL, - "name" TEXT NOT NULL, - "avatar" TEXT, - "accessToken" TEXT NOT NULL, - "refreshToken" TEXT NOT NULL, - "tokenExpiresAt" TIMESTAMP(3) NOT NULL, - "expiresAt" TIMESTAMP(3) NOT NULL, - CONSTRAINT "WebSession_pkey" PRIMARY KEY ("id") -); - -CREATE INDEX "WebSession_expiresAt_idx" ON "WebSession"("expiresAt"); diff --git a/packages/db/prisma/migrations/20261006140000_song_requests/migration.sql b/packages/db/prisma/migrations/20261006140000_song_requests/migration.sql deleted file mode 100644 index a9b5556..0000000 --- a/packages/db/prisma/migrations/20261006140000_song_requests/migration.sql +++ /dev/null @@ -1,28 +0,0 @@ --- Add independent request routing; keep existing auths and notification follows. -CREATE TABLE "SongRequestConfig" ( - "channelId" TEXT, - "guildId" TEXT NOT NULL, - "enabled" BOOLEAN NOT NULL DEFAULT true, - CONSTRAINT "SongRequestConfig_pkey" PRIMARY KEY ("guildId"), - CONSTRAINT "SongRequestConfig_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "GuildConfig"("guildId") ON DELETE CASCADE ON UPDATE CASCADE -); -CREATE UNIQUE INDEX "SongRequestConfig_channelId_key" ON "SongRequestConfig"("channelId"); - --- Older installations may link the same Twitch account in several guilds. --- Assign the oldest link, with guild ID as a stable tie-breaker; retain all links. -INSERT INTO "SongRequestConfig" ("channelId", "guildId") -SELECT DISTINCT ON ("userId") "userId", "guildId" -FROM "TwitchAuth" -ORDER BY "userId", "createdAt", "guildId"; - -CREATE TABLE "TwitchBotAccount" ( - "id" INTEGER NOT NULL DEFAULT 1, - "userId" TEXT NOT NULL, - "username" TEXT NOT NULL, - "accessToken" TEXT NOT NULL, - "refreshToken" TEXT NOT NULL, - "expiresAt" TIMESTAMP(3) NOT NULL, - "scope" TEXT NOT NULL, - CONSTRAINT "TwitchBotAccount_pkey" PRIMARY KEY ("id"), - CONSTRAINT "TwitchBotAccount_singleton" CHECK ("id" = 1) -); diff --git a/packages/db/prisma/migrations/20261007100000_overlay_token_hash/migration.sql b/packages/db/prisma/migrations/20261007100000_overlay_token_hash/migration.sql deleted file mode 100644 index a9d8e7b..0000000 --- a/packages/db/prisma/migrations/20261007100000_overlay_token_hash/migration.sql +++ /dev/null @@ -1,4 +0,0 @@ --- Preserve existing links while removing retrievable URL secrets from storage. -UPDATE "Overlay" SET "token" = encode(sha256(convert_to("token", 'UTF8')), 'hex'); -ALTER TABLE "Overlay" RENAME COLUMN "token" TO "tokenHash"; -ALTER INDEX "Overlay_token_key" RENAME TO "Overlay_tokenHash_key"; diff --git a/packages/db/prisma/migrations/20261007110000_overlay_media_widgets/migration.sql b/packages/db/prisma/migrations/20261007110000_overlay_media_widgets/migration.sql deleted file mode 100644 index 6bb0f78..0000000 --- a/packages/db/prisma/migrations/20261007110000_overlay_media_widgets/migration.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Existing scenes and widgets remain unchanged; uploaded media is reusable per guild. -ALTER TYPE "WidgetType" ADD VALUE 'IMAGE'; -ALTER TYPE "WidgetType" ADD VALUE 'VIDEO'; diff --git a/packages/db/prisma/migrations/20261008090000_overlay_window_widget/migration.sql b/packages/db/prisma/migrations/20261008090000_overlay_window_widget/migration.sql deleted file mode 100644 index 9a79373..0000000 --- a/packages/db/prisma/migrations/20261008090000_overlay_window_widget/migration.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Add empty framed widgets without modifying existing scenes or widget data. -ALTER TYPE "WidgetType" ADD VALUE 'WINDOW'; diff --git a/packages/db/prisma/migrations/20261009100000_intermission_window_widgets/migration.sql b/packages/db/prisma/migrations/20261009100000_intermission_window_widgets/migration.sql deleted file mode 100644 index c71d2f9..0000000 --- a/packages/db/prisma/migrations/20261009100000_intermission_window_widgets/migration.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Convert the two previously fixed frames once. Existing widgets, scene IDs and URLs stay intact. -INSERT INTO "OverlayWidget" ("id", "overlayId", "type", "x", "y", "width", "height", "zIndex", "params", "createdAt", "updatedAt") -SELECT md5(overlay."id" || ':intermission:' || frame.title), overlay."id", 'WINDOW'::"WidgetType", - frame.x, frame.y, frame.width, 32.4 + 1 + (frame.width - 2) * 9.0 / 16.0, 1, - jsonb_build_object( - 'title', frame.title, - 'lockContentAspectRatio', true, - 'color', CASE overlay."settings"->>'theme' - WHEN 'autumn' THEN '#f6aa1c' WHEN 'winter' THEN '#d3d2c6' WHEN 'light' THEN '#171821' ELSE '#ffffff' END, - 'backgroundColor', CASE overlay."settings"->>'theme' - WHEN 'autumn' THEN '#62170854' WHEN 'winter' THEN '#6d6d695e' WHEN 'light' THEN '#f2f2f7' ELSE '#1b191ca1' END - ), CURRENT_TIMESTAMP, CURRENT_TIMESTAMP -FROM "Overlay" AS overlay -CROSS JOIN (VALUES ('Webcam', 38, 22, 498), ('Game', 630, 76, 1252)) AS frame(title, x, y, width) -WHERE overlay."settings"->>'scene' = 'intermission' -ON CONFLICT ("id") DO NOTHING; diff --git a/packages/db/prisma/migrations/20261019100000_song_request_chat_command/migration.sql b/packages/db/prisma/migrations/20261019100000_song_request_chat_command/migration.sql deleted file mode 100644 index 6a07b26..0000000 --- a/packages/db/prisma/migrations/20261019100000_song_request_chat_command/migration.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Keep existing !sr behaviour; channel-point rewards remain independently configurable. -ALTER TABLE "SongRequestConfig" ADD COLUMN "chatCommandEnabled" BOOLEAN NOT NULL DEFAULT true; diff --git a/packages/db/prisma/migrations/20261019120000_obs_connector/migration.sql b/packages/db/prisma/migrations/20261019120000_obs_connector/migration.sql deleted file mode 100644 index 92dbc24..0000000 --- a/packages/db/prisma/migrations/20261019120000_obs_connector/migration.sql +++ /dev/null @@ -1,14 +0,0 @@ -CREATE TABLE "ObsConnection" ( - "guildId" TEXT NOT NULL, - "tokenHash" TEXT NOT NULL, - "bindings" JSONB NOT NULL DEFAULT '{}', - "inventory" JSONB, - "lastSeenAt" TIMESTAMP(3), - "command" JSONB, - "result" JSONB, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT "ObsConnection_pkey" PRIMARY KEY ("guildId") -); -CREATE UNIQUE INDEX "ObsConnection_tokenHash_key" ON "ObsConnection"("tokenHash"); -ALTER TABLE "ObsConnection" ADD CONSTRAINT "ObsConnection_guildId_fkey" - FOREIGN KEY ("guildId") REFERENCES "GuildConfig"("guildId") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/packages/db/prisma/migrations/20261020100000_remove_obs_connector/migration.sql b/packages/db/prisma/migrations/20261020100000_remove_obs_connector/migration.sql deleted file mode 100644 index 64c5345..0000000 --- a/packages/db/prisma/migrations/20261020100000_remove_obs_connector/migration.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Remove the retired connector's pairing, inventory and queued commands. -DROP TABLE "ObsConnection"; diff --git a/packages/db/prisma/migrations/20261119180000_overlay_browser_token/migration.sql b/packages/db/prisma/migrations/20261119180000_overlay_browser_token/migration.sql deleted file mode 100644 index fcf4ea2..0000000 --- a/packages/db/prisma/migrations/20261119180000_overlay_browser_token/migration.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Keep the browser-source token encrypted so existing scene links can be shown again. --- Rows created before this migration keep NULL and need one URL reset to get a stored link. -ALTER TABLE "Overlay" ADD COLUMN "browserToken" TEXT; diff --git a/packages/db/prisma/migrations/20261119200000_twitch_auth_unique_user/migration.sql b/packages/db/prisma/migrations/20261119200000_twitch_auth_unique_user/migration.sql deleted file mode 100644 index 1415175..0000000 --- a/packages/db/prisma/migrations/20261119200000_twitch_auth_unique_user/migration.sql +++ /dev/null @@ -1,18 +0,0 @@ --- One Twitch account may belong to exactly one guild. --- Existing duplicates keep the oldest link; duplicate guilds lose their Twitch connection data. -CREATE TEMP TABLE duplicate_twitch_guilds AS -SELECT "guildId" -FROM ( - SELECT "guildId", row_number() OVER (PARTITION BY "userId" ORDER BY "createdAt" ASC, "guildId" ASC) AS rn - FROM "TwitchAuth" -) ranked -WHERE rn > 1; - -DELETE FROM "TwitchReward" WHERE "guildId" IN (SELECT "guildId" FROM duplicate_twitch_guilds); -DELETE FROM "SongRequestConfig" WHERE "guildId" IN (SELECT "guildId" FROM duplicate_twitch_guilds); -DELETE FROM "TwitchConfig" WHERE "guildId" IN (SELECT "guildId" FROM duplicate_twitch_guilds) AND "mainStream" = true; -DELETE FROM "TwitchAuth" WHERE "guildId" IN (SELECT "guildId" FROM duplicate_twitch_guilds); - -DROP TABLE duplicate_twitch_guilds; - -CREATE UNIQUE INDEX "TwitchAuth_userId_key" ON "TwitchAuth"("userId"); diff --git a/packages/db/prisma/migrations/20260829211257_init/migration.sql b/packages/db/prisma/migrations/20261121170000_init/migration.sql similarity index 64% rename from packages/db/prisma/migrations/20260829211257_init/migration.sql rename to packages/db/prisma/migrations/20261121170000_init/migration.sql index eac3f8c..5001084 100644 --- a/packages/db/prisma/migrations/20260829211257_init/migration.sql +++ b/packages/db/prisma/migrations/20261121170000_init/migration.sql @@ -1,16 +1,30 @@ --- CreateEnum -CREATE TYPE "OverlayType" AS ENUM ('STATIC', 'DYNAMIC'); +-- CreateSchema +CREATE SCHEMA IF NOT EXISTS "public"; -- CreateEnum -CREATE TYPE "WidgetType" AS ENUM ('SPOTIFY_NOW_PLAYING', 'TWITCH_CHAT'); +CREATE TYPE "TwitchRewardKind" AS ENUM ('SPOTIFY_SR'); -- CreateEnum CREATE TYPE "AssetKind" AS ENUM ('IMAGE', 'VIDEO'); +-- CreateTable +CREATE TABLE "WebSession" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "name" TEXT NOT NULL, + "avatar" TEXT, + "accessToken" TEXT NOT NULL, + "refreshToken" TEXT NOT NULL, + "tokenExpiresAt" TIMESTAMP(3) NOT NULL, + "expiresAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "WebSession_pkey" PRIMARY KEY ("id") +); + -- CreateTable CREATE TABLE "GuildConfig" ( "guildId" TEXT NOT NULL, - "logChannel" TEXT, + "logChannel" TEXT NOT NULL, "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL, @@ -20,10 +34,10 @@ CREATE TABLE "GuildConfig" ( -- CreateTable CREATE TABLE "NotificationConfig" ( "guildId" TEXT NOT NULL, - "liveChannel" TEXT, - "partnerChannel" TEXT, - "mainStreamNotification" TEXT, - "partnerStreamNotification" TEXT, + "liveChannel" TEXT NOT NULL, + "partnerChannel" TEXT NOT NULL, + "mainStreamNotification" TEXT NOT NULL DEFAULT 'Hey @everyone! {Username} is now live!', + "partnerStreamNotification" TEXT NOT NULL DEFAULT 'Hey @here! {Username} is now live!', "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL, @@ -37,13 +51,24 @@ CREATE TABLE "TwitchConfig" ( "username" TEXT NOT NULL, "channelId" TEXT NOT NULL, "mainStream" BOOLEAN NOT NULL DEFAULT false, - "spotifySr" TEXT, "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL, CONSTRAINT "TwitchConfig_pkey" PRIMARY KEY ("id") ); +-- CreateTable +CREATE TABLE "TwitchReward" ( + "id" SERIAL NOT NULL, + "guildId" TEXT NOT NULL, + "rewardId" TEXT NOT NULL, + "kind" "TwitchRewardKind" NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "TwitchReward_pkey" PRIMARY KEY ("id") +); + -- CreateTable CREATE TABLE "TwitchAuth" ( "guildId" TEXT NOT NULL, @@ -75,17 +100,38 @@ CREATE TABLE "SpotifyConfig" ( CONSTRAINT "SpotifyConfig_pkey" PRIMARY KEY ("guildId") ); +-- CreateTable +CREATE TABLE "SongRequestConfig" ( + "guildId" TEXT NOT NULL, + "channelId" TEXT, + "enabled" BOOLEAN NOT NULL DEFAULT true, + "chatCommandEnabled" BOOLEAN NOT NULL DEFAULT true, + + CONSTRAINT "SongRequestConfig_pkey" PRIMARY KEY ("guildId") +); + +-- CreateTable +CREATE TABLE "TwitchBotAccount" ( + "id" INTEGER NOT NULL DEFAULT 1, + "userId" TEXT NOT NULL, + "username" TEXT NOT NULL, + "accessToken" TEXT NOT NULL, + "refreshToken" TEXT NOT NULL, + "expiresAt" TIMESTAMP(3) NOT NULL, + "scope" TEXT NOT NULL, + + CONSTRAINT "TwitchBotAccount_pkey" PRIMARY KEY ("id") +); + -- CreateTable CREATE TABLE "Overlay" ( "id" TEXT NOT NULL, "guildId" TEXT NOT NULL, "name" TEXT NOT NULL DEFAULT 'Overlay', - "token" TEXT NOT NULL, - "type" "OverlayType" NOT NULL DEFAULT 'DYNAMIC', + "tokenHash" TEXT NOT NULL, + "browserToken" TEXT, "backgroundAssetId" TEXT, "settings" JSONB, - "customHtml" TEXT, - "customCss" TEXT, "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL, @@ -96,13 +142,15 @@ CREATE TABLE "Overlay" ( CREATE TABLE "OverlayWidget" ( "id" TEXT NOT NULL, "overlayId" TEXT NOT NULL, - "type" "WidgetType" NOT NULL, + "type" TEXT NOT NULL, "x" DOUBLE PRECISION NOT NULL, "y" DOUBLE PRECISION NOT NULL, "width" DOUBLE PRECISION NOT NULL, "height" DOUBLE PRECISION NOT NULL, "zIndex" INTEGER NOT NULL DEFAULT 0, "params" JSONB NOT NULL, + "label" TEXT, + "hidden" BOOLEAN NOT NULL DEFAULT false, "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL, @@ -123,6 +171,9 @@ CREATE TABLE "Asset" ( CONSTRAINT "Asset_pkey" PRIMARY KEY ("id") ); +-- CreateIndex +CREATE INDEX "WebSession_expiresAt_idx" ON "WebSession"("expiresAt"); + -- CreateIndex CREATE INDEX "TwitchConfig_guildId_idx" ON "TwitchConfig"("guildId"); @@ -130,7 +181,19 @@ CREATE INDEX "TwitchConfig_guildId_idx" ON "TwitchConfig"("guildId"); CREATE UNIQUE INDEX "TwitchConfig_guildId_username_key" ON "TwitchConfig"("guildId", "username"); -- CreateIndex -CREATE UNIQUE INDEX "Overlay_token_key" ON "Overlay"("token"); +CREATE INDEX "TwitchReward_guildId_idx" ON "TwitchReward"("guildId"); + +-- CreateIndex +CREATE UNIQUE INDEX "TwitchReward_guildId_rewardId_key" ON "TwitchReward"("guildId", "rewardId"); + +-- CreateIndex +CREATE UNIQUE INDEX "TwitchAuth_userId_key" ON "TwitchAuth"("userId"); + +-- CreateIndex +CREATE UNIQUE INDEX "SongRequestConfig_channelId_key" ON "SongRequestConfig"("channelId"); + +-- CreateIndex +CREATE UNIQUE INDEX "Overlay_tokenHash_key" ON "Overlay"("tokenHash"); -- CreateIndex CREATE INDEX "Overlay_guildId_idx" ON "Overlay"("guildId"); @@ -150,12 +213,18 @@ ALTER TABLE "NotificationConfig" ADD CONSTRAINT "NotificationConfig_guildId_fkey -- AddForeignKey ALTER TABLE "TwitchConfig" ADD CONSTRAINT "TwitchConfig_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "GuildConfig"("guildId") ON DELETE CASCADE ON UPDATE CASCADE; +-- AddForeignKey +ALTER TABLE "TwitchReward" ADD CONSTRAINT "TwitchReward_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "GuildConfig"("guildId") ON DELETE CASCADE ON UPDATE CASCADE; + -- AddForeignKey ALTER TABLE "TwitchAuth" ADD CONSTRAINT "TwitchAuth_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "GuildConfig"("guildId") ON DELETE CASCADE ON UPDATE CASCADE; -- AddForeignKey ALTER TABLE "SpotifyConfig" ADD CONSTRAINT "SpotifyConfig_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "GuildConfig"("guildId") ON DELETE CASCADE ON UPDATE CASCADE; +-- AddForeignKey +ALTER TABLE "SongRequestConfig" ADD CONSTRAINT "SongRequestConfig_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "GuildConfig"("guildId") ON DELETE CASCADE ON UPDATE CASCADE; + -- AddForeignKey ALTER TABLE "Overlay" ADD CONSTRAINT "Overlay_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "GuildConfig"("guildId") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index d899b56..088360f 100644 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -142,11 +142,8 @@ model Overlay { tokenHash String @unique browserToken String? - type OverlayType @default(DYNAMIC) backgroundAssetId String? settings Json? - customHtml String? @db.Text - customCss String? @db.Text createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -161,13 +158,15 @@ model Overlay { model OverlayWidget { id String @id @default(cuid()) overlayId String - type WidgetType + type String x Float y Float width Float height Float zIndex Int @default(0) params Json + label String? + hidden Boolean @default(false) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -194,19 +193,6 @@ model Asset { @@index([guildId]) } -enum OverlayType { - STATIC - DYNAMIC -} - -enum WidgetType { - SPOTIFY_NOW_PLAYING - TWITCH_CHAT - IMAGE - VIDEO - WINDOW -} - enum AssetKind { IMAGE VIDEO diff --git a/packages/db/src/models/overlay/overlay-widget.ts b/packages/db/src/models/overlay/overlay-widget.ts index 06bf826..16f18bf 100644 --- a/packages/db/src/models/overlay/overlay-widget.ts +++ b/packages/db/src/models/overlay/overlay-widget.ts @@ -1,16 +1,17 @@ -import type {WidgetType} from "@streamcat/interfaces" import type {JsonValue} from "./json-value" export interface OverlayWidgetRecord { id: string overlayId: string - type: WidgetType + type: string x: number y: number width: number height: number zIndex: number params: JsonValue + label: string | null + hidden: boolean createdAt: Date updatedAt: Date } diff --git a/packages/db/src/models/overlay/stored-overlay.ts b/packages/db/src/models/overlay/stored-overlay.ts index 7f84193..1afdfba 100644 --- a/packages/db/src/models/overlay/stored-overlay.ts +++ b/packages/db/src/models/overlay/stored-overlay.ts @@ -1,4 +1,3 @@ -import type {OverlayType} from "@streamcat/interfaces" import type {JsonValue} from "./json-value" import type {OverlayWidgetRecord} from "./overlay-widget" @@ -8,11 +7,8 @@ export interface StoredOverlay { name: string tokenHash: string browserToken: string | null - type: OverlayType backgroundAssetId: string | null settings: JsonValue | null - customHtml: string | null - customCss: string | null updatedAt: Date widgets: OverlayWidgetRecord[] } diff --git a/packages/db/src/repositories/overlay/asset.repository.ts b/packages/db/src/repositories/overlay/asset.repository.ts index 09c54c9..5126207 100644 --- a/packages/db/src/repositories/overlay/asset.repository.ts +++ b/packages/db/src/repositories/overlay/asset.repository.ts @@ -75,7 +75,7 @@ export class AssetRepository { { widgets: { some: { - type: {in: ["IMAGE", "VIDEO"]}, + type: "MEDIA", params: {path: ["assetId"], equals: assetId} } } diff --git a/packages/db/src/repositories/overlay/overlay.repository.ts b/packages/db/src/repositories/overlay/overlay.repository.ts index c77dc62..6cebdac 100644 --- a/packages/db/src/repositories/overlay/overlay.repository.ts +++ b/packages/db/src/repositories/overlay/overlay.repository.ts @@ -90,7 +90,7 @@ export class OverlayRepository { }) for (const widget of mediaWidgets) { const asset = referencedAssets.find((asset) => asset.id === widget.params.assetId) - if (!asset || asset.kind !== widget.type) { + if (!asset) { return null } } @@ -121,9 +121,9 @@ function getLayoutSettings(layout: OverlayLayout) { width: layout.width, height: layout.height, theme: layout.theme, + themeColors: layout.themeColors ?? null, scene: layout.scene ?? "widgets", font: layout.font ?? "tiny5", - socials: layout.socials ?? {}, guides: layout.guides ?? {vertical: [], horizontal: []} } } diff --git a/packages/db/tests/overlay-assets.test.ts b/packages/db/tests/overlay-assets.test.ts index 2153c9c..81b0bdb 100644 --- a/packages/db/tests/overlay-assets.test.ts +++ b/packages/db/tests/overlay-assets.test.ts @@ -52,7 +52,7 @@ databaseTest("asset deletion preserves used media and serializes with layout sav widgets: [ { id: randomUUID(), - type: "IMAGE", + type: "MEDIA", x: 0, y: 0, width: 300, @@ -90,7 +90,7 @@ databaseTest("asset deletion preserves used media and serializes with layout sav widgets: [ { ...layout.widgets[0], - type: "IMAGE", + type: "MEDIA", params: {assetId: raceAsset.id, color: "#ffffff", backgroundColor: "transparent"} } ] diff --git a/packages/interfaces/src/index.ts b/packages/interfaces/src/index.ts index 9e28775..f7e1654 100644 --- a/packages/interfaces/src/index.ts +++ b/packages/interfaces/src/index.ts @@ -9,6 +9,8 @@ export * from "./twitch/twitch-reward" export * from "./discord/embed-data" export * from "./oauth/oauth-provider" export * from "./overlay/overlay" +export * from "./overlay/constants" +export * from "./overlay/widgets" export * from "./overlay/overlay-dashboard" export * from "./overlay/color-templates" export * from "./overlay/overlay-presets" diff --git a/packages/interfaces/src/overlay/color-templates.ts b/packages/interfaces/src/overlay/color-templates.ts index 219a414..01aab2e 100644 --- a/packages/interfaces/src/overlay/color-templates.ts +++ b/packages/interfaces/src/overlay/color-templates.ts @@ -2,6 +2,8 @@ export type OverlayColorTemplate = { label: string color: string backgroundColor: string + gradientStart: string + gradientEnd: string tokens?: Record<`--${string}`, string> } @@ -10,33 +12,24 @@ export const OVERLAY_COLOR_TEMPLATES = { label: "Standard", color: "#ffffff", backgroundColor: "#1b191ca1", - tokens: { - "--window-bg": "#1b191c", - "--progress-color": "#1db954", - "--gradient-start": "#8a71b3", - "--gradient-end": "#e88a98" - } + gradientStart: "#8a71b3", + gradientEnd: "#e88a98", + tokens: {"--window-bg": "#1b191c", "--progress-color": "#1db954"} }, autumn: { label: "Herbst", color: "#f6aa1c", backgroundColor: "#62170854", - tokens: { - "--window-bg": "#220901", - "--progress-color": "#941b0c", - "--gradient-start": "#e07a2f", - "--gradient-end": "#6b1d2f" - } + gradientStart: "#e07a2f", + gradientEnd: "#6b1d2f", + tokens: {"--window-bg": "#220901", "--progress-color": "#941b0c"} }, winter: { label: "Winter", color: "#d3d2c6", backgroundColor: "#6d6d695e", - tokens: { - "--window-bg": "#494d4a", - "--progress-color": "#7a879a", - "--gradient-start": "#2c3e50", - "--gradient-end": "#7fb3d8" - } + gradientStart: "#2c3e50", + gradientEnd: "#7fb3d8", + tokens: {"--window-bg": "#494d4a", "--progress-color": "#7a879a"} } } as const satisfies Record diff --git a/packages/interfaces/src/overlay/constants.ts b/packages/interfaces/src/overlay/constants.ts new file mode 100644 index 0000000..7d6c656 --- /dev/null +++ b/packages/interfaces/src/overlay/constants.ts @@ -0,0 +1,6 @@ +export const MAX_OVERLAY_WIDGETS = 22 +export const OVERLAY_WIDTH = 1920 +export const OVERLAY_HEIGHT = 1080 +export const MIN_WIDGET_WIDTH = 120 +export const MIN_WIDGET_HEIGHT = 40 +export const MAX_OVERLAY_GUIDES = 20 diff --git a/packages/interfaces/src/overlay/overlay-dashboard.ts b/packages/interfaces/src/overlay/overlay-dashboard.ts index ea3c947..2805f54 100644 --- a/packages/interfaces/src/overlay/overlay-dashboard.ts +++ b/packages/interfaces/src/overlay/overlay-dashboard.ts @@ -1,83 +1,18 @@ -import type {WidgetType} from "./overlay" +import type {AssetKind} from "./overlay" import type {SpotifyPlaybackState} from "../spotify/song-details" -import type {WidgetDesignId} from "./widget-designs" - -// Includes the two Intermission frames that were previously fixed scene elements. -export const MAX_OVERLAY_WIDGETS = 22 -export const OVERLAY_WIDTH = 1920 -export const OVERLAY_HEIGHT = 1080 -export const MIN_WIDGET_WIDTH = 120 -export const MIN_WIDGET_HEIGHT = 64 -export const MAX_OVERLAY_GUIDES = 20 +import type {EditorWidget, WidgetAppearance} from "./widgets" +import {OVERLAY_HEIGHT, OVERLAY_WIDTH} from "./constants" export type OverlayTheme = "default" | "autumn" | "winter" export type OverlayScene = "intermission" | "starting_soon" | "stream_ending" | "widgets" export type OverlayFont = "tiny5" | "jersey10" -export type EditorWidgetType = WidgetType - -export type WidgetGeometry = { - id: string - x: number - y: number - width: number - height: number - zIndex: number - - label?: string - - hidden?: boolean -} - -export type WidgetAppearance = { - design: WidgetDesignId - color: string - backgroundColor: string - designColors?: Record<`--${string}`, string> -} - -export type SpotifyWidgetParams = WidgetAppearance & { - spectralizer?: boolean - spectrumMode?: "audio" | "simulated" - audioDeviceName?: string -} - -export type ChatWidgetParams = WidgetAppearance & { - chatChannel?: string - chatFont?: number | string - chatSize?: number - chatFade?: number - chatAnimate?: boolean - chatBots?: boolean - chatHideCommands?: boolean - chatHideBadges?: boolean - title?: string -} - -export type WindowWidgetParams = WidgetAppearance & { - title?: string - lockContentAspectRatio?: boolean - greenScreen?: boolean -} - -export type MediaWidgetParams = WidgetAppearance & { - assetId: string - fit?: "contain" | "cover" -} - -export type EditorWidget = WidgetGeometry & - ( - | {type: "SPOTIFY_NOW_PLAYING"; params: SpotifyWidgetParams} - | {type: "TWITCH_CHAT"; params: ChatWidgetParams} - | {type: "WINDOW"; params: WindowWidgetParams} - | {type: "IMAGE" | "VIDEO"; params: MediaWidgetParams} - ) export function withWidgetColors(widget: T, colors: Partial): T { return {...widget, params: {...widget.params, ...colors}} } -export function isMediaWidget(widget: EditorWidget): widget is Extract { - return widget.type === "IMAGE" || widget.type === "VIDEO" +export function isMediaWidget(widget: EditorWidget): widget is Extract { + return widget.type === "MEDIA" } export interface OverlayLayout { @@ -98,7 +33,6 @@ export interface OverlayLayout { } scene?: OverlayScene font?: OverlayFont - socials?: {twitch?: string; twitter?: string; discord?: string} guides?: {vertical: number[]; horizontal: number[]} widgets: EditorWidget[] } @@ -121,7 +55,7 @@ export interface OverlaySnapshot { export interface OverlayAsset { id: string - kind: "IMAGE" | "VIDEO" + kind: AssetKind fileName: string mimeType: string sizeBytes: number diff --git a/packages/interfaces/src/overlay/overlay-presets.ts b/packages/interfaces/src/overlay/overlay-presets.ts index ed0d281..9549b26 100644 --- a/packages/interfaces/src/overlay/overlay-presets.ts +++ b/packages/interfaces/src/overlay/overlay-presets.ts @@ -1,135 +1,178 @@ -import { - OVERLAY_WIDTH, - OVERLAY_HEIGHT, - type EditorWidget, - type ChatWidgetParams, - type OverlayLayout, - type OverlayScene, - type OverlayTheme -} from "./overlay-dashboard" +import {WIDGET_SPECS, type EditorWidget, type WidgetAppearance, type WidgetType} from "./widgets" +import {type OverlayLayout, type OverlayScene, type OverlayTheme} from "./overlay-dashboard" import {OVERLAY_COLOR_TEMPLATES, type OverlayColorTemplate} from "./color-templates" +import {OVERLAY_HEIGHT, OVERLAY_WIDTH} from "./constants" import {windowHeight} from "./window-geometry" -// Keep this order: existing scenes store the chat provider's numeric font index. -export const TWITCH_CHAT_FONTS = [ - "Baloo Tammudu", - "Segoe UI", - "Roboto", - "Lato", - "Noto Sans", - "Source Code Pro", - "Impact", - "Comfortaa", - "Dancing Script", - "Indie Flower", - "Press Start 2P", - "Wallpoet" -] as const - -export const TWITCH_CHAT_DEFAULTS = { - chatChannel: "", - chatFont: 2, - chatSize: 3, - chatFade: 30, - chatAnimate: true, - chatBots: true, - chatHideCommands: true, - chatHideBadges: true -} - -export function twitchChatUrl( - channel: string | null | undefined, - params: Partial = {} -): string | null { - const selected = params.chatChannel?.trim() || channel?.trim() - if (!selected || !/^[a-zA-Z0-9_]{1,25}$/.test(selected)) return null - const settings = {...TWITCH_CHAT_DEFAULTS, ...params} - const url = new URL("https://chat.johnnycyan.com/v2/") - url.search = new URLSearchParams({ - channel: selected.toLowerCase(), - font: - String(settings.chatFont ?? TWITCH_CHAT_DEFAULTS.chatFont).trim() || String(TWITCH_CHAT_DEFAULTS.chatFont), - size: String(settings.chatSize), - fade: String(settings.chatFade), - animate: String(settings.chatAnimate), - bots: String(settings.chatBots), - hide_commands: String(settings.chatHideCommands), - hide_badges: String(settings.chatHideBadges), - small_caps: "false", - invert: "false" - }).toString() - return url.toString() -} - const themeColors = (template: OverlayColorTemplate) => ({ color: template.color, - backgroundColor: template.backgroundColor + backgroundColor: template.backgroundColor, + gradientStart: template.gradientStart, + gradientEnd: template.gradientEnd }) -export const OVERLAY_THEME_COLORS: Record = { +export const OVERLAY_THEME_COLORS: Record< + OverlayTheme, + {color: string; backgroundColor: string; gradientStart: string; gradientEnd: string} +> = { default: themeColors(OVERLAY_COLOR_TEMPLATES.standard), autumn: themeColors(OVERLAY_COLOR_TEMPLATES.autumn), winter: themeColors(OVERLAY_COLOR_TEMPLATES.winter) } -function themeWidgetParams(theme: OverlayTheme) { - return {design: theme, ...OVERLAY_THEME_COLORS[theme]} +const PRESET_DESIGNS: Record = { + SPOTIFY_NOW_PLAYING: "artwork", + TWITCH_CHAT: "windowed", + WINDOW: "windowed", + MEDIA: "media", + BACKGROUND: "animated", + TEXT: "headline", + CLOCK: "stacked", + SOCIALS: "inline", + SHAPE: "rect", + COUNTDOWN: "stacked", + TICKER: "marquee", + PROGRESS: "bar" +} + +const TRANSPARENT_WIDGETS = new Set([ + "BACKGROUND", + "TEXT", + "CLOCK", + "SOCIALS", + "SHAPE", + "COUNTDOWN", + "TICKER", + "PROGRESS" +]) + +function presetAppearance(theme: OverlayTheme, type: WidgetType): WidgetAppearance { + const colors = OVERLAY_THEME_COLORS[theme] + return { + design: PRESET_DESIGNS[type], + color: colors.color, + backgroundColor: TRANSPARENT_WIDGETS.has(type) ? "transparent" : colors.backgroundColor + } +} + +function presetWidget( + type: WidgetType, + id: string, + theme: OverlayTheme, + geometry: {x: number; y: number; width: number; height: number; zIndex: number}, + overrides: Record = {} +): EditorWidget { + const spec = WIDGET_SPECS[type] + const params = { + ...spec.defaults(presetAppearance(theme, type)), + ...overrides + } + return {id, type, ...geometry, params} as EditorWidget } -// The caller supplies IDs so the same preset works in the browser and backend. export function overlayPreset( scene: OverlayScene, ids: [string, string], theme: OverlayTheme = "default" ): OverlayLayout { const intermission = scene === "intermission" - const widgets: EditorWidget[] = - scene === "widgets" - ? [] - : [ - { - id: ids[0], - type: "TWITCH_CHAT", - x: intermission ? 38 : 1344, - y: intermission ? 346 : 96, - width: intermission ? 553 : 480, - height: intermission ? 372 : 518, - zIndex: 1, - params: themeWidgetParams(theme) - }, - { - id: ids[1], - type: "SPOTIFY_NOW_PLAYING", - x: intermission ? 38 : 1152, - y: intermission ? 729 : 646, - width: intermission ? 553 : 672, - height: intermission ? 275 : 302, - zIndex: 2, - params: {...themeWidgetParams(theme), spectralizer: true, audioDeviceName: ""} - } - ] - if (intermission) + const widgets: EditorWidget[] = [] + if (scene !== "widgets") { widgets.push( - { - id: `${ids[0]}-webcam`, - type: "WINDOW", - x: 38, - y: 22, - width: 498, - height: windowHeight(498), - zIndex: 1, - params: {...themeWidgetParams(theme), title: "Webcam", lockContentAspectRatio: true} - }, - { - id: `${ids[0]}-game`, - type: "WINDOW", - x: 630, - y: 76, - width: 1252, - height: windowHeight(1252), - zIndex: 1, - params: {...themeWidgetParams(theme), title: "Game", lockContentAspectRatio: true} - } + presetWidget("BACKGROUND", `${ids[0]}-background`, theme, { + x: 0, + y: 0, + width: OVERLAY_WIDTH, + height: OVERLAY_HEIGHT, + zIndex: 0 + }), + presetWidget( + "TWITCH_CHAT", + ids[0], + theme, + { + x: intermission ? 38 : 1344, + y: intermission ? 346 : 96, + width: intermission ? 553 : 480, + height: intermission ? 372 : 518, + zIndex: 1 + }, + {design: "windowed"} + ), + presetWidget( + "SPOTIFY_NOW_PLAYING", + ids[1], + theme, + { + x: intermission ? 38 : 1152, + y: intermission ? 729 : 646, + width: intermission ? 553 : 672, + height: intermission ? 275 : 302, + zIndex: 2 + }, + {spectralizer: true, audioDeviceName: ""} + ), + presetWidget("SHAPE", `${ids[0]}-taskbar`, theme, { + x: 0, + y: 1026, + width: OVERLAY_WIDTH, + height: 54, + zIndex: 5 + }), + presetWidget("SOCIALS", `${ids[0]}-socials`, theme, { + x: 20, + y: 1026, + width: 700, + height: 54, + zIndex: 6 + }), + presetWidget("CLOCK", `${ids[0]}-clock`, theme, { + x: 1600, + y: 1026, + width: 300, + height: 54, + zIndex: 6 + }) ) + if (intermission) + widgets.push( + presetWidget( + "WINDOW", + `${ids[0]}-webcam`, + theme, + {x: 38, y: 22, width: 498, height: windowHeight(498), zIndex: 1}, + {title: "Webcam", lockContentAspectRatio: true} + ), + presetWidget( + "WINDOW", + `${ids[0]}-game`, + theme, + {x: 630, y: 76, width: 1252, height: windowHeight(1252), zIndex: 1}, + {title: "Game", lockContentAspectRatio: true} + ) + ) + else + widgets.push( + presetWidget( + "TEXT", + `${ids[0]}-title`, + theme, + {x: 96, y: 54, width: 1000, height: 180, zIndex: 6}, + { + text: scene === "starting_soon" ? "STARTING SOON" : "STREAM ENDING" + } + ), + presetWidget( + "TEXT", + `${ids[0]}-title-dots`, + theme, + {x: 1096, y: 54, width: 120, height: 180, zIndex: 6}, + { + text: "...", + animation: "bounce" + } + ) + ) + } return {width: OVERLAY_WIDTH, height: OVERLAY_HEIGHT, theme, scene, font: "tiny5", widgets} } diff --git a/packages/interfaces/src/overlay/overlay.ts b/packages/interfaces/src/overlay/overlay.ts index fd7269b..1e9a285 100644 --- a/packages/interfaces/src/overlay/overlay.ts +++ b/packages/interfaces/src/overlay/overlay.ts @@ -1,3 +1 @@ -export type OverlayType = "STATIC" | "DYNAMIC" -export type WidgetType = "SPOTIFY_NOW_PLAYING" | "TWITCH_CHAT" | "IMAGE" | "VIDEO" | "WINDOW" export type AssetKind = "IMAGE" | "VIDEO" diff --git a/packages/interfaces/src/overlay/widgets/appearance.ts b/packages/interfaces/src/overlay/widgets/appearance.ts new file mode 100644 index 0000000..7a26b05 --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/appearance.ts @@ -0,0 +1,74 @@ +import {isWidgetDesignId, type WidgetDesignId} from "../widget-designs" +import {WidgetParamError, type WidgetAppearance} from "./types" + +const COLOR_PATTERN = /^(?:transparent|#[a-fA-F0-9]{3,4}|#[a-fA-F0-9]{6}|#[a-fA-F0-9]{8})$/ +const DESIGN_COLOR_KEY_PATTERN = /^--[a-z0-9-]{1,60}$/ + +function isColor(value: unknown): value is string { + return typeof value === "string" && COLOR_PATTERN.test(value) +} + +function readDesign(raw: Record, fallbackDesign: WidgetDesignId): WidgetDesignId { + if (raw.design === undefined) return fallbackDesign + if (isWidgetDesignId(raw.design)) return raw.design + throw new WidgetParamError("Ungültiges Widget-Design.") +} + +function readColor(raw: Record, key: string): string { + const value = raw[key] + if (!isColor(value)) throw new WidgetParamError("Ungültige Widget-Farbe.") + return value +} + +function readDesignColors(raw: Record): Record<`--${string}`, string> | undefined { + const value = raw.designColors + if (value === undefined) return undefined + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new WidgetParamError("Ungültige Design-Farben.") + } + const entries = Object.entries(value) + if (entries.length > 20) throw new WidgetParamError("Zu viele Design-Farben.") + const colors: Record = {} + for (const [key, entry] of entries) { + if (!DESIGN_COLOR_KEY_PATTERN.test(key)) throw new WidgetParamError("Ungültiger Design-Farbname.") + if (!isColor(entry)) throw new WidgetParamError("Ungültige Widget-Farbe.") + colors[key] = entry + } + return Object.keys(colors).length ? (colors as Record<`--${string}`, string>) : undefined +} + +function safeDesignColors(value: unknown): Record<`--${string}`, string> | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined + const entries = Object.entries(value) + if (!entries.length || entries.length > 20) return undefined + const colors: Record = {} + for (const [key, entry] of entries) { + if (!DESIGN_COLOR_KEY_PATTERN.test(key) || !isColor(entry)) return undefined + colors[key] = entry + } + return colors as Record<`--${string}`, string> +} + +export function parseAppearance(raw: Record, fallbackDesign: WidgetDesignId): WidgetAppearance { + return { + design: readDesign(raw, fallbackDesign), + color: readColor(raw, "color"), + backgroundColor: readColor(raw, "backgroundColor"), + designColors: readDesignColors(raw) + } +} + +export function normalizeAppearance( + raw: Record | null, + fallbackDesign: WidgetDesignId +): WidgetAppearance { + const data = raw ?? {} + const design = + data.design === undefined ? fallbackDesign : isWidgetDesignId(data.design) ? data.design : fallbackDesign + return { + design, + color: isColor(data.color) ? data.color : "#ffffff", + backgroundColor: isColor(data.backgroundColor) ? data.backgroundColor : "#18181b", + designColors: safeDesignColors(data.designColors) + } +} diff --git a/packages/interfaces/src/overlay/widgets/background.ts b/packages/interfaces/src/overlay/widgets/background.ts new file mode 100644 index 0000000..4fc60ac --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/background.ts @@ -0,0 +1,47 @@ +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export type BackgroundWidgetParams = WidgetAppearance & { + speedSeconds: number + blur: number + dim: number +} + +function numberInRange(value: unknown, key: string, min: number, max: number): number { + if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) + throw new WidgetParamError(`Ungültige Hintergrund-Einstellung: ${key}.`) + return value +} + +function safeNumber(value: unknown, fallback: number, min: number, max: number): number { + return typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback +} + +export const backgroundSpec: WidgetSpec = { + width: 1920, + height: 1080, + defaults(appearance) { + return { + ...appearance, + speedSeconds: 15, + blur: 0, + dim: 0 + } + }, + parse(raw, {appearance}) { + return { + ...appearance, + speedSeconds: numberInRange(raw.speedSeconds ?? 15, "Geschwindigkeit", 1, 120), + blur: numberInRange(raw.blur ?? 0, "Weichzeichnen", 0, 50), + dim: numberInRange(raw.dim ?? 0, "Abdunklung", 0, 1) + } + }, + normalize(stored, appearance) { + const raw = stored ?? {} + return { + ...appearance, + speedSeconds: safeNumber(raw.speedSeconds, 15, 1, 120), + blur: safeNumber(raw.blur, 0, 0, 50), + dim: safeNumber(raw.dim, 0, 0, 1) + } + } +} diff --git a/packages/interfaces/src/overlay/widgets/clock.ts b/packages/interfaces/src/overlay/widgets/clock.ts new file mode 100644 index 0000000..c9fa477 --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/clock.ts @@ -0,0 +1,78 @@ +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export type ClockDateStyle = "dmy-dot" | "dmy-slash" | "mdy-slash" | "ymd-dash" + +export type ClockWidgetParams = WidgetAppearance & { + timeZone: string + dateStyle: ClockDateStyle + hour12: boolean + showSeconds: boolean + showDate: boolean +} + +const DATE_STYLES = ["dmy-dot", "dmy-slash", "mdy-slash", "ymd-dash"] as const + +function booleanValue(value: unknown, fallback: boolean): boolean { + if (value === undefined) return fallback + if (typeof value !== "boolean") throw new WidgetParamError("Ungültige Uhr-Einstellung.") + return value +} + +function dateStyleValue(value: unknown): ClockDateStyle { + if (value === undefined) return "dmy-dot" + if (typeof value === "string" && DATE_STYLES.includes(value as ClockDateStyle)) return value as ClockDateStyle + throw new WidgetParamError("Ungültiges Datumsformat.") +} + +function validTimeZone(value: string): boolean { + if (!value) return true + try { + new Intl.DateTimeFormat("en", {timeZone: value}) + return true + } catch { + return false + } +} + +export const clockSpec: WidgetSpec = { + width: 320, + height: 80, + defaults(appearance) { + return { + ...appearance, + timeZone: "", + dateStyle: "dmy-dot", + hour12: false, + showSeconds: false, + showDate: true + } + }, + parse(raw, {appearance}) { + const timeZone = typeof raw.timeZone === "string" ? raw.timeZone.trim() : "" + if (timeZone && !validTimeZone(timeZone)) throw new WidgetParamError("Ungültige Zeitzone.") + return { + ...appearance, + timeZone, + dateStyle: dateStyleValue(raw.dateStyle), + hour12: booleanValue(raw.hour12, false), + showSeconds: booleanValue(raw.showSeconds, false), + showDate: booleanValue(raw.showDate, true) + } + }, + normalize(stored, appearance) { + const raw = stored ?? {} + const timeZone = + typeof raw.timeZone === "string" && validTimeZone(raw.timeZone.trim()) ? raw.timeZone.trim() : "" + const dateStyle = DATE_STYLES.includes(raw.dateStyle as ClockDateStyle) + ? (raw.dateStyle as ClockDateStyle) + : "dmy-dot" + return { + ...appearance, + timeZone, + dateStyle, + hour12: raw.hour12 === true, + showSeconds: raw.showSeconds === true, + showDate: raw.showDate !== false + } + } +} diff --git a/packages/interfaces/src/overlay/widgets/countdown.ts b/packages/interfaces/src/overlay/widgets/countdown.ts new file mode 100644 index 0000000..83f6c48 --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/countdown.ts @@ -0,0 +1,67 @@ +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export type CountdownWidgetParams = WidgetAppearance & { + target: string + label: string + completeText: string + format: "dhms" | "hms" | "ms" +} + +const FORMATS = ["dhms", "hms", "ms"] as const + +function textValue(value: unknown, fallback: string, max: number): string { + if (value === undefined) return fallback + if (typeof value !== "string" || value.length > max) throw new WidgetParamError("Ungültige Countdown-Einstellung.") + return value +} + +function formatValue(value: unknown): "dhms" | "hms" | "ms" { + if (value === undefined) return "dhms" + if (typeof value === "string" && FORMATS.includes(value as (typeof FORMATS)[number])) + return value as (typeof FORMATS)[number] + throw new WidgetParamError("Ungültiges Countdown-Format.") +} + +function validTarget(value: string): boolean { + return !value || Number.isFinite(Date.parse(value)) +} + +export const countdownSpec: WidgetSpec = { + width: 520, + height: 140, + defaults(appearance) { + return { + ...appearance, + target: "", + label: "Countdown", + completeText: "Jetzt!", + format: "dhms" + } + }, + parse(raw, {appearance}) { + const target = textValue(raw.target, "", 60) + if (!validTarget(target)) throw new WidgetParamError("Ungültiges Countdown-Datum.") + return { + ...appearance, + target, + label: textValue(raw.label, "Countdown", 80), + completeText: textValue(raw.completeText, "Jetzt!", 80), + format: formatValue(raw.format) + } + }, + normalize(stored, appearance) { + const raw = stored ?? {} + const target = + typeof raw.target === "string" && raw.target.length <= 60 && validTarget(raw.target) ? raw.target : "" + const format = FORMATS.includes(raw.format as (typeof FORMATS)[number]) + ? (raw.format as (typeof FORMATS)[number]) + : "dhms" + return { + ...appearance, + target, + label: typeof raw.label === "string" ? raw.label.slice(0, 80) : "Countdown", + completeText: typeof raw.completeText === "string" ? raw.completeText.slice(0, 80) : "Jetzt!", + format + } + } +} diff --git a/packages/interfaces/src/overlay/widgets/index.ts b/packages/interfaces/src/overlay/widgets/index.ts new file mode 100644 index 0000000..32427ec --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/index.ts @@ -0,0 +1,56 @@ +import {backgroundSpec} from "./background" +import {clockSpec} from "./clock" +import {countdownSpec} from "./countdown" +import {mediaSpec} from "./media" +import {progressSpec} from "./progress" +import {shapeSpec} from "./shape" +import {socialsSpec} from "./socials" +import {spotifySpec} from "./spotify" +import {textSpec} from "./text" +import {tickerSpec} from "./ticker" +import {twitchChatSpec} from "./twitch-chat" +import {windowSpec} from "./window" +import type {WidgetGeometry, WidgetSpec} from "./types" + +export const WIDGET_SPECS = { + SPOTIFY_NOW_PLAYING: spotifySpec, + TWITCH_CHAT: twitchChatSpec, + WINDOW: windowSpec, + MEDIA: mediaSpec, + BACKGROUND: backgroundSpec, + TEXT: textSpec, + CLOCK: clockSpec, + SOCIALS: socialsSpec, + SHAPE: shapeSpec, + COUNTDOWN: countdownSpec, + TICKER: tickerSpec, + PROGRESS: progressSpec +} satisfies Record> + +export type WidgetType = keyof typeof WIDGET_SPECS +export type WidgetParamsByType = { + [K in WidgetType]: (typeof WIDGET_SPECS)[K] extends WidgetSpec ? P : never +} +export type EditorWidget = WidgetGeometry & + { + [K in WidgetType]: {type: K; params: WidgetParamsByType[K]} + }[WidgetType] + +export function isWidgetType(value: unknown): value is WidgetType { + return typeof value === "string" && Object.hasOwn(WIDGET_SPECS, value) +} + +export * from "./types" +export * from "./appearance" +export * from "./spotify" +export * from "./twitch-chat" +export * from "./window" +export * from "./media" +export * from "./background" +export * from "./text" +export * from "./clock" +export * from "./socials" +export * from "./shape" +export * from "./countdown" +export * from "./ticker" +export * from "./progress" diff --git a/packages/interfaces/src/overlay/widgets/media.ts b/packages/interfaces/src/overlay/widgets/media.ts new file mode 100644 index 0000000..28e8c6d --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/media.ts @@ -0,0 +1,37 @@ +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export type MediaWidgetParams = WidgetAppearance & { + assetId: string + fit?: "contain" | "cover" +} + +export const mediaSpec: WidgetSpec = { + width: 480, + height: 270, + defaults(appearance) { + return { + ...appearance, + assetId: "", + fit: "contain" + } + }, + parse(raw, {appearance}) { + if (typeof raw.assetId !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(raw.assetId)) + throw new WidgetParamError("Wähle ein hochgeladenes Medium für dieses Widget.") + if (raw.fit !== undefined && raw.fit !== "contain" && raw.fit !== "cover") + throw new WidgetParamError("Ungültige Medien-Skalierung.") + return { + ...appearance, + assetId: raw.assetId, + fit: raw.fit === "cover" ? "cover" : "contain" + } + }, + normalize(stored, appearance) { + const raw = stored ?? {} + return { + ...appearance, + assetId: typeof raw.assetId === "string" && /^[a-zA-Z0-9_-]{1,100}$/.test(raw.assetId) ? raw.assetId : "", + fit: raw.fit === "cover" ? "cover" : "contain" + } + } +} diff --git a/packages/interfaces/src/overlay/widgets/progress.ts b/packages/interfaces/src/overlay/widgets/progress.ts new file mode 100644 index 0000000..f944b30 --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/progress.ts @@ -0,0 +1,54 @@ +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export type ProgressWidgetParams = WidgetAppearance & { + label: string + current: number + target: number + showValue: boolean +} + +function numberValue(value: unknown, fallback: number, max: number): number { + if (value === undefined) return fallback + if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > max) + throw new WidgetParamError("Ungültige Fortschritts-Einstellung.") + return value +} + +function safeNumber(value: unknown, fallback: number, max: number): number { + return typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(0, value)) : fallback +} + +export const progressSpec: WidgetSpec = { + width: 600, + height: 90, + defaults(appearance) { + return { + ...appearance, + label: "Ziel", + current: 0, + target: 100, + showValue: true + } + }, + parse(raw, {appearance}) { + if (raw.showValue !== undefined && typeof raw.showValue !== "boolean") + throw new WidgetParamError("Ungültige Fortschritts-Einstellung.") + return { + ...appearance, + label: typeof raw.label === "string" && raw.label.length <= 80 ? raw.label : "Ziel", + current: numberValue(raw.current, 0, 1_000_000_000), + target: numberValue(raw.target, 100, 1_000_000_000), + showValue: raw.showValue !== false + } + }, + normalize(stored, appearance) { + const raw = stored ?? {} + return { + ...appearance, + label: typeof raw.label === "string" ? raw.label.slice(0, 80) : "Ziel", + current: safeNumber(raw.current, 0, 1_000_000_000), + target: safeNumber(raw.target, 100, 1_000_000_000), + showValue: raw.showValue !== false + } + } +} diff --git a/packages/interfaces/src/overlay/widgets/shape.ts b/packages/interfaces/src/overlay/widgets/shape.ts new file mode 100644 index 0000000..d0ac488 --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/shape.ts @@ -0,0 +1,44 @@ +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export type ShapeWidgetParams = WidgetAppearance & { + radius: number + opacity: number +} + +function numberValue(value: unknown, fallback: number, min: number, max: number): number { + if (value === undefined) return fallback + if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) + throw new WidgetParamError("Ungültige Form-Einstellung.") + return value +} + +function safeNumber(value: unknown, fallback: number, min: number, max: number): number { + return typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback +} + +export const shapeSpec: WidgetSpec = { + width: 1920, + height: 54, + defaults(appearance) { + return { + ...appearance, + radius: 0, + opacity: 1 + } + }, + parse(raw, {appearance}) { + return { + ...appearance, + radius: numberValue(raw.radius, 0, 0, 100), + opacity: numberValue(raw.opacity, 1, 0, 1) + } + }, + normalize(stored, appearance) { + const raw = stored ?? {} + return { + ...appearance, + radius: safeNumber(raw.radius, 0, 0, 100), + opacity: safeNumber(raw.opacity, 1, 0, 1) + } + } +} diff --git a/packages/interfaces/src/overlay/widgets/socials.ts b/packages/interfaces/src/overlay/widgets/socials.ts new file mode 100644 index 0000000..519da61 --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/socials.ts @@ -0,0 +1,67 @@ +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export type SocialsWidgetParams = WidgetAppearance & { + twitch: string + twitter: string + discord: string + direction: "row" | "column" + showLabels: boolean + showIcons: boolean +} + +const DIRECTIONS = ["row", "column"] as const + +function handle(value: unknown): string { + if (value === undefined) return "" + if (typeof value !== "string" || value.length > 100) throw new WidgetParamError("Ungültiger Social-Handle.") + return value.trim() +} + +function booleanValue(value: unknown, fallback: boolean): boolean { + if (value === undefined) return fallback + if (typeof value !== "boolean") throw new WidgetParamError("Ungültige Social-Einstellung.") + return value +} + +export const socialsSpec: WidgetSpec = { + width: 700, + height: 54, + defaults(appearance) { + return { + ...appearance, + twitch: "", + twitter: "", + discord: "", + direction: "row", + showLabels: true, + showIcons: true + } + }, + parse(raw, {appearance}) { + if (raw.direction !== undefined && raw.direction !== "row" && raw.direction !== "column") + throw new WidgetParamError("Ungültige Social-Einstellung.") + return { + ...appearance, + twitch: handle(raw.twitch), + twitter: handle(raw.twitter), + discord: handle(raw.discord), + direction: raw.direction === "column" ? "column" : "row", + showLabels: booleanValue(raw.showLabels, true), + showIcons: booleanValue(raw.showIcons, true) + } + }, + normalize(stored, appearance) { + const raw = stored ?? {} + return { + ...appearance, + twitch: typeof raw.twitch === "string" ? raw.twitch.slice(0, 100) : "", + twitter: typeof raw.twitter === "string" ? raw.twitter.slice(0, 100) : "", + discord: typeof raw.discord === "string" ? raw.discord.slice(0, 100) : "", + direction: DIRECTIONS.includes(raw.direction as (typeof DIRECTIONS)[number]) + ? (raw.direction as (typeof DIRECTIONS)[number]) + : "row", + showLabels: raw.showLabels !== false, + showIcons: raw.showIcons !== false + } + } +} diff --git a/packages/interfaces/src/overlay/widgets/spotify.ts b/packages/interfaces/src/overlay/widgets/spotify.ts new file mode 100644 index 0000000..ec1770e --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/spotify.ts @@ -0,0 +1,50 @@ +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export type SpotifyWidgetParams = WidgetAppearance & { + spectralizer?: boolean + spectrumMode?: "audio" | "simulated" + audioDeviceName?: string +} + +function spectrumMode(value: unknown): "audio" | "simulated" { + if (value === undefined) return "audio" + if (value === "audio" || value === "simulated") return value + throw new WidgetParamError("Unbekannter Spektrum-Modus.") +} + +export const spotifySpec: WidgetSpec = { + width: 640, + height: 300, + defaults(appearance) { + return { + ...appearance, + spectralizer: false, + spectrumMode: "audio", + audioDeviceName: "" + } + }, + parse(raw, {appearance}) { + if (raw.spectralizer !== undefined && typeof raw.spectralizer !== "boolean") + throw new WidgetParamError("Ungültige Spektrum-Einstellung.") + if ( + raw.audioDeviceName !== undefined && + (typeof raw.audioDeviceName !== "string" || raw.audioDeviceName.length > 200) + ) + throw new WidgetParamError("Ungültiger Audioeingang.") + return { + ...appearance, + spectralizer: raw.spectralizer === true, + spectrumMode: spectrumMode(raw.spectrumMode), + audioDeviceName: (raw.audioDeviceName as string | undefined) ?? "" + } + }, + normalize(stored, appearance) { + const raw = stored ?? {} + return { + ...appearance, + spectralizer: raw.spectralizer === true, + spectrumMode: raw.spectrumMode === "simulated" ? "simulated" : "audio", + audioDeviceName: typeof raw.audioDeviceName === "string" ? raw.audioDeviceName.slice(0, 200) : "" + } + } +} diff --git a/packages/interfaces/src/overlay/widgets/text.ts b/packages/interfaces/src/overlay/widgets/text.ts new file mode 100644 index 0000000..973144c --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/text.ts @@ -0,0 +1,88 @@ +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export type TextWidgetParams = WidgetAppearance & { + text: string + fontSize: number + fontWeight: "normal" | "bold" + align: "left" | "center" | "right" + animation: "none" | "bounce" | "pulse" | "typewriter" + animationSeconds: number + letterSpacing: number +} + +const ALIGNMENTS = ["left", "center", "right"] as const +const ANIMATIONS = ["none", "bounce", "pulse", "typewriter"] as const + +function stringValue(value: unknown, fallback: string, max: number): string { + if (value === undefined) return fallback + if (typeof value !== "string" || value.length > max) throw new WidgetParamError("Ungültiger Text.") + return value +} + +function numberValue(value: unknown, fallback: number, min: number, max: number): number { + if (value === undefined) return fallback + if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) + throw new WidgetParamError("Ungültige Text-Einstellung.") + return value +} + +function choice(value: unknown, options: T, fallback: T[number]): T[number] { + if (value === undefined) return fallback + if (typeof value === "string" && options.includes(value)) return value + throw new WidgetParamError("Ungültige Text-Einstellung.") +} + +function safeNumber(value: unknown, fallback: number, min: number, max: number): number { + return typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback +} + +export const textSpec: WidgetSpec = { + width: 1100, + height: 180, + defaults(appearance) { + return { + ...appearance, + text: "Text", + fontSize: 134.4, + fontWeight: "bold", + align: "left", + animation: "none", + animationSeconds: 1.4, + letterSpacing: 0 + } + }, + parse(raw, {appearance}) { + const weight = raw.fontWeight === "normal" ? "normal" : "bold" + if (raw.fontWeight !== undefined && raw.fontWeight !== "normal" && raw.fontWeight !== "bold") + throw new WidgetParamError("Ungültige Text-Einstellung.") + return { + ...appearance, + text: stringValue(raw.text, "Text", 200), + fontSize: numberValue(raw.fontSize, 134.4, 8, 400), + fontWeight: weight, + align: choice(raw.align, ALIGNMENTS, "left"), + animation: choice(raw.animation, ANIMATIONS, "none"), + animationSeconds: numberValue(raw.animationSeconds, 1.4, 0.2, 20), + letterSpacing: numberValue(raw.letterSpacing, 0, -10, 50) + } + }, + normalize(stored, appearance) { + const raw = stored ?? {} + const align = ALIGNMENTS.includes(raw.align as (typeof ALIGNMENTS)[number]) + ? (raw.align as (typeof ALIGNMENTS)[number]) + : "left" + const animation = ANIMATIONS.includes(raw.animation as (typeof ANIMATIONS)[number]) + ? (raw.animation as (typeof ANIMATIONS)[number]) + : "none" + return { + ...appearance, + text: typeof raw.text === "string" ? raw.text.slice(0, 200) : "Text", + fontSize: safeNumber(raw.fontSize, 134.4, 8, 400), + fontWeight: raw.fontWeight === "normal" ? "normal" : "bold", + align, + animation, + animationSeconds: safeNumber(raw.animationSeconds, 1.4, 0.2, 20), + letterSpacing: safeNumber(raw.letterSpacing, 0, -10, 50) + } + } +} diff --git a/packages/interfaces/src/overlay/widgets/ticker.ts b/packages/interfaces/src/overlay/widgets/ticker.ts new file mode 100644 index 0000000..ab535c5 --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/ticker.ts @@ -0,0 +1,60 @@ +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export type TickerWidgetParams = WidgetAppearance & { + text: string + separator: string + speedSeconds: number + direction: "left" | "right" +} + +function textValue(value: unknown, fallback: string, max: number): string { + if (value === undefined) return fallback + if (typeof value !== "string" || value.length > max) throw new WidgetParamError("Ungültige Ticker-Einstellung.") + return value +} + +function numberValue(value: unknown, fallback: number, min: number, max: number): number { + if (value === undefined) return fallback + if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) + throw new WidgetParamError("Ungültige Ticker-Geschwindigkeit.") + return value +} + +function safeNumber(value: unknown, fallback: number, min: number, max: number): number { + return typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback +} + +export const tickerSpec: WidgetSpec = { + width: 1200, + height: 60, + defaults(appearance) { + return { + ...appearance, + text: "", + separator: " • ", + speedSeconds: 20, + direction: "left" + } + }, + parse(raw, {appearance}) { + if (raw.direction !== undefined && raw.direction !== "left" && raw.direction !== "right") + throw new WidgetParamError("Ungültige Ticker-Richtung.") + return { + ...appearance, + text: textValue(raw.text, "", 500), + separator: textValue(raw.separator, " • ", 20), + speedSeconds: numberValue(raw.speedSeconds, 20, 2, 120), + direction: raw.direction === "right" ? "right" : "left" + } + }, + normalize(stored, appearance) { + const raw = stored ?? {} + return { + ...appearance, + text: typeof raw.text === "string" ? raw.text.slice(0, 500) : "", + separator: typeof raw.separator === "string" ? raw.separator.slice(0, 20) : " • ", + speedSeconds: safeNumber(raw.speedSeconds, 20, 2, 120), + direction: raw.direction === "right" ? "right" : "left" + } + } +} diff --git a/packages/interfaces/src/overlay/widgets/twitch-chat.ts b/packages/interfaces/src/overlay/widgets/twitch-chat.ts new file mode 100644 index 0000000..84f4059 --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/twitch-chat.ts @@ -0,0 +1,180 @@ +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export const TWITCH_CHAT_FONTS = [ + "Baloo Tammudu", + "Segoe UI", + "Roboto", + "Lato", + "Noto Sans", + "Source Code Pro", + "Impact", + "Comfortaa", + "Dancing Script", + "Indie Flower", + "Press Start 2P", + "Wallpoet" +] as const + +export const TWITCH_CHAT_DEFAULTS = { + chatChannel: "", + chatFont: 2, + chatSize: 3, + chatFade: 30, + chatAnimate: true, + chatBots: true, + chatHideCommands: true, + chatHideBadges: true +} + +export type ChatWidgetParams = WidgetAppearance & { + chatChannel?: string + chatFont?: number | string + chatSize?: number + chatFade?: number + chatAnimate?: boolean + chatBots?: boolean + chatHideCommands?: boolean + chatHideBadges?: boolean + title?: string +} + +export function twitchChatUrl( + channel: string | null | undefined, + params: Partial = {} +): string | null { + const selected = params.chatChannel?.trim() || channel?.trim() + if (!selected || !/^[a-zA-Z0-9_]{1,25}$/.test(selected)) return null + const settings = {...TWITCH_CHAT_DEFAULTS, ...params} + const url = new URL("https://chat.johnnycyan.com/v2/") + url.search = new URLSearchParams({ + channel: selected.toLowerCase(), + font: + String(settings.chatFont ?? TWITCH_CHAT_DEFAULTS.chatFont).trim() || String(TWITCH_CHAT_DEFAULTS.chatFont), + size: String(settings.chatSize), + fade: String(settings.chatFade), + animate: String(settings.chatAnimate), + bots: String(settings.chatBots), + hide_commands: String(settings.chatHideCommands), + hide_badges: String(settings.chatHideBadges), + small_caps: "false", + invert: "false" + }).toString() + return url.toString() +} + +function chatFont(value: unknown): number | string { + if (typeof value === "number" && Number.isInteger(value) && value >= 0 && value < TWITCH_CHAT_FONTS.length) + return value + if (typeof value === "string") { + const name = value.trim() + if (!name) return TWITCH_CHAT_DEFAULTS.chatFont + if (name.length <= 100 && /^[a-z0-9][a-z0-9 -]*$/i.test(name) && /[a-z]/i.test(name)) return name + } + throw new WidgetParamError("Ungültige Chat-Schrift. Gib einen Schriftnamen ein, z. B. Tiny5.") +} + +function safeChatFont(value: unknown): number | string { + try { + return chatFont(value) + } catch { + return TWITCH_CHAT_DEFAULTS.chatFont + } +} + +function chatTitle(value: unknown): string { + if (value === undefined) return "Stream Chat" + if (typeof value !== "string" || value.length > 80) + throw new WidgetParamError("Der Fenstertitel darf maximal 80 Zeichen enthalten.") + return value.trim() || "Stream Chat" +} + +function safeChatTitle(value: unknown): string { + return typeof value === "string" && value.length <= 80 ? value.trim() || "Stream Chat" : "Stream Chat" +} + +function chatChannel(value: unknown): string { + const channel = value ?? "" + if (typeof channel !== "string" || (channel.trim() && !/^[a-zA-Z0-9_]{1,25}$/.test(channel.trim()))) + throw new WidgetParamError("Ungültiger Twitch-Kanal.") + return channel.trim() +} + +function numberSetting(raw: Record, key: "chatSize" | "chatFade", max: number): number | undefined { + if (raw[key] === undefined) return undefined + const value = raw[key] + if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > max) + throw new WidgetParamError("Ungültige Chat-Einstellung.") + return value +} + +function booleanSetting(raw: Record, key: keyof typeof TWITCH_CHAT_DEFAULTS): boolean | undefined { + if (raw[key] === undefined) return undefined + if (typeof raw[key] !== "boolean") throw new WidgetParamError("Ungültige Chat-Einstellung.") + return raw[key] +} + +export const twitchChatSpec: WidgetSpec = { + width: 440, + height: 560, + defaults(appearance) { + return { + ...appearance, + ...TWITCH_CHAT_DEFAULTS, + title: "Stream Chat" + } + }, + parse(raw, {appearance}) { + const settings = { + ...TWITCH_CHAT_DEFAULTS, + ...appearance, + title: chatTitle(raw.title), + chatChannel: chatChannel(raw.chatChannel), + chatFont: chatFont(raw.chatFont ?? TWITCH_CHAT_DEFAULTS.chatFont) + } + const size = numberSetting(raw, "chatSize", 3) + const fade = numberSetting(raw, "chatFade", 3600) + const animate = booleanSetting(raw, "chatAnimate") + const bots = booleanSetting(raw, "chatBots") + const hideCommands = booleanSetting(raw, "chatHideCommands") + const hideBadges = booleanSetting(raw, "chatHideBadges") + if (size !== undefined) settings.chatSize = size + if (fade !== undefined) settings.chatFade = fade + if (animate !== undefined) settings.chatAnimate = animate + if (bots !== undefined) settings.chatBots = bots + if (hideCommands !== undefined) settings.chatHideCommands = hideCommands + if (hideBadges !== undefined) settings.chatHideBadges = hideBadges + return settings + }, + normalize(stored, appearance) { + const raw = stored ?? {} + return { + ...appearance, + ...TWITCH_CHAT_DEFAULTS, + title: safeChatTitle(raw.title), + chatChannel: typeof raw.chatChannel === "string" ? raw.chatChannel.slice(0, 25) : "", + chatFont: safeChatFont(raw.chatFont), + chatSize: + typeof raw.chatSize === "number" && + Number.isInteger(raw.chatSize) && + raw.chatSize >= 0 && + raw.chatSize <= 3 + ? raw.chatSize + : TWITCH_CHAT_DEFAULTS.chatSize, + chatFade: + typeof raw.chatFade === "number" && + Number.isInteger(raw.chatFade) && + raw.chatFade >= 0 && + raw.chatFade <= 3600 + ? raw.chatFade + : TWITCH_CHAT_DEFAULTS.chatFade, + chatAnimate: typeof raw.chatAnimate === "boolean" ? raw.chatAnimate : TWITCH_CHAT_DEFAULTS.chatAnimate, + chatBots: typeof raw.chatBots === "boolean" ? raw.chatBots : TWITCH_CHAT_DEFAULTS.chatBots, + chatHideCommands: + typeof raw.chatHideCommands === "boolean" + ? raw.chatHideCommands + : TWITCH_CHAT_DEFAULTS.chatHideCommands, + chatHideBadges: + typeof raw.chatHideBadges === "boolean" ? raw.chatHideBadges : TWITCH_CHAT_DEFAULTS.chatHideBadges + } + } +} diff --git a/packages/interfaces/src/overlay/widgets/types.ts b/packages/interfaces/src/overlay/widgets/types.ts new file mode 100644 index 0000000..b5c10de --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/types.ts @@ -0,0 +1,42 @@ +import type {WidgetDesignId} from "../widget-designs" + +export type WidgetGeometry = { + id: string + x: number + y: number + width: number + height: number + zIndex: number + + label?: string + + hidden?: boolean +} + +export type WidgetAppearance = { + design: WidgetDesignId + color: string + backgroundColor: string + designColors?: Record<`--${string}`, string> +} + +export type WidgetParseContext = { + appearance: WidgetAppearance + width: number + height: number +} + +export type WidgetSpec

= { + width: number + height: number + defaults(appearance: WidgetAppearance): P + parse(raw: Record, context: WidgetParseContext): P + normalize(stored: Record | null, appearance: WidgetAppearance): P +} + +export class WidgetParamError extends Error { + constructor(message: string) { + super(message) + this.name = "WidgetParamError" + } +} diff --git a/packages/interfaces/src/overlay/widgets/window.ts b/packages/interfaces/src/overlay/widgets/window.ts new file mode 100644 index 0000000..6b74594 --- /dev/null +++ b/packages/interfaces/src/overlay/widgets/window.ts @@ -0,0 +1,55 @@ +import {windowHeight} from "../window-geometry" +import {WidgetParamError, type WidgetAppearance, type WidgetSpec} from "./types" + +export type WindowWidgetParams = WidgetAppearance & { + title?: string + lockContentAspectRatio?: boolean + greenScreen?: boolean +} + +function windowTitle(value: unknown): string { + if (value === undefined) return "Fenster" + if (typeof value !== "string" || value.length > 80) + throw new WidgetParamError("Der Fenstertitel darf maximal 80 Zeichen enthalten.") + return value.trim() || "Fenster" +} + +function safeWindowTitle(value: unknown): string { + return typeof value === "string" && value.length <= 80 ? value.trim() || "Fenster" : "Fenster" +} + +export const windowSpec: WidgetSpec = { + width: 640, + height: 300, + defaults(appearance) { + return { + ...appearance, + title: "Fenster", + lockContentAspectRatio: false, + greenScreen: false + } + }, + parse(raw, {appearance, width, height}) { + if (raw.lockContentAspectRatio !== undefined && typeof raw.lockContentAspectRatio !== "boolean") + throw new WidgetParamError("Ungültige 16:9-Einstellung.") + if (raw.greenScreen !== undefined && typeof raw.greenScreen !== "boolean") + throw new WidgetParamError("Ungültige Greenscreen-Einstellung.") + if (raw.lockContentAspectRatio === true && Math.abs(height - windowHeight(width)) > 0.01) + throw new WidgetParamError("Die gesperrte Content-Fläche muss 16:9 sein; der Header zählt nicht dazu.") + return { + ...appearance, + title: windowTitle(raw.title), + lockContentAspectRatio: raw.lockContentAspectRatio === true, + greenScreen: raw.greenScreen === true + } + }, + normalize(stored, appearance) { + const raw = stored ?? {} + return { + ...appearance, + title: safeWindowTitle(raw.title), + lockContentAspectRatio: raw.lockContentAspectRatio === true, + greenScreen: raw.greenScreen === true + } + } +} diff --git a/packages/interfaces/src/overlay/window-geometry.ts b/packages/interfaces/src/overlay/window-geometry.ts index c945345..13a8b3e 100644 --- a/packages/interfaces/src/overlay/window-geometry.ts +++ b/packages/interfaces/src/overlay/window-geometry.ts @@ -1,11 +1,12 @@ -import {OVERLAY_WIDTH, OVERLAY_HEIGHT, type EditorWidget} from "./overlay-dashboard" +import {OVERLAY_WIDTH, OVERLAY_HEIGHT} from "./constants" +import type {WidgetGeometry} from "./widgets/types" export const WINDOW_HEADER_HEIGHT = 32.4 export const WINDOW_CONTENT_BORDER = 1 export const WINDOW_CONTENT_RATIO = 16 / 9 export const WINDOW_CORNER_RADIUS = 10.8 -export function windowContentBounds(widget: Pick) { +export function windowContentBounds(widget: Pick) { return { x: widget.x + WINDOW_CONTENT_BORDER, y: widget.y + WINDOW_HEADER_HEIGHT, @@ -15,7 +16,7 @@ export function windowContentBounds(widget: Pick, + bounds: Pick, baseWidth: number, baseHeight: number ) { diff --git a/packages/ui/overlay-engine/README.md b/packages/ui/overlay-engine/README.md index 9b8be93..d50b519 100644 --- a/packages/ui/overlay-engine/README.md +++ b/packages/ui/overlay-engine/README.md @@ -40,34 +40,63 @@ Fonts, fallback theme and all overlay CSS ship with the package. No separate ass ## Widget designs -Each widget owns its design components: +Widget types come from `WIDGET_SPECS` in `packages/interfaces/src/overlay/widgets/`. That list is the only widget type source used by the editor, the renderer and the backend. + +Each widget owns its folder: ```text widgets/ - registry.ts - settings.tsx - types.ts - shared/ - spotify/ + clock/ index.ts - logic/ designs/ - artwork.tsx - default.ts - autumn.ts - winter.ts + stacked/ + index.ts + stacked.tsx + stacked.css + inline/ + index.ts + inline.tsx + inline.css + logic/ + clock-widget.tsx + use-clock.ts + clock-settings.tsx + clock-glyph.tsx ``` -Each design file exports one complete design definition: id, label, defaults, `colorControls`, optional design `settings`, and the component. The widget's `index.ts` only aggregates them. Adding a design means adding one definition file and one entry in that widget module. +Rules: + +- `index.ts` aggregates the widget module and metadata. It contains no JSX and imports no CSS. +- Each design folder exports one `WidgetDesign` and imports its own CSS from the TSX file. +- CSS shared by several designs of the same widget lives in `designs/-base.css`. +- `logic/` holds behavior, hooks, settings and the layer glyph. +- Widget-specific CSS never lives in `styles/renderer.css` or `styles/editor.css`. -Built-in designs: Spotify `default`/`autumn`/`winter`, Twitch chat `windowed`/`none`, Window `default`/`autumn`/`winter`, Image/Video `default`/`autumn`/`winter`. +Every design declares `colorControls`. The editor sidebar renders that list directly; it does not keep a hardcoded color list. -Color templates live in `packages/interfaces/src/overlay/color-templates.ts` as `OVERLAY_COLOR_TEMPLATES`. Scene themes and widget design defaults both use them, so the source of a color is always that file. +Built-in designs: + +- Spotify `artwork` +- Twitch chat `windowed`, `none` +- Window `windowed` +- Media `media` +- Background `animated`, `solid` +- Text `headline`, `plain` +- Clock `stacked`, `inline` +- Socials `inline`, `icons` +- Shape `rect`, `line`, `ellipse` +- Countdown `stacked`, `inline` +- Ticker `marquee` +- Progress `bar` + +Color templates live in `packages/interfaces/src/overlay/color-templates.ts` as `OVERLAY_COLOR_TEMPLATES`. Scene themes and preset defaults both use them. `colorControls` declare what the editor may change. Keys are `color`, `backgroundColor`, or CSS custom properties such as `--window-bg`. Defaults come from the design's `color`, `backgroundColor` and `tokens`; user values are stored in `params.color`, `params.backgroundColor` and `params.designColors`. Design components must use `currentColor` or CSS variables for customizable parts. Color-control defaults must be hex values because the editor uses a native color picker. +Starter scenes are built only from widgets. `overlayPreset()` creates background, title, taskbar, socials and clock as normal layers, so every scene element can be selected, moved, styled and deleted. + ## Usage The components run in the browser. Inject the request function from the host app. diff --git a/packages/ui/overlay-engine/src/assets/add-dialog.tsx b/packages/ui/overlay-engine/src/assets/add-dialog.tsx index f680f81..1eb30a6 100644 --- a/packages/ui/overlay-engine/src/assets/add-dialog.tsx +++ b/packages/ui/overlay-engine/src/assets/add-dialog.tsx @@ -7,12 +7,6 @@ import {Dialog, EditorTab, Select} from "../ui/dialog" import {TrashIcon} from "../ui/icons" import {widgetModule, WIDGET_CATALOG_TYPES, type AddableWidgetType} from "../widgets/registry" -const CATEGORY_OF: Record = { - SPOTIFY_NOW_PLAYING: "Audio", - TWITCH_CHAT: "Chat", - WINDOW: "Fenster" -} - export function AddDialog({ defaultTab, widgetCount, @@ -52,30 +46,38 @@ export function AddDialog({ const widgets = useMemo(() => { const query = search.trim().toLowerCase() - return WIDGET_CATALOG_TYPES.filter((type) => - query - ? widgetModule(type).label.toLowerCase().includes(query) || - CATEGORY_OF[type].toLowerCase().includes(query) - : true - ) + return WIDGET_CATALOG_TYPES.filter((type) => { + if (!query) return true + const module = widgetModule(type) + return [module.label, module.description, module.category].some((value) => + value.toLowerCase().includes(query) + ) + }) }, [search]) const counts = useMemo(() => { const query = search.trim().toLowerCase() - const matches = (type: AddableWidgetType) => - query - ? widgetModule(type).label.toLowerCase().includes(query) || - CATEGORY_OF[type].toLowerCase().includes(query) - : true + const matches = (type: AddableWidgetType) => { + if (!query) return true + const module = widgetModule(type) + return [module.label, module.description, module.category].some((value) => + value.toLowerCase().includes(query) + ) + } const result: Record = {} for (const type of WIDGET_CATALOG_TYPES) { - const category = CATEGORY_OF[type] + const category = widgetModule(type).category result[category] = (result[category] ?? 0) + (matches(type) ? 1 : 0) } result["Alle"] = widgets.length return result }, [widgets, search]) + const categories = useMemo( + () => ["Alle", ...new Set(WIDGET_CATALOG_TYPES.map((type) => widgetModule(type).category))], + [] + ) + const widgetFull = widgetCount >= maxWidgets const selectedAsset = assets.find((asset) => asset.id === assetId) ?? null const selectedModule = widgetType ? widgetModule(widgetType) : null @@ -163,12 +165,7 @@ export function AddDialog({ />

    - {[ - "Alle", - ...Object.keys(CATEGORY_OF) - .map((type) => CATEGORY_OF[type as AddableWidgetType]) - .filter((value, index, list) => list.indexOf(value) === index) - ].map((category) => ( + {categories.map((category) => (
  • {category} {counts[category] ?? 0} @@ -180,22 +177,26 @@ export function AddDialog({

    - {widgets.map((type) => ( - - ))} + {widgets.map((type) => { + const module = widgetModule(type) + const Glyph = module.glyph + return ( + + ) + })}
    )} diff --git a/packages/ui/overlay-engine/src/canvas.tsx b/packages/ui/overlay-engine/src/canvas.tsx index dbe6ad4..b2cf065 100644 --- a/packages/ui/overlay-engine/src/canvas.tsx +++ b/packages/ui/overlay-engine/src/canvas.tsx @@ -13,6 +13,7 @@ import { type OverlayPlayback } from "@streamcat/interfaces" import {OverlayRenderer} from "./renderer" +import {widgetModule} from "./widgets/registry" import {widgetName} from "./widgets/shared/widget-name" import {ASSET_DRAG_TYPE} from "./assets/use-overlay-assets" import {snapWidget} from "./alignment/snap" @@ -265,8 +266,7 @@ export function OverlayCanvas({ width: widget.width, height: widget.height, zIndex: widget.zIndex, - borderRadius: - widget.type === "IMAGE" || widget.type === "VIDEO" ? 0 : undefined + borderRadius: widgetModule(widget.type).frame === "none" ? 0 : undefined }} onFocus={() => { onSelect({type: "widget", id: widget.id}) diff --git a/packages/ui/overlay-engine/src/css-modules.d.ts b/packages/ui/overlay-engine/src/css-modules.d.ts new file mode 100644 index 0000000..d7e961e --- /dev/null +++ b/packages/ui/overlay-engine/src/css-modules.d.ts @@ -0,0 +1 @@ +declare module "*.css" diff --git a/packages/ui/overlay-engine/src/editor.tsx b/packages/ui/overlay-engine/src/editor.tsx index b97287f..3c76e0f 100644 --- a/packages/ui/overlay-engine/src/editor.tsx +++ b/packages/ui/overlay-engine/src/editor.tsx @@ -3,6 +3,7 @@ import {useEffect, useState, type ElementType, type ReactNode} from "react" import { MAX_OVERLAY_WIDGETS, + WIDGET_SPECS, isMediaWidget, type EditorWidget, type OverlayChat, @@ -184,30 +185,46 @@ function OverlaySession({ if (window.confirm(`„${asset.fileName}“ endgültig löschen?`)) void media.removeAsset(asset) } - function addWidget(type: AddableWidgetType, design = "default") { + function addWidget(type: AddableWidgetType, design?: string) { if (!layout || layout.widgets.length >= MAX_OVERLAY_WIDGETS) return const module = widgetModule(type) - const moduleDesign = module.designs[design] ?? module.designs[module.defaultDesign] + const moduleDesign = (design ? module.designs[design] : undefined) ?? module.designs[module.defaultDesign] + const spec = WIDGET_SPECS[type] + const x = Math.max(0, Math.min(80 + (layout.widgets.length % 8) * 40, layout.width - spec.width)) + const y = Math.max(0, Math.min(80 + (layout.widgets.length % 8) * 40, layout.height - spec.height)) const widget: EditorWidget = { id: crypto.randomUUID(), type, - x: 80 + (layout.widgets.length % 8) * 40, - y: 80 + (layout.widgets.length % 8) * 40, - width: module.width, - height: module.height, + x, + y, + width: spec.width, + height: spec.height, zIndex: Math.min(1000, Math.max(0, ...layout.widgets.map((item) => item.zIndex)) + 1), - params: { + params: spec.defaults({ design: moduleDesign.id, color: moduleDesign.color, - backgroundColor: moduleDesign.backgroundColor, - ...(type === "WINDOW" ? {title: "Fenster"} : {}) - } - } + backgroundColor: moduleDesign.backgroundColor + }) as EditorWidget["params"] + } as EditorWidget setLayout({...layout, widgets: [...layout.widgets, widget]}) setSelection({type: "widget", id: widget.id}) setNotice(null) } + function mediaParams(assetId: string, fit: "contain" | "cover") { + const module = widgetModule("MEDIA") + const design = module.designs[module.defaultDesign] + return { + ...WIDGET_SPECS.MEDIA.defaults({ + design: design.id, + color: "#ffffff", + backgroundColor: "transparent" + }), + assetId, + fit + } + } + function addPlacedAsset(asset: OverlayAsset, asBackground: boolean, fit: "contain" | "cover") { if (!layout || layout.widgets.length >= MAX_OVERLAY_WIDGETS) { setError(`Maximal ${MAX_OVERLAY_WIDGETS} Widgets pro Szene. Entferne zuerst ein Widget.`) @@ -225,15 +242,9 @@ function OverlaySession({ } const widget: EditorWidget = { id, - type: asset.kind, + type: "MEDIA", ...background, - params: { - design: layout.theme, - color: "#ffffff", - backgroundColor: "transparent", - assetId: asset.id, - fit - } + params: mediaParams(asset.id, fit) } setLayout({...layout, widgets: [...layout.widgets, widget]}) setSelection({type: "widget", id}) @@ -241,7 +252,7 @@ function OverlaySession({ } async function createWithTheme(name: string, scene: OverlayScene, theme: OverlayTheme, font: OverlayFont) { - const created = await createScene(name, scene) + const created = await createScene(name, scene, theme) if (created) { setLayout((current) => (current ? {...current, theme, font} : current)) } @@ -256,19 +267,13 @@ function OverlaySession({ const top = Math.max(0, ...current.widgets.map((widget) => widget.zIndex)) const widgets: EditorWidget[] = available.map((asset, index) => ({ id: ids[index], - type: asset.kind, + type: "MEDIA", x: Math.min(x + index * 30, current.width - 480), y: Math.min(y + index * 30, current.height - 270), width: 480, height: 270, zIndex: Math.min(1000, top + index + 1), - params: { - design: current.theme, - color: "#ffffff", - backgroundColor: "transparent", - assetId: asset.id, - fit: "contain" - } + params: mediaParams(asset.id, "contain") })) return {...current, widgets: [...current.widgets, ...widgets]} }) diff --git a/packages/ui/overlay-engine/src/renderer.tsx b/packages/ui/overlay-engine/src/renderer.tsx index 6e37f9c..ebb7859 100644 --- a/packages/ui/overlay-engine/src/renderer.tsx +++ b/packages/ui/overlay-engine/src/renderer.tsx @@ -6,12 +6,14 @@ import { type OverlayLayout, type OverlayPlayback } from "@streamcat/interfaces" -import {StandardScene} from "./scene/standard-scene" import {widgetModule} from "./widgets/registry" export const EMPTY_PLAYBACK: OverlayPlayback = {status: "disconnected", text: "Spotify nicht verbunden", albumUrl: null} -// Both the editor and the OBS page render these same logical pixels. +function widgetTypeClass(type: string) { + return type.toLowerCase().replaceAll("_", "-") +} + export function OverlayRenderer({ layout, playback, @@ -27,7 +29,6 @@ export function OverlayRenderer({ interactive?: boolean audioEnabled?: boolean }) { - const scene = layout.scene ?? "widgets" const themeTemplate = OVERLAY_COLOR_TEMPLATES[layout.theme === "default" ? "standard" : layout.theme] const themeTokens = { "--progress-color": layout.themeColors?.primary ?? themeTemplate.tokens?.["--progress-color"] ?? "#1db954", @@ -47,29 +48,23 @@ export function OverlayRenderer({ className={`overlay-renderer overlay-theme-${layout.theme} overlay-font-${layout.font ?? "tiny5"}`} style={{width: layout.width, height: layout.height, ...themeVars}} > - {layout.widgets.map((widget) => { if (widget.hidden) return null - const media = widget.type === "IMAGE" || widget.type === "VIDEO" const module = widgetModule(widget.type) + const frameless = module.frame === "none" const design = module.designs[widget.params.design] ?? module.designs[module.defaultDesign] const designTokens = { - // Scene theme beats design defaults; per-widget overrides win last. ...(design.tokens ?? {}), ...themeTokens, ...(widget.params.designColors ?? {}) } as CSSProperties - const title = - widget.type === "WINDOW" - ? (widget.params.title ?? "Fenster") - : widget.type === "TWITCH_CHAT" - ? (widget.params.title ?? "Stream Chat") - : "Currently Playing" + const title = module.titleFor?.(widget) ?? module.label const DesignComponent = design.component return (
    , string][] = [ ["Primär", "primary", colors.tokens?.["--progress-color"] ?? "#1db954"], - ["Sekundär", "secondary", colors.tokens?.["--gradient-end"] ?? colors.color], - ["Fläche", "surface", colors.tokens?.["--gradient-start"] ?? colors.backgroundColor], + ["Sekundär", "secondary", colors.gradientEnd], + ["Fläche", "surface", colors.gradientStart], ["Fenster", "window", colors.tokens?.["--window-bg"] ?? "#1b191c"], ["Text", "text", colors.color] ] @@ -94,7 +93,7 @@ export function SceneSidebar({

    Primär ist die Standardfarbe für Fortschritt. Sekundär und Fläche bilden den Verlauf, - Fenster die Flächen, Text Titel und Taskbar. Widget-Farben überschreiben das Theme. + Fenster die Flächen, Text die Textfarbe. Widget-Farben überschreiben das Theme.

    @@ -150,47 +149,6 @@ export function SceneSidebar({ Standardlayout laden )} - - - -
    - - {(["twitch", "twitter", "discord"] as const).map((provider) => ( - - ))}
    diff --git a/packages/ui/overlay-engine/src/scene/standard-scene.tsx b/packages/ui/overlay-engine/src/scene/standard-scene.tsx deleted file mode 100644 index 6b5bfcc..0000000 --- a/packages/ui/overlay-engine/src/scene/standard-scene.tsx +++ /dev/null @@ -1,80 +0,0 @@ -"use client" - -import {useEffect, useState} from "react" -import type {OverlayChat, OverlayLayout, OverlayScene} from "@streamcat/interfaces" - -function SocialIcon({provider}: {provider: "twitch" | "twitter" | "discord"}) { - const paths = { - twitch: "M3 2 1 6v14h5v3h3l3-3h4l7-7V2H3Zm18 10-4 4h-5l-3 3v-3H5V4h16v8ZM15 6h2v6h-2V6Zm-5 0h2v6h-2V6Z", - twitter: - "M23 4.5a9 9 0 0 1-2.6.7 4.5 4.5 0 0 0 2-2.5 9 9 0 0 1-2.9 1.1 4.5 4.5 0 0 0-7.7 4.1A12.8 12.8 0 0 1 2.5 3.2a4.5 4.5 0 0 0 1.4 6 4.5 4.5 0 0 1-2-.6 4.5 4.5 0 0 0 3.6 4.5 4.5 4.5 0 0 1-2 .1 4.5 4.5 0 0 0 4.2 3.1A9 9 0 0 1 1 18.2a12.8 12.8 0 0 0 19.7-10.8v-.6A9 9 0 0 0 23 4.5Z", - discord: - "M20.3 4.6a19.6 19.6 0 0 0-4.8-1.5l-.6 1.3a18.3 18.3 0 0 0-5.8 0l-.6-1.3a19.7 19.7 0 0 0-4.8 1.5C.7 9 .0 13.4.4 17.7a19.7 19.7 0 0 0 6 3l1.2-2a12.7 12.7 0 0 1-1.9-.9l.5-.4a14.6 14.6 0 0 0 11.6 0l.5.4-1.9.9 1.2 2a19.7 19.7 0 0 0 6-3c.5-5-1-9.3-3.3-13.1ZM8 15.3c-1.1 0-2-1-2-2.3s.9-2.3 2-2.3 2 1 2 2.3-.9 2.3-2 2.3Zm8 0c-1.1 0-2-1-2-2.3s.9-2.3 2-2.3 2 1 2 2.3-.9 2.3-2 2.3Z" - } - return ( - - ) -} - -export function StandardScene({ - scene, - chat, - socials -}: { - scene: OverlayScene - chat: OverlayChat - socials?: OverlayLayout["socials"] -}) { - const [clock, setClock] = useState({time: "", date: ""}) - useEffect(() => { - if (scene === "widgets") return - function update() { - const now = new Date() - setClock({time: now.toLocaleTimeString("de-DE"), date: now.toLocaleDateString("de-DE")}) - } - update() - const timer = setInterval(update, 1000) - return () => clearInterval(timer) - }, [scene]) - - if (scene === "widgets") return null - const handles = { - twitch: socials?.twitch || (chat.channel ? `/${chat.channel}` : ""), - twitter: socials?.twitter, - discord: socials?.discord - } - return ( - <> -
    -
    -
    - {scene !== "intermission" && ( -
    - {scene === "starting_soon" ? "STARTING SOON" : "STREAM ENDING"} - . - . - . -
    - )} -
    -
    - {(["twitch", "twitter", "discord"] as const).map( - (provider) => - handles[provider] && ( - - - {handles[provider]} - - ) - )} -
    -
    - {clock.time} - {clock.date} -
    -
    - - ) -} diff --git a/packages/ui/overlay-engine/src/scene/use-overlay-scenes.ts b/packages/ui/overlay-engine/src/scene/use-overlay-scenes.ts index bf20809..a1a179a 100644 --- a/packages/ui/overlay-engine/src/scene/use-overlay-scenes.ts +++ b/packages/ui/overlay-engine/src/scene/use-overlay-scenes.ts @@ -1,7 +1,7 @@ "use client" import {useCallback, useEffect, useRef, useState} from "react" -import type {GuildOverlay, OverlayLink, OverlayScene} from "@streamcat/interfaces" +import type {GuildOverlay, OverlayLink, OverlayScene, OverlayTheme} from "@streamcat/interfaces" import {isAuthError, postJson, type OverlayRequest} from "../api/transport" import {useLayoutHistory} from "../history/use-layout-history" @@ -113,11 +113,11 @@ export function useOverlayScenes(basePath: string, request: OverlayRequest, demo setError(null) } - function createScene(name: string, scene: OverlayScene) { + function createScene(name: string, scene: OverlayScene, theme: OverlayTheme = "default") { return run("create", async (signal) => { const result = await request<{overlay: GuildOverlay; browserSourceUrl: string}>( `${path}/scenes`, - postJson({name, scene}, signal) + postJson({name, scene, theme}, signal) ) if (signal.aborted) return setOverlay(result.overlay) diff --git a/packages/ui/overlay-engine/src/styles/editor.css b/packages/ui/overlay-engine/src/styles/editor.css index 8bbe53c..707987e 100644 --- a/packages/ui/overlay-engine/src/styles/editor.css +++ b/packages/ui/overlay-engine/src/styles/editor.css @@ -978,9 +978,6 @@ padding: var(--space-1) var(--space-2); cursor: pointer; } -.overlay-scene-toggle { - margin: var(--space-2) 0; -} .overlay-switch-confirm .actions { margin-top: var(--space-3); } @@ -1108,6 +1105,9 @@ background: var(--color-paper-3); } .overlay-add-widget-glyph { + display: inline-flex; + align-items: center; + justify-content: center; color: var(--color-ink-2); font-size: 16px; line-height: 1; diff --git a/packages/ui/overlay-engine/src/styles/renderer.css b/packages/ui/overlay-engine/src/styles/renderer.css index 69af2b6..b2de07f 100644 --- a/packages/ui/overlay-engine/src/styles/renderer.css +++ b/packages/ui/overlay-engine/src/styles/renderer.css @@ -1,4 +1,3 @@ -/* Shared editor/OBS rendering. */ .overlay-renderer { position: relative; background: transparent; @@ -8,8 +7,10 @@ --gradient-end: #e88a98; --window-bg: #1b191c; --progress-color: #1db954; + --scene-text: #ffffff; isolation: isolate; } + .overlay-widget { position: absolute; border-radius: 10.8px; @@ -18,38 +19,13 @@ line-height: 1.3; filter: var(--widget-shadow, drop-shadow(-9.6px 10.8px 5px #00000080)); } -.overlay-chat { - width: 133.333%; - height: 133.333%; - border: 0; - display: block; - color-scheme: normal; - background: transparent; - transform: scale(0.75); - transform-origin: 0 0; -} -.overlay-chat-plain { - width: 100%; - height: 100%; + +.overlay-widget--frameless { + border-radius: 0; + filter: none; overflow: hidden; - border-radius: inherit; -} -.overlay-chat-unavailable { - display: flex; - height: 100%; - flex-direction: column; - justify-content: center; - padding: 28px; - gap: 14px; -} -.overlay-chat-unavailable span { - font-size: 17px; - letter-spacing: 2px; - opacity: 0.7; -} -.overlay-chat-unavailable strong { - font-size: 30px; } + @font-face { font-family: Tiny5; font-style: normal; @@ -57,6 +33,7 @@ font-display: swap; src: url("./fonts/tiny5.ttf") format("truetype"); } + @font-face { font-family: "Jersey 10"; font-style: normal; @@ -64,370 +41,34 @@ font-display: swap; src: url("./fonts/jersey10.ttf") format("truetype"); } + .overlay-font-jersey10 { font-family: "Jersey 10", monospace; } + .overlay-theme-autumn { --gradient-start: #e07a2f; --gradient-end: #6b1d2f; --window-bg: #220901; --progress-color: #941b0c; + --scene-text: #f6aa1c; } + .overlay-theme-winter { --gradient-start: #2c3e50; --gradient-end: #7fb3d8; --window-bg: #494d4a; --progress-color: #7a879a; + --scene-text: #d3d2c6; } + .overlay-theme-light { --gradient-start: #cfc3e6; --gradient-end: #f6d5dd; --window-bg: #e4ddeb; + --scene-text: #171821; } + .overlay-theme-glass { --window-bg: #1b191c80; } -.overlay-design-glass { - border: none; -} -.overlay-window { - width: 100%; - height: 100%; - display: flex; - flex-direction: column; - border-radius: var(--window-corner-radius); - overflow: hidden; - backdrop-filter: blur(5px); -} -.overlay-window-header { - flex: 0 0 var(--window-header-height); - min-height: 0; - display: flex; - justify-content: space-between; - align-items: center; - padding: 3.24px 13.44px; - background: var(--window-bg); - font-size: 27px; - line-height: 1; -} -.overlay-window-header > span { - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; -} -.overlay-window-controls { - display: flex; - flex-shrink: 0; - width: 57.6px; - justify-content: space-between; -} -.overlay-window-controls i { - width: 14.4px; - height: 14.4px; - border-radius: 50%; - background: #3f3d42; -} -.overlay-window-controls i:last-child { - background: #9f1f0a; -} -.overlay-window-content { - flex: 1; - min-height: 0; - border: var(--window-content-border) solid var(--window-bg); - border-top: none; - overflow: hidden; -} -.overlay-spotify { - display: flex; - align-items: stretch; - padding: 19.2px; - gap: 19.2px; - width: 100%; - height: 100%; -} -.overlay-album { - width: auto; - max-width: 45%; - height: 100%; - max-height: none; - aspect-ratio: 1; - object-fit: contain; - border-radius: 10.8px; - flex-shrink: 0; - animation: overlay-artwork-in 0.5s ease-out; -} -.overlay-album-placeholder { - display: grid; - place-items: center; - background: var(--window-bg, #1b191c); - border: 1px solid #ffffff24; - color: var(--color-muted, #929292); - font-family: var(--font-body, monospace); - font-size: 64px; - line-height: 1; -} -@keyframes overlay-artwork-in { - from { - opacity: 0; - } - to { - opacity: 1; - } -} -.overlay-track-info { - display: flex; - flex-direction: column; - justify-content: flex-end; - align-items: stretch; - min-width: 0; - flex: 1; - overflow: hidden; -} -.overlay-spectrum { - width: 100%; - min-height: 0; - flex: 1; - display: block; -} -.overlay-spectrum-simulated { - display: flex; - align-items: flex-end; - gap: 1px; - overflow: hidden; -} -.overlay-spectrum-simulated i { - flex: 1; - height: 100%; - background: currentColor; - transform-origin: bottom; -} -.overlay-title-viewport { - overflow: hidden; - flex: none; -} -.overlay-track-title, -.overlay-track-artist { - display: block; - white-space: nowrap; - overflow: hidden; - margin-bottom: 8px; - flex: none; -} -.overlay-track-title { - font-size: 37.8px; - font-weight: bold; -} -.overlay-title-text { - display: inline-block; -} -.overlay-track-title.scrolling { - display: inline-block; - overflow: visible; - padding-left: 100%; - animation: overlay-scroll-text 10s linear infinite; -} -.overlay-track-artist { - font-size: 24.84px; - text-overflow: ellipsis; -} -@keyframes overlay-scroll-text { - from { - transform: translateX(0); - } - to { - transform: translateX(-100%); - } -} -.overlay-progress { - width: 100%; - height: 5.4px; - background: currentColor; - border-radius: 2.7px; - flex: none; - overflow: hidden; -} -.overlay-progress[hidden] { - display: none; -} -.overlay-progress-fill { - width: 0; - height: 100%; - background: var(--progress-color); - border-radius: inherit; - transition: width 1s linear; -} -.overlay-scene-background { - position: absolute; - inset: 0; - overflow: hidden; -} -.overlay-gradient { - position: absolute; - width: 2554px; - height: 2554px; - top: 50%; - left: 50%; - background: linear-gradient(45deg, var(--gradient-start), var(--gradient-end)); - animation: overlay-rotate 15s linear infinite; -} -@keyframes overlay-rotate { - from { - transform: translate(-50%, -50%) rotate(0); - } - to { - transform: translate(-50%, -50%) rotate(360deg); - } -} -.overlay-scene-title { - position: absolute; - left: 96px; - top: 54px; - color: var(--scene-text, #ffffff); - font-size: 134.4px; - font-weight: bold; - filter: drop-shadow(-9.6px 10.8px 5px #00000080); -} -.overlay-scene-title span { - display: inline-block; - animation: overlay-bounce 1.4s infinite; -} -.overlay-scene-title span:nth-child(2) { - animation-delay: 0.2s; -} -.overlay-scene-title span:nth-child(3) { - animation-delay: 0.4s; -} -@keyframes overlay-bounce { - 0%, - 100% { - transform: translateY(0); - } - 50% { - transform: translateY(10px); - } -} -.overlay-taskbar { - position: absolute; - bottom: 0; - left: 0; - right: 0; - height: 54px; - display: flex; - justify-content: space-between; - align-items: center; - padding: 0 20px; - color: var(--scene-text, #ffffff); - background: var(--window-bg); - font-size: 27px; -} -.overlay-taskbar > div { - display: flex; - flex-direction: column; - align-items: center; - font-size: 21.6px; -} -.overlay-theme-autumn .overlay-scene-title, -.overlay-theme-autumn .overlay-taskbar { - color: #f6aa1c; -} -.overlay-theme-winter .overlay-scene-title, -.overlay-theme-winter .overlay-taskbar { - color: #d3d2c6; -} -.overlay-theme-light .overlay-scene-title, -.overlay-theme-light .overlay-taskbar { - color: #171821; -} - -.overlay-renderer[style*="--scene-text"] .overlay-scene-title, -.overlay-renderer[style*="--scene-text"] .overlay-taskbar { - color: var(--scene-text); -} -@media (prefers-reduced-motion: reduce) { - .overlay-gradient, - .overlay-track-title.scrolling, - .overlay-scene-title span { - animation: none; - } - .overlay-track-title.scrolling { - padding-left: 0; - } -} -.overlay-media-widget { - border-radius: 0; - filter: none; - overflow: hidden; -} -.overlay-media { - display: block; - width: 100%; - height: 100%; -} -.overlay-taskbar .overlay-social-links { - display: flex; - flex-direction: row; - gap: 38.4px; - min-width: 0; -} -.overlay-social-link { - display: flex; - align-items: center; - gap: 10px; - position: relative; - padding-bottom: 5px; - font-size: 27px; -} -.overlay-social-link::after { - content: ""; - position: absolute; - bottom: -10px; - height: 5px; - width: 100%; - background: var(--social-color); -} -.overlay-social-twitch { - --social-color: #9146ff; -} -.overlay-social-twitter { - --social-color: #1da1f2; -} -.overlay-social-discord { - --social-color: #5865f2; -} -.overlay-social-icon { - width: 32.4px; - height: 32.4px; - flex: none; - animation: overlay-social-pulse 9s infinite; -} -.overlay-social-twitter .overlay-social-icon { - animation-delay: 3s; -} -.overlay-social-discord .overlay-social-icon { - animation-delay: 6s; -} -@keyframes overlay-social-pulse { - 0%, - 30%, - 100% { - color: inherit; - } - 10%, - 20% { - color: var(--social-color); - } -} -@media (prefers-reduced-motion: reduce) { - .overlay-social-icon { - animation: none; - } -} -.overlay-social-link { - max-width: 460px; - overflow: hidden; - white-space: nowrap; -} -.overlay-scene-title, -.overlay-taskbar { - z-index: 1; -} diff --git a/packages/ui/overlay-engine/src/ui/dialog.tsx b/packages/ui/overlay-engine/src/ui/dialog.tsx index 782e80c..7550cbc 100644 --- a/packages/ui/overlay-engine/src/ui/dialog.tsx +++ b/packages/ui/overlay-engine/src/ui/dialog.tsx @@ -219,7 +219,8 @@ export function Select({ onChange, disabled, placeholder, - inline + inline, + searchable }: { label?: string value: string | null @@ -228,11 +229,25 @@ export function Select({ disabled?: boolean placeholder?: string inline?: boolean + searchable?: boolean }) { const [open, setOpen] = useState(false) + const [query, setQuery] = useState("") const fieldRef = useRef(null) const {rootRef, menuRef, rect} = useFloatingMenuRect(open, fieldRef, () => setOpen(false)) const selected = options.find((option) => option.value === value) ?? null + useEffect(() => { + if (!open) setQuery("") + }, [open]) + const normalizedQuery = query.trim().toLowerCase() + const visibleOptions = + searchable && normalizedQuery + ? options.filter( + (option) => + option.label.toLowerCase().includes(normalizedQuery) || + option.value.toLowerCase().includes(normalizedQuery) + ) + : options return (
    @@ -265,7 +280,19 @@ export function Select({ ...(rect.above ? {bottom: window.innerHeight - rect.top} : {top: rect.top}) }} > - {options.map((option) => ( + {searchable && ( +
  • + setQuery(event.target.value)} + /> +
  • + )} + {visibleOptions.map((option) => (
  • - {widget.type === "VIDEO" && ( + {asset?.kind === "VIDEO" && (

    Videos laufen automatisch, stumm und in einer Schleife.

    )} diff --git a/packages/ui/overlay-engine/src/widgets/progress/designs/bar/bar.css b/packages/ui/overlay-engine/src/widgets/progress/designs/bar/bar.css new file mode 100644 index 0000000..d8451f3 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/progress/designs/bar/bar.css @@ -0,0 +1,32 @@ +.overlay-progress-widget { + width: 100%; + height: 100%; + display: flex; + flex-direction: column; + justify-content: center; + gap: 8px; + color: var(--scene-text, inherit); +} + +.overlay-progress-head { + display: flex; + justify-content: space-between; + align-items: baseline; + gap: 12px; + font-size: 18px; +} + +.overlay-progress-track { + width: 100%; + height: 14px; + background: var(--progress-track, #ffffff33); + border-radius: 7px; + overflow: hidden; +} + +.overlay-progress-fill-widget { + height: 100%; + background: var(--progress-color, #1db954); + border-radius: inherit; + transition: width 0.4s ease-out; +} diff --git a/packages/ui/overlay-engine/src/widgets/progress/designs/bar/bar.tsx b/packages/ui/overlay-engine/src/widgets/progress/designs/bar/bar.tsx new file mode 100644 index 0000000..974d75f --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/progress/designs/bar/bar.tsx @@ -0,0 +1,25 @@ +import type {EditorWidget} from "@streamcat/interfaces" +import type {WidgetRenderProps} from "../../../types" +import "./bar.css" + +type ProgressWidget = Extract + +export function ProgressBarDesign({widget}: WidgetRenderProps) { + const params = (widget as ProgressWidget).params + const percent = params.target > 0 ? Math.min(100, Math.max(0, (params.current / params.target) * 100)) : 0 + return ( +
    +
    + {params.label} + {params.showValue && ( + + {params.current} / {params.target} + + )} +
    +
    +
    +
    +
    + ) +} diff --git a/packages/ui/overlay-engine/src/widgets/progress/designs/bar/index.ts b/packages/ui/overlay-engine/src/widgets/progress/designs/bar/index.ts new file mode 100644 index 0000000..5ab6634 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/progress/designs/bar/index.ts @@ -0,0 +1,20 @@ +import type {WidgetColorControl, WidgetDesign} from "../../../types" +import {ProgressBarDesign} from "./bar" + +export const progressBarControls = [ + {key: "--scene-text", label: "Text"}, + {key: "--progress-color", label: "Fortschritt"}, + {key: "--progress-track", label: "Leiste"} +] as const satisfies readonly WidgetColorControl[] + +export const progressBarDesign: WidgetDesign = { + id: "bar", + label: "Leiste", + color: "#ffffff", + backgroundColor: "transparent", + tokens: { + "--progress-track": "#ffffff33" + }, + colorControls: progressBarControls, + component: ProgressBarDesign +} diff --git a/packages/ui/overlay-engine/src/widgets/progress/index.ts b/packages/ui/overlay-engine/src/widgets/progress/index.ts new file mode 100644 index 0000000..ab99da9 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/progress/index.ts @@ -0,0 +1,32 @@ +import type {EditorWidget} from "@streamcat/interfaces" +import type {WidgetModule} from "../types" +import {progressBarDesign} from "./designs/bar" +import {ProgressGlyph} from "./logic/progress-glyph" +import {ProgressSettings} from "./logic/progress-settings" + +function progressLabel(widget: EditorWidget) { + if (widget.type !== "PROGRESS") return "Fortschritt" + return widget.params.label || "Fortschritt" +} + +export const progressModule: WidgetModule = { + type: "PROGRESS", + label: "Fortschritt", + description: "Manueller Fortschrittsbalken für Ziele und Meilensteine.", + category: "Szene", + glyph: ProgressGlyph, + addable: true, + defaultDesign: "bar", + designs: { + bar: progressBarDesign + }, + settings: ProgressSettings, + sectionLabel: "Fortschritt", + sectionSummary: (widget) => { + if (widget.type !== "PROGRESS") return null + return `${widget.params.current} / ${widget.params.target}` + }, + nameFor: (widget) => progressLabel(widget), + titleFor: () => "Fortschritt", + frame: "widget" +} diff --git a/packages/ui/overlay-engine/src/widgets/progress/logic/progress-glyph.tsx b/packages/ui/overlay-engine/src/widgets/progress/logic/progress-glyph.tsx new file mode 100644 index 0000000..b4dd611 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/progress/logic/progress-glyph.tsx @@ -0,0 +1,15 @@ +export function ProgressGlyph() { + return ( + + ) +} diff --git a/packages/ui/overlay-engine/src/widgets/progress/logic/progress-settings.tsx b/packages/ui/overlay-engine/src/widgets/progress/logic/progress-settings.tsx new file mode 100644 index 0000000..3d96299 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/progress/logic/progress-settings.tsx @@ -0,0 +1,59 @@ +import type {EditorWidget} from "@streamcat/interfaces" +import type {WidgetSettingsProps} from "../../types" + +export function ProgressSettings({widget: value, onChange}: WidgetSettingsProps) { + const widget = value as Extract + return ( + <> + + + + + + ) +} diff --git a/packages/ui/overlay-engine/src/widgets/registry.ts b/packages/ui/overlay-engine/src/widgets/registry.ts index 85454ec..bed8ebd 100644 --- a/packages/ui/overlay-engine/src/widgets/registry.ts +++ b/packages/ui/overlay-engine/src/widgets/registry.ts @@ -1,21 +1,39 @@ -import type {EditorWidgetType} from "@streamcat/interfaces" +import type {WidgetType} from "@streamcat/interfaces" import type {WidgetModule} from "./types" -import {imageModule, videoModule} from "./media" +import {backgroundModule} from "./background" +import {clockModule} from "./clock" +import {countdownModule} from "./countdown" +import {mediaModule} from "./media" +import {progressModule} from "./progress" +import {shapeModule} from "./shape" +import {socialsModule} from "./socials" import {spotifyModule} from "./spotify" +import {textModule} from "./text" +import {tickerModule} from "./ticker" import {twitchChatModule} from "./twitch-chat" import {windowModule} from "./window" -export const WIDGET_MODULES: Record = { +export const WIDGET_MODULES: Record = { SPOTIFY_NOW_PLAYING: spotifyModule, TWITCH_CHAT: twitchChatModule, WINDOW: windowModule, - IMAGE: imageModule, - VIDEO: videoModule + MEDIA: mediaModule, + BACKGROUND: backgroundModule, + TEXT: textModule, + CLOCK: clockModule, + SOCIALS: socialsModule, + SHAPE: shapeModule, + COUNTDOWN: countdownModule, + TICKER: tickerModule, + PROGRESS: progressModule } -export const WIDGET_CATALOG_TYPES = ["SPOTIFY_NOW_PLAYING", "TWITCH_CHAT", "WINDOW"] as const -export type AddableWidgetType = (typeof WIDGET_CATALOG_TYPES)[number] +export const WIDGET_CATALOG_TYPES = Object.values(WIDGET_MODULES) + .filter((module) => module.addable) + .map((module) => module.type) -export function widgetModule(type: EditorWidgetType): WidgetModule { +export type AddableWidgetType = WidgetType + +export function widgetModule(type: WidgetType): WidgetModule { return WIDGET_MODULES[type] } diff --git a/packages/ui/overlay-engine/src/widgets/settings.tsx b/packages/ui/overlay-engine/src/widgets/settings.tsx index a83fb7f..c35850e 100644 --- a/packages/ui/overlay-engine/src/widgets/settings.tsx +++ b/packages/ui/overlay-engine/src/widgets/settings.tsx @@ -4,12 +4,11 @@ import {useState} from "react" import {SidebarSection, Select} from "../ui/dialog" import { OVERLAY_COLOR_TEMPLATES, - OVERLAY_WIDTH, OVERLAY_HEIGHT, + OVERLAY_THEME_COLORS, + OVERLAY_WIDTH, MIN_WIDGET_WIDTH, MIN_WIDGET_HEIGHT, - TWITCH_CHAT_DEFAULTS, - TWITCH_CHAT_FONTS, withWidgetColors, windowWidth, windowHeight, @@ -45,51 +44,6 @@ function withDesignColor(widget: T, key: `--${string}`, } } -function moduleSectionLabel(type: EditorWidget["type"]) { - if (type === "SPOTIFY_NOW_PLAYING") return "Audio Einstellungen" - if (type === "TWITCH_CHAT") return "Overlay Einstellungen" - if (type === "WINDOW") return "Fenster" - if (type === "IMAGE" || type === "VIDEO") return "Bild Einstellungen" - return "Einstellungen" -} - -function moduleSectionSummary(widget: EditorWidget, assets: OverlayAsset[]) { - switch (widget.type) { - case "TWITCH_CHAT": { - const fontName = - typeof widget.params.chatFont === "number" - ? (TWITCH_CHAT_FONTS[widget.params.chatFont] ?? "Schrift") - : (widget.params.chatFont ?? "Schrift") - const fade = widget.params.chatFade ?? TWITCH_CHAT_DEFAULTS.chatFade - return `${widget.params.chatChannel || "Kanal"} - ${fontName} - Fade ${fade}s` - } - case "SPOTIFY_NOW_PLAYING": { - if (widget.params.spectralizer !== true) return "Spektrum aus" - const mode = widget.params.spectrumMode === "simulated" ? "Simuliert" : "Audioeingang" - const audio = - widget.params.spectrumMode === "audio" - ? ` // Audio: ${widget.params.audioDeviceName || "Standard"}` - : "" - return `Spektrum an // Modus: ${mode}${audio}` - } - case "WINDOW": { - const title = widget.params.title || "Fenstertitel" - const ratio = widget.params.lockContentAspectRatio === true ? "16:9" : "Frei" - const green = widget.params.greenScreen === true ? "Greenscreen" : "Kein Greenscreen" - return `${title} - ${ratio} - ${green}` - } - case "IMAGE": - case "VIDEO": { - const asset = widget.params.assetId ? assets.find((item) => item.id === widget.params.assetId) : null - const name = asset?.fileName ?? (widget.type === "VIDEO" ? "Video" : "Bild") - const fit = widget.params.fit === "cover" ? "Fläche ausfüllen" : "Ganzes Bild" - return `${name} - ${fit}` - } - default: - return null - } -} - export function WidgetSettings({ widget, assets = [], @@ -115,16 +69,21 @@ export function WidgetSettings({ theme?: OverlayTheme themeColors?: OverlayLayout["themeColors"] }) { + const locked = widget.type === "WINDOW" && widget.params.lockContentAspectRatio === true + const module = widgetModule(widget.type) + const Settings = module.settings + const design = module.designs[widget.params.design] ?? module.designs[module.defaultDesign] const themeTemplate = OVERLAY_COLOR_TEMPLATES[theme === "default" ? "standard" : theme] + const themePalette = OVERLAY_THEME_COLORS[theme] const themeColor = (key: `--${string}`): string | undefined => { if (key === "--window-bg") return themeColors?.window ?? themeTemplate.tokens?.["--window-bg"] if (key === "--progress-color") return themeColors?.primary ?? themeTemplate.tokens?.["--progress-color"] + if (key === "--gradient-start") return themeColors?.surface ?? themePalette.gradientStart + if (key === "--gradient-end") return themeColors?.secondary ?? themePalette.gradientEnd + if (key === "--scene-text" || key === "--clock-date-color" || key === "--countdown-label-color") + return themeColors?.text ?? themePalette.color return undefined } - const locked = widget.type === "WINDOW" && widget.params.lockContentAspectRatio === true - const module = widgetModule(widget.type) - const Settings = module.settings - const design = module.designs[widget.params.design] ?? module.designs[module.defaultDesign] const [renaming, setRenaming] = useState(false) const [renameValue, setRenameValue] = useState("") const limits = { @@ -170,7 +129,7 @@ export function WidgetSettings({ onChange({...widget, [field]: Math.min(limits[field][1], Math.max(limits[field][0], parsedValue))}) } - const summary = moduleSectionSummary(widget, assets) + const summary = module.sectionSummary?.(widget, assets) ?? null return (
    @@ -311,7 +270,7 @@ export function WidgetSettings({
    - +
    + +export function ShapeEllipseDesign({widget}: WidgetRenderProps) { + return +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/designs/ellipse/index.ts b/packages/ui/overlay-engine/src/widgets/shape/designs/ellipse/index.ts new file mode 100644 index 0000000..1e24235 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/designs/ellipse/index.ts @@ -0,0 +1,19 @@ +import type {WidgetColorControl, WidgetDesign} from "../../../types" +import {ShapeEllipseDesign} from "./ellipse" + +export const shapeEllipseControls = [ + {key: "--window-bg", label: "Fläche"}, + {key: "--shape-border", label: "Rahmen"} +] as const satisfies readonly WidgetColorControl[] + +export const shapeEllipseDesign: WidgetDesign = { + id: "ellipse", + label: "Ellipse", + color: "#ffffff", + backgroundColor: "transparent", + tokens: { + "--shape-border": "transparent" + }, + colorControls: shapeEllipseControls, + component: ShapeEllipseDesign +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/designs/line/index.ts b/packages/ui/overlay-engine/src/widgets/shape/designs/line/index.ts new file mode 100644 index 0000000..d439569 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/designs/line/index.ts @@ -0,0 +1,19 @@ +import type {WidgetColorControl, WidgetDesign} from "../../../types" +import {ShapeLineDesign} from "./line" + +export const shapeLineControls = [ + {key: "--window-bg", label: "Linie"}, + {key: "--shape-border", label: "Rahmen"} +] as const satisfies readonly WidgetColorControl[] + +export const shapeLineDesign: WidgetDesign = { + id: "line", + label: "Linie", + color: "#ffffff", + backgroundColor: "transparent", + tokens: { + "--shape-border": "transparent" + }, + colorControls: shapeLineControls, + component: ShapeLineDesign +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/designs/line/line.css b/packages/ui/overlay-engine/src/widgets/shape/designs/line/line.css new file mode 100644 index 0000000..6c3c9f7 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/designs/line/line.css @@ -0,0 +1,3 @@ +.overlay-shape--line { + border-radius: 999px; +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/designs/line/line.tsx b/packages/ui/overlay-engine/src/widgets/shape/designs/line/line.tsx new file mode 100644 index 0000000..7744540 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/designs/line/line.tsx @@ -0,0 +1,10 @@ +import type {EditorWidget} from "@streamcat/interfaces" +import type {WidgetRenderProps} from "../../../types" +import {ShapeContent} from "../../logic/shape-content" +import "./line.css" + +type ShapeWidget = Extract + +export function ShapeLineDesign({widget}: WidgetRenderProps) { + return +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/designs/rect/index.ts b/packages/ui/overlay-engine/src/widgets/shape/designs/rect/index.ts new file mode 100644 index 0000000..a076661 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/designs/rect/index.ts @@ -0,0 +1,19 @@ +import type {WidgetColorControl, WidgetDesign} from "../../../types" +import {ShapeRectDesign} from "./rect" + +export const shapeRectControls = [ + {key: "--window-bg", label: "Füllung"}, + {key: "--shape-border", label: "Rahmen"} +] as const satisfies readonly WidgetColorControl[] + +export const shapeRectDesign: WidgetDesign = { + id: "rect", + label: "Rechteck", + color: "#ffffff", + backgroundColor: "transparent", + tokens: { + "--shape-border": "transparent" + }, + colorControls: shapeRectControls, + component: ShapeRectDesign +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/designs/rect/rect.css b/packages/ui/overlay-engine/src/widgets/shape/designs/rect/rect.css new file mode 100644 index 0000000..248eaca --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/designs/rect/rect.css @@ -0,0 +1,3 @@ +.overlay-shape--rect { + border-radius: var(--shape-radius, 0); +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/designs/rect/rect.tsx b/packages/ui/overlay-engine/src/widgets/shape/designs/rect/rect.tsx new file mode 100644 index 0000000..13730bc --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/designs/rect/rect.tsx @@ -0,0 +1,10 @@ +import type {EditorWidget} from "@streamcat/interfaces" +import type {WidgetRenderProps} from "../../../types" +import {ShapeContent} from "../../logic/shape-content" +import "./rect.css" + +type ShapeWidget = Extract + +export function ShapeRectDesign({widget}: WidgetRenderProps) { + return +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/designs/shape-base.css b/packages/ui/overlay-engine/src/widgets/shape/designs/shape-base.css new file mode 100644 index 0000000..41c2cd6 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/designs/shape-base.css @@ -0,0 +1,8 @@ +.overlay-shape { + width: 100%; + height: 100%; + box-sizing: border-box; + background: var(--window-bg); + border: 1px solid var(--shape-border, transparent); + border-radius: var(--shape-radius, 0); +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/index.ts b/packages/ui/overlay-engine/src/widgets/shape/index.ts new file mode 100644 index 0000000..dc31dcb --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/index.ts @@ -0,0 +1,33 @@ +import type {EditorWidget} from "@streamcat/interfaces" +import type {WidgetModule} from "../types" +import {shapeEllipseDesign} from "./designs/ellipse" +import {shapeLineDesign} from "./designs/line" +import {shapeRectDesign} from "./designs/rect" +import {ShapeGlyph} from "./logic/shape-glyph" +import {ShapeSettings} from "./logic/shape-settings" + +function shapeSummary(widget: EditorWidget) { + if (widget.type !== "SHAPE") return null + return `Radius ${widget.params.radius} - Deckkraft ${widget.params.opacity}` +} + +export const shapeModule: WidgetModule = { + type: "SHAPE", + label: "Form", + description: "Taskbar, Linie, Fläche oder Ellipse.", + category: "Szene", + glyph: ShapeGlyph, + addable: true, + defaultDesign: "rect", + designs: { + rect: shapeRectDesign, + line: shapeLineDesign, + ellipse: shapeEllipseDesign + }, + settings: ShapeSettings, + sectionLabel: "Form", + sectionSummary: shapeSummary, + nameFor: () => "Form", + titleFor: () => "Form", + frame: "none" +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/logic/shape-content.tsx b/packages/ui/overlay-engine/src/widgets/shape/logic/shape-content.tsx new file mode 100644 index 0000000..cfe0fc2 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/logic/shape-content.tsx @@ -0,0 +1,13 @@ +import type {CSSProperties} from "react" +import type {EditorWidget} from "@streamcat/interfaces" +import "../designs/shape-base.css" + +type ShapeWidget = Extract + +export function ShapeContent({widget, variant}: {widget: ShapeWidget; variant: "rect" | "line" | "ellipse"}) { + const style = { + "--shape-radius": `${widget.params.radius}px`, + opacity: widget.params.opacity + } as CSSProperties + return
    +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/logic/shape-glyph.tsx b/packages/ui/overlay-engine/src/widgets/shape/logic/shape-glyph.tsx new file mode 100644 index 0000000..fb75db1 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/logic/shape-glyph.tsx @@ -0,0 +1,14 @@ +export function ShapeGlyph() { + return ( + + ) +} diff --git a/packages/ui/overlay-engine/src/widgets/shape/logic/shape-settings.tsx b/packages/ui/overlay-engine/src/widgets/shape/logic/shape-settings.tsx new file mode 100644 index 0000000..a7f07d3 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shape/logic/shape-settings.tsx @@ -0,0 +1,38 @@ +import type {EditorWidget} from "@streamcat/interfaces" +import type {WidgetSettingsProps} from "../../types" + +export function ShapeSettings({widget: value, onChange}: WidgetSettingsProps) { + const widget = value as Extract + return ( + <> + + + + ) +} diff --git a/packages/ui/overlay-engine/src/widgets/shared/widget-layers.tsx b/packages/ui/overlay-engine/src/widgets/shared/widget-layers.tsx index f736e05..4c7c7e1 100644 --- a/packages/ui/overlay-engine/src/widgets/shared/widget-layers.tsx +++ b/packages/ui/overlay-engine/src/widgets/shared/widget-layers.tsx @@ -2,6 +2,7 @@ import {useState} from "react" import {isMediaWidget, type EditorWidget, type OverlayAsset, type OverlayLayout} from "@streamcat/interfaces" +import {widgetModule} from "../registry" import {widgetName} from "./widget-name" export function moveWidgetToBackground(layout: OverlayLayout, widgetId: string): OverlayLayout { @@ -29,83 +30,6 @@ export function moveWidgetToBackground(layout: OverlayLayout, widgetId: string): } } -function glyphFor(type: EditorWidget["type"]) { - if (type === "SPOTIFY_NOW_PLAYING") - return ( - - ) - if (type === "TWITCH_CHAT") - return ( - - ) - if (type === "WINDOW") - return ( - - ) - if (type === "VIDEO") - return ( - - ) - return ( - - ) -} - function DragHandleGlyph() { return ( { const hidden = widget.hidden === true const renaming = renamingId === widget.id + const Glyph = widgetModule(widget.type).glyph return (
    {renaming ? ( item.id === widget.params.assetId) : undefined - return asset ? `${name} · ${asset.fileName}` : name + const module = widgetModule(widget.type) + return module.nameFor?.(widget, assets) ?? module.label } diff --git a/packages/ui/overlay-engine/src/widgets/shared/window-frame.css b/packages/ui/overlay-engine/src/widgets/shared/window-frame.css new file mode 100644 index 0000000..a6ec20c --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/shared/window-frame.css @@ -0,0 +1,53 @@ +.overlay-window { + width: 100%; + height: 100%; + display: flex; + flex-direction: column; + border-radius: var(--window-corner-radius); + overflow: hidden; + backdrop-filter: blur(5px); +} + +.overlay-window-header { + flex: 0 0 var(--window-header-height); + min-height: 0; + display: flex; + justify-content: space-between; + align-items: center; + padding: 3.24px 13.44px; + background: var(--window-bg); + font-size: 27px; + line-height: 1; +} + +.overlay-window-header > span { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.overlay-window-controls { + display: flex; + flex-shrink: 0; + width: 57.6px; + justify-content: space-between; +} + +.overlay-window-controls i { + width: 14.4px; + height: 14.4px; + border-radius: 50%; + background: #3f3d42; +} + +.overlay-window-controls i:last-child { + background: #9f1f0a; +} + +.overlay-window-content { + flex: 1; + min-height: 0; + border: var(--window-content-border) solid var(--window-bg); + border-top: none; + overflow: hidden; +} diff --git a/packages/ui/overlay-engine/src/widgets/shared/window-frame.tsx b/packages/ui/overlay-engine/src/widgets/shared/window-frame.tsx index 4eace13..8788b00 100644 --- a/packages/ui/overlay-engine/src/widgets/shared/window-frame.tsx +++ b/packages/ui/overlay-engine/src/widgets/shared/window-frame.tsx @@ -1,5 +1,6 @@ import type {CSSProperties, ReactNode} from "react" import {WINDOW_HEADER_HEIGHT, WINDOW_CONTENT_BORDER, WINDOW_CORNER_RADIUS} from "@streamcat/interfaces" +import "./window-frame.css" const geometry = { "--window-header-height": `${WINDOW_HEADER_HEIGHT}px`, diff --git a/packages/ui/overlay-engine/src/widgets/socials/designs/icons/icons.css b/packages/ui/overlay-engine/src/widgets/socials/designs/icons/icons.css new file mode 100644 index 0000000..d430067 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/designs/icons/icons.css @@ -0,0 +1,3 @@ +.overlay-socials--icons { + gap: 20px; +} diff --git a/packages/ui/overlay-engine/src/widgets/socials/designs/icons/icons.tsx b/packages/ui/overlay-engine/src/widgets/socials/designs/icons/icons.tsx new file mode 100644 index 0000000..5be91ba --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/designs/icons/icons.tsx @@ -0,0 +1,10 @@ +import type {EditorWidget} from "@streamcat/interfaces" +import type {WidgetRenderProps} from "../../../types" +import {SocialsContent} from "../../logic/socials-content" +import "./icons.css" + +type SocialsWidget = Extract + +export function SocialsIconsDesign({widget, chat}: WidgetRenderProps) { + return +} diff --git a/packages/ui/overlay-engine/src/widgets/socials/designs/icons/index.ts b/packages/ui/overlay-engine/src/widgets/socials/designs/icons/index.ts new file mode 100644 index 0000000..b400020 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/designs/icons/index.ts @@ -0,0 +1,23 @@ +import type {WidgetColorControl, WidgetDesign} from "../../../types" +import {SocialsIconsDesign} from "./icons" + +export const socialsIconsControls = [ + {key: "--scene-text", label: "Symbole"}, + {key: "--socials-twitch", label: "Twitch"}, + {key: "--socials-twitter", label: "Twitter"}, + {key: "--socials-discord", label: "Discord"} +] as const satisfies readonly WidgetColorControl[] + +export const socialsIconsDesign: WidgetDesign = { + id: "icons", + label: "Nur Symbole", + color: "#ffffff", + backgroundColor: "transparent", + tokens: { + "--socials-twitch": "#9146ff", + "--socials-twitter": "#1da1f2", + "--socials-discord": "#5865f2" + }, + colorControls: socialsIconsControls, + component: SocialsIconsDesign +} diff --git a/packages/ui/overlay-engine/src/widgets/socials/designs/inline/index.ts b/packages/ui/overlay-engine/src/widgets/socials/designs/inline/index.ts new file mode 100644 index 0000000..b6bec85 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/designs/inline/index.ts @@ -0,0 +1,23 @@ +import type {WidgetColorControl, WidgetDesign} from "../../../types" +import {SocialsInlineDesign} from "./inline" + +export const socialsInlineControls = [ + {key: "--scene-text", label: "Text"}, + {key: "--socials-twitch", label: "Twitch"}, + {key: "--socials-twitter", label: "Twitter"}, + {key: "--socials-discord", label: "Discord"} +] as const satisfies readonly WidgetColorControl[] + +export const socialsInlineDesign: WidgetDesign = { + id: "inline", + label: "Mit Text", + color: "#ffffff", + backgroundColor: "transparent", + tokens: { + "--socials-twitch": "#9146ff", + "--socials-twitter": "#1da1f2", + "--socials-discord": "#5865f2" + }, + colorControls: socialsInlineControls, + component: SocialsInlineDesign +} diff --git a/packages/ui/overlay-engine/src/widgets/socials/designs/inline/inline.css b/packages/ui/overlay-engine/src/widgets/socials/designs/inline/inline.css new file mode 100644 index 0000000..e3e7273 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/designs/inline/inline.css @@ -0,0 +1,3 @@ +.overlay-socials--inline { + padding-bottom: 10px; +} diff --git a/packages/ui/overlay-engine/src/widgets/socials/designs/inline/inline.tsx b/packages/ui/overlay-engine/src/widgets/socials/designs/inline/inline.tsx new file mode 100644 index 0000000..1f22c20 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/designs/inline/inline.tsx @@ -0,0 +1,10 @@ +import type {EditorWidget} from "@streamcat/interfaces" +import type {WidgetRenderProps} from "../../../types" +import {SocialsContent} from "../../logic/socials-content" +import "./inline.css" + +type SocialsWidget = Extract + +export function SocialsInlineDesign({widget, chat}: WidgetRenderProps) { + return +} diff --git a/packages/ui/overlay-engine/src/widgets/socials/designs/socials-base.css b/packages/ui/overlay-engine/src/widgets/socials/designs/socials-base.css new file mode 100644 index 0000000..ab58366 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/designs/socials-base.css @@ -0,0 +1,84 @@ +.overlay-socials { + width: 100%; + height: 100%; + display: flex; + align-items: center; + color: var(--scene-text, inherit); + font-size: 27px; +} + +.overlay-socials--row { + flex-direction: row; + gap: 38.4px; +} + +.overlay-socials--column { + flex-direction: column; + align-items: flex-start; + gap: 8px; +} + +.overlay-socials-link { + display: flex; + align-items: center; + gap: 10px; + position: relative; + padding-bottom: 5px; + max-width: 460px; + overflow: hidden; + white-space: nowrap; +} + +.overlay-socials--inline .overlay-socials-link::after { + content: ""; + position: absolute; + bottom: -10px; + height: 5px; + width: 100%; + background: var(--social-color); +} + +.overlay-socials-link.overlay-socials-twitch { + --social-color: var(--socials-twitch, #9146ff); +} + +.overlay-socials-link.overlay-socials-twitter { + --social-color: var(--socials-twitter, #1da1f2); +} + +.overlay-socials-link.overlay-socials-discord { + --social-color: var(--socials-discord, #5865f2); +} + +.overlay-socials-icon { + width: 32.4px; + height: 32.4px; + flex: none; + animation: overlay-socials-pulse 9s infinite; +} + +.overlay-socials-twitter .overlay-socials-icon { + animation-delay: 3s; +} + +.overlay-socials-discord .overlay-socials-icon { + animation-delay: 6s; +} + +@keyframes overlay-socials-pulse { + 0%, + 30%, + 100% { + color: var(--scene-text, inherit); + } + 10%, + 20% { + color: var(--social-color); + } +} + +@media (prefers-reduced-motion: reduce) { + .overlay-socials-icon { + animation: none; + } +} diff --git a/packages/ui/overlay-engine/src/widgets/socials/index.ts b/packages/ui/overlay-engine/src/widgets/socials/index.ts new file mode 100644 index 0000000..01a1604 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/index.ts @@ -0,0 +1,32 @@ +import type {EditorWidget} from "@streamcat/interfaces" +import type {WidgetModule} from "../types" +import {socialsIconsDesign} from "./designs/icons" +import {socialsInlineDesign} from "./designs/inline" +import {SocialsGlyph} from "./logic/socials-glyph" +import {SocialsSettings} from "./logic/socials-settings" + +function socialsSummary(widget: EditorWidget) { + if (widget.type !== "SOCIALS") return null + const values = [widget.params.twitch, widget.params.twitter, widget.params.discord].filter(Boolean) + return values.length ? values.join(" · ") : "Keine Handles" +} + +export const socialsModule: WidgetModule = { + type: "SOCIALS", + label: "Socials", + description: "Twitch-, Twitter- und Discord-Handles.", + category: "Szene", + glyph: SocialsGlyph, + addable: true, + defaultDesign: "inline", + designs: { + inline: socialsInlineDesign, + icons: socialsIconsDesign + }, + settings: SocialsSettings, + sectionLabel: "Socials", + sectionSummary: socialsSummary, + nameFor: () => "Socials", + titleFor: () => "Socials", + frame: "none" +} diff --git a/packages/ui/overlay-engine/src/widgets/socials/logic/socials-content.tsx b/packages/ui/overlay-engine/src/widgets/socials/logic/socials-content.tsx new file mode 100644 index 0000000..7f7a3cf --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/logic/socials-content.tsx @@ -0,0 +1,36 @@ +import type {EditorWidget, OverlayChat} from "@streamcat/interfaces" +import "../designs/socials-base.css" +import {SocialIcon} from "./socials-icons" + +type SocialsWidget = Extract + +export function SocialsContent({ + widget, + chat, + variant +}: { + widget: SocialsWidget + chat: OverlayChat + variant: "inline" | "icons" +}) { + const params = widget.params + const handles = { + twitch: params.twitch || (chat.channel ? `/${chat.channel}` : ""), + twitter: params.twitter, + discord: params.discord + } + const showLabels = variant === "inline" && params.showLabels + return ( +
    + {(["twitch", "twitter", "discord"] as const).map( + (provider) => + handles[provider] && ( + + {params.showIcons && } + {showLabels && {handles[provider]}} + + ) + )} +
    + ) +} diff --git a/packages/ui/overlay-engine/src/widgets/socials/logic/socials-glyph.tsx b/packages/ui/overlay-engine/src/widgets/socials/logic/socials-glyph.tsx new file mode 100644 index 0000000..db489f4 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/logic/socials-glyph.tsx @@ -0,0 +1,17 @@ +export function SocialsGlyph() { + return ( + + ) +} diff --git a/packages/ui/overlay-engine/src/widgets/socials/logic/socials-icons.tsx b/packages/ui/overlay-engine/src/widgets/socials/logic/socials-icons.tsx new file mode 100644 index 0000000..9ce5836 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/logic/socials-icons.tsx @@ -0,0 +1,14 @@ +export function SocialIcon({provider}: {provider: "twitch" | "twitter" | "discord"}) { + const paths = { + twitch: "M3 2 1 6v14h5v3h3l3-3h4l7-7V2H3Zm18 10-4 4h-5l-3 3v-3H5V4h16v8ZM15 6h2v6h-2V6Zm-5 0h2v6h-2V6Z", + twitter: + "M23 4.5a9 9 0 0 1-2.6.7 4.5 4.5 0 0 0 2-2.5 9 9 0 0 1-2.9 1.1 4.5 4.5 0 0 0-7.7 4.1A12.8 12.8 0 0 1 2.5 3.2a4.5 4.5 0 0 0 1.4 6 4.5 4.5 0 0 1-2-.6 4.5 4.5 0 0 0 3.6 4.5 4.5 4.5 0 0 1-2 .1 4.5 4.5 0 0 0 4.2 3.1A9 9 0 0 1 1 18.2a12.8 12.8 0 0 0 19.7-10.8v-.6A9 9 0 0 0 23 4.5Z", + discord: + "M20.3 4.6a19.6 19.6 0 0 0-4.8-1.5l-.6 1.3a18.3 18.3 0 0 0-5.8 0l-.6-1.3a19.7 19.7 0 0 0-4.8 1.5C.7 9 .0 13.4.4 17.7a19.7 19.7 0 0 0 6 3l1.2-2a12.7 12.7 0 0 1-1.9-.9l.5-.4a14.6 14.6 0 0 0 11.6 0l.5.4-1.9.9 1.2 2a19.7 19.7 0 0 0 6-3c.5-5-1-9.3-3.3-13.1ZM8 15.3c-1.1 0-2-1-2-2.3s.9-2.3 2-2.3 2 1 2 2.3-.9 2.3-2 2.3Zm8 0c-1.1 0-2-1-2-2.3s.9-2.3 2-2.3 2 1 2 2.3-.9 2.3-2 2.3Z" + } + return ( + + ) +} diff --git a/packages/ui/overlay-engine/src/widgets/socials/logic/socials-settings.tsx b/packages/ui/overlay-engine/src/widgets/socials/logic/socials-settings.tsx new file mode 100644 index 0000000..4c87954 --- /dev/null +++ b/packages/ui/overlay-engine/src/widgets/socials/logic/socials-settings.tsx @@ -0,0 +1,67 @@ +import type {EditorWidget} from "@streamcat/interfaces" +import type {WidgetSettingsProps} from "../../types" +import {Select} from "../../../ui/dialog" + +export function SocialsSettings({widget: value, onChange}: WidgetSettingsProps) { + const widget = value as Extract + return ( + <> + {(["twitch", "twitter", "discord"] as const).map((provider) => ( + + ))} + + onChange({...widget, params: {...widget.params, showLabels: event.target.checked}}) + } + /> +