Apply the auto-fixable lint rules and the formatter, and drop the Vite build artifacts.
Checks / checks (push) Successful in 2m11s
Trigger cinny-mobile / dispatch (push) Successful in 1s

This commit is contained in:
2026-11-01 04:23:53 +11:00
parent 3cd159a63e
commit a6ad8651b3
605 changed files with 11480 additions and 9125 deletions
+5 -5
View File
@@ -39,7 +39,7 @@ export class ASCIILexicalTable {
console.warn(
`[!] Warning: ASCIILexicalTable size is larger than the Number.MAX_SAFE_INTEGER: ${this.size()} > ${
Number.MAX_SAFE_INTEGER
}`
}`,
);
}
}
@@ -333,7 +333,7 @@ export class ASCIILexicalTable {
const findNextFilledKey = (
fromIndex: number,
keys: Array<string | undefined>
keys: Array<string | undefined>,
): [number, string] | [-1, undefined] => {
for (let j = fromIndex; j < keys.length; j += 1) {
const key = keys[j];
@@ -347,11 +347,11 @@ const findNextFilledKey = (
export const orderKeys = (
lex: ASCIILexicalTable,
keys: Array<string | undefined>
keys: Array<string | undefined>,
): Array<string> | undefined => {
const newKeys: string[] = [];
for (let i = 0; i < keys.length; ) {
for (let i = 0; i < keys.length;) {
const key = keys[i];
const collectedKeys: string[] = [];
const [nextKeyIndex, nextKey] = findNextFilledKey(i + 1, keys);
@@ -368,7 +368,7 @@ export const orderKeys = (
const generatedKeys = lex.nBetween(
keyToGenerateCount,
key ?? lex.first(),
nextKey ?? lex.last()
nextKey ?? lex.last(),
);
if (generatedKeys) {
collectedKeys.push(...generatedKeys);
+4 -4
View File
@@ -14,18 +14,18 @@ export type AsyncSearchOption = {
export type MatchHandler<TSearchItem extends object | string | number> = (
item: TSearchItem,
query: string
query: string,
) => boolean;
export type ResultHandler<TSearchItem extends object | string | number> = (
results: TSearchItem[],
query: string
query: string,
) => void;
export type AsyncSearchHandler = (query: string) => void;
export type TerminateAsyncSearch = () => void;
export const normalize = (str: string, options?: NormalizeOption) => {
let nStr = str.normalize(options?.normalizeUnicode ?? true ? 'NFKC' : 'NFC');
let nStr = str.normalize((options?.normalizeUnicode ?? true) ? 'NFKC' : 'NFC');
if (!options?.caseSensitive) nStr = nStr.toLocaleLowerCase();
if (options?.ignoreWhitespace ?? true) nStr = nStr.replace(/\s/g, '');
return nStr;
@@ -40,7 +40,7 @@ export const AsyncSearch = <TSearchItem extends object | string | number>(
list: TSearchItem[],
match: MatchHandler<TSearchItem>,
onResult: ResultHandler<TSearchItem>,
options?: AsyncSearchOption
options?: AsyncSearchOption,
): [AsyncSearchHandler, TerminateAsyncSearch] => {
let resultList: TSearchItem[] = [];
+6 -5
View File
@@ -30,7 +30,7 @@ interface AndroidShareHandlerPlugin {
clearPendingShare(): Promise<void>;
addListener(
eventName: 'shareReceived',
listenerFunc: (payload: AndroidSharePayload) => void
listenerFunc: (payload: AndroidSharePayload) => void,
): Promise<PluginListenerHandle>;
}
@@ -41,7 +41,8 @@ const getAndroidShareHandler = async (): Promise<AndroidShareHandlerPlugin> => {
/** Returns true when the Android share bridge is available. */
export const isAndroidShareSupported = (): boolean => {
const capacitor = (window as typeof window & { Capacitor?: CapacitorCoreModule['Capacitor'] }).Capacitor;
const capacitor = (window as typeof window & { Capacitor?: CapacitorCoreModule['Capacitor'] })
.Capacitor;
return Boolean(capacitor?.isNativePlatform?.() && capacitor.getPlatform() === 'android');
};
@@ -62,7 +63,7 @@ export const clearPendingAndroidShare = async (): Promise<void> => {
/** Subscribes to new incoming native share payloads. */
export const listenForAndroidShares = async (
listener: (payload: AndroidSharePayload) => void
listener: (payload: AndroidSharePayload) => void,
): Promise<PluginListenerHandle | undefined> => {
if (!isAndroidShareSupported()) return undefined;
const AndroidShareHandler = await getAndroidShareHandler();
@@ -72,7 +73,7 @@ export const listenForAndroidShares = async (
/** Converts a cached native shared file into a browser File for upload. */
export const materializeSharedFile = async (
sharedFile: AndroidSharedFile,
receivedAt: number
receivedAt: number,
): Promise<File> => {
const { Capacitor } = await loadCapacitorCore();
const fileUrl = Capacitor.convertFileSrc(sharedFile.path);
@@ -86,4 +87,4 @@ export const materializeSharedFile = async (
type: sharedFile.mimeType || blob.type,
lastModified: receivedAt,
});
};
};
+8 -9
View File
@@ -1,8 +1,7 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import lottie from 'lottie-web/build/player/lottie_light';
// eslint-disable-next-line import/no-extraneous-dependencies
import { inflate } from 'pako';
// eslint-disable-next-line import/no-extraneous-dependencies
import GIF from 'gif.js';
/** Animation item type from lottie-web */
@@ -18,7 +17,7 @@ const GIF_QUALITY = 10;
const MAX_GIF_SIZE = 256;
/** Transparency key color (magenta) - this color becomes transparent in the GIF */
const TRANSPARENT_COLOR = 0xFF00FF;
const TRANSPARENT_COLOR = 0xff00ff;
/**
* Decompress a TGS file (gzipped Lottie JSON)
@@ -40,7 +39,7 @@ function decompressTgs(tgsData: ArrayBuffer): object {
async function renderLottieToGif(
animationData: object,
width: number,
height: number
height: number,
): Promise<Blob> {
return new Promise((resolve, reject) => {
// Create a hidden container for rendering
@@ -130,7 +129,7 @@ async function renderLottieToGif(
// Calculate the animation frame to seek to
const progress = frameIndex / framesToCapture;
const animFrame = Math.floor(progress * totalFrames);
animation.goToAndStop(animFrame, true);
// Get the SVG content and render to canvas
@@ -194,7 +193,7 @@ async function renderLottieToGif(
export async function tgsToGif(
tgsBlob: Blob,
targetWidth = 256,
targetHeight = 256
targetHeight = 256,
): Promise<Blob> {
// eslint-disable-next-line no-console
console.log('tgsToGif: Starting conversion, blob size:', tgsBlob.size);
@@ -218,7 +217,7 @@ export async function tgsToGif(
export async function webmToGif(
webmBlob: Blob,
targetWidth = 256,
targetHeight = 256
targetHeight = 256,
): Promise<Blob> {
// eslint-disable-next-line no-console
console.log('webmToGif: Starting conversion, blob size:', webmBlob.size);
@@ -226,7 +225,7 @@ export async function webmToGif(
const video = document.createElement('video');
video.muted = true;
video.playsInline = true;
const canvas = document.createElement('canvas');
const width = Math.min(targetWidth, MAX_GIF_SIZE);
const height = Math.min(targetHeight, MAX_GIF_SIZE);
+8 -8
View File
@@ -38,7 +38,7 @@ export function getGlobalMatrixClient(): MatrixClient | null {
export function updateSessionToken(userId: string, newToken: string): void {
const sessions = getLocalStorageItem<Sessions>(MATRIX_SESSIONS_KEY, []);
const sessionIndex = sessions.findIndex((s: Session) => s.userId === userId);
if (sessionIndex >= 0) {
sessions[sessionIndex] = {
...sessions[sessionIndex],
@@ -53,7 +53,7 @@ export function updateSessionToken(userId: string, newToken: string): void {
* Prioritizes the token from the active MatrixClient instance (most up-to-date),
* then falls back to localStorage. This ensures we always use the freshest token,
* even if it's been refreshed by the SDK.
*
*
* @returns The current access token or undefined if no session is active
*/
export function getCurrentAccessToken(): string | undefined {
@@ -65,31 +65,31 @@ export function getCurrentAccessToken(): string | undefined {
return clientToken;
}
}
// Fall back to localStorage if MatrixClient is not available or doesn't have a token
const currentUserId = getLocalStorageItem<string | undefined>(CURRENT_SESSION_KEY, undefined);
if (!currentUserId) {
// Fallback to old single-account storage for migration
return localStorage.getItem('cinny_access_token') ?? undefined;
}
const sessions = getLocalStorageItem<Sessions>(MATRIX_SESSIONS_KEY, []);
const currentSession = sessions.find((s: Session) => s.userId === currentUserId);
return currentSession?.accessToken;
}
/**
* Get the access token for a specific user.
* Useful when you need to fetch data for a non-active account.
*
*
* @param userId - The Matrix user ID
* @returns The access token for the specified user or undefined
*/
export function getAccessTokenForUser(userId: string): string | undefined {
const sessions = getLocalStorageItem<Sessions>(MATRIX_SESSIONS_KEY, []);
const session = sessions.find((s: Session) => s.userId === userId);
return session?.accessToken;
}
+2 -3
View File
@@ -9,8 +9,7 @@ const inflight = new Map<string, Promise<string>>();
export const isAuthenticatedMediaUrl = (url: string): boolean =>
url.includes('/_matrix/client/v1/media/download') ||
url.includes('/_matrix/client/v1/media/thumbnail') ||
(url.includes('/_matrix/media/') &&
(url.includes('/download/') || url.includes('/thumbnail/')));
(url.includes('/_matrix/media/') && (url.includes('/download/') || url.includes('/thumbnail/')));
export const getCachedAuthenticatedMediaUrl = (src: string | undefined): string | undefined => {
if (!src) return undefined;
@@ -56,7 +55,7 @@ const fetchBlobUrl = async (src: string): Promise<string> => {
*/
export const resolveAuthenticatedMediaUrl = async (
src: string,
useAuthentication: boolean
useAuthentication: boolean,
): Promise<string> => {
if (!useAuthentication || !isAuthenticatedMediaUrl(src)) {
return src;
+33 -19
View File
@@ -62,15 +62,15 @@ interface MatrixBackgroundSyncPlugin {
resolveUnifiedPushGateway(options: { endpoint: string }): Promise<{ gatewayUrl: string }>;
addListener(
eventName: 'unifiedPushNewEndpoint',
listenerFunc: (event: UnifiedPushEndpointEvent) => void
listenerFunc: (event: UnifiedPushEndpointEvent) => void,
): Promise<PluginListenerHandle>;
addListener(
eventName: 'unifiedPushUnregistered',
listenerFunc: (event: UnifiedPushUnregisteredEvent) => void
listenerFunc: (event: UnifiedPushUnregisteredEvent) => void,
): Promise<PluginListenerHandle>;
addListener(
eventName: 'unifiedPushRegistrationFailed',
listenerFunc: (event: UnifiedPushRegistrationFailedEvent) => void
listenerFunc: (event: UnifiedPushRegistrationFailedEvent) => void,
): Promise<PluginListenerHandle>;
}
@@ -79,13 +79,15 @@ type StoredPusherState = {
appId: string;
};
const DEFAULT_UNIFIED_PUSH_GATEWAY = 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify';
const DEFAULT_UNIFIED_PUSH_GATEWAY =
'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify';
const PUSHER_APP_ID_BASE = 'com.paarrot.app.android';
const PUSHER_STORAGE_PREFIX = 'paarrot.unifiedpush';
/** Returns true when the current platform is Android Capacitor. */
export const isBackgroundSyncSupported = (): boolean => {
const capacitor = (window as typeof window & { Capacitor?: CapacitorCoreModule['Capacitor'] }).Capacitor;
const capacitor = (window as typeof window & { Capacitor?: CapacitorCoreModule['Capacitor'] })
.Capacitor;
return Boolean(capacitor?.isNativePlatform?.() && capacitor.getPlatform() === 'android');
};
@@ -99,7 +101,7 @@ const buildPusherAppId = (deviceId: string | null): string => {
const loadStoredPusherState = (
userId: string | null,
deviceId: string | null
deviceId: string | null,
): StoredPusherState | undefined => {
if (typeof window === 'undefined' || !window.localStorage) return undefined;
@@ -116,7 +118,7 @@ const loadStoredPusherState = (
const saveStoredPusherState = (
userId: string | null,
deviceId: string | null,
state: StoredPusherState
state: StoredPusherState,
): void => {
if (typeof window === 'undefined' || !window.localStorage) return;
window.localStorage.setItem(getStoredPusherKey(userId, deviceId), JSON.stringify(state));
@@ -196,8 +198,13 @@ class AndroidUnifiedPushManager {
const { Capacitor, registerPlugin } = await loadCapacitorCore();
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
console.log('[BackgroundSync] start() called, platform:', Capacitor.getPlatform(), 'isNative:', Capacitor.isNativePlatform());
console.log(
'[BackgroundSync] start() called, platform:',
Capacitor.getPlatform(),
'isNative:',
Capacitor.isNativePlatform(),
);
if (!isBackgroundSyncSupported()) {
console.log('[BackgroundSync] Background sync not supported on this platform');
return;
@@ -208,7 +215,12 @@ class AndroidUnifiedPushManager {
const userId = mx.getUserId();
const deviceId = mx.getDeviceId();
console.log('[BackgroundSync] Credentials check:', { userId, deviceId, hasToken: !!accessToken, hasUrl: !!homeserverUrl });
console.log('[BackgroundSync] Credentials check:', {
userId,
deviceId,
hasToken: !!accessToken,
hasUrl: !!homeserverUrl,
});
if (!homeserverUrl || !accessToken || !userId) {
console.warn('[BackgroundSync] Missing credentials, not starting');
@@ -246,7 +258,7 @@ class AndroidUnifiedPushManager {
const { registerPlugin } = await loadCapacitorCore();
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
const client = this.client;
const { client } = this;
if (client) {
const deviceId = client.getDeviceId();
const userId = client.getUserId();
@@ -269,7 +281,7 @@ class AndroidUnifiedPushManager {
/** Update the Matrix pusher when a new native endpoint is published. */
private async handleNewEndpoint(event: UnifiedPushEndpointEvent): Promise<void> {
const client = this.client;
const { client } = this;
if (!client) return;
if (event.previousEndpoint) {
@@ -281,7 +293,7 @@ class AndroidUnifiedPushManager {
/** Remove the Matrix pusher when UnifiedPush unregisters this instance. */
private async handleUnregistered(event: UnifiedPushUnregisteredEvent): Promise<void> {
const client = this.client;
const { client } = this;
if (!client) return;
const stored = loadStoredPusherState(client.getUserId(), client.getDeviceId());
@@ -311,7 +323,8 @@ class AndroidUnifiedPushManager {
private async tryRequestDistributorSetup(): Promise<void> {
try {
const { registerPlugin } = await loadCapacitorCore();
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
const MatrixBackgroundSync =
registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
const setupResult = await MatrixBackgroundSync.requestDistributorSetup();
console.warn('[BackgroundSync] requestDistributorSetup result:', setupResult);
const status = await this.safeGetStatus();
@@ -319,7 +332,7 @@ class AndroidUnifiedPushManager {
const distributors = normalizeDistributors(status?.distributors ?? []);
if (distributors.length === 0) {
console.error(
'[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.'
'[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.',
);
this.showNoDistributorPrompt();
}
@@ -336,7 +349,7 @@ class AndroidUnifiedPushManager {
const distributors = normalizeDistributors(status.distributors);
if (!status.registered && distributors.length === 0) {
console.error(
'[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.'
'[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.',
);
this.showNoDistributorPrompt();
}
@@ -395,7 +408,7 @@ class AndroidUnifiedPushManager {
/** Reconcile an already-persisted native endpoint after app startup. */
private async syncExistingEndpoint(): Promise<void> {
const client = this.client;
const { client } = this;
if (!client) return;
const { registerPlugin } = await loadCapacitorCore();
@@ -457,7 +470,7 @@ class AndroidUnifiedPushManager {
private async removePusher(
mx: MatrixClient,
endpoint: string,
appId = buildPusherAppId(mx.getDeviceId())
appId = buildPusherAppId(mx.getDeviceId()),
): Promise<void> {
try {
await mx.setPusher({
@@ -474,7 +487,8 @@ class AndroidUnifiedPushManager {
private async safeGetStatus(): Promise<UnifiedPushStatus | undefined> {
try {
const { registerPlugin } = await loadCapacitorCore();
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
const MatrixBackgroundSync =
registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
return await MatrixBackgroundSync.getStatus();
} catch (err) {
console.warn('[BackgroundSync] Failed to read UnifiedPush status:', err);
+1 -1
View File
@@ -3,7 +3,7 @@ import { encode, isBlurhashValid } from 'blurhash';
export const encodeBlurHash = (
img: HTMLImageElement | HTMLVideoElement,
width?: number,
height?: number
height?: number,
): string | undefined => {
const imgWidth = img instanceof HTMLVideoElement ? img.videoWidth : img.width;
const imgHeight = img instanceof HTMLVideoElement ? img.videoHeight : img.height;
+12 -11
View File
@@ -1,6 +1,8 @@
import { DiscordCollectibleItem } from './discordCollectibles';
function introDurationFromEffectMeta(effect: Record<string, unknown> | undefined): number | undefined {
function introDurationFromEffectMeta(
effect: Record<string, unknown> | undefined,
): number | undefined {
if (!effect) return undefined;
const raw = effect.duration ?? effect.durationMs;
if (typeof raw !== 'number' || raw <= 0) return undefined;
@@ -49,19 +51,21 @@ export function pickCatalogProfileEffectLoopUrl(item: DiscordCollectibleItem): s
return catalogAssetUrl(item, 'effect_1', 'effect_0', 'effect_2', 'effect_3');
}
export function catalogProfileEffectIntroDurationMs(item: DiscordCollectibleItem): number | undefined {
export function catalogProfileEffectIntroDurationMs(
item: DiscordCollectibleItem,
): number | undefined {
const effect = item.effect?.effects?.[0] as Record<string, unknown> | undefined;
return introDurationFromEffectMeta(effect);
}
export function pickStoredProfileEffectIntroUrl(
assetUrls: Record<string, string | undefined>
assetUrls: Record<string, string | undefined>,
): string | undefined {
return assetUrls['profile_effect:effect_0'];
}
export function pickStoredProfileEffectLoopUrl(
assetUrls: Record<string, string | undefined>
assetUrls: Record<string, string | undefined>,
): string | undefined {
return (
assetUrls['profile_effect:effect_1'] ||
@@ -76,7 +80,7 @@ export function isCatalogVideoPreview(url?: string): boolean {
}
export function pickNameplateUrl(
assetUrls: Record<string, string | undefined>
assetUrls: Record<string, string | undefined>,
): string | undefined {
return (
assetUrls['nameplate:animated'] ||
@@ -87,16 +91,13 @@ export function pickNameplateUrl(
}
export function pickAvatarDecorationUrl(
assetUrls: Record<string, string | undefined>
assetUrls: Record<string, string | undefined>,
): string | undefined {
return assetUrls['avatar_decoration:animated'] || assetUrls['avatar_decoration:animated.png'];
}
export function pickProfileEffectUrl(
assetUrls: Record<string, string | undefined>
assetUrls: Record<string, string | undefined>,
): string | undefined {
return (
pickStoredProfileEffectLoopUrl(assetUrls) ||
assetUrls['profile_effect:reduced_motion']
);
return pickStoredProfileEffectLoopUrl(assetUrls) || assetUrls['profile_effect:reduced_motion'];
}
+15 -13
View File
@@ -1,6 +1,5 @@
import { IconName, IconSrc } from '../components/icons';
export const bytesToSize = (bytes: number): string => {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0KB';
@@ -53,7 +52,7 @@ export const fulfilledPromiseSettledResult = <T>(prs: PromiseSettledResult<T>[])
}, []);
export const promiseFulfilledResult = <T>(
settledResult: PromiseSettledResult<T>
settledResult: PromiseSettledResult<T>,
): T | undefined => {
if (settledResult.status === 'fulfilled') return settledResult.value;
return undefined;
@@ -92,7 +91,7 @@ export const fitMediaSize = (
w: number,
h: number,
maxW: number,
maxH: number
maxH: number,
): { width: number; height: number } => {
if (w <= 0 || h <= 0) {
return { width: maxW, height: Math.round(maxW * 0.75) };
@@ -170,15 +169,18 @@ export const stripAlphaFromColor = (color: string): string => {
const b = parseInt(rgbaMatch[3], 10).toString(16).padStart(2, '0');
return `#${r}${g}${b}`.toUpperCase();
}
// Handle hex format
let hex = color.replace('#', '');
// Convert shorthand #RGB or #RGBA to full form
if (hex.length === 3 || hex.length === 4) {
hex = hex.split('').map(c => c + c).join('');
hex = hex
.split('')
.map((c) => c + c)
.join('');
}
// Take only the first 6 characters (RGB), ignore alpha if present
return `#${hex.substring(0, 6).toUpperCase()}`;
};
@@ -191,15 +193,15 @@ export const stripAlphaFromColor = (color: string): string => {
export const getContrastingTextColor = (bgColor: string): string => {
// Remove # if present
const hex = bgColor.replace('#', '');
// Parse RGB values (ignore alpha if present)
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
// Calculate relative luminance using WCAG formula
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
// Return black for light backgrounds, white for dark backgrounds
return luminance > 0.5 ? '#000000' : '#FFFFFF';
};
@@ -212,15 +214,15 @@ export const getContrastingTextColor = (bgColor: string): string => {
export const getTextShadowColor = (textColor: string): string => {
// Remove # if present
const hex = textColor.replace('#', '');
// Parse RGB values (ignore alpha if present)
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
// Calculate relative luminance using WCAG formula
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
// Return white shadow only for very dark text (luminance < 0.2)
return luminance < 0.2 ? '#FFFFFF' : '#000000';
};
+18 -20
View File
@@ -3,13 +3,13 @@ import { timeHourMinute } from './time';
/**
* Processes selected text from the chat timeline and formats it as:
* "Username - Time: Message"
*
*
* This intercepts the copy event on the timeline and reformats the copied text.
*/
export const setupCopyHandler = (
containerRef: React.RefObject<HTMLElement>,
getMessageData: (eventId: string) => { sender: string; ts: number; content: string } | null,
hour24Clock: boolean
hour24Clock: boolean,
): (() => void) => {
const container = containerRef.current;
if (!container) return () => {};
@@ -20,16 +20,16 @@ export const setupCopyHandler = (
const range = selection.getRangeAt(0);
const selectedContainer = range.commonAncestorContainer;
// Only process if selection is within our container
if (!container.contains(selectedContainer)) return;
// Find all message elements within the selection
const messages: Array<{ sender: string; time: string; content: string }> = [];
// Get all message elements in the container
const messageElements = Array.from(container.querySelectorAll('[data-message-id]'));
messageElements.forEach((msgEl) => {
const eventId = msgEl.getAttribute('data-message-id');
if (!eventId) return;
@@ -38,8 +38,10 @@ export const setupCopyHandler = (
if (!data) return;
// Find content elements within the message (skip headers, timestamps, etc.)
const contentEl = msgEl.querySelector('[class*="MessageTextBody"], [class*="message-content"], [class*="MessageBody"]') as HTMLElement;
const contentEl = msgEl.querySelector(
'[class*="MessageTextBody"], [class*="message-content"], [class*="MessageBody"]',
) as HTMLElement;
if (!contentEl) return;
// Check if the content element intersects with the selection
@@ -47,12 +49,8 @@ export const setupCopyHandler = (
let isSelected = false;
try {
// Try to detect if this node or its children are in the selection
const walker = document.createTreeWalker(
contentEl,
NodeFilter.SHOW_TEXT,
null
);
const walker = document.createTreeWalker(contentEl, NodeFilter.SHOW_TEXT, null);
let textNode = walker.nextNode();
while (textNode && !isSelected) {
if (range.intersectsNode(textNode)) {
@@ -69,17 +67,17 @@ export const setupCopyHandler = (
// Format the time
const timeStr = timeHourMinute(data.ts, hour24Clock);
// Extract the selected text from within this message's content
let selectedText = '';
// Create a range for this message's content
const contentRange = document.createRange();
contentRange.selectNodeContents(contentEl);
// Clone the selection range to avoid modifying it
const extractRange = range.cloneRange();
// Constrain the extract range to be within the content element
// If selection starts before content, move start to content start
if (contentRange.compareBoundaryPoints(Range.START_TO_START, extractRange) > 0) {
@@ -89,9 +87,9 @@ export const setupCopyHandler = (
if (contentRange.compareBoundaryPoints(Range.END_TO_END, extractRange) < 0) {
extractRange.setEnd(contentRange.endContainer, contentRange.endOffset);
}
selectedText = extractRange.toString().trim();
if (selectedText) {
messages.push({
sender: data.sender,
@@ -106,7 +104,7 @@ export const setupCopyHandler = (
const formattedText = messages
.map((msg) => `${msg.sender} - ${msg.time}: ${msg.content}`)
.join('\n');
event.preventDefault();
event.clipboardData?.setData('text/plain', formattedText);
}
+12 -9
View File
@@ -51,7 +51,9 @@ type PublishedCatalog = {
items: DiscordCollectibleItem[];
};
function isPublishedCatalog(value: unknown): value is { schema_version: number; items: DiscordCollectibleItem[] } {
function isPublishedCatalog(
value: unknown,
): value is { schema_version: number; items: DiscordCollectibleItem[] } {
if (!value || typeof value !== 'object') return false;
const catalog = value as Record<string, unknown>;
return (
@@ -62,7 +64,7 @@ function isPublishedCatalog(value: unknown): value is { schema_version: number;
item &&
typeof item === 'object' &&
typeof (item as DiscordCollectibleItem).id === 'string' &&
Array.isArray((item as DiscordCollectibleItem).assets)
Array.isArray((item as DiscordCollectibleItem).assets),
)
);
}
@@ -94,7 +96,7 @@ function saveCachedCatalog(catalog: PublishedCatalog): void {
}
export async function fetchPublishedCollectiblesCatalog(
force = false
force = false,
): Promise<DiscordCollectibleItem[]> {
const cached = loadCachedCatalog();
if (!force && cached) return cached.items;
@@ -107,7 +109,7 @@ export async function fetchPublishedCollectiblesCatalog(
const catalog = await response.json();
if (!isPublishedCatalog(catalog)) throw new Error('Catalog has an unsupported schema.');
return catalog;
})
}),
);
const items = documents.flatMap((catalog) => catalog.items);
if (items.length === 0) throw new Error('Catalog is empty.');
@@ -148,7 +150,7 @@ function replaceCdnUrls<T>(value: T, urlToMxc: Map<string, string>): T {
}
export async function downloadCollectibleAssets(
assets: DiscordCollectibleAsset[]
assets: DiscordCollectibleAsset[],
): Promise<DownloadedCollectibleAsset[]> {
const api = window.electron?.discordCollectibles;
if (api) {
@@ -169,19 +171,20 @@ export async function downloadCollectibleAssets(
assets.map(async (asset) => {
if (!isCdnUrl(asset.url)) throw new Error('Collectible asset URL is not a Discord CDN URL.');
const response = await fetch(asset.url);
if (!response.ok) throw new Error(`Failed to download ${asset.filename}: HTTP ${response.status}.`);
if (!response.ok)
throw new Error(`Failed to download ${asset.filename}: HTTP ${response.status}.`);
return {
...asset,
data: new Uint8Array(await response.arrayBuffer()),
};
})
}),
);
}
export async function uploadCollectibleToMatrix(
mx: MatrixClient,
item: DiscordCollectibleItem,
onProgress?: (message: string) => void
onProgress?: (message: string) => void,
): Promise<StoredCollectible> {
onProgress?.('Downloading from Discord…');
const downloaded = await downloadCollectibleAssets(item.assets);
@@ -287,7 +290,7 @@ export function groupCollectibleItems(items: DiscordCollectibleItem[]): Collecti
return [...map.entries()]
.map(([id, groupItems]) => {
const items = dedupeVariantItems(groupItems).sort((a, b) =>
variantItemLabel(a).localeCompare(variantItemLabel(b))
variantItemLabel(a).localeCompare(variantItemLabel(b)),
);
return {
id,
+3 -3
View File
@@ -4,13 +4,13 @@ export type DisposeCallback<DisposeArgs extends unknown[] = [], DisposeReturn =
export type DisposableContext<
DisposableArgs extends unknown[] = [],
DisposeArgs extends unknown[] = [],
DisposeReturn = void
DisposeReturn = void,
> = (...args: DisposableArgs) => DisposeCallback<DisposeArgs, DisposeReturn>;
export const disposable = <
DisposableArgs extends unknown[],
DisposeArgs extends unknown[] = [],
DisposeReturn = void
DisposeReturn = void,
>(
context: DisposableContext<DisposableArgs, DisposeArgs, DisposeReturn>
context: DisposableContext<DisposableArgs, DisposeArgs, DisposeReturn>,
) => context;
+6 -10
View File
@@ -13,7 +13,7 @@ export const editableActiveElement = (): boolean =>
export const isIntersectingScrollView = (
scrollElement: HTMLElement,
childElement: HTMLElement
childElement: HTMLElement,
): boolean => {
const scrollTop = scrollElement.offsetTop + scrollElement.scrollTop;
const scrollBottom = scrollTop + scrollElement.offsetHeight;
@@ -38,7 +38,7 @@ export const isInScrollView = (scrollElement: HTMLElement, childElement: HTMLEle
export const canFitInScrollView = (
scrollElement: HTMLElement,
childElement: HTMLElement
childElement: HTMLElement,
): boolean => childElement.offsetHeight < scrollElement.offsetHeight;
export type FilesOrFile<T extends boolean | undefined = undefined> = T extends true ? File[] : File;
@@ -56,7 +56,7 @@ export const getFilesFromFileList = (fileList: FileList): File[] => {
export const selectFile = <M extends boolean | undefined = undefined>(
accept: string,
multiple?: M
multiple?: M,
): Promise<FilesOrFile<M> | undefined> =>
new Promise((resolve) => {
const input = document.createElement('input');
@@ -147,7 +147,7 @@ export const getThumbnail = (
img: HTMLImageElement | SVGImageElement | HTMLVideoElement,
width: number,
height: number,
thumbnailMimeType?: string
thumbnailMimeType?: string,
): Promise<Blob | undefined> =>
new Promise((resolve) => {
const canvas = document.createElement('canvas');
@@ -193,7 +193,7 @@ export const scrollToPosition = (scrollEl: HTMLElement, position: ScrollPosition
*/
export const scrollElementIntoView = (
element: HTMLElement,
options?: ScrollIntoViewOptions
options?: ScrollIntoViewOptions,
): void => {
element.scrollIntoView(options);
};
@@ -230,11 +230,7 @@ export const isScrolledToBottom = (scrollEl: HTMLElement, threshold = 50): boole
* Shared auto-scroll behavior for chat-like timelines that should stay pinned to bottom.
* Only scrolls if already near the bottom unless a call site explicitly forces it.
*/
export const autoScrollToBottom = (
scrollEl: HTMLElement,
smooth = false,
force = false
): void => {
export const autoScrollToBottom = (scrollEl: HTMLElement, smooth = false, force = false): void => {
if (force || isScrolledToBottom(scrollEl)) {
scrollToBottom(scrollEl, smooth ? 'smooth' : 'instant');
}
+27 -35
View File
@@ -14,13 +14,13 @@ const EMOTICON_MAP: Record<string, string> = {
'=)': '😊',
':]': '😊',
':>': '😊',
// Sad faces
':(': '☹️',
':-(': '☹️',
'=[': '☹️',
':<': '☹️',
// Other emotions
';)': '😉',
';-)': '😉',
@@ -28,8 +28,8 @@ const EMOTICON_MAP: Record<string, string> = {
':-P': '😛',
':p': '😛',
':-p': '😛',
'xD': '😆',
'XD': '😆',
xD: '😆',
XD: '😆',
':|': '😐',
':-|': '😐',
':O': '😮',
@@ -42,21 +42,21 @@ const EMOTICON_MAP: Record<string, string> = {
':-*': '😘',
'<3': '❤️',
'</3': '💔',
// Surprised/Shocked
':0': '😯',
':-0': '😯',
// Cool
'8)': '😎',
'8-)': '😎',
'B)': '😎',
'B-)': '😎',
// Crying
':\'(': '😢',
':\')': '😂',
":'(": '😢',
":')": '😂',
// Neutral
':/': '😕',
':-/': '😕',
@@ -72,22 +72,19 @@ const EMOTICON_MAP: Record<string, string> = {
*/
export function convertEmoticons(text: string): string {
let result = text;
// Sort emoticons by length (longest first) to handle overlapping patterns
// e.g., :-) before :)
const emoticons = Object.keys(EMOTICON_MAP).sort((a, b) => b.length - a.length);
for (const emoticon of emoticons) {
// Escape special regex characters
const escapedEmoticon = emoticon.replace(/[.*+?^${}()|[\]\\<>]/g, '\\$&');
// Match emoticons with optional backslash escape
// Matches either \:) (escaped) or :) (not escaped, and not preceded by backslash)
const regex = new RegExp(
`(^|\\s)(\\\\)?(${escapedEmoticon})(?=\\s|$)`,
'g'
);
const regex = new RegExp(`(^|\\s)(\\\\)?(${escapedEmoticon})(?=\\s|$)`, 'g');
result = result.replace(regex, (match, prefix, backslash, emote) => {
// If backslash is present, remove it but keep the emoticon literal
if (backslash) {
@@ -97,7 +94,7 @@ export function convertEmoticons(text: string): string {
return prefix + EMOTICON_MAP[emoticon];
});
}
return result;
}
@@ -110,26 +107,21 @@ export function convertEmoticons(text: string): string {
*/
export function convertEmoticonsInHtml(html: string): string {
let result = html;
// Sort emoticons by length (longest first) to handle overlapping patterns
const emoticons = Object.keys(EMOTICON_MAP).sort((a, b) => b.length - a.length);
for (const emoticon of emoticons) {
// Convert emoticon to HTML entity version (for < and >)
const htmlEmoticon = emoticon
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
const htmlEmoticon = emoticon.replace(/</g, '&lt;').replace(/>/g, '&gt;');
// Escape special regex characters
const escapedEmoticon = htmlEmoticon.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Match emoticons at start of string, after whitespace, or after HTML tags
// With optional backslash escape
const regex = new RegExp(
`(^|\\s|>)(\\\\)?(${escapedEmoticon})(?=\\s|<|$)`,
'g'
);
const regex = new RegExp(`(^|\\s|>)(\\\\)?(${escapedEmoticon})(?=\\s|<|$)`, 'g');
result = result.replace(regex, (match, prefix, backslash, emote) => {
// If backslash is present, remove it but keep the emoticon literal
if (backslash) {
@@ -139,7 +131,7 @@ export function convertEmoticonsInHtml(html: string): string {
return prefix + EMOTICON_MAP[emoticon];
});
}
return result;
}
@@ -150,15 +142,15 @@ export function convertEmoticonsInHtml(html: string): string {
*/
export function containsEmoticons(text: string): boolean {
const emoticons = Object.keys(EMOTICON_MAP);
for (const emoticon of emoticons) {
const escapedEmoticon = emoticon.replace(/[.*+?^${}()|[\]\\<>]/g, '\\$&');
const regex = new RegExp(`(^|\\s)(${escapedEmoticon})(?=\\s|$)`);
if (regex.test(text)) {
return true;
}
}
return false;
}
+2 -2
View File
@@ -1,6 +1,6 @@
export type ReplaceCallback<R> = (
match: RegExpExecArray | RegExpMatchArray,
pushIndex: number
pushIndex: number,
) => R;
export type ConvertPartCallback<R> = (text: string, pushIndex: number) => R;
@@ -8,7 +8,7 @@ export const findAndReplace = <ReplaceReturnType, ConvertReturnType>(
text: string,
regex: RegExp,
replace: ReplaceCallback<ReplaceReturnType>,
convertPart: ConvertPartCallback<ConvertReturnType>
convertPart: ConvertPartCallback<ConvertReturnType>,
): Array<ReplaceReturnType | ConvertReturnType> => {
const result: Array<ReplaceReturnType | ConvertReturnType> = [];
let lastEnd = 0;
+5 -2
View File
@@ -80,7 +80,10 @@ export function fuzzyMatch(query: string, text: string): FuzzyMatch | null {
}
/** Best fuzzy match across multiple strings (title, keywords, etc.). */
export function fuzzyMatchAny(query: string, texts: Array<string | undefined | null>): FuzzyMatch | null {
export function fuzzyMatchAny(
query: string,
texts: Array<string | undefined | null>,
): FuzzyMatch | null {
let best: FuzzyMatch | null = null;
for (const text of texts) {
if (!text) continue;
@@ -95,7 +98,7 @@ export function fuzzyMatchAny(query: string, texts: Array<string | undefined | n
export function fuzzyFilter<T>(
items: T[],
query: string,
getTexts: (item: T) => Array<string | undefined | null>
getTexts: (item: T) => Array<string | undefined | null>,
): Array<{ item: T; score: number }> {
const q = query.trim();
if (!q) {
+59 -56
View File
@@ -1,14 +1,14 @@
/**
* Utilities for reading and writing GIF metadata (Application Extension blocks)
* Used to embed user color in avatar images
*
*
* GIF structure:
* - Header: GIF87a or GIF89a (6 bytes)
* - Logical Screen Descriptor (7 bytes)
* - Optional Global Color Table
* - Extension blocks and image data
* - Trailer: 0x3B
*
*
* Application Extension format:
* - 0x21 (Extension Introducer)
* - 0xFF (Application Extension Label)
@@ -20,7 +20,7 @@
/* eslint-disable no-bitwise */
/* eslint-disable no-plusplus */
/* eslint-disable no-console */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-continue */
@@ -33,14 +33,14 @@ const PAARROT_APP_ID = 'PAARROT\0'; // 8 bytes, null-padded
const PAARROT_APP_ID_BYTES = new TextEncoder().encode(PAARROT_APP_ID);
/** Application authentication code (3 bytes) */
const PAARROT_AUTH_CODE = new Uint8Array([0x31, 0x2E, 0x30]); // "1.0"
const PAARROT_AUTH_CODE = new Uint8Array([0x31, 0x2e, 0x30]); // "1.0"
/**
* Check if data is a valid GIF file
*/
function isGIF(data: Uint8Array): boolean {
if (data.length < 6) return false;
// Check GIF87a
let is87a = true;
for (let i = 0; i < 6; i++) {
@@ -50,7 +50,7 @@ function isGIF(data: Uint8Array): boolean {
}
}
if (is87a) return true;
// Check GIF89a
let is89a = true;
for (let i = 0; i < 6; i++) {
@@ -71,15 +71,18 @@ function getGlobalColorTableSize(data: Uint8Array): number {
const packedByte = data[10];
const hasGCT = (packedByte & 0x80) !== 0;
if (!hasGCT) return 0;
const gctSize = packedByte & 0x07;
return 3 * (2 ** (gctSize + 1));
return 3 * 2 ** (gctSize + 1);
}
/**
* Find all Application Extension blocks
*/
function findAppExtensions(data: Uint8Array, startOffset: number): Array<{
function findAppExtensions(
data: Uint8Array,
startOffset: number,
): Array<{
offset: number;
length: number;
appId: string;
@@ -93,37 +96,37 @@ function findAppExtensions(data: Uint8Array, startOffset: number): Array<{
authCode: Uint8Array;
dataBlocks: Uint8Array[];
}> = [];
let offset = startOffset;
while (offset < data.length - 1) {
// Look for Extension Introducer (0x21)
if (data[offset] === 0x21 && data[offset + 1] === 0xFF) {
if (data[offset] === 0x21 && data[offset + 1] === 0xff) {
// Application Extension
const blockSize = data[offset + 2];
if (blockSize !== 0x0B) {
if (blockSize !== 0x0b) {
offset++;
continue;
}
const appId = new TextDecoder().decode(data.slice(offset + 3, offset + 11));
const authCode = data.slice(offset + 11, offset + 14);
// Read data sub-blocks
let subOffset = offset + 14;
const dataBlocks: Uint8Array[] = [];
let totalLength = 14; // header length
while (subOffset < data.length && data[subOffset] !== 0x00) {
const subBlockSize = data[subOffset];
dataBlocks.push(data.slice(subOffset + 1, subOffset + 1 + subBlockSize));
subOffset += 1 + subBlockSize;
totalLength += 1 + subBlockSize;
}
// Add terminator
totalLength += 1;
extensions.push({
offset,
length: totalLength,
@@ -131,16 +134,16 @@ function findAppExtensions(data: Uint8Array, startOffset: number): Array<{
authCode,
dataBlocks,
});
offset = subOffset + 1;
} else if (data[offset] === 0x3B) {
} else if (data[offset] === 0x3b) {
// Trailer - end of GIF
break;
} else {
offset++;
}
}
return extensions;
}
@@ -149,33 +152,33 @@ function findAppExtensions(data: Uint8Array, startOffset: number): Array<{
*/
function createPaarrotExtension(color: string): Uint8Array {
const colorBytes = new TextEncoder().encode(color);
// Calculate total size
// 0x21 + 0xFF + 0x0B + appId(8) + authCode(3) + sub-block(1 + colorBytes.length) + 0x00
const totalSize = 2 + 1 + 8 + 3 + 1 + colorBytes.length + 1;
const extension = new Uint8Array(totalSize);
let offset = 0;
extension[offset++] = 0x21; // Extension Introducer
extension[offset++] = 0xFF; // Application Extension Label
extension[offset++] = 0x0B; // Block size (always 11)
extension[offset++] = 0xff; // Application Extension Label
extension[offset++] = 0x0b; // Block size (always 11)
// Application Identifier (8 bytes)
extension.set(PAARROT_APP_ID_BYTES, offset);
offset += 8;
// Application Authentication Code (3 bytes)
extension.set(PAARROT_AUTH_CODE, offset);
offset += 3;
// Data sub-block
extension[offset++] = colorBytes.length;
extension.set(colorBytes, offset);
offset += colorBytes.length;
// Block terminator
extension[offset] = 0x00;
return extension;
}
@@ -184,16 +187,16 @@ function createPaarrotExtension(color: string): Uint8Array {
*/
export function extractColorFromGIF(imageData: ArrayBuffer | Uint8Array): string | undefined {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
if (!isGIF(data)) {
return undefined;
}
const gctSize = getGlobalColorTableSize(data);
const startOffset = 13 + gctSize; // Header(6) + LSD(7) + GCT
const extensions = findAppExtensions(data, startOffset);
for (const ext of extensions) {
if (ext.appId.startsWith('PAARROT')) {
if (ext.dataBlocks.length > 0) {
@@ -202,25 +205,28 @@ export function extractColorFromGIF(imageData: ArrayBuffer | Uint8Array): string
}
}
}
return undefined;
}
/**
* Embed paarrot color into GIF image data
*/
export function embedColorInGIF(imageData: ArrayBuffer | Uint8Array, color: string): Uint8Array | null {
export function embedColorInGIF(
imageData: ArrayBuffer | Uint8Array,
color: string,
): Uint8Array | null {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
if (!isGIF(data)) {
return null;
}
const gctSize = getGlobalColorTableSize(data);
const insertOffset = 13 + gctSize; // After Header + LSD + GCT
const extensions = findAppExtensions(data, insertOffset);
// Find existing PAARROT extension
let existingExt: { offset: number; length: number } | null = null;
for (const ext of extensions) {
@@ -229,12 +235,12 @@ export function embedColorInGIF(imageData: ArrayBuffer | Uint8Array, color: stri
break;
}
}
// Create new extension
const newExtension = createPaarrotExtension(color);
let newData: Uint8Array;
if (existingExt) {
// Replace existing extension
newData = new Uint8Array(data.length - existingExt.length + newExtension.length);
@@ -242,7 +248,7 @@ export function embedColorInGIF(imageData: ArrayBuffer | Uint8Array, color: stri
newData.set(newExtension, existingExt.offset);
newData.set(
data.slice(existingExt.offset + existingExt.length),
existingExt.offset + newExtension.length
existingExt.offset + newExtension.length,
);
} else {
// Insert after GCT (before any other blocks)
@@ -251,7 +257,7 @@ export function embedColorInGIF(imageData: ArrayBuffer | Uint8Array, color: stri
newData.set(newExtension, insertOffset);
newData.set(data.slice(insertOffset), insertOffset + newExtension.length);
}
return newData;
}
@@ -260,16 +266,16 @@ export function embedColorInGIF(imageData: ArrayBuffer | Uint8Array, color: stri
*/
export function removeColorFromGIF(imageData: ArrayBuffer | Uint8Array): Uint8Array | null {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
if (!isGIF(data)) {
return null;
}
const gctSize = getGlobalColorTableSize(data);
const startOffset = 13 + gctSize;
const extensions = findAppExtensions(data, startOffset);
// Find existing PAARROT extension
let existingExt: { offset: number; length: number } | null = null;
for (const ext of extensions) {
@@ -278,18 +284,15 @@ export function removeColorFromGIF(imageData: ArrayBuffer | Uint8Array): Uint8Ar
break;
}
}
if (!existingExt) {
return data;
}
// Remove the extension
const newData = new Uint8Array(data.length - existingExt.length);
newData.set(data.slice(0, existingExt.offset), 0);
newData.set(
data.slice(existingExt.offset + existingExt.length),
existingExt.offset
);
newData.set(data.slice(existingExt.offset + existingExt.length), existingExt.offset);
return newData;
}
+50 -40
View File
@@ -43,8 +43,7 @@ class LRUCache<K, V> {
set(key: K, value: V): void {
if (this.cache.has(key)) {
this.cache.delete(key);
}
else if (this.cache.size >= this.maxSize) {
} else if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
if (firstKey !== undefined) {
this.cache.delete(firstKey);
@@ -90,7 +89,7 @@ const RIFF_SIGNATURE = [0x52, 0x49, 0x46, 0x46]; // "RIFF"
const WEBP_OFFSET_SIGNATURE = [0x57, 0x45, 0x42, 0x50]; // "WEBP" at offset 8
/** JPEG signature */
const JPEG_SIGNATURE = [0xFF, 0xD8];
const JPEG_SIGNATURE = [0xff, 0xd8];
/** GIF signatures */
const GIF87A_SIGNATURE = [0x47, 0x49, 0x46, 0x38, 0x37, 0x61]; // "GIF87a"
@@ -103,9 +102,9 @@ export type ImageFormat = 'png' | 'webp' | 'jpeg' | 'gif' | 'unknown';
*/
export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat {
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
if (bytes.length < 12) return 'unknown';
// Check PNG signature
let isPNG = true;
for (let i = 0; i < 8; i++) {
@@ -115,7 +114,7 @@ export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat {
}
}
if (isPNG) return 'png';
// Check WebP signature (RIFF + WEBP)
let isRIFF = true;
for (let i = 0; i < 4; i++) {
@@ -134,12 +133,12 @@ export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat {
}
if (isWebP) return 'webp';
}
// Check JPEG signature (FFD8)
if (bytes[0] === JPEG_SIGNATURE[0] && bytes[1] === JPEG_SIGNATURE[1]) {
return 'jpeg';
}
// Check GIF signatures
let isGIF87a = true;
for (let i = 0; i < 6; i++) {
@@ -149,7 +148,7 @@ export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat {
}
}
if (isGIF87a) return 'gif';
let isGIF89a = true;
for (let i = 0; i < 6; i++) {
if (bytes[i] !== GIF89A_SIGNATURE[i]) {
@@ -158,7 +157,7 @@ export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat {
}
}
if (isGIF89a) return 'gif';
return 'unknown';
}
@@ -169,9 +168,9 @@ export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat {
*/
export function extractColorFromImage(imageData: ArrayBuffer | Uint8Array): string | undefined {
const format = detectImageFormat(imageData);
console.log('[extractColorFromImage] Detected format:', format);
switch (format) {
case 'png':
return extractColorFromPNG(imageData);
@@ -194,7 +193,7 @@ export function extractColorFromImage(imageData: ArrayBuffer | Uint8Array): stri
*/
export function extractBannerFromImage(imageData: ArrayBuffer | Uint8Array): string | undefined {
const format = detectImageFormat(imageData);
switch (format) {
case 'png':
return extractBannerFromPNG(imageData);
@@ -212,9 +211,9 @@ export function extractBannerFromImage(imageData: ArrayBuffer | Uint8Array): str
*/
export function extractMetadataFromImage(imageData: ArrayBuffer | Uint8Array): ImageMetadata {
const format = detectImageFormat(imageData);
console.log('[extractMetadataFromImage] Detected format:', format);
switch (format) {
case 'png':
const pngMetadata = extractMetadataFromPNG(imageData);
@@ -240,9 +239,12 @@ export function extractMetadataFromImage(imageData: ArrayBuffer | Uint8Array): I
* @param color - The color string to embed (e.g., '#ff5500')
* @returns New image data with embedded color, or null if not a supported format
*/
export function embedColorInImage(imageData: ArrayBuffer | Uint8Array, color: string): Uint8Array | null {
export function embedColorInImage(
imageData: ArrayBuffer | Uint8Array,
color: string,
): Uint8Array | null {
const format = detectImageFormat(imageData);
switch (format) {
case 'png':
return embedColorInPNG(imageData, color);
@@ -269,7 +271,7 @@ export function needsPngForMetadata(metadata: ImageMetadata): boolean {
* Convert image data to PNG via canvas (needed for banner/border/gradient metadata).
*/
export async function convertImageDataToPng(
imageData: ArrayBuffer | Uint8Array
imageData: ArrayBuffer | Uint8Array,
): Promise<Uint8Array | null> {
const bytes = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
const format = detectImageFormat(bytes);
@@ -320,7 +322,7 @@ export function uint8ArrayToBlob(data: Uint8Array, type: string): Blob {
*/
export function embedMetadataInImage(
imageData: ArrayBuffer | Uint8Array,
metadata: ImageMetadata
metadata: ImageMetadata,
): Uint8Array | null {
const format = detectImageFormat(imageData);
const bytes = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
@@ -335,7 +337,7 @@ export function embedMetadataInImage(
if (needsPngForMetadata(metadata)) {
console.warn(
'[embedMetadataInImage] Banner/border/gradient require PNG; convert with convertImageDataToPng first. Got:',
format
format,
);
return null;
}
@@ -357,7 +359,7 @@ export function embedMetadataInImage(
*/
export function removeColorFromImage(imageData: ArrayBuffer | Uint8Array): Uint8Array | null {
const format = detectImageFormat(imageData);
switch (format) {
case 'png':
return removeColorFromPNG(imageData);
@@ -410,7 +412,9 @@ export function getExtension(format: ImageFormat): string {
}
// LRU cache for avatar metadata to avoid refetching
const avatarMetadataCache = new LRUCache<string, { metadata: ImageMetadata; timestamp: number }>(100);
const avatarMetadataCache = new LRUCache<string, { metadata: ImageMetadata; timestamp: number }>(
100,
);
const METADATA_CACHE_TTL_MS = 30 * 60 * 1000; // 30 minutes
// In-flight fetch tracking to prevent duplicate parallel requests
@@ -423,7 +427,10 @@ const inflightMetadataFetches = new Map<string, Promise<ImageMetadata>>();
* @param accessToken - Optional access token for authenticated media
* @returns The color string if found, or undefined
*/
export async function fetchAndExtractColor(url: string, accessToken?: string | null): Promise<string | undefined> {
export async function fetchAndExtractColor(
url: string,
accessToken?: string | null,
): Promise<string | undefined> {
// Check if full metadata is cached
const cached = avatarMetadataCache.get(url);
if (cached && Date.now() - cached.timestamp < METADATA_CACHE_TTL_MS) {
@@ -440,27 +447,27 @@ export async function fetchAndExtractColor(url: string, accessToken?: string | n
}
console.log('[fetchAndExtractColor] Fetching and extracting color from', url);
const fetchPromise = (async () => {
try {
const response = await fetch(url, {
method: 'GET',
headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
});
console.log('[fetchAndExtractColor] Fetch response status:', response.ok, response.status);
if (!response.ok) return undefined;
const data = await response.arrayBuffer();
console.log('[fetchAndExtractColor] Downloaded', data.byteLength, 'bytes');
const color = extractColorFromImage(data);
console.log('[fetchAndExtractColor] Extracted color:', color);
// Don't cache here - fetchAndExtractMetadata will cache full metadata
// This avoids cache collision where color-only fetch overwrites full metadata
return color;
} catch (error) {
console.error('[fetchAndExtractColor] Error fetching/extracting color:', error);
@@ -480,7 +487,10 @@ export async function fetchAndExtractColor(url: string, accessToken?: string | n
* @param accessToken - Optional access token for authenticated media
* @returns Object with color and banner if found
*/
export async function fetchAndExtractMetadata(url: string, accessToken?: string | null): Promise<ImageMetadata> {
export async function fetchAndExtractMetadata(
url: string,
accessToken?: string | null,
): Promise<ImageMetadata> {
// Check cache first
const cached = avatarMetadataCache.get(url);
if (cached && Date.now() - cached.timestamp < METADATA_CACHE_TTL_MS) {
@@ -504,23 +514,23 @@ export async function fetchAndExtractMetadata(url: string, accessToken?: string
method: 'GET',
headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
});
console.log('[fetchAndExtractMetadata] Fetch response status:', response.ok, response.status);
if (!response.ok) return {};
const data = await response.arrayBuffer();
console.log('[fetchAndExtractMetadata] Downloaded', data.byteLength, 'bytes');
const metadata = extractMetadataFromImage(data);
console.log('[fetchAndExtractMetadata] Extracted metadata:', metadata);
// Cache the result
avatarMetadataCache.set(url, {
metadata,
timestamp: Date.now()
avatarMetadataCache.set(url, {
metadata,
timestamp: Date.now(),
});
return metadata;
} catch {
return {};
+57 -53
View File
@@ -1,7 +1,7 @@
/**
* Utilities for reading and writing JPEG metadata (XMP/APP1 segments)
* Used to embed user color in avatar images
*
*
* JPEG structure:
* - Starts with FFD8 (SOI marker)
* - Contains segments: FF + marker type + length (2 bytes BE) + data
@@ -11,12 +11,12 @@
/* eslint-disable no-bitwise */
/* eslint-disable no-plusplus */
/* eslint-disable no-console */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-continue */
/** JPEG signature bytes */
const JPEG_SOI = new Uint8Array([0xFF, 0xD8]); // Start of Image
const JPEG_SOI = new Uint8Array([0xff, 0xd8]); // Start of Image
/** XMP namespace identifier in APP1 segment */
const XMP_NAMESPACE = 'http://ns.adobe.com/xap/1.0/\0';
@@ -31,7 +31,7 @@ const PAARROT_XMP_END = '<?xpacket end="w"?>';
*/
function isJPEG(data: Uint8Array): boolean {
if (data.length < 2) return false;
return data[0] === 0xFF && data[1] === 0xD8;
return data[0] === 0xff && data[1] === 0xd8;
}
/**
@@ -77,50 +77,52 @@ function extractColorFromXMP(xmpData: string): string | undefined {
/**
* Parse JPEG segments
*/
function parseSegments(data: Uint8Array): Array<{ marker: number; data: Uint8Array; offset: number; length: number }> {
function parseSegments(
data: Uint8Array,
): Array<{ marker: number; data: Uint8Array; offset: number; length: number }> {
const segments: Array<{ marker: number; data: Uint8Array; offset: number; length: number }> = [];
let offset = 2; // Skip SOI marker
while (offset < data.length - 1) {
// Find next marker (0xFF followed by non-zero, non-0xFF byte)
if (data[offset] !== 0xFF) {
if (data[offset] !== 0xff) {
offset++;
continue;
}
const marker = data[offset + 1];
// Skip padding bytes (0xFF)
if (marker === 0xFF || marker === 0x00) {
if (marker === 0xff || marker === 0x00) {
offset++;
continue;
}
// EOI (End of Image) or SOS (Start of Scan) - stop parsing
if (marker === 0xD9 || marker === 0xDA) {
if (marker === 0xd9 || marker === 0xda) {
break;
}
// Markers without length field (RST0-RST7, SOI, EOI)
if ((marker >= 0xD0 && marker <= 0xD7) || marker === 0xD8 || marker === 0xD9) {
if ((marker >= 0xd0 && marker <= 0xd7) || marker === 0xd8 || marker === 0xd9) {
offset += 2;
continue;
}
// Read segment length (includes the 2 length bytes)
const segmentLength = readUint16BE(data, offset + 2);
const segmentData = data.slice(offset + 4, offset + 2 + segmentLength);
segments.push({
marker,
data: segmentData,
offset,
length: 2 + segmentLength, // marker (2) + length field + data
});
offset += 2 + segmentLength;
}
return segments;
}
@@ -130,11 +132,11 @@ function parseSegments(data: Uint8Array): Array<{ marker: number; data: Uint8Arr
function isPaarrotXMP(segmentData: Uint8Array): boolean {
// Check for XMP namespace
if (segmentData.length < XMP_NAMESPACE_BYTES.length) return false;
for (let i = 0; i < XMP_NAMESPACE_BYTES.length; i++) {
if (segmentData[i] !== XMP_NAMESPACE_BYTES[i]) return false;
}
const xmpString = new TextDecoder().decode(segmentData.slice(XMP_NAMESPACE_BYTES.length));
return xmpString.includes('paarrot:color') || xmpString.includes('paarrot.app');
}
@@ -144,16 +146,16 @@ function isPaarrotXMP(segmentData: Uint8Array): boolean {
*/
export function extractColorFromJPEG(imageData: ArrayBuffer | Uint8Array): string | undefined {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
if (!isJPEG(data)) {
return undefined;
}
const segments = parseSegments(data);
for (const segment of segments) {
// APP1 marker (0xE1) is used for XMP
if (segment.marker === 0xE1) {
if (segment.marker === 0xe1) {
// Check for XMP namespace
if (segment.data.length >= XMP_NAMESPACE_BYTES.length) {
let isXMP = true;
@@ -163,9 +165,11 @@ export function extractColorFromJPEG(imageData: ArrayBuffer | Uint8Array): strin
break;
}
}
if (isXMP) {
const xmpString = new TextDecoder().decode(segment.data.slice(XMP_NAMESPACE_BYTES.length));
const xmpString = new TextDecoder().decode(
segment.data.slice(XMP_NAMESPACE_BYTES.length),
);
const color = extractColorFromXMP(xmpString);
if (color) {
return color;
@@ -174,49 +178,52 @@ export function extractColorFromJPEG(imageData: ArrayBuffer | Uint8Array): strin
}
}
}
return undefined;
}
/**
* Embed paarrot color into JPEG image data
*/
export function embedColorInJPEG(imageData: ArrayBuffer | Uint8Array, color: string): Uint8Array | null {
export function embedColorInJPEG(
imageData: ArrayBuffer | Uint8Array,
color: string,
): Uint8Array | null {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
if (!isJPEG(data)) {
return null;
}
const segments = parseSegments(data);
// Find existing paarrot XMP segment
let existingSegment: { offset: number; length: number } | null = null;
for (const segment of segments) {
if (segment.marker === 0xE1 && isPaarrotXMP(segment.data)) {
if (segment.marker === 0xe1 && isPaarrotXMP(segment.data)) {
existingSegment = { offset: segment.offset, length: segment.length };
break;
}
}
// Create XMP APP1 segment
const xmpData = createXMPData(color);
const xmpBytes = new TextEncoder().encode(xmpData);
const segmentData = new Uint8Array(XMP_NAMESPACE_BYTES.length + xmpBytes.length);
segmentData.set(XMP_NAMESPACE_BYTES, 0);
segmentData.set(xmpBytes, XMP_NAMESPACE_BYTES.length);
// APP1 segment: FF E1 + length (2 bytes) + data
const segmentLength = 2 + segmentData.length; // length field + data
const app1Segment = new Uint8Array(4 + segmentData.length);
app1Segment[0] = 0xFF;
app1Segment[1] = 0xE1;
app1Segment[0] = 0xff;
app1Segment[1] = 0xe1;
app1Segment.set(writeUint16BE(segmentLength), 2);
app1Segment.set(segmentData, 4);
let newData: Uint8Array;
if (existingSegment) {
// Replace existing segment
newData = new Uint8Array(data.length - existingSegment.length + app1Segment.length);
@@ -224,7 +231,7 @@ export function embedColorInJPEG(imageData: ArrayBuffer | Uint8Array, color: str
newData.set(app1Segment, existingSegment.offset);
newData.set(
data.slice(existingSegment.offset + existingSegment.length),
existingSegment.offset + app1Segment.length
existingSegment.offset + app1Segment.length,
);
} else {
// Insert after SOI marker (at offset 2)
@@ -233,7 +240,7 @@ export function embedColorInJPEG(imageData: ArrayBuffer | Uint8Array, color: str
newData.set(app1Segment, 2);
newData.set(data.slice(2), 2 + app1Segment.length);
}
return newData;
}
@@ -242,34 +249,31 @@ export function embedColorInJPEG(imageData: ArrayBuffer | Uint8Array, color: str
*/
export function removeColorFromJPEG(imageData: ArrayBuffer | Uint8Array): Uint8Array | null {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
if (!isJPEG(data)) {
return null;
}
const segments = parseSegments(data);
// Find existing paarrot XMP segment
let existingSegment: { offset: number; length: number } | null = null;
for (const segment of segments) {
if (segment.marker === 0xE1 && isPaarrotXMP(segment.data)) {
if (segment.marker === 0xe1 && isPaarrotXMP(segment.data)) {
existingSegment = { offset: segment.offset, length: segment.length };
break;
}
}
if (!existingSegment) {
return data;
}
// Remove the segment
const newData = new Uint8Array(data.length - existingSegment.length);
newData.set(data.slice(0, existingSegment.offset), 0);
newData.set(
data.slice(existingSegment.offset + existingSegment.length),
existingSegment.offset
);
newData.set(data.slice(existingSegment.offset + existingSegment.length), existingSegment.offset);
return newData;
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { CryptoApi } from 'matrix-js-sdk/lib/crypto-api';
export const verifiedDevice = async (
api: CryptoApi,
userId: string,
deviceId: string
deviceId: string,
): Promise<boolean | null> => {
const status = await api.getDeviceVerificationStatus(userId, deviceId);
+1 -1
View File
@@ -2,7 +2,7 @@ import { AuthType, IAuthData, UIAFlow } from 'matrix-js-sdk';
export const getSupportedUIAFlows = (uiaFlows: UIAFlow[], supportedStages: string[]): UIAFlow[] => {
const supportedUIAFlows = uiaFlows.filter((flow) =>
flow.stages.every((stage) => supportedStages.includes(stage))
flow.stages.every((stage) => supportedStages.includes(stage)),
);
return supportedUIAFlows;
+22 -20
View File
@@ -43,7 +43,7 @@ export const getCanonicalAliasRoomId = (mx: MatrixClient, alias: string): string
?.find(
(room) =>
room.getCanonicalAlias() === alias &&
getStateEvent(room, StateEvent.RoomTombstone) === undefined
getStateEvent(room, StateEvent.RoomTombstone) === undefined,
)?.roomId;
export const getCanonicalAliasOrRoomId = (mx: MatrixClient, roomId: string): string => {
@@ -105,7 +105,7 @@ export const getThumbnailContent = (thumbnailInfo: {
};
export const encryptFile = async (
file: File | Blob
file: File | Blob,
): Promise<{
encInfo: EncryptedAttachmentInfo;
file: File;
@@ -126,7 +126,7 @@ export const encryptFile = async (
export const decryptFile = async (
dataBuffer: ArrayBuffer,
type: string,
encInfo: EncryptedAttachmentInfo
encInfo: EncryptedAttachmentInfo,
): Promise<Blob> => {
const dataArray = await decryptAttachment(dataBuffer, encInfo);
const blob = new Blob([dataArray], { type });
@@ -148,7 +148,7 @@ export type ContentUploadOptions = {
export const uploadContent = async (
mx: MatrixClient,
file: TUploadContent,
options: ContentUploadOptions
options: ContentUploadOptions,
) => {
const { name, fileType, hideFilename, onProgress, onPromise, onSuccess, onError } = options;
@@ -186,7 +186,7 @@ export const getDMRoomFor = (mx: MatrixClient, userId: string): Room | undefined
(room) =>
room.getMyMembership() === Membership.Join &&
room.hasEncryptionStateEvent() &&
room.getMembers().length <= 2
room.getMembers().length <= 2,
);
return dmLikeRooms.find((room) => room.getMember(userId));
@@ -220,7 +220,7 @@ export const guessDmRoomUserId = (room: Room, myUserId: string): string => {
// if there are no joined members other than us, use the oldest member
const member1 = getOldestMember(
room.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getMembers() ?? []
room.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getMembers() ?? [],
);
return member1?.userId ?? myUserId;
};
@@ -228,7 +228,7 @@ export const guessDmRoomUserId = (room: Room, myUserId: string): string => {
export const addRoomIdToMDirect = async (
mx: MatrixClient,
roomId: string,
userId: string
userId: string,
): Promise<void> => {
const mDirectsEvent = mx.getAccountData(AccountDataEvent.Direct as any);
let userIdToRoomIds: Record<string, string[]> = {};
@@ -284,7 +284,7 @@ export const mxcUrlToHttp = (
height?: number,
resizeMethod?: string,
allowDirectLinks?: boolean,
allowRedirects?: boolean
allowRedirects?: boolean,
): string | null =>
mx.mxcUrlToHttp(
mxcUrl,
@@ -293,7 +293,7 @@ export const mxcUrlToHttp = (
resizeMethod,
allowDirectLinks,
allowRedirects,
useAuthentication
useAuthentication,
);
/**
@@ -302,40 +302,42 @@ export const mxcUrlToHttp = (
export const isAuthenticatedMediaUrl = (url: string): boolean =>
url.includes('/_matrix/client/v1/media/download') ||
url.includes('/_matrix/client/v1/media/thumbnail') ||
url.includes('/_matrix/media/') &&
(url.includes('/download/') || url.includes('/thumbnail/'));
(url.includes('/_matrix/media/') && (url.includes('/download/') || url.includes('/thumbnail/')));
/**
* Downloads media with optional authentication.
* For authenticated media URLs, the access token is required.
* Falls back to unauthenticated request if authenticated request fails with 401.
* Returns an empty blob with error type if all attempts fail, to prevent cascading failures.
*
*
* @param src - The media URL to download
* @param accessToken - Optional access token (if not provided, will use current session's token)
*/
export const downloadMedia = async (src: string, accessToken?: string | null): Promise<Blob> => {
// Import here to avoid circular dependencies
const { getCurrentAccessToken } = await import('./auth');
// Use provided token, or fall back to current session's token
const token = accessToken ?? getCurrentAccessToken();
const needsAuth = isAuthenticatedMediaUrl(src);
const headers: HeadersInit = {};
if (needsAuth && token) {
headers.Authorization = `Bearer ${token}`;
}
try {
let res = await fetch(src, { method: 'GET', headers });
// If we got a 401 and we tried with auth, fallback to unauthenticated request
if (!res.ok && res.status === 401 && needsAuth && token) {
console.warn('[downloadMedia] Auth failed (401), attempting unauthenticated fallback for:', src);
console.warn(
'[downloadMedia] Auth failed (401), attempting unauthenticated fallback for:',
src,
);
res = await fetch(src, { method: 'GET' });
}
if (!res.ok) {
console.warn(`[downloadMedia] Failed to download media (${res.status}) from:`, src);
throw new Error(`Failed to download media: ${res.status}`);
@@ -352,7 +354,7 @@ export const downloadMedia = async (src: string, accessToken?: string | null): P
export const downloadEncryptedMedia = async (
src: string,
decryptContent: (buf: ArrayBuffer) => Promise<Blob>,
accessToken?: string | null
accessToken?: string | null,
): Promise<Blob> => {
const encryptedContent = await downloadMedia(src, accessToken);
const decryptedContent = await decryptContent(await encryptedContent.arrayBuffer());
@@ -363,7 +365,7 @@ export const downloadEncryptedMedia = async (
export const rateLimitedActions = async <T, R = void>(
data: T[],
callback: (item: T, index: number) => Promise<R>,
maxRetryCount?: number
maxRetryCount?: number,
) => {
let retryCount = 0;
+1 -1
View File
@@ -21,6 +21,6 @@ export async function markAsRead(mx: MatrixClient, roomId: string, privateReceip
await mx.sendReadReceipt(
latestEvent,
privateReceipt ? ReceiptType.ReadPrivate : ReceiptType.Read
privateReceipt ? ReceiptType.ReadPrivate : ReceiptType.Read,
);
}
+98 -73
View File
@@ -9,6 +9,8 @@
/* eslint-disable no-console */
/** PNG signature bytes */
import type { ImageMetadata, ProfileGradient } from './imageMetadata';
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
/** Key used to store user color in PNG metadata */
@@ -26,12 +28,12 @@ export const PAARROT_GRADIENT_KEY = 'paarrot:gradient';
let crc32Table: Uint32Array | null = null;
function getCRC32Table(): Uint32Array {
if (crc32Table) return crc32Table;
crc32Table = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let j = 0; j < 8; j++) {
c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
}
crc32Table[i] = c;
}
@@ -44,11 +46,11 @@ function getCRC32Table(): Uint32Array {
function crc32(data: Uint8Array): number {
let crc = 0xffffffff;
const table = getCRC32Table();
for (let i = 0; i < data.length; i++) {
crc = (crc >>> 8) ^ table[(crc ^ data[i]) & 0xff];
}
return (crc ^ 0xffffffff) >>> 0;
}
@@ -56,7 +58,9 @@ function crc32(data: Uint8Array): number {
* Read a 32-bit big-endian integer from a buffer
*/
function readUint32BE(data: Uint8Array, offset: number): number {
return (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
return (
(data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]
);
}
/**
@@ -77,55 +81,57 @@ function writeUint32BE(value: number): Uint8Array {
function createTextChunk(key: string, value: string): Uint8Array {
const keyBytes = new TextEncoder().encode(key);
const valueBytes = new TextEncoder().encode(value);
// tEXt chunk data: key + null byte + value
const chunkData = new Uint8Array(keyBytes.length + 1 + valueBytes.length);
chunkData.set(keyBytes, 0);
chunkData[keyBytes.length] = 0; // null separator
chunkData.set(valueBytes, keyBytes.length + 1);
const chunkType = new TextEncoder().encode('tEXt');
// Calculate CRC over type + data
const crcData = new Uint8Array(4 + chunkData.length);
crcData.set(chunkType, 0);
crcData.set(chunkData, 4);
const crc = crc32(crcData);
// Full chunk: length (4) + type (4) + data + crc (4)
const chunk = new Uint8Array(4 + 4 + chunkData.length + 4);
chunk.set(writeUint32BE(chunkData.length), 0);
chunk.set(chunkType, 4);
chunk.set(chunkData, 8);
chunk.set(writeUint32BE(crc), 8 + chunkData.length);
return chunk;
}
/**
* Parse PNG chunks from image data
*/
function parseChunks(data: Uint8Array): Array<{ type: string; data: Uint8Array; offset: number; length: number }> {
function parseChunks(
data: Uint8Array,
): Array<{ type: string; data: Uint8Array; offset: number; length: number }> {
const chunks: Array<{ type: string; data: Uint8Array; offset: number; length: number }> = [];
let offset = 8; // Skip PNG signature
while (offset < data.length) {
const length = readUint32BE(data, offset);
const type = new TextDecoder().decode(data.slice(offset + 4, offset + 8));
const chunkData = data.slice(offset + 8, offset + 8 + length);
chunks.push({
type,
data: chunkData,
offset,
length: 12 + length, // length field + type + data + crc
});
offset += 12 + length;
if (type === 'IEND') break;
}
return chunks;
}
@@ -135,10 +141,10 @@ function parseChunks(data: Uint8Array): Array<{ type: string; data: Uint8Array;
function parseTextChunk(data: Uint8Array): { key: string; value: string } | null {
const nullIndex = data.indexOf(0);
if (nullIndex === -1) return null;
const key = new TextDecoder().decode(data.slice(0, nullIndex));
const value = new TextDecoder().decode(data.slice(nullIndex + 1));
return { key, value };
}
@@ -149,7 +155,7 @@ function parseTextChunk(data: Uint8Array): { key: string; value: string } | null
*/
export function extractColorFromPNG(imageData: ArrayBuffer | Uint8Array): string | undefined {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
// Verify PNG signature
for (let i = 0; i < 8; i++) {
if (data[i] !== PNG_SIGNATURE[i]) {
@@ -157,10 +163,10 @@ export function extractColorFromPNG(imageData: ArrayBuffer | Uint8Array): string
return undefined; // Not a PNG
}
}
const chunks = parseChunks(data);
console.log('[extractColorFromPNG] Found', chunks.length, 'chunks');
let textChunksFound = 0;
for (const chunk of chunks) {
if (chunk.type === 'tEXt') {
@@ -175,8 +181,12 @@ export function extractColorFromPNG(imageData: ArrayBuffer | Uint8Array): string
}
}
}
console.log('[extractColorFromPNG] No paarrot:color found (found', textChunksFound, 'tEXt chunks)');
console.log(
'[extractColorFromPNG] No paarrot:color found (found',
textChunksFound,
'tEXt chunks)',
);
return undefined;
}
@@ -187,16 +197,16 @@ export function extractColorFromPNG(imageData: ArrayBuffer | Uint8Array): string
*/
export function extractBannerFromPNG(imageData: ArrayBuffer | Uint8Array): string | undefined {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
// Verify PNG signature
for (let i = 0; i < 8; i++) {
if (data[i] !== PNG_SIGNATURE[i]) {
return undefined; // Not a PNG
}
}
const chunks = parseChunks(data);
for (const chunk of chunks) {
if (chunk.type === 'tEXt') {
const text = parseTextChunk(chunk.data);
@@ -205,12 +215,10 @@ export function extractBannerFromPNG(imageData: ArrayBuffer | Uint8Array): strin
}
}
}
return undefined;
}
import type { ImageMetadata, ProfileGradient } from './imageMetadata';
/**
* Extract all paarrot metadata from PNG image data
* @param imageData - Raw PNG image data as ArrayBuffer or Uint8Array
@@ -219,7 +227,7 @@ import type { ImageMetadata, ProfileGradient } from './imageMetadata';
export function extractMetadataFromPNG(imageData: ArrayBuffer | Uint8Array): ImageMetadata {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
const metadata: ImageMetadata = {};
// Verify PNG signature
for (let i = 0; i < 8; i++) {
if (data[i] !== PNG_SIGNATURE[i]) {
@@ -227,10 +235,10 @@ export function extractMetadataFromPNG(imageData: ArrayBuffer | Uint8Array): Ima
return metadata; // Not a PNG
}
}
const chunks = parseChunks(data);
console.log('[extractMetadataFromPNG] Found', chunks.length, 'chunks');
let textChunksFound = 0;
for (const chunk of chunks) {
if (chunk.type === 'tEXt') {
@@ -254,9 +262,15 @@ export function extractMetadataFromPNG(imageData: ArrayBuffer | Uint8Array): Ima
}
}
}
console.log('[extractMetadataFromPNG] Final metadata extracted:', metadata, 'found', textChunksFound, 'tEXt chunks');
console.log(
'[extractMetadataFromPNG] Final metadata extracted:',
metadata,
'found',
textChunksFound,
'tEXt chunks',
);
return metadata;
}
@@ -266,22 +280,25 @@ export function extractMetadataFromPNG(imageData: ArrayBuffer | Uint8Array): Ima
* @param color - The color string to embed (e.g., '#ff5500')
* @returns New PNG data with embedded color, or null if not a valid PNG
*/
export function embedColorInPNG(imageData: ArrayBuffer | Uint8Array, color: string): Uint8Array | null {
export function embedColorInPNG(
imageData: ArrayBuffer | Uint8Array,
color: string,
): Uint8Array | null {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
// Verify PNG signature
for (let i = 0; i < 8; i++) {
if (data[i] !== PNG_SIGNATURE[i]) {
return null; // Not a PNG
}
}
const chunks = parseChunks(data);
// Find IHDR chunk (always first) and any existing paarrot tEXt chunk
let insertOffset = 8; // After signature
let existingPaarrotChunk: { offset: number; length: number } | null = null;
for (const chunk of chunks) {
if (chunk.type === 'IHDR') {
insertOffset = chunk.offset + chunk.length; // Insert after IHDR
@@ -292,13 +309,13 @@ export function embedColorInPNG(imageData: ArrayBuffer | Uint8Array, color: stri
}
}
}
// Create new tEXt chunk with color
const colorChunk = createTextChunk(PAARROT_COLOR_KEY, color);
// Build new PNG data
let newData: Uint8Array;
if (existingPaarrotChunk) {
// Replace existing chunk
newData = new Uint8Array(data.length - existingPaarrotChunk.length + colorChunk.length);
@@ -306,7 +323,7 @@ export function embedColorInPNG(imageData: ArrayBuffer | Uint8Array, color: stri
newData.set(colorChunk, existingPaarrotChunk.offset);
newData.set(
data.slice(existingPaarrotChunk.offset + existingPaarrotChunk.length),
existingPaarrotChunk.offset + colorChunk.length
existingPaarrotChunk.offset + colorChunk.length,
);
} else {
// Insert new chunk after IHDR
@@ -315,12 +332,17 @@ export function embedColorInPNG(imageData: ArrayBuffer | Uint8Array, color: stri
newData.set(colorChunk, insertOffset);
newData.set(data.slice(insertOffset), insertOffset + colorChunk.length);
}
return newData;
}
/** All paarrot metadata keys */
const PAARROT_KEYS = [PAARROT_COLOR_KEY, PAARROT_BANNER_KEY, PAARROT_BORDER_COLOR_KEY, PAARROT_GRADIENT_KEY];
const PAARROT_KEYS = [
PAARROT_COLOR_KEY,
PAARROT_BANNER_KEY,
PAARROT_BORDER_COLOR_KEY,
PAARROT_GRADIENT_KEY,
];
/**
* Embed paarrot metadata into PNG image data
@@ -331,34 +353,37 @@ const PAARROT_KEYS = [PAARROT_COLOR_KEY, PAARROT_BANNER_KEY, PAARROT_BORDER_COLO
*/
export function embedMetadataInPNG(
imageData: ArrayBuffer | Uint8Array,
metadata: ImageMetadata
metadata: ImageMetadata,
): Uint8Array | null {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
// Verify PNG signature
for (let i = 0; i < 8; i++) {
if (data[i] !== PNG_SIGNATURE[i]) {
return null; // Not a PNG
}
}
const chunks = parseChunks(data);
// Get existing metadata
const existing = extractMetadataFromPNG(data);
// Merge with new metadata
const finalMetadata: ImageMetadata = {
color: metadata.color !== undefined ? metadata.color : existing.color,
banner: metadata.banner !== undefined ? metadata.banner : existing.banner,
avatarBorderColor: metadata.avatarBorderColor !== undefined ? metadata.avatarBorderColor : existing.avatarBorderColor,
avatarBorderColor:
metadata.avatarBorderColor !== undefined
? metadata.avatarBorderColor
: existing.avatarBorderColor,
gradient: metadata.gradient !== undefined ? metadata.gradient : existing.gradient,
};
// Find IHDR chunk and existing paarrot chunks
let insertOffset = 8;
const existingChunks: { key: string; offset: number; length: number }[] = [];
for (const chunk of chunks) {
if (chunk.type === 'IHDR') {
insertOffset = chunk.offset + chunk.length;
@@ -369,7 +394,7 @@ export function embedMetadataInPNG(
}
}
}
// Create new chunks
const newChunks: Uint8Array[] = [];
if (finalMetadata.color) {
@@ -384,46 +409,46 @@ export function embedMetadataInPNG(
if (finalMetadata.gradient) {
newChunks.push(createTextChunk(PAARROT_GRADIENT_KEY, JSON.stringify(finalMetadata.gradient)));
}
// Calculate new size
const removedSize = existingChunks.reduce((sum, chunk) => sum + chunk.length, 0);
const addedSize = newChunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
const newSize = data.length - removedSize + addedSize;
// Build new PNG
const newData = new Uint8Array(newSize);
let writeOffset = 0;
let readOffset = 0;
// Sort existing chunks by offset
existingChunks.sort((a, b) => a.offset - b.offset);
// Copy data, skipping old chunks and inserting new ones
for (const existingChunk of existingChunks) {
// Copy data before this chunk
newData.set(data.slice(readOffset, existingChunk.offset), writeOffset);
writeOffset += existingChunk.offset - readOffset;
// Skip the old chunk
readOffset = existingChunk.offset + existingChunk.length;
}
// If no existing chunks, insert at insertOffset
if (existingChunks.length === 0) {
newData.set(data.slice(0, insertOffset), 0);
writeOffset = insertOffset;
readOffset = insertOffset;
}
// Insert new chunks
for (const newChunk of newChunks) {
newData.set(newChunk, writeOffset);
writeOffset += newChunk.byteLength;
}
// Copy remaining data
newData.set(data.slice(readOffset), writeOffset);
return newData;
}
@@ -434,19 +459,19 @@ export function embedMetadataInPNG(
*/
export function removeColorFromPNG(imageData: ArrayBuffer | Uint8Array): Uint8Array | null {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
// Verify PNG signature
for (let i = 0; i < 8; i++) {
if (data[i] !== PNG_SIGNATURE[i]) {
return null; // Not a PNG
}
}
const chunks = parseChunks(data);
// Find existing paarrot tEXt chunk
let existingPaarrotChunk: { offset: number; length: number } | null = null;
for (const chunk of chunks) {
if (chunk.type === 'tEXt') {
const text = parseTextChunk(chunk.data);
@@ -456,20 +481,20 @@ export function removeColorFromPNG(imageData: ArrayBuffer | Uint8Array): Uint8Ar
}
}
}
if (!existingPaarrotChunk) {
// No color to remove
return data;
}
// Build new PNG data without the color chunk
const newData = new Uint8Array(data.length - existingPaarrotChunk.length);
newData.set(data.slice(0, existingPaarrotChunk.offset), 0);
newData.set(
data.slice(existingPaarrotChunk.offset + existingPaarrotChunk.length),
existingPaarrotChunk.offset
existingPaarrotChunk.offset,
);
return newData;
}
@@ -482,7 +507,7 @@ export async function fetchAndExtractColor(url: string): Promise<string | undefi
try {
const response = await fetch(url);
if (!response.ok) return undefined;
const arrayBuffer = await response.arrayBuffer();
return extractColorFromPNG(arrayBuffer);
} catch {
+1 -1
View File
@@ -24,7 +24,7 @@ function evictOldest(): void {
export async function getProfileAssetUrl(
mx: MatrixClient,
mxcUrl: string,
useAuthentication: boolean
useAuthentication: boolean,
): Promise<string | undefined> {
if (!mxcUrl) return undefined;
+38 -14
View File
@@ -83,14 +83,18 @@ export function parseColorPreference(value: unknown): ColorPreference | undefine
if (!value || typeof value !== 'object') return undefined;
const obj = value as Record<string, unknown>;
const on_dark = typeof obj.on_dark === 'string' && isValidHexColor(obj.on_dark) ? obj.on_dark : undefined;
const on_light = typeof obj.on_light === 'string' && isValidHexColor(obj.on_light) ? obj.on_light : undefined;
const on_dark =
typeof obj.on_dark === 'string' && isValidHexColor(obj.on_dark) ? obj.on_dark : undefined;
const on_light =
typeof obj.on_light === 'string' && isValidHexColor(obj.on_light) ? obj.on_light : undefined;
if (!on_dark && !on_light) return undefined;
return { on_dark, on_light };
}
export function extractColorPreferenceFromProfile(profile: Record<string, unknown>): ColorPreference | undefined {
export function extractColorPreferenceFromProfile(
profile: Record<string, unknown>,
): ColorPreference | undefined {
const stable = parseColorPreference(profile[PROFILE_KEY_COLOR_PREFERENCE_STABLE]);
if (stable) return stable;
return parseColorPreference(profile[PROFILE_KEY_COLOR_PREFERENCE_UNSTABLE]);
@@ -98,7 +102,7 @@ export function extractColorPreferenceFromProfile(profile: Record<string, unknow
export function resolveColorForTheme(
preference: ColorPreference | undefined,
themeKind: ThemeKind
themeKind: ThemeKind,
): string | undefined {
if (!preference) return undefined;
if (themeKind === ThemeKind.Dark) {
@@ -126,7 +130,7 @@ function parseStoredCollectible(value: unknown): StoredCollectible | undefined {
const obj = value as Record<string, unknown>;
const sku_id = typeof obj.sku_id === 'string' ? obj.sku_id : undefined;
const name = typeof obj.name === 'string' ? obj.name : undefined;
const assets = obj.assets;
const { assets } = obj;
if (!sku_id || !name || !assets || typeof assets !== 'object') return undefined;
const parsedAssets: Record<string, string> = {};
@@ -145,7 +149,9 @@ function parseStoredCollectible(value: unknown): StoredCollectible | undefined {
};
}
export function extractCollectiblesFromProfile(profile: Record<string, unknown>): CollectibleProfileFields {
export function extractCollectiblesFromProfile(
profile: Record<string, unknown>,
): CollectibleProfileFields {
return {
profile_effect: parseStoredCollectible(profile[PROFILE_KEY_PROFILE_EFFECT]),
nameplate: parseStoredCollectible(profile[PROFILE_KEY_NAMEPLATE]),
@@ -153,14 +159,17 @@ export function extractCollectiblesFromProfile(profile: Record<string, unknown>)
};
}
export async function loadUserCollectibles(mx: MatrixClient, userId: string): Promise<CollectibleProfileFields> {
export async function loadUserCollectibles(
mx: MatrixClient,
userId: string,
): Promise<CollectibleProfileFields> {
return extractCollectiblesFromProfile(await getProfileFields(mx, userId));
}
export async function saveCollectible(
mx: MatrixClient,
key: string,
collectible: StoredCollectible | undefined
collectible: StoredCollectible | undefined,
): Promise<void> {
if (!(await mx.doesServerSupportExtendedProfiles())) {
throw new Error('Server does not support extended profile fields (MSC4133)');
@@ -174,15 +183,24 @@ export async function saveCollectible(
await mx.setExtendedProfileProperty(key, collectible);
}
export async function saveProfileEffect(mx: MatrixClient, collectible: StoredCollectible | undefined): Promise<void> {
export async function saveProfileEffect(
mx: MatrixClient,
collectible: StoredCollectible | undefined,
): Promise<void> {
await saveCollectible(mx, PROFILE_KEY_PROFILE_EFFECT, collectible);
}
export async function saveNameplate(mx: MatrixClient, collectible: StoredCollectible | undefined): Promise<void> {
export async function saveNameplate(
mx: MatrixClient,
collectible: StoredCollectible | undefined,
): Promise<void> {
await saveCollectible(mx, PROFILE_KEY_NAMEPLATE, collectible);
}
export async function saveAvatarDecoration(mx: MatrixClient, collectible: StoredCollectible | undefined): Promise<void> {
export async function saveAvatarDecoration(
mx: MatrixClient,
collectible: StoredCollectible | undefined,
): Promise<void> {
await saveCollectible(mx, PROFILE_KEY_AVATAR_DECORATION, collectible);
}
@@ -228,12 +246,15 @@ export async function getColorPreferenceProfileKey(mx: MatrixClient): Promise<st
export async function loadColorPreference(
mx: MatrixClient,
userId: string
userId: string,
): Promise<ColorPreference | undefined> {
return extractColorPreferenceFromProfile(await getProfileFields(mx, userId));
}
export function extractMemberColorPreference(room: Room | undefined, userId: string): ColorPreference | undefined {
export function extractMemberColorPreference(
room: Room | undefined,
userId: string,
): ColorPreference | undefined {
if (!room || typeof (room as Room).getMember !== 'function' || !userId) return undefined;
const member = room.getMember(userId);
const content = member?.events.member?.getContent();
@@ -241,7 +262,10 @@ export function extractMemberColorPreference(room: Room | undefined, userId: str
return extractColorPreferenceFromProfile(content as Record<string, unknown>);
}
export async function saveColorPreference(mx: MatrixClient, preference: ColorPreference): Promise<void> {
export async function saveColorPreference(
mx: MatrixClient,
preference: ColorPreference,
): Promise<void> {
if (!(await mx.doesServerSupportExtendedProfiles())) {
throw new Error('Server does not support extended profile fields (MSC4133)');
}
+1 -1
View File
@@ -34,5 +34,5 @@ export const EMOJI_REG_G = new RegExp(`${URL_NEG_LB}(${EMOJI_SEQUENCE})`, 'gu');
/** Plain-text messages that are only emoji / :shortcodes: (up to 10). */
export const JUMBO_EMOJI_REG = new RegExp(
`^(?:(?:${EMOJI_SEQUENCE}|:[^\\s:]+:)(?:${VARIATION_SELECTOR_PATTERN}|\\s)*){1,10}$`,
'u'
'u',
);
+8 -2
View File
@@ -21,11 +21,17 @@ async function blobToUint8Array(blob: Blob): Promise<Uint8Array> {
return new Uint8Array(buffer);
}
function guessFilters(filename: string, mimeType?: string): Array<{ name: string; extensions: string[] }> {
function guessFilters(
filename: string,
mimeType?: string,
): Array<{ name: string; extensions: string[] }> {
const ext = filename.includes('.') ? filename.split('.').pop()!.toLowerCase() : '';
const mime = (mimeType || '').toLowerCase();
if (mime.startsWith('image/') || ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) {
if (
mime.startsWith('image/') ||
['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)
) {
return [
{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'] },
{ name: 'All Files', extensions: ['*'] },
+23 -26
View File
@@ -1,5 +1,3 @@
import { IconName, IconSrc } from '../components/icons';
import {
EventTimeline,
EventTimelineSet,
@@ -18,6 +16,7 @@ import {
RoomMember,
} from 'matrix-js-sdk';
import { CryptoBackend } from 'matrix-js-sdk/lib/common-crypto/CryptoBackend';
import { IconName, IconSrc } from '../components/icons';
import { AccountDataEvent } from '../../types/matrix/accountData';
import {
IRoomCreateContent,
@@ -34,7 +33,7 @@ import {
export const getStateEvent = (
room: Room,
eventType: StateEvent,
stateKey = ''
stateKey = '',
): MatrixEvent | undefined => {
const fromCurrent = room.currentState?.getStateEvents(eventType, stateKey);
if (fromCurrent) return fromCurrent;
@@ -52,7 +51,7 @@ export const getStateEvents = (room: Room, eventType: StateEvent): MatrixEvent[]
export const getAccountData = (
mx: MatrixClient,
eventType: AccountDataEvent
eventType: AccountDataEvent,
): MatrixEvent | undefined => mx.getAccountData(eventType as any);
export const getMDirects = (mDirectEvent: MatrixEvent): Set<string> => {
@@ -175,7 +174,7 @@ export const shouldShowForumLobby = isForumContainer;
export const findForumRootSpace = (
mx: MatrixClient,
roomId: string,
roomToParents: RoomToParents
roomToParents: RoomToParents,
): string | undefined => {
const ordered = [roomId, ...Array.from(getAllParents(roomToParents, roomId))];
for (const id of ordered) {
@@ -199,10 +198,7 @@ export const isUnsupportedRoom = (room: Room | null): boolean => {
if (!room) return false;
const roomType = getRoomCreateType(room);
if (!roomType) return true; // Consider room unsupported if m.room.create event doesn't exist
return (
roomType !== RoomType.Space &&
roomType !== RoomType.Forum
);
return roomType !== RoomType.Space && roomType !== RoomType.Forum;
};
export function isValidChild(mEvent: MatrixEvent): boolean {
@@ -240,7 +236,7 @@ export const getSpaceChildren = (room: Room) =>
export const mapParentWithChildren = (
roomToParents: RoomToParents,
roomId: string,
children: string[]
children: string[],
) => {
const allParents = getAllParents(roomToParents, roomId);
children.forEach((childId) => {
@@ -266,7 +262,7 @@ export const getRoomToParents = (mx: MatrixClient): RoomToParents => {
export const getOrphanParents = (roomToParents: RoomToParents, roomId: string): string[] => {
const parents = getAllParents(roomToParents, roomId);
const orphanParents = Array.from(parents).filter(
(parentRoomId) => !roomToParents.has(parentRoomId)
(parentRoomId) => !roomToParents.has(parentRoomId),
);
return orphanParents;
@@ -373,7 +369,7 @@ export const getUnreadInfos = (mx: MatrixClient): UnreadInfo[] => {
export const joinRuleToIconSrc = (
icons: Record<IconName, IconSrc>,
joinRule: JoinRule,
space: boolean
space: boolean,
): IconSrc | undefined => {
if (joinRule === JoinRule.Restricted) {
return space ? icons.Space : icons.Hash;
@@ -394,11 +390,12 @@ export const getRoomAvatarUrl = (
mx: MatrixClient,
room: Room,
size: 32 | 96 = 32,
useAuthentication = false
useAuthentication = false,
): string | undefined => {
const mxcUrl = room.getMxcAvatarUrl();
return mxcUrl
? mx.mxcUrlToHttp(mxcUrl, size, size, 'crop', undefined, false, useAuthentication) ?? undefined
? (mx.mxcUrlToHttp(mxcUrl, size, size, 'crop', undefined, false, useAuthentication) ??
undefined)
: undefined;
};
@@ -406,7 +403,7 @@ export const getDirectRoomAvatarUrl = (
mx: MatrixClient,
room: Room,
size: 32 | 96 = 32,
useAuthentication = false
useAuthentication = false,
): string | undefined => {
const mxcUrl = room.getAvatarFallbackMember()?.getMxcAvatarUrl();
@@ -441,10 +438,10 @@ export const parseReplyFormattedBody = (
roomId: string,
userId: string,
eventId: string,
formattedBody: string
formattedBody: string,
): string => {
const replyToLink = `<a href="https://matrix.to/#/${encodeURIComponent(
roomId
roomId,
)}/${encodeURIComponent(eventId)}">In reply to</a>`;
const userLink = `<a href="https://matrix.to/#/${encodeURIComponent(userId)}">${userId}</a>`;
@@ -461,7 +458,7 @@ export const getMemberDisplayName = (room: Room, userId: string): string | undef
export const getMemberSearchStr = (
member: RoomMember,
query: string,
mxIdToName: (mxId: string) => string
mxIdToName: (mxId: string) => string,
): string[] => [
member.rawDisplayName === member.userId ? mxIdToName(member.userId) : member.rawDisplayName,
query.startsWith('@') || query.indexOf(':') > -1 ? member.userId : mxIdToName(member.userId),
@@ -500,7 +497,7 @@ export const getEventReactions = (timelineSet: EventTimelineSet, eventId: string
timelineSet.relations.getChildEventsForEvent(
eventId,
RelationType.Annotation,
EventType.Reaction
EventType.Reaction,
);
export const getEventEdits = (timelineSet: EventTimelineSet, eventId: string, eventType: string) =>
@@ -508,7 +505,7 @@ export const getEventEdits = (timelineSet: EventTimelineSet, eventId: string, ev
export const getLatestEdit = (
targetEvent: MatrixEvent,
editEvents: MatrixEvent[]
editEvents: MatrixEvent[],
): MatrixEvent | undefined => {
const eventByTargetSender = (rEvent: MatrixEvent) =>
rEvent.getSender() === targetEvent.getSender();
@@ -518,7 +515,7 @@ export const getLatestEdit = (
export const getEditedEvent = (
mEventId: string,
mEvent: MatrixEvent,
timelineSet: EventTimelineSet
timelineSet: EventTimelineSet,
): MatrixEvent | undefined => {
const edits = getEventEdits(timelineSet, mEventId, mEvent.getType());
return edits && getLatestEdit(mEvent, edits.getRelations());
@@ -539,7 +536,7 @@ export const canEditEvent = (mx: MatrixClient, mEvent: MatrixEvent) => {
export const getLatestEditableEvt = (
timeline: EventTimeline,
canEdit: (mEvent: MatrixEvent) => boolean
canEdit: (mEvent: MatrixEvent) => boolean,
): MatrixEvent | undefined => {
const events = timeline.getEvents();
@@ -569,7 +566,7 @@ export const getMentionContent = (userIds: string[], room: boolean): IMentions =
export const getCommonRooms = (
mx: MatrixClient,
rooms: string[],
otherUserId: string
otherUserId: string,
): string[] => {
const commonRooms: string[] = [];
@@ -615,7 +612,7 @@ export const getAllVersionsRoomCreator = (room: Room): Set<string> => {
export const guessPerfectParent = (
mx: MatrixClient,
roomId: string,
parents: string[]
parents: string[],
): string | undefined => {
if (parents.length === 1) {
return parents[0];
@@ -631,7 +628,7 @@ export const guessPerfectParent = (
const powerLevels = getStateEvent(
r,
StateEvent.RoomPowerLevels
StateEvent.RoomPowerLevels,
)?.getContent<IPowerLevelsContent>();
const { users_default: usersDefault, users } = powerLevels ?? {};
@@ -654,7 +651,7 @@ export const guessPerfectParent = (
parents.forEach((parentId) => {
const parentSpecialUsers = getSpecialUsers(parentId);
const matchedUsersCount = parentSpecialUsers.filter((userId) =>
roomSpecialUsers.includes(userId)
roomSpecialUsers.includes(userId),
).length;
if (matchedUsersCount > score) {
+1 -1
View File
@@ -34,7 +34,7 @@ export const saveMediaBlob = async (blob: Blob, filename: string): Promise<void>
export const downloadAndSaveMedia = async (
src: string,
filename: string,
accessToken?: string | null
accessToken?: string | null,
): Promise<void> => {
let blob: Blob;
try {
+44 -35
View File
@@ -4,11 +4,11 @@
*/
export const openExternalUrl = async (url: string): Promise<void> => {
console.log('[openExternalUrl] called with:', url);
// Use Electron's shell.openExternal if in Electron
if (isElectron()) {
try {
const electron = (window as any).electron;
const { electron } = window as any;
if (electron?.shell?.openExternal) {
await electron.shell.openExternal(url);
console.log('[openExternalUrl] Electron shell.openExternal succeeded');
@@ -18,7 +18,7 @@ export const openExternalUrl = async (url: string): Promise<void> => {
console.warn('[openExternalUrl] Electron shell.openExternal failed:', err);
}
}
// Use Tauri for actual Tauri builds
if (isTauri() && !isElectron()) {
try {
@@ -30,7 +30,7 @@ export const openExternalUrl = async (url: string): Promise<void> => {
return;
} catch (pluginErr) {
console.warn('[openExternalUrl] Tauri opener plugin failed:', pluginErr);
// Fallback: try the custom command (useful if plugin fails due to ACL)
try {
console.log('[openExternalUrl] trying Tauri invoke command fallback...');
@@ -43,7 +43,7 @@ export const openExternalUrl = async (url: string): Promise<void> => {
}
}
}
console.log('[openExternalUrl] falling back to window.open');
window.open(url, '_blank');
};
@@ -71,7 +71,7 @@ export const getYouTubeStream = async (url: string): Promise<YouTubeStreamInfo>
}
// Check for Electron
const electron = (window as any).electron;
const { electron } = window as any;
if (electron?.youtube?.getStream) {
const result = await electron.youtube.getStream(url);
// Electron returns { success: true, data: { video_url, title } } or { success: false, error }
@@ -100,7 +100,7 @@ export const isYouTubeStreamingAvailable = (): boolean => {
}
// Check for Electron
const electron = (window as any).electron;
const { electron } = window as any;
if (electron?.youtube?.getStream) {
return true;
}
@@ -137,7 +137,7 @@ export const focusWindow = async (): Promise<void> => {
// Use Electron's window focus if in Electron
if (isElectron()) {
try {
const electron = (window as any).electron;
const { electron } = window as any;
if (electron?.window?.focus) {
await electron.window.focus();
}
@@ -164,13 +164,15 @@ export const focusWindow = async (): Promise<void> => {
* Set up listener for notification tap/click actions
* Call this once at app startup with a navigation callback
*/
export const setupNotificationTapListener = async (onTap: (path: string) => void): Promise<void> => {
export const setupNotificationTapListener = async (
onTap: (path: string) => void,
): Promise<void> => {
notificationTapCallback = onTap;
// Use Electron's native notification handler if in Electron
if (isElectron()) {
try {
const electron = (window as any).electron;
const { electron } = window as any;
if (electron?.notification?.onNavigate) {
electron.notification.onNavigate((data: { path?: string }) => {
if (data.path && typeof data.path === 'string' && notificationTapCallback) {
@@ -184,16 +186,16 @@ export const setupNotificationTapListener = async (onTap: (path: string) => void
return;
}
}
// Use Tauri plugin for actual Tauri builds (not Electron)
if (isTauri() && !isElectron()) {
try {
const { onAction } = await import('@tauri-apps/plugin-notification');
await onAction(async (notification) => {
// Bring window to front first
await focusWindow();
// Get the path from extra data and navigate
const path = notification.notification?.extra?.path;
if (path && typeof path === 'string' && notificationTapCallback) {
@@ -208,13 +210,16 @@ export const setupNotificationTapListener = async (onTap: (path: string) => void
if (isCapacitorNative()) {
try {
const { LocalNotifications } = await importCapacitorLocalNotifications();
await LocalNotifications.addListener('localNotificationActionPerformed', async (event: any) => {
await focusWindow();
const path = event?.notification?.extra?.path;
if (path && typeof path === 'string' && notificationTapCallback) {
notificationTapCallback(path);
}
});
await LocalNotifications.addListener(
'localNotificationActionPerformed',
async (event: any) => {
await focusWindow();
const path = event?.notification?.extra?.path;
if (path && typeof path === 'string' && notificationTapCallback) {
notificationTapCallback(path);
}
},
);
} catch (err) {
console.warn('Failed to set up Capacitor notification tap listener:', err);
}
@@ -224,14 +229,12 @@ export const setupNotificationTapListener = async (onTap: (path: string) => void
/**
* Check if we're running inside a Tauri application
*/
export const isTauri = (): boolean =>
'__TAURI__' in window || '__TAURI_INTERNALS__' in window;
export const isTauri = (): boolean => '__TAURI__' in window || '__TAURI_INTERNALS__' in window;
/**
* Check if we're running inside Electron (not Tauri)
*/
export const isElectron = (): boolean =>
typeof window !== 'undefined' && 'electron' in window;
export const isElectron = (): boolean => typeof window !== 'undefined' && 'electron' in window;
/**
* Check if we're running inside a Capacitor native app
@@ -239,7 +242,11 @@ export const isElectron = (): boolean =>
export const isCapacitorNative = (): boolean => {
if (typeof window === 'undefined') return false;
const cap = (window as any).Capacitor;
return Boolean(cap?.isNativePlatform?.() || cap?.getPlatform?.() === 'android' || cap?.getPlatform?.() === 'ios');
return Boolean(
cap?.isNativePlatform?.() ||
cap?.getPlatform?.() === 'android' ||
cap?.getPlatform?.() === 'ios',
);
};
/**
@@ -327,7 +334,7 @@ const ensureNotificationChannel = async (): Promise<void> => {
try {
const { createChannel, Importance } = await import('@tauri-apps/plugin-notification');
await createChannel({
id: 'messages',
name: 'Messages',
@@ -336,7 +343,7 @@ const ensureNotificationChannel = async (): Promise<void> => {
vibration: true,
sound: 'default',
});
notificationChannelCreated = true;
} catch (err) {
console.warn('Failed to create notification channel:', err);
@@ -431,7 +438,7 @@ export const sendNotification = async (options: {
// Use Electron's native notification API if in Electron
if (isElectron()) {
try {
const electron = (window as any).electron;
const { electron } = window as any;
if (electron?.notification?.show) {
await electron.notification.show({
title,
@@ -511,7 +518,7 @@ export const sendNotification = async (options: {
console.warn('Capacitor notification failed:', err);
}
}
// Fallback to browser notification
sendBrowserNotification({ title, body, icon, onClick });
};
@@ -532,7 +539,7 @@ export const readClipboardImage = async (): Promise<File | null> => {
// Use Electron's clipboard API if in Electron
if (isElectron()) {
try {
const electron = (window as any).electron;
const { electron } = window as any;
if (electron?.clipboard?.readImage) {
const result = await electron.clipboard.readImage();
// IPC may return a data URL string or { success, data } depending on path.
@@ -543,7 +550,7 @@ export const readClipboardImage = async (): Promise<File | null> => {
? result.data
: null;
if (!dataUrl) return null;
// Convert data URL to File
const response = await fetch(dataUrl);
const blob = await response.blob();
@@ -561,7 +568,7 @@ export const readClipboardImage = async (): Promise<File | null> => {
try {
const { invoke } = await import('@tauri-apps/api/core');
const dataUrl = await invoke<string | null>('read_clipboard_image');
if (!dataUrl) return null;
// Convert data URL to File
@@ -574,7 +581,7 @@ export const readClipboardImage = async (): Promise<File | null> => {
return null;
}
}
return null;
};
@@ -593,7 +600,9 @@ export interface BackgroundSyncCredentials {
* Start background Matrix sync on mobile
* This runs the sync in native Rust code, allowing notifications even when the app is backgrounded
*/
export const startBackgroundSync = async (credentials: BackgroundSyncCredentials): Promise<void> => {
export const startBackgroundSync = async (
credentials: BackgroundSyncCredentials,
): Promise<void> => {
if (!isTauriMobile()) {
console.log('[BackgroundSync] Not on mobile, skipping');
return;
+39 -47
View File
@@ -69,12 +69,12 @@ export type ImportProgressCallback = (current: number, total: number, status: st
*/
export function extractPackName(url: string): string | null {
const trimmed = url.trim();
// Direct pack name (no URL)
if (/^[a-zA-Z0-9_]+$/.test(trimmed)) {
return trimmed;
}
// URL format: t.me/addstickers/PackName or https://t.me/addstickers/PackName
const match = trimmed.match(/(?:https?:\/\/)?t\.me\/addstickers\/([a-zA-Z0-9_]+)/i);
return match ? match[1] : null;
@@ -88,22 +88,22 @@ export function extractPackName(url: string): string | null {
*/
export async function fetchStickerSet(
botToken: string,
setName: string
setName: string,
): Promise<TelegramStickerSet> {
const response = await fetch(
`${TELEGRAM_API}${botToken}/getStickerSet?name=${encodeURIComponent(setName)}`
`${TELEGRAM_API}${botToken}/getStickerSet?name=${encodeURIComponent(setName)}`,
);
if (!response.ok) {
throw new Error(`Failed to fetch sticker set: ${response.statusText}`);
}
const data: TelegramResponse<TelegramStickerSet> = await response.json();
if (!data.ok || !data.result) {
throw new Error(data.description || 'Failed to fetch sticker set');
}
return data.result;
}
@@ -115,17 +115,17 @@ export async function fetchStickerSet(
*/
async function getFilePath(botToken: string, fileId: string): Promise<string> {
const response = await fetch(`${TELEGRAM_API}${botToken}/getFile?file_id=${fileId}`);
if (!response.ok) {
throw new Error(`Failed to get file path: ${response.statusText}`);
}
const data: TelegramResponse<{ file_path: string }> = await response.json();
if (!data.ok || !data.result) {
throw new Error(data.description || 'Failed to get file path');
}
return data.result.file_path;
}
@@ -138,11 +138,11 @@ async function getFilePath(botToken: string, fileId: string): Promise<string> {
*/
async function downloadFile(botToken: string, filePath: string): Promise<Blob> {
const response = await tauriFetch(`${TELEGRAM_FILE_API}${botToken}/${filePath}`);
if (!response.ok) {
throw new Error(`Failed to download file: ${response.statusText}`);
}
return response.blob();
}
@@ -153,16 +153,12 @@ async function downloadFile(botToken: string, filePath: string): Promise<Blob> {
* @param filename - Filename for the upload
* @returns mxc:// URL
*/
async function uploadToMatrix(
mx: MatrixClient,
blob: Blob,
filename: string
): Promise<string> {
async function uploadToMatrix(mx: MatrixClient, blob: Blob, filename: string): Promise<string> {
const response = await mx.uploadContent(blob, {
name: filename,
type: blob.type || 'image/webp',
});
return response.content_uri;
}
@@ -192,51 +188,51 @@ export async function importTelegramStickerPack(
mx: MatrixClient,
botToken: string,
packUrl: string,
onProgress?: ImportProgressCallback
onProgress?: ImportProgressCallback,
): Promise<{ packId: string; content: PackContent }> {
// Extract pack name from URL
const packName = extractPackName(packUrl);
if (!packName) {
throw new Error('Invalid Telegram sticker pack URL');
}
onProgress?.(0, 1, 'Fetching sticker pack info...');
// Fetch sticker set from Telegram
const stickerSet = await fetchStickerSet(botToken, packName);
const total = stickerSet.stickers.length;
const images: PackImages = {};
// Download and upload each sticker sequentially
// (Using sequential await is intentional to avoid overwhelming APIs)
for (let i = 0; i < stickerSet.stickers.length; i += 1) {
const sticker = stickerSet.stickers[i];
const isAnimated = sticker.is_animated;
const isVideo = sticker.is_video;
let stickerType = 'static';
if (isAnimated) stickerType = 'animated';
else if (isVideo) stickerType = 'video';
onProgress?.(i + 1, total, `Importing ${stickerType} sticker ${i + 1}/${total}...`);
try {
// Get file path from Telegram
// eslint-disable-next-line no-await-in-loop
const filePath = await getFilePath(botToken, sticker.file_id);
// Download the sticker
// eslint-disable-next-line no-await-in-loop
let blob = await downloadFile(botToken, filePath);
// Generate a shortcode from emoji or index
const shortcode = sticker.emoji
? `${packName}_${sticker.emoji.codePointAt(0)?.toString(16) || i}`
: `${packName}_${i}`;
let finalMimeType = getMimeType(filePath);
let extension = 'webp';
// Convert animated stickers to GIF
if (isAnimated && filePath.endsWith('.tgs')) {
onProgress?.(i + 1, total, `Converting animated sticker ${i + 1}/${total} to GIF...`);
@@ -251,15 +247,11 @@ export async function importTelegramStickerPack(
finalMimeType = 'image/gif';
extension = 'gif';
}
// Upload to Matrix
// eslint-disable-next-line no-await-in-loop
const mxcUrl = await uploadToMatrix(
mx,
blob,
`${shortcode}.${extension}`
);
const mxcUrl = await uploadToMatrix(mx, blob, `${shortcode}.${extension}`);
// Add to images
images[shortcode] = {
url: mxcUrl,
@@ -278,11 +270,11 @@ export async function importTelegramStickerPack(
console.error(`Failed to import sticker ${i + 1}:`, err);
}
}
if (Object.keys(images).length === 0) {
throw new Error('Failed to import any stickers from the pack');
}
// eslint-disable-next-line no-console
console.log(`Successfully imported ${Object.keys(images).length} stickers`);
@@ -294,14 +286,14 @@ export async function importTelegramStickerPack(
},
images,
};
// Generate a unique pack ID
const packId = `telegram_${packName}`;
// Get existing user emotes or create new
const existingEvent = getAccountData(mx, AccountDataEvent.PoniesUserEmotes);
const existingEmotes = existingEvent?.getContent() as PackContent | undefined;
// Merge with existing pack if any
const mergedContent: PackContent = {
pack: existingEmotes?.pack || { usage: [ImageUsage.Emoticon, ImageUsage.Sticker] },
@@ -310,7 +302,7 @@ export async function importTelegramStickerPack(
...images,
},
};
// Save to user account data
// eslint-disable-next-line no-console
console.log('Saving merged pack to account data:', AccountDataEvent.PoniesUserEmotes);
@@ -320,13 +312,13 @@ export async function importTelegramStickerPack(
await mx.setAccountData(AccountDataEvent.PoniesUserEmotes as any, mergedContent as any);
// eslint-disable-next-line no-console
console.log('Pack saved successfully');
// Force the account data event to be emitted for UI refresh
const updatedEvent = getAccountData(mx, AccountDataEvent.PoniesUserEmotes);
// eslint-disable-next-line no-console
console.log('Updated account data after save:', updatedEvent?.getContent());
onProgress?.(total, total, 'Import complete!');
return { packId, content: packContent };
}
+3 -3
View File
@@ -49,18 +49,18 @@ export const enableViewTransitionsForNavigation = (): void => {
// Intercept link clicks and navigation to add view transitions
const handleLinkClick = (event: MouseEvent) => {
const target = (event.target as HTMLElement).closest('a');
if (!target) return;
if (target.target === '_blank') return;
if (target.origin !== window.location.origin) return;
if (event.metaKey || event.ctrlKey || event.shiftKey) return;
const url = new URL(target.href);
// Only handle same-origin navigation
if (url.origin === window.location.origin) {
event.preventDefault();
withViewTransition(() => {
window.history.pushState({}, '', target.href);
window.dispatchEvent(new PopStateEvent('popstate'));
+46 -39
View File
@@ -1,7 +1,7 @@
/**
* Utilities for reading and writing WebP metadata (custom XMP chunks)
* Used to embed user color in avatar images
*
*
* WebP uses RIFF container format:
* - File starts with "RIFF" (4 bytes) + file size (4 bytes LE) + "WEBP" (4 bytes)
* - Chunks: chunk ID (4 bytes) + chunk size (4 bytes LE) + chunk data (+ padding byte if odd size)
@@ -9,7 +9,7 @@
/* eslint-disable no-bitwise */
/* eslint-disable no-plusplus */
/* eslint-disable no-console */
/* eslint-disable no-restricted-syntax */
/** RIFF signature bytes */
@@ -20,13 +20,15 @@ const WEBP_SIGNATURE = new Uint8Array([0x57, 0x45, 0x42, 0x50]); // "WEBP"
export const PAARROT_COLOR_KEY = 'paarrot:color';
/** Custom chunk ID for paarrot color - using XMP_ as it's a standard metadata chunk */
const XMP_CHUNK_ID = new Uint8Array([0x58, 0x4D, 0x50, 0x20]); // "XMP "
const XMP_CHUNK_ID = new Uint8Array([0x58, 0x4d, 0x50, 0x20]); // "XMP "
/**
* Read a 32-bit little-endian integer from a buffer
*/
function readUint32LE(data: Uint8Array, offset: number): number {
return data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24);
return (
data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)
);
}
/**
@@ -46,17 +48,17 @@ function writeUint32LE(value: number): Uint8Array {
*/
function isWebP(data: Uint8Array): boolean {
if (data.length < 12) return false;
// Check RIFF signature
for (let i = 0; i < 4; i++) {
if (data[i] !== RIFF_SIGNATURE[i]) return false;
}
// Check WEBP signature at offset 8
for (let i = 0; i < 4; i++) {
if (data[8 + i] !== WEBP_SIGNATURE[i]) return false;
}
return true;
}
@@ -90,28 +92,30 @@ function extractColorFromXMP(xmpData: string): string | undefined {
/**
* Parse WebP chunks from image data
*/
function parseChunks(data: Uint8Array): Array<{ id: string; data: Uint8Array; offset: number; length: number }> {
function parseChunks(
data: Uint8Array,
): Array<{ id: string; data: Uint8Array; offset: number; length: number }> {
const chunks: Array<{ id: string; data: Uint8Array; offset: number; length: number }> = [];
let offset = 12; // Skip RIFF header (4) + size (4) + WEBP (4)
while (offset + 8 <= data.length) {
const id = new TextDecoder().decode(data.slice(offset, offset + 4));
const size = readUint32LE(data, offset + 4);
const chunkData = data.slice(offset + 8, offset + 8 + size);
// Chunk length includes padding byte if size is odd
const paddedSize = size + (size % 2);
chunks.push({
id,
data: chunkData,
offset,
length: 8 + paddedSize, // header (8) + data + optional padding
});
offset += 8 + paddedSize;
}
return chunks;
}
@@ -122,13 +126,13 @@ function parseChunks(data: Uint8Array): Array<{ id: string; data: Uint8Array; of
*/
export function extractColorFromWebP(imageData: ArrayBuffer | Uint8Array): string | undefined {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
if (!isWebP(data)) {
return undefined;
}
const chunks = parseChunks(data);
for (const chunk of chunks) {
if (chunk.id === 'XMP ') {
const xmpString = new TextDecoder().decode(chunk.data);
@@ -138,7 +142,7 @@ export function extractColorFromWebP(imageData: ArrayBuffer | Uint8Array): strin
}
}
}
return undefined;
}
@@ -148,18 +152,21 @@ export function extractColorFromWebP(imageData: ArrayBuffer | Uint8Array): strin
* @param color - The color string to embed (e.g., '#ff5500')
* @returns New WebP data with embedded color, or null if not a valid WebP
*/
export function embedColorInWebP(imageData: ArrayBuffer | Uint8Array, color: string): Uint8Array | null {
export function embedColorInWebP(
imageData: ArrayBuffer | Uint8Array,
color: string,
): Uint8Array | null {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
if (!isWebP(data)) {
return null;
}
const chunks = parseChunks(data);
// Find existing XMP chunk with our color
let existingXMPChunk: { offset: number; length: number } | null = null;
for (const chunk of chunks) {
if (chunk.id === 'XMP ') {
const xmpString = new TextDecoder().decode(chunk.data);
@@ -169,21 +176,21 @@ export function embedColorInWebP(imageData: ArrayBuffer | Uint8Array, color: str
}
}
}
// Create XMP chunk with color
const xmpData = createXMPData(color);
const xmpBytes = new TextEncoder().encode(xmpData);
const xmpPaddedSize = xmpBytes.length + (xmpBytes.length % 2); // Add padding byte if odd
// XMP chunk: ID (4) + size (4) + data + optional padding
const xmpChunk = new Uint8Array(8 + xmpPaddedSize);
xmpChunk.set(XMP_CHUNK_ID, 0);
xmpChunk.set(writeUint32LE(xmpBytes.length), 4);
xmpChunk.set(xmpBytes, 8);
// Padding byte is already 0 from Uint8Array initialization
let newData: Uint8Array;
if (existingXMPChunk) {
// Replace existing chunk
newData = new Uint8Array(data.length - existingXMPChunk.length + xmpChunk.length);
@@ -191,7 +198,7 @@ export function embedColorInWebP(imageData: ArrayBuffer | Uint8Array, color: str
newData.set(xmpChunk, existingXMPChunk.offset);
newData.set(
data.slice(existingXMPChunk.offset + existingXMPChunk.length),
existingXMPChunk.offset + xmpChunk.length
existingXMPChunk.offset + xmpChunk.length,
);
} else {
// Insert new chunk at end (before any trailing data)
@@ -199,11 +206,11 @@ export function embedColorInWebP(imageData: ArrayBuffer | Uint8Array, color: str
newData.set(data, 0);
newData.set(xmpChunk, data.length);
}
// Update RIFF file size (at offset 4)
const newFileSize = newData.length - 8; // RIFF size excludes first 8 bytes
newData.set(writeUint32LE(newFileSize), 4);
return newData;
}
@@ -214,16 +221,16 @@ export function embedColorInWebP(imageData: ArrayBuffer | Uint8Array, color: str
*/
export function removeColorFromWebP(imageData: ArrayBuffer | Uint8Array): Uint8Array | null {
const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData);
if (!isWebP(data)) {
return null;
}
const chunks = parseChunks(data);
// Find existing XMP chunk with our color
let existingXMPChunk: { offset: number; length: number } | null = null;
for (const chunk of chunks) {
if (chunk.id === 'XMP ') {
const xmpString = new TextDecoder().decode(chunk.data);
@@ -233,24 +240,24 @@ export function removeColorFromWebP(imageData: ArrayBuffer | Uint8Array): Uint8A
}
}
}
if (!existingXMPChunk) {
// No color to remove
return data;
}
// Build new WebP data without the XMP chunk
const newData = new Uint8Array(data.length - existingXMPChunk.length);
newData.set(data.slice(0, existingXMPChunk.offset), 0);
newData.set(
data.slice(existingXMPChunk.offset + existingXMPChunk.length),
existingXMPChunk.offset
existingXMPChunk.offset,
);
// Update RIFF file size
const newFileSize = newData.length - 8;
newData.set(writeUint32LE(newFileSize), 4);
return newData;
}
@@ -263,7 +270,7 @@ export async function fetchAndExtractColorFromWebP(url: string): Promise<string
try {
const response = await fetch(url);
if (!response.ok) return undefined;
const data = await response.arrayBuffer();
return extractColorFromWebP(data);
} catch {