Reworked composer URL previews (#34279)
* one slow preview no longer blocks up the current batch of previews from loading * show failed and loading url previews * composer url preview summary bar * prefer site icon * icon to show when there is no icon to show * loading and failed previews * collapse working * clear all button working * clear cache on empty composer * remove preview button * attach empty bundle when all urls previews are to be suppressed * Reconcile url-preview foundation with develop's base - Restore entries-based visibility/skip logic in the view model (drop leftover previews-based branch from the cherry-pick merge) - Pass collapsed/toggleCollapsed in both wrapper render paths - Pass collapse props from the storybook wrapper * fixed lint errors * fixed more lint errors * shut up sonar qube * updated shared-components unit test snapshots * made bar a div again * update snapshot * fixed aria label violations * wait for tall image to load before capturing snapshot (claude wrote this) * updated snapshot * added onkeydown handler to summary div * fixed tests for new view model * made summary bar no longer clickable * banners snapshot update * bundles error-solid in vitest * updated snapshot * use uncollapsed composer url preview in vitest * formatting * restore mocks after each test * corrected mocking logic * sitename is not returned by /preview_url and so is not used * uncollapse the composer url preview during test * refactored to remove code duplication (and pass the CI) * chrome tests fix * updated test * tests for failed/loading entries in composer url preview * formatting * fixed issue where composer url preview pops up after message is sent * ensured links not in the preview view will not be shown * changed css to match design * fixed linter errors * updated storybook screnshots * updated css to not use hard values * resolves some of the reviews * some more of the reviews resolves * usecallback * uses translations * apply some review changes * fixed more reviews stuff * applied comments * removes matrix.to links from urlpreviews * fixed some oxlint stuff * regenerated snapshot * removed pointless void * fixed tests and stuff * dark theme icon lightness * reviews * corrected types * uses predefined colours
@@ -5,6 +5,7 @@
|
||||
* Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { SettingLevel } from "../../../src/settings/SettingLevel";
|
||||
import { test, expect } from "../../element-web-test";
|
||||
|
||||
const PREVIEW_URL_PATTERN = /.*\/_matrix\/(client\/v1\/media|media\/v3)\/preview_url.*/;
|
||||
@@ -18,6 +19,11 @@ test.describe("Composer URL preview", () => {
|
||||
},
|
||||
});
|
||||
|
||||
test.beforeEach(async ({ app, user /* trigger user fixture to load the app so mxSettingsStore exists */ }) => {
|
||||
// Composer URL previews are collapsed by default; expand so the preview links render
|
||||
await app.settings.setValue("composerUrlPreviewCollapsed", null, SettingLevel.DEVICE, false);
|
||||
});
|
||||
|
||||
for (const editor of ["cider", "rich text"]) {
|
||||
test.describe(`in ${editor}`, () => {
|
||||
test.use({
|
||||
|
||||
@@ -405,7 +405,7 @@ export class MessageComposer extends React.Component<IProps, IState> {
|
||||
// otherwise the send message function will think there are no URLs in
|
||||
// message and will not attach URL bundles
|
||||
const urlPreviewSnapshot = this.props.urlPreviewVm.getSnapshot();
|
||||
void this.props.urlPreviewVm.updateWithText({ content: "", debounced: false });
|
||||
this.props.urlPreviewVm.updateWithText({ content: "", debounced: false });
|
||||
if (this.state.haveRecording && this.voiceRecordingButton.current) {
|
||||
// There shouldn't be any text message to send when a voice recording is active, so
|
||||
// just send out the voice recording.
|
||||
@@ -434,7 +434,7 @@ export class MessageComposer extends React.Component<IProps, IState> {
|
||||
};
|
||||
|
||||
private onChange = (model: EditorModel): void => {
|
||||
void this.props.urlPreviewVm.updateWithText({
|
||||
this.props.urlPreviewVm.updateWithText({
|
||||
content: model.contentPlainText,
|
||||
debounced: true,
|
||||
});
|
||||
@@ -444,7 +444,7 @@ export class MessageComposer extends React.Component<IProps, IState> {
|
||||
};
|
||||
|
||||
private onWysiwygChange = (content: string): void => {
|
||||
void this.props.urlPreviewVm.updateWithText({ content, debounced: true });
|
||||
this.props.urlPreviewVm.updateWithText({ content, debounced: true });
|
||||
this.setState({
|
||||
composerContent: content,
|
||||
isComposerEmpty: content?.length === 0,
|
||||
@@ -762,7 +762,7 @@ export default function MessageComposerWrapper(props: Omit<IProps, "mxClient" |
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void urlPreviewVm.updateUrlPreviewVisible(showUrlPreview);
|
||||
urlPreviewVm.updateUrlPreviewVisible(showUrlPreview);
|
||||
}, [urlPreviewVm, showUrlPreview]);
|
||||
|
||||
return <MessageComposerWithMatrixClient {...props} urlPreviewVm={urlPreviewVm} />;
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
MessageComposerUrlPreviewViewModel,
|
||||
type MessageComposerUrlPreviewViewModelProps,
|
||||
} from "../../../viewmodels/composer/MessageComposerUrlPreviewViewModel";
|
||||
import SettingsStore from "../../../settings/SettingsStore";
|
||||
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
@@ -53,7 +54,7 @@ function getUrlPreviewVm(client: MatrixClient, content?: string): MessageCompose
|
||||
const vm = new MessageComposerUrlPreviewViewModel(props);
|
||||
if (content !== undefined) {
|
||||
// Mirror how MessageComposer drives the view model so previews are actually computed.
|
||||
void vm.updateWithText({ content, debounced: false });
|
||||
vm.updateWithText({ content, debounced: false });
|
||||
}
|
||||
return vm;
|
||||
}
|
||||
@@ -70,9 +71,16 @@ describe("MessageComposerUrlPreview", () => {
|
||||
...mockClientMethodsUser(),
|
||||
getUrlPreview: vi.fn().mockResolvedValue(BASIC_PREVIEW_OGDATA),
|
||||
});
|
||||
|
||||
const realGetValue = SettingsStore.getValue;
|
||||
vi.spyOn(SettingsStore, "getValue").mockImplementation(
|
||||
(settingsName, roomId, excludeDefault) =>
|
||||
settingsName !== "composerUrlPreviewCollapsed" && realGetValue(settingsName, roomId, excludeDefault),
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
window.mxModuleApi = originalMxModuleApi;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function wrapComponent(component: Parameters<typeof render>[0]): ReturnType<typeof render> {
|
||||
@@ -102,7 +110,7 @@ describe("MessageComposerUrlPreview", () => {
|
||||
);
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(getByText("Example.org")).toBeDefined();
|
||||
expect(getByText("This is an example!")).toBeDefined();
|
||||
},
|
||||
{ timeout: DEBOUNCE_REQUEST_TIMEOUT_MS },
|
||||
);
|
||||
|
||||
@@ -5,12 +5,15 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import React, { type ReactNode } from "react";
|
||||
import React, { type JSX, useCallback, type ReactNode } from "react";
|
||||
import { MessageComposerUrlPreviewView, useViewModel } from "@element-hq/web-shared-components";
|
||||
|
||||
import { type MessageComposerUrlPreviewViewModel } from "../../../viewmodels/composer/MessageComposerUrlPreviewViewModel";
|
||||
import { useScopedRoomContext } from "../../../contexts/ScopedRoomContext";
|
||||
import { ModuleApi } from "../../../modules/Api";
|
||||
import { useSettingValue } from "../../../hooks/useSettings";
|
||||
import SettingsStore from "../../../settings/SettingsStore";
|
||||
import { SettingLevel } from "../../../settings/SettingLevel";
|
||||
|
||||
export function MessageComposerUrlPreviewWrapper({
|
||||
urlPreviewVm: vm,
|
||||
@@ -21,9 +24,26 @@ export function MessageComposerUrlPreviewWrapper({
|
||||
}): ReactNode | null {
|
||||
const { roomId } = useScopedRoomContext("showUrlPreview", "roomId");
|
||||
const { content } = useViewModel(vm);
|
||||
const customComponent = moduleApi.customComponents.renderComposerPreview({ text: content, roomId: roomId! }, () => (
|
||||
<MessageComposerUrlPreviewView vm={vm} />
|
||||
));
|
||||
|
||||
return customComponent ?? <MessageComposerUrlPreviewView vm={vm} />;
|
||||
const urlPreviewBundlesEnabled = useSettingValue("feature_msc4095_url_preview_bundle");
|
||||
const collapsed = useSettingValue("composerUrlPreviewCollapsed");
|
||||
|
||||
const toggleCollapsed = useCallback(() => {
|
||||
void SettingsStore.setValue("composerUrlPreviewCollapsed", null, SettingLevel.DEVICE, !collapsed);
|
||||
}, [collapsed]);
|
||||
|
||||
const makeDefaultComposer = (): JSX.Element => (
|
||||
<MessageComposerUrlPreviewView
|
||||
vm={vm}
|
||||
collapsed={collapsed}
|
||||
toggleCollapsed={toggleCollapsed}
|
||||
removePreview={urlPreviewBundlesEnabled ? vm.removePreview : undefined}
|
||||
/>
|
||||
);
|
||||
|
||||
const customComponent = moduleApi.customComponents.renderComposerPreview(
|
||||
{ text: content, roomId: roomId! },
|
||||
makeDefaultComposer,
|
||||
);
|
||||
return customComponent ?? makeDefaultComposer();
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ import { EMOJI_REGEX } from "../../../HtmlUtils";
|
||||
import { attachMentions, attachRelation, attachUrlPreviews } from "../../../utils/messages";
|
||||
import { type RoomUploadViewModel, useRoomUploadViewModel } from "../../../viewmodels/room/RoomUploadViewModel";
|
||||
import { type MessageComposerUrlPreviewViewModel } from "../../../viewmodels/composer/MessageComposerUrlPreviewViewModel";
|
||||
import { linksIn } from "../../../utils/UrlUtils";
|
||||
import { type MessageComposerUrlPreviewSnapshot } from "@element-hq/web-shared-components";
|
||||
|
||||
// The prefix used when persisting editor drafts to localstorage.
|
||||
@@ -451,9 +452,10 @@ export class SendMessageComposer extends React.Component<ISendMessageComposerPro
|
||||
// don't bother sending an empty message
|
||||
if (!content.body.trim()) return;
|
||||
|
||||
attachUrlPreviews(urlPreviewSnapshot, content, linksIn(this.model.contentPlainText).size !== 0);
|
||||
|
||||
// clear composer first so the user doesn't actually see the delay of attach URL preview image files
|
||||
clearComposerAndPushHistory();
|
||||
attachUrlPreviews(urlPreviewSnapshot, content);
|
||||
|
||||
if (SettingsStore.getValue("Performance.addSendMessageTimingMetadata")) {
|
||||
decorateStartSendingTime(content);
|
||||
|
||||
@@ -35,6 +35,7 @@ import { runSlashCommand, shouldSendAnyway } from "../../../../../editor/command
|
||||
import { Action } from "../../../../../dispatcher/actions";
|
||||
import { addReplyToMessageContent } from "../../../../../utils/Reply";
|
||||
import { attachRelation, attachUrlPreviews } from "../../../../../utils/messages";
|
||||
import { linksIn } from "../../../../../utils/UrlUtils";
|
||||
|
||||
export interface SendMessageParams {
|
||||
mxClient: MatrixClient;
|
||||
@@ -114,7 +115,7 @@ export async function sendMessage(
|
||||
|
||||
// if content is null, we haven't done any slash command processing, so generate some content
|
||||
content ??= await createMessageContent(message, isHTML, params);
|
||||
attachUrlPreviews(urlPreviewSnapshot, content);
|
||||
attachUrlPreviews(urlPreviewSnapshot, content, linksIn(message).size !== 0);
|
||||
|
||||
// TODO replace emotion end of message ?
|
||||
|
||||
|
||||
@@ -369,6 +369,7 @@ export interface Settings {
|
||||
"RoomList.OrderedCustomSections": IBaseSetting<ReorderableSection[]>;
|
||||
"RoomList.SectionExpansionState": IBaseSetting<SectionExpansionState>;
|
||||
"RoomList.showSections": IBaseSetting<boolean>;
|
||||
"composerUrlPreviewCollapsed": IBaseSetting<boolean>;
|
||||
}
|
||||
|
||||
export type SettingKey = keyof Settings;
|
||||
@@ -1219,6 +1220,10 @@ export const SETTINGS: Settings = {
|
||||
default: true,
|
||||
displayName: _td("settings|show_sections"),
|
||||
},
|
||||
"composerUrlPreviewCollapsed": {
|
||||
supportedLevels: LEVELS_DEVICE_ONLY_SETTINGS,
|
||||
default: true,
|
||||
},
|
||||
"RightPanel.phasesGlobal": {
|
||||
supportedLevels: [SettingLevel.DEVICE],
|
||||
default: null,
|
||||
|
||||
@@ -6,6 +6,8 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com
|
||||
Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { isPermalinkHost } from "./permalinks/Permalinks";
|
||||
|
||||
/**
|
||||
* If a url has no path component, etc. abbreviate it to just the hostname
|
||||
*
|
||||
@@ -43,6 +45,34 @@ export function unabbreviateUrl(u?: string): string {
|
||||
return longUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the URLs in a block of text.
|
||||
*
|
||||
* Links are inserted in the order they appear in the text, which guarantees
|
||||
* iteration order to be the same.
|
||||
*
|
||||
* @param content The text to search, e.g. plaintext from the message composer.
|
||||
* @returns The set of whitespace-separated words which parse as a URL.
|
||||
*/
|
||||
export function linksIn(content: string): Set<string> {
|
||||
return new Set(
|
||||
content
|
||||
.split(" ")
|
||||
.map((w) => w.trim())
|
||||
.filter(linkPreviewable),
|
||||
);
|
||||
}
|
||||
|
||||
export function linkPreviewable(s: string): boolean {
|
||||
if (!s || !URL.canParse(s)) return false;
|
||||
|
||||
const url = new URL(s);
|
||||
if (!["http:", "https:"].includes(url.protocol)) return false;
|
||||
if (isPermalinkHost(url.host)) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function parseUrl(u: string): URL {
|
||||
if (!u.includes(":")) {
|
||||
u = window.location.protocol + u;
|
||||
|
||||
@@ -6,7 +6,10 @@ Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type MatrixEvent, type IContent, type IMentions, type IEventRelation } from "matrix-js-sdk/src/matrix";
|
||||
import { type MessageComposerUrlPreviewSnapshot } from "@element-hq/web-shared-components";
|
||||
import {
|
||||
type MessageComposerUrlPreviewSnapshotEntryLoaded,
|
||||
type MessageComposerUrlPreviewSnapshot,
|
||||
} from "@element-hq/web-shared-components";
|
||||
|
||||
import type EditorModel from "../editor/model";
|
||||
import { Type } from "../editor/parts";
|
||||
@@ -110,14 +113,19 @@ export function attachRelation(content: IContent, relation?: IEventRelation): vo
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Attaches URL preview bundle to message event (MSC4095)
|
||||
export function attachUrlPreviews(
|
||||
urlPreviewSnapshot: MessageComposerUrlPreviewSnapshot,
|
||||
content: RoomMessageEventContent,
|
||||
messageHasLinks: boolean,
|
||||
): void {
|
||||
if (!SettingsStore.getValue("feature_msc4095_url_preview_bundle")) return;
|
||||
|
||||
if (urlPreviewSnapshot.previews.length) {
|
||||
content["com.beeper.linkpreviews"] = urlPreviewSnapshot.previews.map((preview) => {
|
||||
const bundle = urlPreviewSnapshot.entries
|
||||
.filter((entry) => entry.include && entry.status === "loaded")
|
||||
.map((entry) => (entry as MessageComposerUrlPreviewSnapshotEntryLoaded).preview)
|
||||
.map((preview) => {
|
||||
return {
|
||||
"matched_url": preview.link,
|
||||
"og:url": preview.ogUrl,
|
||||
@@ -130,5 +138,8 @@ export function attachUrlPreviews(
|
||||
"matrix:image:size": preview.image?.fileSize,
|
||||
};
|
||||
});
|
||||
|
||||
if (messageHasLinks) {
|
||||
content["com.beeper.linkpreviews"] = bundle;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,10 +5,13 @@
|
||||
* Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { vi, describe, it, expect, type Mock, beforeAll, afterAll } from "vitest";
|
||||
|
||||
import type { MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
import { MessageComposerUrlPreviewViewModel } from "./MessageComposerUrlPreviewViewModel";
|
||||
import { type MessageComposerUrlPreviewSnapshotEntry } from "@element-hq/web-shared-components";
|
||||
|
||||
const IMAGE_MXC = "mxc://example.org/abc";
|
||||
const BASIC_PREVIEW_OGDATA = {
|
||||
@@ -36,6 +39,14 @@ function getViewModel({ visible } = { visible: true }): {
|
||||
return { vm, client: client as unknown as { getUrlPreview: Mock; mxcUrlToHttp: Mock } };
|
||||
}
|
||||
|
||||
function getEntrySummary({ matched_url, include, status }: MessageComposerUrlPreviewSnapshotEntry): {
|
||||
matched_url: string;
|
||||
status: "loading" | "loaded" | "failed";
|
||||
include: boolean;
|
||||
} {
|
||||
return { matched_url, include, status };
|
||||
}
|
||||
|
||||
describe("MessageComposerUrlPreviewViewModel", () => {
|
||||
let originalDevicePixelRatio: Window["devicePixelRatio"];
|
||||
beforeAll(() => {
|
||||
@@ -50,7 +61,7 @@ describe("MessageComposerUrlPreviewViewModel", () => {
|
||||
expect(getViewModel().vm.getSnapshot()).toMatchInlineSnapshot(`
|
||||
{
|
||||
"content": "",
|
||||
"previews": [],
|
||||
"entries": [],
|
||||
}
|
||||
`);
|
||||
});
|
||||
@@ -58,22 +69,47 @@ describe("MessageComposerUrlPreviewViewModel", () => {
|
||||
it("should preview a valid URL in text", async () => {
|
||||
const { vm, client } = getViewModel();
|
||||
client.getUrlPreview.mockResolvedValueOnce(BASIC_PREVIEW_OGDATA);
|
||||
await vm.updateWithText({ content: "Check out https://example.org today", debounced: false });
|
||||
expect(vm.getSnapshot()).toMatchSnapshot();
|
||||
vm.updateWithText({ content: "Check out https://example.org today", debounced: false });
|
||||
await vi.waitFor(() => {
|
||||
expect(vm.getSnapshot()).toEqual({
|
||||
content: "Check out https://example.org today",
|
||||
entries: [
|
||||
{
|
||||
include: true,
|
||||
matched_url: "https://example.org",
|
||||
preview: {
|
||||
description: "This is a description",
|
||||
link: "https://example.org",
|
||||
ogUrl: "https://example.org",
|
||||
showTooltipOnLink: false,
|
||||
siteName: "Example.org",
|
||||
title: "This is an example!",
|
||||
},
|
||||
status: "loaded",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("should return empty list when preview is not visible", async () => {
|
||||
const { vm, client } = getViewModel({ visible: false });
|
||||
await vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
expect(vm.getSnapshot().previews).toHaveLength(0);
|
||||
expect(client.getUrlPreview).not.toHaveBeenCalled();
|
||||
vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
await vi.waitFor(() => {
|
||||
expect(vm.getSnapshot().entries).toHaveLength(0);
|
||||
expect(client.getUrlPreview).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("should return empty list when all URL fetches fail", async () => {
|
||||
it("should return list of failed previews when all URL fetches fail", async () => {
|
||||
const { vm, client } = getViewModel();
|
||||
client.getUrlPreview.mockRejectedValue(new Error("Forced test failure"));
|
||||
await vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
expect(vm.getSnapshot().previews).toHaveLength(0);
|
||||
vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
await vi.waitFor(() => {
|
||||
expect(vm.getSnapshot().entries.map(getEntrySummary)).toEqual([
|
||||
{ matched_url: "https://example.org", include: true, status: "failed" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("should use all URLs with a valid preview when multiple are given", async () => {
|
||||
@@ -81,45 +117,69 @@ describe("MessageComposerUrlPreviewViewModel", () => {
|
||||
client.getUrlPreview
|
||||
.mockRejectedValueOnce(new Error("First URL failed"))
|
||||
.mockResolvedValueOnce(BASIC_PREVIEW_OGDATA);
|
||||
await vm.updateWithText({ content: "https://example.org/one https://example.org/two", debounced: false });
|
||||
expect(vm.getSnapshot().previews[0]?.link).toEqual("https://example.org/two");
|
||||
expect(vm.getSnapshot().previews).toHaveLength(1);
|
||||
vm.updateWithText({ content: "https://example.org/one https://example.org/two", debounced: false });
|
||||
await vi.waitFor(() => {
|
||||
expect(vm.getSnapshot().entries.map(getEntrySummary)).toEqual([
|
||||
{
|
||||
matched_url: "https://example.org/one",
|
||||
status: "failed",
|
||||
include: true,
|
||||
},
|
||||
{
|
||||
matched_url: "https://example.org/two",
|
||||
status: "loaded",
|
||||
include: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("should not re-fetch when text changes but the URL set does not", async () => {
|
||||
const { vm, client } = getViewModel();
|
||||
client.getUrlPreview.mockResolvedValue(BASIC_PREVIEW_OGDATA);
|
||||
await vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
await vm.updateWithText({ content: "https://example.org some extra words", debounced: false });
|
||||
expect(client.getUrlPreview).toHaveBeenCalledTimes(1);
|
||||
vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
vm.updateWithText({ content: "https://example.org some extra words", debounced: false });
|
||||
await vi.waitFor(() => {
|
||||
expect(client.getUrlPreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("should deduplicate repeated URLs", async () => {
|
||||
const { vm, client } = getViewModel();
|
||||
client.getUrlPreview.mockResolvedValue(BASIC_PREVIEW_OGDATA);
|
||||
await vm.updateWithText({
|
||||
vm.updateWithText({
|
||||
content: "https://example.org https://example.org https://example.org",
|
||||
debounced: false,
|
||||
});
|
||||
expect(client.getUrlPreview).toHaveBeenCalledTimes(1);
|
||||
await vi.waitFor(() => {
|
||||
expect(client.getUrlPreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("should hide preview when made invisible", async () => {
|
||||
const { vm, client } = getViewModel();
|
||||
client.getUrlPreview.mockResolvedValue(BASIC_PREVIEW_OGDATA);
|
||||
await vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
expect(vm.getSnapshot().previews).not.toHaveLength(0);
|
||||
await vm.updateUrlPreviewVisible(false);
|
||||
expect(vm.getSnapshot().previews).toHaveLength(0);
|
||||
vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
await vi.waitFor(() => {
|
||||
expect(vm.getSnapshot().entries).not.toHaveLength(0);
|
||||
});
|
||||
vm.updateUrlPreviewVisible(false);
|
||||
await vi.waitFor(() => {
|
||||
expect(vm.getSnapshot().entries).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
it("should restore preview when made visible again", async () => {
|
||||
const { vm, client } = getViewModel({ visible: false });
|
||||
client.getUrlPreview.mockResolvedValue(BASIC_PREVIEW_OGDATA);
|
||||
await vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
expect(vm.getSnapshot().previews).toHaveLength(0);
|
||||
await vm.updateUrlPreviewVisible(true);
|
||||
expect(vm.getSnapshot().previews).not.toHaveLength(0);
|
||||
vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
await vi.waitFor(() => {
|
||||
expect(vm.getSnapshot().entries).toHaveLength(0);
|
||||
});
|
||||
vm.updateUrlPreviewVisible(true);
|
||||
await vi.waitFor(() => {
|
||||
expect(vm.getSnapshot().entries).not.toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
it("should preview a URL with media", async () => {
|
||||
@@ -139,7 +199,34 @@ describe("MessageComposerUrlPreviewViewModel", () => {
|
||||
if (width) return "https://example.org/image/thumb";
|
||||
return "https://example.org/image/src";
|
||||
});
|
||||
await vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
expect(vm.getSnapshot()).toMatchSnapshot();
|
||||
vm.updateWithText({ content: "https://example.org", debounced: false });
|
||||
await vi.waitFor(() => {
|
||||
expect(vm.getSnapshot()).toEqual({
|
||||
content: "https://example.org",
|
||||
entries: [
|
||||
{
|
||||
include: true,
|
||||
matched_url: "https://example.org",
|
||||
preview: {
|
||||
image: {
|
||||
fileSize: 10000,
|
||||
height: 128,
|
||||
imageFull: "https://example.org/image/src",
|
||||
imageThumb: "https://example.org/image/thumb",
|
||||
mxcImageFull: "mxc://example.org/abc",
|
||||
playable: false,
|
||||
width: 128,
|
||||
},
|
||||
link: "https://example.org",
|
||||
ogUrl: "https://example.org",
|
||||
showTooltipOnLink: false,
|
||||
siteName: "example.org",
|
||||
title: "Media example",
|
||||
},
|
||||
status: "loaded",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,14 +5,16 @@
|
||||
* Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { logger as rootLogger } from "matrix-js-sdk/src/logger";
|
||||
import { type MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
import { BaseViewModel, type MessageComposerUrlPreviewSnapshot } from "@element-hq/web-shared-components";
|
||||
import {
|
||||
BaseViewModel,
|
||||
type MessageComposerUrlPreviewSnapshotEntry,
|
||||
type MessageComposerUrlPreviewSnapshot,
|
||||
} from "@element-hq/web-shared-components";
|
||||
import { debounce } from "lodash";
|
||||
|
||||
import { UrlPreviewFetcher } from "../../utils/UrlPreviewFetcher";
|
||||
|
||||
const logger = rootLogger.getChild("MessageComposerUrlPreviewViewModel");
|
||||
import { linksIn } from "../../utils/UrlUtils";
|
||||
|
||||
export const DEBOUNCE_REQUEST_TIMEOUT_MS = 500;
|
||||
|
||||
@@ -43,29 +45,36 @@ export class MessageComposerUrlPreviewViewModel extends BaseViewModel<
|
||||
*/
|
||||
private urlPreviewVisible: boolean;
|
||||
|
||||
/**
|
||||
* Composer content when updateWithText is most recently called
|
||||
*/
|
||||
private content: string;
|
||||
|
||||
/**
|
||||
* The list of all previews that are currently loading, loaded or failed to load
|
||||
* - loading entries are immediately added when computeSnapshot detects new link in the composer
|
||||
* - loaded/failed to load entries replaces the loading entry when it resolves
|
||||
* - not all previews in cache are displayed: the preview only selects the previews which link is in the composer,
|
||||
* and preview.include is true where the preview has not been removed
|
||||
* - the cache is cleared when the composer is emptied: intentionally by user or by sending a message,
|
||||
* this reloads all previews and forgets all preview.include states, causing all previously removed previews to be unremoved
|
||||
*/
|
||||
private readonly previewCache: Map<string, MessageComposerUrlPreviewSnapshotEntry> = new Map();
|
||||
|
||||
public constructor(props: MessageComposerUrlPreviewViewModelProps) {
|
||||
super(props, { previews: [], content: props.content ?? "" });
|
||||
super(props, { entries: [], content: props.content ?? "" });
|
||||
this.urlPreviewVisible = props.visible;
|
||||
this.fetcher = new UrlPreviewFetcher(props.client, Date.now(), props.showTooltips);
|
||||
this.content = this.snapshot.current.content;
|
||||
}
|
||||
|
||||
private async computeSnapshot(content: string): Promise<void> {
|
||||
const newLinksOrdered = content
|
||||
.split(" ")
|
||||
.map((w) => w.trim())
|
||||
.filter((word) => URL.canParse(word));
|
||||
const newLinks = new Set(newLinksOrdered);
|
||||
|
||||
private computeSnapshot(content: string): void {
|
||||
if (!this.urlPreviewVisible) {
|
||||
// Clear any existing previews whenever previews are hidden, regardless of
|
||||
// whether the URL set has changed (e.g. when toggled invisible).
|
||||
this.snapshot.set({ previews: [], content });
|
||||
this.snapshot.set({ entries: [], content });
|
||||
return;
|
||||
}
|
||||
|
||||
const newLinks = linksIn(content);
|
||||
if (this.links.symmetricDifference(newLinks).size === 0) {
|
||||
// Skip if the URL set hasn't changed
|
||||
return;
|
||||
@@ -73,52 +82,73 @@ export class MessageComposerUrlPreviewViewModel extends BaseViewModel<
|
||||
|
||||
this.links = newLinks;
|
||||
|
||||
let previews;
|
||||
if (this.props.urlPreviewBundle) {
|
||||
const previewRequests = Array.from(this.links).map(async (link) => {
|
||||
try {
|
||||
return await this.fetcher.fetchPreview(link, true);
|
||||
} catch (ex) {
|
||||
logger.warn("Fetching preview failed", ex);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
const entries = Array.from(this.links).map((link) => {
|
||||
// if not in cache, add to VM now, fetch later
|
||||
if (!this.previewCache.has(link)) {
|
||||
this.previewCache.set(link, {
|
||||
status: "loading",
|
||||
include: true,
|
||||
matched_url: link,
|
||||
});
|
||||
|
||||
// Fetch previews for all links in the message text,
|
||||
// And remove the ones with erroneous responses
|
||||
const previewResponses = await Promise.all(previewRequests);
|
||||
previews = previewResponses.filter((res) => res !== null);
|
||||
|
||||
this.snapshot.set({ previews, content });
|
||||
} else {
|
||||
for (const link of this.links) {
|
||||
try {
|
||||
const preview = await this.fetcher.fetchPreview(link, true);
|
||||
if (preview) {
|
||||
this.snapshot.set({ previews: [preview], content });
|
||||
return;
|
||||
void this.fetcher.fetchPreview(link, true).then((fetched) => {
|
||||
// update cache
|
||||
const currentEntry = this.previewCache.get(link);
|
||||
if (fetched === null) {
|
||||
this.previewCache.set(link, {
|
||||
status: "failed",
|
||||
include: currentEntry?.include ?? true,
|
||||
matched_url: link,
|
||||
});
|
||||
} else {
|
||||
this.previewCache.set(link, {
|
||||
status: "loaded",
|
||||
include: currentEntry?.include ?? true,
|
||||
matched_url: link,
|
||||
preview: fetched,
|
||||
});
|
||||
}
|
||||
} catch (ex) {
|
||||
logger.warn("Fetching preview failed", ex);
|
||||
}
|
||||
|
||||
// insert to snapshot
|
||||
const updatedEntry = this.previewCache.get(link);
|
||||
if (updatedEntry === undefined) return;
|
||||
|
||||
const snapshot = this.snapshot.current;
|
||||
|
||||
this.snapshot.set({
|
||||
content: snapshot.content,
|
||||
entries: snapshot.entries.map((entry) =>
|
||||
entry.matched_url === updatedEntry.matched_url ? updatedEntry : entry,
|
||||
),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
this.snapshot.set({ previews: [], content });
|
||||
}
|
||||
return this.previewCache.get(link)!;
|
||||
});
|
||||
|
||||
this.snapshot.set({ entries, content });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a recalculation of the links in the provided text.
|
||||
* @param content Plaintext from the message composer.
|
||||
*/
|
||||
public async updateWithText({ content, debounced }: { content?: string; debounced: boolean }): Promise<void> {
|
||||
public updateWithText({ content, debounced }: { content?: string; debounced: boolean }): void {
|
||||
if (content !== undefined) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
if (content === "") {
|
||||
this.previewCache.clear();
|
||||
this.computeSnapshotDebounced.cancel();
|
||||
return this.computeSnapshot("");
|
||||
}
|
||||
|
||||
if (debounced) {
|
||||
return this.computeSnapshotDebounced(this.content);
|
||||
} else {
|
||||
this.computeSnapshotDebounced.cancel();
|
||||
return this.computeSnapshot(this.content);
|
||||
}
|
||||
}
|
||||
@@ -134,9 +164,26 @@ export class MessageComposerUrlPreviewViewModel extends BaseViewModel<
|
||||
*
|
||||
* @returns A promise that completes when the snapshot has been recomputed.
|
||||
*/
|
||||
public readonly updateUrlPreviewVisible = (urlPreviewVisible: boolean): Promise<void> => {
|
||||
public readonly updateUrlPreviewVisible = (urlPreviewVisible: boolean): void => {
|
||||
this.urlPreviewVisible = urlPreviewVisible;
|
||||
this.fetcher.clearCache();
|
||||
return this.computeSnapshot(this.content);
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove a preview of a URL and remembers it until cache is cleared
|
||||
* @param url A URL that has been previously requested since the last time composer is empty
|
||||
*/
|
||||
public readonly removePreview = (url: string): void => {
|
||||
const entry = this.previewCache.get(url);
|
||||
if (entry === undefined) return;
|
||||
entry.include = false;
|
||||
|
||||
const snapshot = this.snapshot.current;
|
||||
|
||||
this.snapshot.set({
|
||||
content: snapshot.content,
|
||||
entries: snapshot.entries.filter((entry) => entry.include),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`MessageComposerUrlPreviewViewModel > should preview a URL with media 1`] = `
|
||||
{
|
||||
"content": "https://example.org",
|
||||
"previews": [
|
||||
{
|
||||
"author": undefined,
|
||||
"description": undefined,
|
||||
"image": {
|
||||
"alt": undefined,
|
||||
"fileSize": 10000,
|
||||
"height": 128,
|
||||
"imageFull": "https://example.org/image/src",
|
||||
"imageThumb": "https://example.org/image/thumb",
|
||||
"imageType": undefined,
|
||||
"mxcImageFull": "mxc://example.org/abc",
|
||||
"playable": false,
|
||||
"width": 128,
|
||||
},
|
||||
"link": "https://example.org",
|
||||
"ogUrl": "https://example.org",
|
||||
"showTooltipOnLink": false,
|
||||
"siteIcon": undefined,
|
||||
"siteName": "example.org",
|
||||
"title": "Media example",
|
||||
},
|
||||
],
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`MessageComposerUrlPreviewViewModel > should preview a valid URL in text 1`] = `
|
||||
{
|
||||
"content": "Check out https://example.org today",
|
||||
"previews": [
|
||||
{
|
||||
"author": undefined,
|
||||
"description": "This is a description",
|
||||
"image": undefined,
|
||||
"link": "https://example.org",
|
||||
"ogUrl": "https://example.org",
|
||||
"showTooltipOnLink": false,
|
||||
"siteIcon": undefined,
|
||||
"siteName": "Example.org",
|
||||
"title": "This is an example!",
|
||||
},
|
||||
],
|
||||
}
|
||||
`;
|
||||
@@ -68,7 +68,7 @@ describe("message", () => {
|
||||
await sendMessage("", true, {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -84,7 +84,7 @@ describe("message", () => {
|
||||
await sendMessage(message, true, {
|
||||
roomContext: mockRoomContextWithoutId,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -98,7 +98,7 @@ describe("message", () => {
|
||||
await sendMessage(message, true, {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -110,7 +110,7 @@ describe("message", () => {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
relation: {},
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -125,7 +125,7 @@ describe("message", () => {
|
||||
event_id: "valid_id",
|
||||
rel_type: "m.does_not_match",
|
||||
},
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -141,7 +141,7 @@ describe("message", () => {
|
||||
event_id: "valid_id",
|
||||
rel_type: "m.thread",
|
||||
},
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -154,7 +154,7 @@ describe("message", () => {
|
||||
await sendMessage(message, true, {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -182,7 +182,7 @@ describe("message", () => {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
replyToEvent: mockReplyEvent,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -212,7 +212,7 @@ describe("message", () => {
|
||||
await sendMessage(message, true, {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -227,7 +227,7 @@ describe("message", () => {
|
||||
await sendMessage("🎉", false, {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -243,7 +243,7 @@ describe("message", () => {
|
||||
await sendMessage(validCommand, true, {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -256,7 +256,7 @@ describe("message", () => {
|
||||
await sendMessage(invalidPrefixCommand, true, {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -274,7 +274,7 @@ describe("message", () => {
|
||||
const result = await sendMessage(validCommand, true, {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// Then
|
||||
@@ -289,7 +289,7 @@ describe("message", () => {
|
||||
await sendMessage(inputText, true, {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
expect(mockClient.sendMessage).toHaveBeenCalledWith(
|
||||
"myfakeroom",
|
||||
@@ -309,7 +309,7 @@ describe("message", () => {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
relation: mockRelation,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
expect(mockClient.sendMessage).toHaveBeenCalledWith(
|
||||
@@ -326,7 +326,7 @@ describe("message", () => {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
replyToEvent: mockEvent,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
expect(addReplySpy).toHaveBeenCalledTimes(1);
|
||||
@@ -341,7 +341,7 @@ describe("message", () => {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
replyToEvent: mockEvent,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
@@ -356,7 +356,7 @@ describe("message", () => {
|
||||
await sendMessage(invalidCommandInput, true, {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
// we expect the message to have been sent
|
||||
@@ -377,7 +377,7 @@ describe("message", () => {
|
||||
const result = await sendMessage(invalidCommandInput, true, {
|
||||
roomContext: defaultRoomContext,
|
||||
mxClient: mockClient,
|
||||
urlPreviewSnapshot: { previews: [], content: "" },
|
||||
urlPreviewSnapshot: { entries: [], content: "" },
|
||||
});
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
|
||||
@@ -7,7 +7,7 @@ Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type IContent } from "matrix-js-sdk/src/matrix";
|
||||
import { type MessageComposerUrlPreviewSnapshot } from "@element-hq/web-shared-components";
|
||||
import { type UrlPreview, type MessageComposerUrlPreviewSnapshot } from "@element-hq/web-shared-components";
|
||||
|
||||
import { attachMentions, attachUrlPreviews } from "../../../src/utils/messages";
|
||||
import EditorModel from "../../../src/editor/model";
|
||||
@@ -32,28 +32,33 @@ describe("attachUrlPreviews", () => {
|
||||
({ msgtype: "m.text", body: "hi https://example.com" }) as RoomMessageEventContent;
|
||||
|
||||
const snapshot = (image?: object): MessageComposerUrlPreviewSnapshot => ({
|
||||
previews: [
|
||||
entries: [
|
||||
{
|
||||
link: "https://example.com",
|
||||
showTooltipOnLink: false,
|
||||
title: "Example",
|
||||
siteName: "example.com",
|
||||
description: "desc",
|
||||
...(image ? { image } : {}),
|
||||
} as any,
|
||||
status: "loaded",
|
||||
matched_url: "https://example.com",
|
||||
include: true,
|
||||
preview: {
|
||||
link: "https://example.com",
|
||||
showTooltipOnLink: false,
|
||||
title: "Example",
|
||||
siteName: "example.com",
|
||||
description: "desc",
|
||||
...(image ? { image } : {}),
|
||||
} as UrlPreview,
|
||||
},
|
||||
],
|
||||
content: "https://example.com",
|
||||
});
|
||||
|
||||
it("does nothing when there are no previews", () => {
|
||||
const content = makeContent();
|
||||
attachUrlPreviews({ previews: [], content: "" }, content);
|
||||
attachUrlPreviews({ entries: [], content: "" }, content, false);
|
||||
expect(content["com.beeper.linkpreviews"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("attaches a preview with no image", () => {
|
||||
const content = makeContent();
|
||||
attachUrlPreviews(snapshot(), content);
|
||||
attachUrlPreviews(snapshot(), content, true);
|
||||
expect(content["com.beeper.linkpreviews"]).toEqual([
|
||||
expect.objectContaining({ "og:title": "Example", "og:image": undefined }),
|
||||
]);
|
||||
@@ -73,6 +78,7 @@ describe("attachUrlPreviews", () => {
|
||||
playable: false,
|
||||
}),
|
||||
content,
|
||||
true,
|
||||
);
|
||||
|
||||
expect(content["com.beeper.linkpreviews"]![0]).toEqual(
|
||||
|
||||
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 26 KiB |
@@ -43,6 +43,19 @@
|
||||
"preferences": "Preferences",
|
||||
"state_encryption_enabled": "Experimental state encryption enabled"
|
||||
},
|
||||
"composer": {
|
||||
"url_preview": {
|
||||
"clear_all": "Clear all",
|
||||
"collapse": "Collapse URL previews",
|
||||
"failed": "Failed to fetch preview",
|
||||
"loading": "Fetching preview…",
|
||||
"n_links": {
|
||||
"one": "%(count)s link",
|
||||
"other": "%(count)s links"
|
||||
},
|
||||
"remove": "Remove URL preview"
|
||||
}
|
||||
},
|
||||
"devtools": {
|
||||
"toggle_event": "toggle event"
|
||||
},
|
||||
|
||||
@@ -5,6 +5,132 @@
|
||||
* Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
.wrapper {
|
||||
background-color: var(--cpd-color-bg-subtle-secondary);
|
||||
padding: 0 var(--cpd-space-2x) var(--cpd-space-2x) var(--cpd-space-2x);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.wrapper.collapsed {
|
||||
padding-bottom: var(--cpd-space-1x);
|
||||
}
|
||||
|
||||
.left {
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.right {
|
||||
margin-right: var(--cpd-space-1-5x);
|
||||
}
|
||||
|
||||
.spanLike {
|
||||
background: none;
|
||||
border: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
text-align: inherit;
|
||||
line-height: 100%;
|
||||
}
|
||||
|
||||
.summary {
|
||||
justify-content: space-between;
|
||||
display: flex;
|
||||
padding: var(--cpd-space-2x) 0px var(--cpd-space-1x) var(--cpd-space-2x);
|
||||
|
||||
* {
|
||||
vertical-align: center;
|
||||
line-height: 100%;
|
||||
}
|
||||
|
||||
/* give the icons a bit of overlap */
|
||||
.summaryIcon:not(:first-of-type) {
|
||||
margin-left: calc(-1 * var(--cpd-space-1x));
|
||||
}
|
||||
|
||||
.summaryIcon {
|
||||
overflow: hidden;
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 4px;
|
||||
|
||||
box-shadow: 0px 0px 0px 2px var(--cpd-color-bg-subtle-secondary);
|
||||
background-color: var(--cpd-color-bg-subtle-secondary);
|
||||
|
||||
text-align: center;
|
||||
line-height: 18px;
|
||||
|
||||
font-weight: 700;
|
||||
color: var(--cpd-color-text-on-solid-primary);
|
||||
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
object-position: center;
|
||||
}
|
||||
|
||||
svg {
|
||||
/* the spinner svg has its size set to 20x20px, overriding that */
|
||||
width: 50% !important;
|
||||
height: 50% !important;
|
||||
}
|
||||
}
|
||||
|
||||
.summaryIconFailed {
|
||||
background-color: var(--cpd-color-bg-critical-primary);
|
||||
}
|
||||
|
||||
.summaryIconLoading {
|
||||
background-color: var(--cpd-color-bg-subtle-primary);
|
||||
}
|
||||
|
||||
.linkCount {
|
||||
margin-left: var(--cpd-space-3x);
|
||||
font-weight: 500;
|
||||
font-size: var(--cpd-font-size-body-sm);
|
||||
}
|
||||
|
||||
.clearAll {
|
||||
font-size: var(--cpd-font-size-body-xs);
|
||||
margin-right: var(--cpd-space-2x);
|
||||
color: var(--cpd-color-gray-900);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.clearAll:hover {
|
||||
color: var(--cpd-color-text-primary);
|
||||
}
|
||||
|
||||
.collapse {
|
||||
display: inline-block;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
text-align: center;
|
||||
line-height: 100%;
|
||||
transition: rotate 300ms ease;
|
||||
color: var(--cpd-color-gray-900);
|
||||
|
||||
cursor: pointer;
|
||||
|
||||
svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.wrapper.collapsed .collapse {
|
||||
rotate: 180deg;
|
||||
}
|
||||
|
||||
.container {
|
||||
container-type: inline-size;
|
||||
container-name: banner;
|
||||
@@ -12,7 +138,7 @@
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--cpd-space-4x);
|
||||
padding: var(--cpd-space-3x) var(--cpd-space-4x);
|
||||
padding: var(--cpd-space-2x) var(--cpd-space-2x);
|
||||
border-top: 1px solid var(--cpd-color-gray-400);
|
||||
|
||||
> div {
|
||||
@@ -24,27 +150,116 @@
|
||||
.text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
> a {
|
||||
color: var(--cpd-color-text-action-accent);
|
||||
font-weight: 400;
|
||||
font-size: 13px;
|
||||
}
|
||||
> .description {
|
||||
margin: 0;
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 1;
|
||||
line-clamp: 1;
|
||||
overflow: hidden;
|
||||
/* Cap the max width of a line so it doesn't go on forever. */
|
||||
max-width: 40em;
|
||||
font-size: 85%;
|
||||
}
|
||||
}
|
||||
|
||||
.linkSiteName {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.linkTitle {
|
||||
line-clamp: 1;
|
||||
-webkit-line-clamp: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.image {
|
||||
.container:last-of-type {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.removePreview {
|
||||
color: var(--cpd-color-gray-900);
|
||||
cursor: pointer;
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
|
||||
svg {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
}
|
||||
}
|
||||
|
||||
.entryIcon,
|
||||
.loadingSpinner,
|
||||
.failedIcon {
|
||||
flex-shrink: 0;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 6px;
|
||||
object-fit: scale-down;
|
||||
overflow: hidden;
|
||||
|
||||
align-items: center;
|
||||
vertical-align: middle;
|
||||
|
||||
text-align: center;
|
||||
line-height: 40px;
|
||||
font-weight: 700;
|
||||
font-size: 20px;
|
||||
|
||||
color: var(--cpd-color-text-on-solid-primary);
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
object-position: center;
|
||||
}
|
||||
|
||||
svg {
|
||||
vertical-align: middle;
|
||||
}
|
||||
}
|
||||
|
||||
.failedIcon {
|
||||
color: var(--cpd-color-icon-critical-primary);
|
||||
}
|
||||
|
||||
/*
|
||||
* Sites with no thumbnail get their initial on one of six decorative colours, keyed off
|
||||
* `data-color` (1-6, from Compound's `useIdColorHash`) so the same site always looks the
|
||||
* same. Mirrors how Compound's Avatar colours its imageless fallback; the buckets have to
|
||||
* be enumerated because `attr()` is not usable outside `content` in all browsers.
|
||||
*
|
||||
* Declared after the `.summary`-nested `.summaryIcon` rule, which it ties with on
|
||||
* specificity and so needs to follow in source order to win.
|
||||
*/
|
||||
.summaryIcon[data-color],
|
||||
.entryIcon[data-color] {
|
||||
background-color: var(--cpd-color-bg-decorative-1);
|
||||
color: var(--cpd-color-text-decorative-1);
|
||||
}
|
||||
|
||||
.summaryIcon[data-color="2"],
|
||||
.entryIcon[data-color="2"] {
|
||||
background-color: var(--cpd-color-bg-decorative-2);
|
||||
color: var(--cpd-color-text-decorative-2);
|
||||
}
|
||||
|
||||
.summaryIcon[data-color="3"],
|
||||
.entryIcon[data-color="3"] {
|
||||
background-color: var(--cpd-color-bg-decorative-3);
|
||||
color: var(--cpd-color-text-decorative-3);
|
||||
}
|
||||
|
||||
.summaryIcon[data-color="4"],
|
||||
.entryIcon[data-color="4"] {
|
||||
background-color: var(--cpd-color-bg-decorative-4);
|
||||
color: var(--cpd-color-text-decorative-4);
|
||||
}
|
||||
|
||||
.summaryIcon[data-color="5"],
|
||||
.entryIcon[data-color="5"] {
|
||||
background-color: var(--cpd-color-bg-decorative-5);
|
||||
color: var(--cpd-color-text-decorative-5);
|
||||
}
|
||||
|
||||
.summaryIcon[data-color="6"],
|
||||
.entryIcon[data-color="6"] {
|
||||
background-color: var(--cpd-color-bg-decorative-6);
|
||||
color: var(--cpd-color-text-decorative-6);
|
||||
}
|
||||
|
||||
@@ -6,24 +6,46 @@
|
||||
*/
|
||||
|
||||
import React, { type JSX } from "react";
|
||||
import { fn } from "storybook/test";
|
||||
|
||||
import type { Meta, StoryFn } from "@storybook/react-vite";
|
||||
import siteIconFile from "../../../../static/element.png";
|
||||
import imagePreviewFile from "../../../../static/wideImage.png";
|
||||
import { MessageComposerUrlPreviewView, type MessageComposerUrlPreviewSnapshot } from "./MessageComposerUrlPreview";
|
||||
import {
|
||||
type MessageComposerUrlPreviewSnapshotEntryLoaded,
|
||||
MessageComposerUrlPreviewView,
|
||||
type MessageComposerUrlPreviewSnapshot,
|
||||
} from "./MessageComposerUrlPreview";
|
||||
import { useMockedViewModel } from "../../../core/viewmodel";
|
||||
import { LinkedTextContext } from "../../../core/utils/LinkedText";
|
||||
import { withViewDocs } from "../../../../.storybook/withViewDocs";
|
||||
|
||||
type MessageComposerUrlPreviewWrapperProps = MessageComposerUrlPreviewSnapshot;
|
||||
type MessageComposerUrlPreviewWrapperProps = MessageComposerUrlPreviewSnapshot & {
|
||||
/**
|
||||
* Whether the previews are collapsed down to the summary row.
|
||||
*/
|
||||
collapsed: boolean;
|
||||
/**
|
||||
* Set to render the remove/clear affordances, as the app does when the URL
|
||||
* preview bundle feature is enabled.
|
||||
*/
|
||||
removePreview?: (url: string) => void;
|
||||
};
|
||||
|
||||
const MessageComposerUrlPreviewViewWrapperImpl = ({
|
||||
collapsed,
|
||||
removePreview,
|
||||
...rest
|
||||
}: MessageComposerUrlPreviewWrapperProps): JSX.Element | null => {
|
||||
const vm = useMockedViewModel(rest, {});
|
||||
return (
|
||||
<LinkedTextContext.Provider value={{}}>
|
||||
<MessageComposerUrlPreviewView vm={vm} />
|
||||
<MessageComposerUrlPreviewView
|
||||
vm={vm}
|
||||
collapsed={collapsed}
|
||||
removePreview={removePreview}
|
||||
toggleCollapsed={() => {}}
|
||||
/>
|
||||
</LinkedTextContext.Provider>
|
||||
);
|
||||
};
|
||||
@@ -37,7 +59,9 @@ export default {
|
||||
title: "Composer/MessageComposerUrlPreview",
|
||||
component: MessageComposerUrlPreviewViewWrapper,
|
||||
tags: ["autodocs"],
|
||||
args: {},
|
||||
args: {
|
||||
collapsed: true,
|
||||
},
|
||||
parameters: {
|
||||
design: {
|
||||
type: "figma",
|
||||
@@ -52,44 +76,59 @@ const Template: StoryFn<typeof MessageComposerUrlPreviewViewWrapper> = (args) =>
|
||||
|
||||
export const Default = Template.bind({});
|
||||
Default.args = {
|
||||
previews: [
|
||||
entries: [
|
||||
{
|
||||
title: "A simple title",
|
||||
description: "A simple description",
|
||||
link: "https://matrix.org",
|
||||
siteName: "matrix.org",
|
||||
showTooltipOnLink: false,
|
||||
status: "loaded",
|
||||
matched_url: "https://matrix.org",
|
||||
include: true,
|
||||
preview: {
|
||||
title: "A simple title",
|
||||
description: "A simple description",
|
||||
link: "https://matrix.org",
|
||||
siteName: "matrix.org",
|
||||
showTooltipOnLink: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const WithImage = Template.bind({});
|
||||
WithImage.args = {
|
||||
previews: [
|
||||
entries: [
|
||||
{
|
||||
...Default.args.previews![0]!,
|
||||
image: {
|
||||
imageThumb: imagePreviewFile,
|
||||
imageFull: imagePreviewFile,
|
||||
alt: "The element logo",
|
||||
playable: false,
|
||||
mxcImageFull: "mxc://server/file",
|
||||
status: "loaded",
|
||||
matched_url: "https://matrix.org",
|
||||
include: true,
|
||||
preview: {
|
||||
image: {
|
||||
imageThumb: imagePreviewFile,
|
||||
imageFull: imagePreviewFile,
|
||||
alt: "The element logo",
|
||||
playable: false,
|
||||
mxcImageFull: "mxc://server/file",
|
||||
},
|
||||
...(Default.args.entries![0] as MessageComposerUrlPreviewSnapshotEntryLoaded).preview,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
export const WithImageAndSiteIcon = Template.bind({});
|
||||
WithImageAndSiteIcon.args = {
|
||||
previews: [
|
||||
entries: [
|
||||
{
|
||||
...Default.args.previews![0]!,
|
||||
siteIcon: siteIconFile,
|
||||
image: {
|
||||
imageThumb: imagePreviewFile,
|
||||
imageFull: imagePreviewFile,
|
||||
alt: "The element logo",
|
||||
playable: false,
|
||||
mxcImageFull: "mxc://server/file",
|
||||
status: "loaded",
|
||||
matched_url: "https://matrix.org",
|
||||
include: true,
|
||||
preview: {
|
||||
image: {
|
||||
imageThumb: imagePreviewFile,
|
||||
imageFull: imagePreviewFile,
|
||||
alt: "The element logo",
|
||||
playable: false,
|
||||
mxcImageFull: "mxc://server/file",
|
||||
},
|
||||
siteIcon: siteIconFile,
|
||||
...(Default.args.entries![0] as MessageComposerUrlPreviewSnapshotEntryLoaded).preview,
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -97,10 +136,13 @@ WithImageAndSiteIcon.args = {
|
||||
|
||||
export const WithImageAndLoadsOfText = Template.bind({});
|
||||
WithImageAndLoadsOfText.args = {
|
||||
previews: [
|
||||
entries: [
|
||||
{
|
||||
...Default.args.previews![0]!,
|
||||
description: `Molestiae aliquam quos possimus molestiae id sit nulla rerum. Sunt cumque illum alias. Illo ipsa ut iure quia nulla magnam repellat.
|
||||
status: "loaded",
|
||||
matched_url: "https://matrix.org",
|
||||
include: true,
|
||||
preview: {
|
||||
description: `Molestiae aliquam quos possimus molestiae id sit nulla rerum. Sunt cumque illum alias. Illo ipsa ut iure quia nulla magnam repellat.
|
||||
|
||||
Esse velit corporis sapiente temporibus quia ipsam. Pariatur est rem veritatis. Inventore sit consequatur odio ipsa error non assumenda. Est eum ex dignissimos voluptatibus voluptatem delectus modi. Nisi quia eius ea quibusdam. Aut eveniet maxime non.
|
||||
|
||||
@@ -109,13 +151,70 @@ WithImageAndLoadsOfText.args = {
|
||||
Incidunt ut ea quae nobis. Reiciendis inventore quas qui eum voluptatem ex et qui. Adipisci quibusdam dolores hic inventore et suscipit cupiditate consequuntur.
|
||||
|
||||
Temporibus similique sint quo. Omnis tempora quidem explicabo in quidem magnam quia. Aut sunt accusantium ut et ut laborum debitis in. Enim nihil sit consectetur facilis quidem voluptatem. Quod impedit odit veritatis est laudantium tempore sit labore. Atque minima aliquam nostrum et.`,
|
||||
image: {
|
||||
imageThumb: imagePreviewFile,
|
||||
imageFull: imagePreviewFile,
|
||||
alt: "The element logo",
|
||||
playable: false,
|
||||
mxcImageFull: "mxc://server/file",
|
||||
image: {
|
||||
imageThumb: imagePreviewFile,
|
||||
imageFull: imagePreviewFile,
|
||||
alt: "The element logo",
|
||||
playable: false,
|
||||
mxcImageFull: "mxc://server/file",
|
||||
},
|
||||
...(Default.args.entries![0]! as MessageComposerUrlPreviewSnapshotEntryLoaded).preview,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const Expanded = Template.bind({});
|
||||
Expanded.args = {
|
||||
...Default.args,
|
||||
collapsed: false,
|
||||
};
|
||||
|
||||
export const ExpandedWithImage = Template.bind({});
|
||||
ExpandedWithImage.args = {
|
||||
...WithImage.args,
|
||||
collapsed: false,
|
||||
};
|
||||
|
||||
export const ExpandedWithImageAndSiteIcon = Template.bind({});
|
||||
ExpandedWithImageAndSiteIcon.args = {
|
||||
...WithImageAndSiteIcon.args,
|
||||
collapsed: false,
|
||||
};
|
||||
|
||||
export const ExpandedWithImageAndLoadsOfText = Template.bind({});
|
||||
ExpandedWithImageAndLoadsOfText.args = {
|
||||
...WithImageAndLoadsOfText.args,
|
||||
collapsed: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* The loading and failed placeholders only show their text in the expanded view.
|
||||
*/
|
||||
export const ExpandedWithLoadingAndFailedEntries = Template.bind({});
|
||||
ExpandedWithLoadingAndFailedEntries.args = {
|
||||
collapsed: false,
|
||||
entries: [
|
||||
Default.args.entries![0]!,
|
||||
{
|
||||
status: "loading",
|
||||
matched_url: "https://element.io",
|
||||
include: true,
|
||||
},
|
||||
{
|
||||
status: "failed",
|
||||
matched_url: "https://example.com",
|
||||
include: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/**
|
||||
* The app only passes `removePreview` when the URL preview bundle feature is
|
||||
* enabled, which adds the per-entry remove buttons and the "Clear all" button.
|
||||
*/
|
||||
export const ExpandedWithRemoveButtons = Template.bind({});
|
||||
ExpandedWithRemoveButtons.args = {
|
||||
...ExpandedWithLoadingAndFailedEntries.args,
|
||||
removePreview: fn(),
|
||||
};
|
||||
|
||||
@@ -5,15 +5,40 @@
|
||||
* Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { render } from "@test-utils";
|
||||
import { render, screen } from "@test-utils";
|
||||
import { composeStories } from "@storybook/react-vite";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import React from "react";
|
||||
|
||||
import * as stories from "./MessageComposerUrlPreview.stories.tsx";
|
||||
import {
|
||||
MessageComposerUrlPreviewView,
|
||||
type MessageComposerUrlPreviewSnapshot,
|
||||
type MessageComposerUrlPreviewSnapshotEntry,
|
||||
} from "./MessageComposerUrlPreview";
|
||||
import { MockViewModel } from "../../../core/viewmodel";
|
||||
import { LinkedTextContext } from "../../../core/utils/LinkedText";
|
||||
|
||||
const { Default, WithImage } = composeStories(stories);
|
||||
|
||||
function renderView(entries: MessageComposerUrlPreviewSnapshotEntry[], collapsed: boolean): ReturnType<typeof render> {
|
||||
const snapshot: MessageComposerUrlPreviewSnapshot = {
|
||||
content: entries.map((entry) => entry.matched_url).join(" "),
|
||||
entries,
|
||||
};
|
||||
const vm = new MockViewModel(snapshot);
|
||||
return render(
|
||||
<LinkedTextContext.Provider value={{}}>
|
||||
<MessageComposerUrlPreviewView
|
||||
vm={vm}
|
||||
collapsed={collapsed}
|
||||
toggleCollapsed={() => {}}
|
||||
removePreview={() => {}}
|
||||
/>
|
||||
</LinkedTextContext.Provider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("MessageComposerUrlPreview", () => {
|
||||
it("renders a preview", () => {
|
||||
const { container } = render(<Default />);
|
||||
@@ -23,4 +48,73 @@ describe("MessageComposerUrlPreview", () => {
|
||||
const { container } = render(<WithImage />);
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
it("renders the expanded previews when not collapsed", () => {
|
||||
// Drive the view directly rather than using the `Expanded` story, so that the
|
||||
// remove affordances are covered too (equivalent to the composerUrlPreviewCollapsed
|
||||
// setting being false with the URL preview bundle feature enabled).
|
||||
const snapshot: MessageComposerUrlPreviewSnapshot = {
|
||||
content: "https://matrix.org",
|
||||
entries: Default.args.entries!,
|
||||
};
|
||||
const vm = new MockViewModel(snapshot);
|
||||
const { container } = render(
|
||||
<LinkedTextContext.Provider value={{}}>
|
||||
<MessageComposerUrlPreviewView
|
||||
vm={vm}
|
||||
collapsed={false}
|
||||
toggleCollapsed={() => {}}
|
||||
removePreview={() => {}}
|
||||
/>
|
||||
</LinkedTextContext.Provider>,
|
||||
);
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
|
||||
const loadingEntry: MessageComposerUrlPreviewSnapshotEntry = {
|
||||
status: "loading",
|
||||
matched_url: "https://element.io",
|
||||
include: true,
|
||||
};
|
||||
const failedEntry: MessageComposerUrlPreviewSnapshotEntry = {
|
||||
status: "failed",
|
||||
matched_url: "https://example.com",
|
||||
include: true,
|
||||
};
|
||||
|
||||
describe("loading entries", () => {
|
||||
it("renders the loading placeholder when expanded", () => {
|
||||
const { container } = renderView([loadingEntry], false);
|
||||
expect(screen.getByText("Fetching preview…")).toBeInTheDocument();
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("renders the loading summary icon when collapsed", () => {
|
||||
const { container } = renderView([loadingEntry], true);
|
||||
expect(screen.getByText("1 link")).toBeInTheDocument();
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe("failed entries", () => {
|
||||
it("renders the failed placeholder when expanded", () => {
|
||||
const { container } = renderView([failedEntry], false);
|
||||
expect(screen.getByText("Failed to fetch preview")).toBeInTheDocument();
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("renders the failed summary icon when collapsed", () => {
|
||||
const { container } = renderView([failedEntry], true);
|
||||
expect(screen.getByText("1 link")).toBeInTheDocument();
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders a mix of loaded, loading and failed entries", () => {
|
||||
const entries: MessageComposerUrlPreviewSnapshotEntry[] = [Default.args.entries![0], loadingEntry, failedEntry];
|
||||
const { container } = renderView(entries, false);
|
||||
expect(screen.getByText("Fetching preview…")).toBeInTheDocument();
|
||||
expect(screen.getByText("Failed to fetch preview")).toBeInTheDocument();
|
||||
expect(screen.getByText("3 links")).toBeInTheDocument();
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,19 +5,58 @@
|
||||
* Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import React, { type JSX } from "react";
|
||||
import { Text } from "@vector-im/compound-web";
|
||||
import React, { useCallback, type JSX } from "react";
|
||||
import classNames from "classnames";
|
||||
// note: useIdColorHash is not used as a hook here
|
||||
import { IconButton, InlineSpinner, useIdColorHash as idColorHash } from "@vector-im/compound-web";
|
||||
import { ErrorSolidIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
|
||||
import ChevronDownIcon from "@vector-im/compound-design-tokens/assets/web/icons/chevron-down";
|
||||
import CloseIcon from "@vector-im/compound-design-tokens/assets/web/icons/close";
|
||||
|
||||
import { type UrlPreview } from "../../timeline/event-tile/UrlPreviewGroupView";
|
||||
import styles from "./MessageComposerUrlPreview.module.css";
|
||||
import { LinkSiteName, LinkTitle } from "../../timeline/event-tile/UrlPreviewGroupView/LinkPreview/LinkPreview";
|
||||
import { useViewModel, type ViewModel } from "../../../core/viewmodel";
|
||||
import { useI18n } from "../../../core/i18n/i18nContext";
|
||||
|
||||
export interface MessageComposerUrlPreviewSnapshotEntryLoaded {
|
||||
status: "loaded";
|
||||
preview: UrlPreview;
|
||||
}
|
||||
|
||||
export interface MessageComposerUrlPreviewSnapshotEntryLoading {
|
||||
status: "loading";
|
||||
}
|
||||
|
||||
export interface MessageComposerUrlPreviewSnapshotEntryFailed {
|
||||
status: "failed";
|
||||
}
|
||||
|
||||
export type MessageComposerUrlPreviewSnapshotEntryState =
|
||||
| MessageComposerUrlPreviewSnapshotEntryFailed
|
||||
| MessageComposerUrlPreviewSnapshotEntryLoaded
|
||||
| MessageComposerUrlPreviewSnapshotEntryLoading;
|
||||
|
||||
/**
|
||||
* An entry in the URL preview box
|
||||
*/
|
||||
export type MessageComposerUrlPreviewSnapshotEntry = MessageComposerUrlPreviewSnapshotEntryState & {
|
||||
/**
|
||||
* default: true
|
||||
* set to false when the preview is removed by the user
|
||||
* so the vm remembers to not show the previews list even after another computeSnapshot
|
||||
*/
|
||||
include: boolean;
|
||||
/**
|
||||
* the url string that the preview is representing
|
||||
*/
|
||||
matched_url: string;
|
||||
};
|
||||
|
||||
/** Snapshot data for rendering a URL preview attached to the composer. */
|
||||
export interface MessageComposerUrlPreviewSnapshot {
|
||||
/** URL preview to render. */
|
||||
previews: UrlPreview[];
|
||||
entries: MessageComposerUrlPreviewSnapshotEntry[];
|
||||
/** Content of the composer when the snapshot is computed */
|
||||
content: string;
|
||||
}
|
||||
@@ -28,37 +67,224 @@ export interface MessageComposerUrlPreviewProps {
|
||||
* The view model for the component.
|
||||
*/
|
||||
vm: ViewModel<MessageComposerUrlPreviewSnapshot>;
|
||||
/**
|
||||
* Whether the preview is collapsed
|
||||
*/
|
||||
collapsed: boolean;
|
||||
/**
|
||||
* Function to call to toggle collapsed state
|
||||
*/
|
||||
toggleCollapsed: () => void;
|
||||
/**
|
||||
* Function to call to toggle collapsed state
|
||||
*/
|
||||
removePreview?: (url: string) => void;
|
||||
/**
|
||||
* Extra CSS classes to apply to the component.
|
||||
*/
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function hostNameFirstChar(hostName: string): string {
|
||||
return hostName.slice(0, 1).toUpperCase();
|
||||
}
|
||||
|
||||
function useEntryContents(entry: MessageComposerUrlPreviewSnapshotEntry): {
|
||||
entryIcon: JSX.Element;
|
||||
entryTitle: string;
|
||||
showTooltipOnLink: boolean;
|
||||
} {
|
||||
const { translate: _t } = useI18n();
|
||||
const hostname = new URL(entry.matched_url).hostname;
|
||||
|
||||
switch (entry.status) {
|
||||
case "loaded": {
|
||||
const thumbnail = entry.preview?.image?.imageThumb !== undefined && (
|
||||
<img src={entry.preview.image?.imageThumb} alt={entry.preview.image.alt} />
|
||||
);
|
||||
return {
|
||||
entryIcon: (
|
||||
// Sites without a thumbnail fall back to their initial on a decorative
|
||||
// background, picked by `data-color` - see the module CSS.
|
||||
<div className={styles.entryIcon} data-color={thumbnail ? undefined : idColorHash(hostname)}>
|
||||
{thumbnail || hostNameFirstChar(hostname)}
|
||||
</div>
|
||||
),
|
||||
entryTitle: entry.preview.title,
|
||||
showTooltipOnLink: entry.preview.showTooltipOnLink,
|
||||
};
|
||||
}
|
||||
case "loading":
|
||||
return {
|
||||
entryIcon: (
|
||||
<div className={styles.loadingSpinner}>
|
||||
<InlineSpinner />
|
||||
</div>
|
||||
),
|
||||
entryTitle: _t("composer|url_preview|loading"),
|
||||
showTooltipOnLink: false,
|
||||
};
|
||||
|
||||
case "failed":
|
||||
return {
|
||||
entryIcon: (
|
||||
<div className={styles.failedIcon}>
|
||||
<ErrorSolidIcon />
|
||||
</div>
|
||||
),
|
||||
entryTitle: _t("composer|url_preview|failed"),
|
||||
showTooltipOnLink: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function UrlPreviewExpandedEntry({
|
||||
entry,
|
||||
removePreview,
|
||||
className,
|
||||
}: {
|
||||
entry: MessageComposerUrlPreviewSnapshotEntry;
|
||||
removePreview?: (url: string) => void;
|
||||
className?: string;
|
||||
}): JSX.Element {
|
||||
const { translate: _t } = useI18n();
|
||||
const { entryIcon, entryTitle, showTooltipOnLink } = useEntryContents(entry);
|
||||
|
||||
const onRemovePreview = useCallback((): void => {
|
||||
removePreview?.(entry.matched_url);
|
||||
}, [removePreview, entry.matched_url]);
|
||||
|
||||
return (
|
||||
<div key={entry.matched_url} className={classNames(className, styles.container)}>
|
||||
<div className={styles.left}>
|
||||
{entryIcon}
|
||||
<div className={styles.text}>
|
||||
<LinkTitle
|
||||
title={entryTitle}
|
||||
showTooltipOnLink={showTooltipOnLink}
|
||||
link={entry.matched_url}
|
||||
className={styles.linkTitle}
|
||||
/>
|
||||
<LinkSiteName siteName={new URL(entry.matched_url).hostname} className={styles.linkSiteName} />
|
||||
</div>
|
||||
</div>
|
||||
{removePreview ? (
|
||||
<IconButton
|
||||
onClick={onRemovePreview}
|
||||
className={classNames(styles.removePreview, styles.spanLike)}
|
||||
aria-label={_t("composer|url_preview|remove")}
|
||||
>
|
||||
<CloseIcon aria-hidden={true} />
|
||||
</IconButton>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* MessageComposerUrlPreviewView renders a preview of all previewable URLs above the messasge composer.
|
||||
*/
|
||||
export function MessageComposerUrlPreviewView({ vm, className }: MessageComposerUrlPreviewProps): JSX.Element | null {
|
||||
const { previews } = useViewModel(vm);
|
||||
if (previews.length === 0) {
|
||||
export function MessageComposerUrlPreviewView({
|
||||
vm,
|
||||
className,
|
||||
collapsed,
|
||||
toggleCollapsed,
|
||||
removePreview,
|
||||
}: MessageComposerUrlPreviewProps): JSX.Element | null {
|
||||
const { translate: _t } = useI18n();
|
||||
|
||||
const { entries } = useViewModel(vm);
|
||||
const links = entries.filter((entry) => entry.include);
|
||||
|
||||
const clearAll = useCallback(() => {
|
||||
links.forEach((entry) => removePreview?.(entry.matched_url));
|
||||
}, [links, removePreview]);
|
||||
|
||||
if (links.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Show only the first preview to revert back to previous behaviour
|
||||
// But have previews fetch all URL previews in the message text
|
||||
const previewViews = previews.slice(0, 1).map((preview) => (
|
||||
<div key={preview.link} className={classNames(className, styles.container)}>
|
||||
<div>
|
||||
{preview?.image?.imageThumb && (
|
||||
<img className={styles.image} src={preview.image?.imageThumb} alt={preview.image.alt} />
|
||||
)}
|
||||
<div className={styles.text}>
|
||||
<LinkSiteName {...preview} />
|
||||
<LinkTitle {...preview} />
|
||||
<Text className={styles.description}>{preview?.description}</Text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
));
|
||||
const previewViews = collapsed
|
||||
? null
|
||||
: links.map((entry) => (
|
||||
<UrlPreviewExpandedEntry
|
||||
key={entry.matched_url}
|
||||
entry={entry}
|
||||
removePreview={removePreview}
|
||||
className={className}
|
||||
/>
|
||||
));
|
||||
|
||||
return <>{previewViews}</>;
|
||||
const summary = (
|
||||
<div className={styles.summary}>
|
||||
<span className={styles.left}>
|
||||
<span className={styles.icons}>
|
||||
{links.map((entry) => {
|
||||
let colorHash: number | undefined;
|
||||
let className: string | undefined;
|
||||
let icon: JSX.Element;
|
||||
switch (entry.status) {
|
||||
case "failed":
|
||||
className = styles.summaryIconFailed;
|
||||
icon = <ErrorSolidIcon />;
|
||||
break;
|
||||
case "loading":
|
||||
className = styles.summaryIconLoading;
|
||||
icon = <InlineSpinner />;
|
||||
break;
|
||||
case "loaded": {
|
||||
const hostname = new URL(entry.matched_url).hostname;
|
||||
if (entry.preview.image !== undefined) {
|
||||
icon = (
|
||||
<img
|
||||
src={entry.preview.siteIcon || entry.preview.image.imageThumb}
|
||||
alt={entry.preview.image.alt}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
icon = <>{hostNameFirstChar(hostname)}</>;
|
||||
colorHash = idColorHash(hostname);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={entry.matched_url}
|
||||
className={classNames(styles.summaryIcon, className)}
|
||||
data-color={colorHash}
|
||||
>
|
||||
{icon}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</span>
|
||||
<span className={styles.linkCount}>{_t("composer|url_preview|n_links", { count: links.length })}</span>
|
||||
</span>
|
||||
<span className={styles.right}>
|
||||
{removePreview && (
|
||||
<button className={classNames(styles.clearAll, styles.spanLike)} onClick={clearAll} type="button">
|
||||
{_t("composer|url_preview|clear_all")}
|
||||
</button>
|
||||
)}
|
||||
<IconButton
|
||||
className={classNames(styles.collapse, styles.spanLike)}
|
||||
onClick={toggleCollapsed}
|
||||
aria-label={_t("composer|url_preview|collapse")}
|
||||
type="button"
|
||||
>
|
||||
<ChevronDownIcon aria-hidden={true} />
|
||||
</IconButton>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={collapsed ? classNames(styles.wrapper, styles.collapsed) : styles.wrapper}>
|
||||
{summary}
|
||||
{previewViews}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -19,13 +19,21 @@ export interface LinkPreviewActions {
|
||||
onImageClick: () => void;
|
||||
}
|
||||
|
||||
export interface AdditionalClasses {
|
||||
/*
|
||||
* Additional classes at add to the component
|
||||
*/
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export type LinkPreviewProps = UrlPreview & LinkPreviewActions & { collapsed: boolean };
|
||||
|
||||
export function LinkTitle({
|
||||
title,
|
||||
showTooltipOnLink,
|
||||
link,
|
||||
}: Pick<LinkPreviewProps, "title" | "showTooltipOnLink" | "link">): JSX.Element {
|
||||
className,
|
||||
}: Pick<LinkPreviewProps, "title" | "showTooltipOnLink" | "link"> & AdditionalClasses): JSX.Element {
|
||||
const caption = new URL(link).toString();
|
||||
const anchor = (
|
||||
<Text
|
||||
@@ -33,7 +41,7 @@ export function LinkTitle({
|
||||
type="body"
|
||||
weight="semibold"
|
||||
size="md"
|
||||
className={styles.title}
|
||||
className={classNames(styles.title, className)}
|
||||
href={link}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
@@ -44,9 +52,16 @@ export function LinkTitle({
|
||||
return showTooltipOnLink ? <Tooltip label={caption}>{anchor}</Tooltip> : anchor;
|
||||
}
|
||||
|
||||
export function LinkSiteName({ siteIcon, siteName }: { siteIcon?: string; siteName: string }): JSX.Element {
|
||||
export function LinkSiteName({
|
||||
siteIcon,
|
||||
siteName,
|
||||
className,
|
||||
}: {
|
||||
siteIcon?: string;
|
||||
siteName: string;
|
||||
} & AdditionalClasses): JSX.Element {
|
||||
return (
|
||||
<div className={styles.siteName}>
|
||||
<div className={classNames(styles.siteName, className)}>
|
||||
{siteIcon && <Avatar size="16px" name={siteName} id={siteName} src={siteIcon} />}
|
||||
<Text as="span" size="sm" weight="regular">
|
||||
{siteName}
|
||||
|
||||