Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[space][web] Make links in messages clickable

Anand Baburajan81fbe3ac5f22
diff --git a/web/apps/space/src/components/MessageText.tsx b/web/apps/space/src/components/MessageText.tsx
new file mode 100644
index 0000000000..58b1c93018
--- /dev/null
+++ b/web/apps/space/src/components/MessageText.tsx
@@ -0,0 +1,49 @@
+import React from "react";
+
+const messageURLPattern =
+ /\bhttps?:\/\/[^\s<>"']+|(?<![\w@/.:+-])(?:[a-z\d](?:[a-z\d-]*[a-z\d])?\.)+[a-z]{2,}(?![\w@-])(?::\d+)?(?:[/?#][^\s<>"']*)?/gi;
+
+export const SpaceMessageText: React.FC<{ text: string }> = ({ text }) => {
+ const content: React.ReactNode[] = [];
+ let offset = 0;
+
+ for (const match of text.matchAll(messageURLPattern)) {
+ let value = match[0];
+ while (/[.,!?;:)\]}]$/.test(value)) {
+ if (
+ value.endsWith(")") &&
+ value.split("(").length >= value.split(")").length
+ )
+ break;
+ value = value.slice(0, -1);
+ }
+
+ const href = /^https?:\/\//i.test(value) ? value : `https://${value}`;
+ try {
+ new URL(href);
+ } catch {
+ continue;
+ }
+
+ content.push(
+ text.slice(offset, match.index),
+ <a
+ key={match.index}
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ style={{
+ color: "inherit",
+ textDecoration: "underline",
+ WebkitTouchCallout: "default",
+ }}
+ >
+ {value}
+ </a>,
+ );
+ offset = match.index + value.length;
+ }
+
+ content.push(text.slice(offset));
+ return <>{content}</>;
+};
diff --git a/web/apps/space/src/screens/MessagesScreen.tsx b/web/apps/space/src/screens/MessagesScreen.tsx
index 9880584c21..108e8ec0df 100644
--- a/web/apps/space/src/screens/MessagesScreen.tsx
+++ b/web/apps/space/src/screens/MessagesScreen.tsx
@@ -22,6 +22,7 @@ import {
MessageQuickReactions,
MessageReactionPicker,
} from "components/MessageReactionPicker";
+import { SpaceMessageText } from "components/MessageText";
import { SpacePostPhotoInput } from "components/PostPhotoInput";
import {
SpacePostPhotosBadge,
@@ -1383,8 +1384,8 @@ const PostQuotePreview: React.FC<{
);
};
-const isMessageLongPressIgnoredTarget = (target: EventTarget | null) =>
- target instanceof Element && Boolean(target.closest("button"));
+const isMessageInteractiveTarget = (target: EventTarget | null) =>
+ target instanceof Element && Boolean(target.closest("a, button"));
const MessageBubble: React.FC<{
activityPost?: SpaceMessageActivityPost;
@@ -1500,7 +1501,12 @@ const MessageBubble: React.FC<{
);
const handleContextMenu = (event: React.MouseEvent<HTMLElement>) => {
- if (isSystemMessage || isUnavailable) return;
+ if (
+ isSystemMessage ||
+ isUnavailable ||
+ isMessageInteractiveTarget(event.target)
+ )
+ return;
event.preventDefault();
event.stopPropagation();
openActions(event.currentTarget, "contextmenu");
@@ -1513,7 +1519,7 @@ const MessageBubble: React.FC<{
isUnavailable ||
event.button != 0 ||
gestureStartRef.current ||
- isMessageLongPressIgnoredTarget(event.target)
+ isMessageInteractiveTarget(event.target)
) {
cancelGesture();
return;
@@ -1707,6 +1713,10 @@ const MessageBubble: React.FC<{
onKeyDown={(
event: React.KeyboardEvent<HTMLElement>,
) => {
+ if (
+ isMessageInteractiveTarget(event.target)
+ )
+ return;
if (
event.key == "ContextMenu" ||
(event.shiftKey && event.key == "F10")
@@ -1786,11 +1796,13 @@ const MessageBubble: React.FC<{
whiteSpace: "pre-wrap",
}}
>
- {isUnavailable
- ? "Message unavailable"
- : isPoke
- ? pokeText
- : message.text}
+ {isUnavailable ? (
+ "Message unavailable"
+ ) : isPoke ? (
+ pokeText
+ ) : (
+ <SpaceMessageText text={message.text} />
+ )}
</Box>
{!isUnavailable && message.reaction && (
<Box
diff --git a/web/apps/space/tests/message-text.test.ts b/web/apps/space/tests/message-text.test.ts
new file mode 100644
index 0000000000..0566e06045
--- /dev/null
+++ b/web/apps/space/tests/message-text.test.ts
@@ -0,0 +1,79 @@
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { expect, test } from "vitest";
+import { SpaceMessageText } from "../src/components/MessageText";
+
+const renderMessage = (text: string) =>
+ renderToStaticMarkup(createElement(SpaceMessageText, { text }));
+
+test.each(["https://ente.io", "check this: https://ente.io"])(
+ "web links open in a new tab: %s",
+ (text) => {
+ const html = renderMessage(text);
+ expect(html).toContain('href="https://ente.io"');
+ expect(html).toContain('target="_blank"');
+ expect(html).toContain('rel="noopener noreferrer"');
+ expect(html).toContain(">https://ente.io</a>");
+ expect(html.startsWith(text.slice(0, text.indexOf("https")))).toBe(
+ true,
+ );
+ },
+);
+
+test("multiple links preserve surrounding text, line breaks, and punctuation", () => {
+ const html = renderMessage(
+ "Look: https://ente.io/photos,\nthen (http://example.com). Done!",
+ );
+ expect(html).toMatch(/^Look: <a /);
+ expect(html).toContain(">https://ente.io/photos</a>,\nthen (");
+ expect(html).toContain('href="http://example.com"');
+ expect(html).toMatch(/>http:\/\/example\.com<\/a>\)\. Done!$/);
+});
+
+test("bare web addresses use HTTPS", () => {
+ const html = renderMessage("Try www.ente.io or ente.io/photos");
+ expect(html).toContain('href="https://www.ente.io"');
+ expect(html).toContain(">www.ente.io</a> or ");
+ expect(html).toContain('href="https://ente.io/photos"');
+});
+
+test("URL paths, queries, fragments, and balanced parentheses stay intact", () => {
+ const url = "https://example.com/a_(b)?first=1&second=2#section";
+ const html = renderMessage(`See (${url}).`);
+ expect(html).toContain(
+ 'href="https://example.com/a_(b)?first=1&amp;second=2#section"',
+ );
+ expect(html).toMatch(/<\/a>\)\.$/);
+});
+
+test("ordinary text, HTML, and non-web schemes stay as text", () => {
+ const html = renderMessage(
+ '<script>alert("hello")</script>\njavascript:alert(1) ftp://example.com [email protected]',
+ );
+ expect(html).not.toContain("<a ");
+ expect(html).toContain(
+ "&lt;script&gt;alert(&quot;hello&quot;)&lt;/script&gt;",
+ );
+ expect(html).toContain(
+ "\njavascript:alert(1) ftp://example.com [email protected]",
+ );
+ expect(renderMessage("just a message\nwith another line")).toBe(
+ "just a message\nwith another line",
+ );
+});
+
+test.each([
+ "https://%",
+ "http://.",
+ "javascript:example.com",
+ "sftp://example.com",
+])("invalid URLs and non-web addresses stay as text: %s", (text) => {
+ expect(renderMessage(text)).toBe(text);
+});
+
+test("punctuation around links stays outside the link", () => {
+ const html = renderMessage("See (https://ente.io.), then ente.io!");
+ expect(html).toContain(">https://ente.io</a>.), then ");
+ expect(html).toMatch(/>ente\.io<\/a>!$/);
+});
diff --git a/web/apps/space/vitest.config.ts b/web/apps/space/vitest.config.ts
index 391b873843..a52ee61aeb 100644
--- a/web/apps/space/vitest.config.ts
+++ b/web/apps/space/vitest.config.ts
@@ -4,6 +4,7 @@ import wasm from "vite-plugin-wasm";
import { defineConfig } from "vitest/config";
export default defineConfig({
+ oxc: { jsx: { runtime: "automatic" } },
plugins: [wasm() as PluginOption],
resolve: {
alias: {