Files
element-call/src/lotus/lotusDecorations.ts
T

81 lines
2.4 KiB
TypeScript
Raw Normal View History

/*
Copyright 2026 Lotus Guild
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { useSyncExternalStore } from "react";
import { type IWidgetApiRequest } from "matrix-widget-api";
import { widget } from "../widget";
import { LotusWidgetActions } from "./lotusActions";
/**
* Avatar decorations (#6 / A6). The Lotus host (cinny) owns the decoration
* roster (MSC4133 profile decorations) and can't draw them on EC's in-call
* video tiles from outside the iframe. So it pushes a `userId -> image URL`
* map via the `io.lotus.decorations` widget action, and the tile avatar
* component renders the overlay natively.
*/
let decorations: Readonly<Record<string, string>> = {};
const listeners = new Set<() => void>();
function emit(): void {
for (const l of listeners) l();
}
/** Subscribe a tile avatar to its participant's decoration URL (or undefined). */
export function useLotusDecoration(userId: string): string | undefined {
return useSyncExternalStore(
(cb) => {
listeners.add(cb);
return () => listeners.delete(cb);
},
() => decorations[userId],
);
}
function safeImageUrl(raw: unknown): string | null {
if (typeof raw !== "string") return null;
try {
const u = new URL(raw, window.location.href);
return u.protocol === "https:" || u.protocol === "blob:" ? u.href : null;
} catch {
return null;
}
}
/**
* Register the `io.lotus.decorations` handler. No effect unless the host sends
* the action. Returns a teardown function.
*/
export function startLotusDecorations(): () => void {
const w = widget;
if (!w) return () => undefined;
const handler = (ev: CustomEvent<IWidgetApiRequest>): void => {
void w.api.transport.reply(ev.detail, {});
const data = ev.detail.data as
| { decorations?: Record<string, unknown> }
| undefined;
const next: Record<string, string> = {};
if (data?.decorations && typeof data.decorations === "object") {
for (const [userId, url] of Object.entries(data.decorations)) {
const safe = safeImageUrl(url);
if (safe) next[userId] = safe;
}
}
decorations = next;
emit();
};
w.lazyActions.on(LotusWidgetActions.Decorations, handler);
return () => {
w.lazyActions.off(LotusWidgetActions.Decorations, handler);
decorations = {};
emit();
};
}