Finished implementing widgets
This commit is contained in:
1 parent
72db176f4c
commit
7329c7526e
4 files changed
+134
-9
No files matched your search
@@ -38,7 +38,8 @@ export function WidgetIframe({ widget, roomId, mx, onCapabilityRequest }: Widget
|
||||
userId,
|
||||
displayName,
|
||||
avatarUrl,
|
||||
widget.id
|
||||
widget.id,
|
||||
mx
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -60,6 +61,11 @@ export function WidgetIframe({ widget, roomId, mx, onCapabilityRequest }: Widget
|
||||
|
||||
messaging.once('ready', () => setReady(true));
|
||||
|
||||
// Set iframe src after ClientWidgetApi is listening for the load event.
|
||||
// This avoids a race condition where the iframe loads before the widget
|
||||
// API transport is ready to perform the capability handshake.
|
||||
iframe.src = resolvedUrl;
|
||||
|
||||
messaging.on('action:org.matrix.msc2876.read_events', (ev: CustomEvent) => {
|
||||
const room = mx.getRoom(roomId);
|
||||
const events: Partial<IEvent>[] = [];
|
||||
@@ -135,7 +141,6 @@ export function WidgetIframe({ widget, roomId, mx, onCapabilityRequest }: Widget
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
title={widget.name || 'Widget'}
|
||||
src={resolvedUrl}
|
||||
sandbox="allow-forms allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox allow-downloads"
|
||||
allow="camera;microphone;clipboard-write;display-capture;autoplay;encrypted-media"
|
||||
style={{
|
||||
|
||||
@@ -20,7 +20,7 @@ import { IWidget } from 'matrix-widget-api';
|
||||
|
||||
import * as css from './WidgetsDrawer.css';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { useRoomWidgets, RoomWidget } from '../../hooks/useRoomWidgets';
|
||||
import { useRoomWidgets, RoomWidget, enrichWidgetUrl } from '../../hooks/useRoomWidgets';
|
||||
import { WidgetIframe } from './WidgetIframe';
|
||||
import { useSetSetting } from '../../state/hooks/settings';
|
||||
import { settingsAtom } from '../../state/settings';
|
||||
@@ -102,7 +102,7 @@ function AddWidgetForm({ room, onAdded }: AddWidgetFormProps) {
|
||||
const widgetId = `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
||||
await mx.sendStateEvent(room.roomId, StateEvent.RoomWidget as any, {
|
||||
type: 'm.custom',
|
||||
url: url.trim(),
|
||||
url: enrichWidgetUrl(url.trim()),
|
||||
name: name.trim(),
|
||||
id: widgetId,
|
||||
creatorUserId: mx.getUserId(),
|
||||
|
||||
@@ -29,6 +29,7 @@ import { getStateEvent } from '../utils/room';
|
||||
import { splitWithSpace } from '../utils/common';
|
||||
import { createRoomEncryptionState } from '../components/create-room';
|
||||
import { AccountDataEvent } from '../../types/matrix/accountData';
|
||||
import { enrichWidgetUrl } from './useRoomWidgets';
|
||||
|
||||
export const SHRUG = '¯\\_(ツ)_/¯';
|
||||
export const TABLEFLIP = '(╯°□°)╯︵ ┻━┻';
|
||||
@@ -167,6 +168,7 @@ export enum Command {
|
||||
GColor = 'gcolor',
|
||||
Font = 'font',
|
||||
GFont = 'gfont',
|
||||
AddWidget = 'addwidget',
|
||||
}
|
||||
|
||||
export type CommandContent = {
|
||||
@@ -701,6 +703,58 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
}
|
||||
},
|
||||
},
|
||||
[Command.AddWidget]: {
|
||||
name: Command.AddWidget,
|
||||
description: 'Add a widget to this room. Usage: /addwidget <url> [name]',
|
||||
exe: async (payload) => {
|
||||
const userId = mx.getSafeUserId();
|
||||
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new (window as any).matrixcs.MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~nullptr-widget-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
const parts = payload.trim().split(/\s+/);
|
||||
const url = parts[0];
|
||||
const name = parts.slice(1).join(' ') || 'Widget';
|
||||
|
||||
if (!url) {
|
||||
sendFeedback('Usage: /addwidget <url> [name]');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
new URL(url);
|
||||
} catch {
|
||||
sendFeedback('Invalid URL. Please provide a valid widget URL.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const widgetId = `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
||||
await mx.sendStateEvent(room.roomId, StateEvent.RoomWidget as any, {
|
||||
type: 'm.custom',
|
||||
url: enrichWidgetUrl(url),
|
||||
name,
|
||||
id: widgetId,
|
||||
creatorUserId: userId,
|
||||
} as any, widgetId);
|
||||
sendFeedback(`Widget "${name}" added.`);
|
||||
} catch (e: any) {
|
||||
if (e.errcode === 'M_FORBIDDEN') {
|
||||
sendFeedback('Permission denied. You need permission to manage widgets in this room.');
|
||||
} else {
|
||||
sendFeedback(`Failed to add widget: ${e.message || 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
}),
|
||||
[mx, room, navigateRoom]
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Room, MatrixEvent } from 'matrix-js-sdk';
|
||||
import { Room, MatrixEvent, MatrixClient } from 'matrix-js-sdk';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { IWidget } from 'matrix-widget-api';
|
||||
import { useStateEventCallback } from './useStateEventCallback';
|
||||
@@ -17,14 +17,80 @@ export const resolveWidgetUrl = (
|
||||
userId: string,
|
||||
displayName: string,
|
||||
avatarUrl: string,
|
||||
widgetId: string
|
||||
): string =>
|
||||
url
|
||||
widgetId: string,
|
||||
mx?: MatrixClient
|
||||
): string => {
|
||||
const deviceId = mx?.getDeviceId() ?? '';
|
||||
const baseUrl = mx?.baseUrl ?? '';
|
||||
const clientId = 'dev.nullptr.app';
|
||||
const lang = navigator.language || 'en';
|
||||
const theme = document.body.classList.contains('dark-theme') ? 'dark' : 'light';
|
||||
|
||||
let resolved = url
|
||||
.replace(/\$matrix_user_id/g, encodeURIComponent(userId))
|
||||
.replace(/\$matrix_room_id/g, encodeURIComponent(roomId))
|
||||
.replace(/\$matrix_display_name/g, encodeURIComponent(displayName))
|
||||
.replace(/\$matrix_avatar_url/g, encodeURIComponent(avatarUrl))
|
||||
.replace(/\$matrix_widget_id/g, encodeURIComponent(widgetId));
|
||||
.replace(/\$matrix_widget_id/g, encodeURIComponent(widgetId))
|
||||
.replace(/\$org\.matrix\.msc2873\.client_id/g, encodeURIComponent(clientId))
|
||||
.replace(/\$org\.matrix\.msc2873\.client_theme/g, encodeURIComponent(theme))
|
||||
.replace(/\$org\.matrix\.msc2873\.client_language/g, encodeURIComponent(lang))
|
||||
.replace(/\$org\.matrix\.msc3819\.matrix_device_id/g, encodeURIComponent(deviceId))
|
||||
.replace(/\$org\.matrix\.msc4039\.matrix_base_url/g, encodeURIComponent(baseUrl));
|
||||
|
||||
try {
|
||||
const u = new URL(resolved);
|
||||
if (!u.searchParams.has('widgetId')) {
|
||||
u.searchParams.set('widgetId', widgetId);
|
||||
}
|
||||
if (!u.searchParams.has('parentUrl')) {
|
||||
u.searchParams.set('parentUrl', window.location.href);
|
||||
}
|
||||
resolved = u.toString();
|
||||
} catch {
|
||||
// URL parsing failed, return as-is
|
||||
}
|
||||
|
||||
return resolved;
|
||||
};
|
||||
|
||||
/**
|
||||
* Enrich a plain widget URL with standard Matrix template variables.
|
||||
* Used when storing the widget URL in room state so that resolveWidgetUrl
|
||||
* can substitute actual values at render time.
|
||||
*/
|
||||
export const enrichWidgetUrl = (rawUrl: string): string => {
|
||||
if (rawUrl.includes('$matrix_') || rawUrl.includes('$org.matrix.')) {
|
||||
return rawUrl;
|
||||
}
|
||||
|
||||
const templateParams = [
|
||||
'matrix_user_id=$matrix_user_id',
|
||||
'matrix_display_name=$matrix_display_name',
|
||||
'matrix_avatar_url=$matrix_avatar_url',
|
||||
'matrix_room_id=$matrix_room_id',
|
||||
'matrix_widget_id=$matrix_widget_id',
|
||||
'theme=$org.matrix.msc2873.client_theme',
|
||||
'matrix_client_id=$org.matrix.msc2873.client_id',
|
||||
'matrix_client_language=$org.matrix.msc2873.client_language',
|
||||
'matrix_device_id=$org.matrix.msc3819.matrix_device_id',
|
||||
'matrix_base_url=$org.matrix.msc4039.matrix_base_url',
|
||||
].join('&');
|
||||
|
||||
try {
|
||||
const u = new URL(rawUrl);
|
||||
if (u.hash.includes('?')) {
|
||||
return `${rawUrl}&${templateParams}`;
|
||||
}
|
||||
if (u.hash) {
|
||||
return `${rawUrl}?${templateParams}`;
|
||||
}
|
||||
const separator = u.search ? '&' : '?';
|
||||
return `${rawUrl}${separator}${templateParams}`;
|
||||
} catch {
|
||||
return rawUrl;
|
||||
}
|
||||
};
|
||||
|
||||
export const useRoomWidgets = (room: Room): RoomWidget[] => {
|
||||
const [updateCount, forceUpdate] = useForceUpdate();
|
||||
|
||||
Reference in new issue
Block a user