Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions frontend/src/components/chat/MentionText.vue
Original file line number Diff line number Diff line change
@@ -1,24 +1,34 @@
<script setup lang="ts">
import { computed } from "vue";
import { tokenizeMentionText, type MessageMention } from "../../mentions.ts";
import type { MessageMention } from "../../mentions.ts";
import { tokenizeMessageText } from "../../message-text.ts";

const props = defineProps<{
content: string;
mentions?: MessageMention[];
currentUserId?: number;
}>();

const tokens = computed(() => tokenizeMentionText(props.content, props.mentions || []));
const tokens = computed(() => tokenizeMessageText(props.content, props.mentions || []));
</script>

<template>
<template v-for="(token, index) in tokens" :key="`${index}:${token.text}`">
<span v-if="token.type === 'text'">{{ token.text }}</span>
<span
v-else
v-else-if="token.type === 'mention'"
class="message-mention"
:class="{ 'message-mention--self': Number(token.userId) === Number(currentUserId) }"
>{{ token.text }}</span>
<a
v-else
class="message-link"
:href="token.href"
target="_blank"
rel="noopener noreferrer"
@pointerdown.stop
@contextmenu.stop
>{{ token.text }}</a>
</template>
</template>

Expand All @@ -33,4 +43,14 @@ const tokens = computed(() => tokenizeMentionText(props.content, props.mentions
border-radius: 4px;
background: rgba(22, 135, 88, 0.14);
}

.message-link {
color: #006aa6;
text-decoration: none;
overflow-wrap: anywhere;
}

.message-link:hover {
text-decoration: underline;
}
</style>
100 changes: 100 additions & 0 deletions frontend/src/message-text.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { tokenizeMentionText } from "./mentions.js";

const WEB_LINK_PATTERN = /(?:https?:\/\/|www\.)[^\s<>"',。!?、:;]+/giu;
const SIMPLE_TRAILING_PUNCTUATION = new Set([
".",
",",
"!",
"?",
";",
":",
",",
"。",
"!",
"?",
"、",
":",
";",
]);
const CLOSING_BRACKETS = new Map([
[")", "("],
["]", "["],
["}", "{"],
]);

function isLinkBoundary(character) {
return !character || /[\s([{"',。!?、:;]/u.test(character);
}

function countCharacter(value, character) {
let count = 0;
for (const current of value) {
if (current === character) count += 1;
}
return count;
}

function trimLinkEnd(value) {
let end = value.length;
while (end > 0) {
const lastCharacter = value[end - 1];
if (SIMPLE_TRAILING_PUNCTUATION.has(lastCharacter)) {
end -= 1;
continue;
}

const openingBracket = CLOSING_BRACKETS.get(lastCharacter);
if (!openingBracket) break;
const candidate = value.slice(0, end);
if (
countCharacter(candidate, lastCharacter) <=
countCharacter(candidate, openingBracket)
) {
break;
}
end -= 1;
}
return value.slice(0, end);
}

function linkHref(text) {
return text.toLowerCase().startsWith("www.") ? `https://${text}` : text;
}

function isWebLink(text) {
try {
const url = new URL(linkHref(text));
return ["http:", "https:"].includes(url.protocol) && Boolean(url.hostname);
} catch {
return false;
}
}

export function tokenizeWebLinks(text) {
const tokens = [];
let cursor = 0;

for (const match of text.matchAll(WEB_LINK_PATTERN)) {
const offset = match.index;
if (!isLinkBoundary(text[offset - 1])) continue;

const linkText = trimLinkEnd(match[0]);
if (!isWebLink(linkText)) continue;
if (offset > cursor) {
tokens.push({ type: "text", text: text.slice(cursor, offset) });
}
tokens.push({ type: "link", text: linkText, href: linkHref(linkText) });
cursor = offset + linkText.length;
}

if (cursor < text.length) {
tokens.push({ type: "text", text: text.slice(cursor) });
}
return tokens;
}

export function tokenizeMessageText(content, mentions) {
return tokenizeMentionText(content, mentions).flatMap((token) =>
token.type === "text" ? tokenizeWebLinks(token.text) : token,
);
}
11 changes: 11 additions & 0 deletions frontend/src/message-text.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { MentionTextToken } from "./mentions.ts";

export type MessageLinkToken = {
type: "link";
text: string;
href: string;
};

export type MessageTextToken = MentionTextToken | MessageLinkToken;

export { tokenizeMessageText, tokenizeWebLinks } from "./message-text.js";
58 changes: 58 additions & 0 deletions test/frontend-message-links.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";

import {
tokenizeMessageText,
tokenizeWebLinks,
} from "../frontend/src/message-text.js";

const mentionTextComponent = readFileSync(
new URL("../frontend/src/components/chat/MentionText.vue", import.meta.url),
"utf8",
).replaceAll("\r\n", "\n");

test("消息正文识别网页链接并保留句末标点", () => {
const content = "文档:https://example.com/docs?q=chat。备用 www.example.org/path_(v2)。";
const tokens = tokenizeWebLinks(content);

assert.equal(tokens.map((token) => token.text).join(""), content);
assert.deepEqual(
tokens.filter((token) => token.type === "link"),
[
{
type: "link",
text: "https://example.com/docs?q=chat",
href: "https://example.com/docs?q=chat",
},
{
type: "link",
text: "www.example.org/path_(v2)",
href: "https://www.example.org/path_(v2)",
},
],
);
});

test("消息链接与结构化提及可以同时分段", () => {
const content = "@alice 看 https://example.com,javascript:alert(1) 保持为文本";
const tokens = tokenizeMessageText(content, [{ userId: 2, username: "alice" }]);

assert.equal(tokens.map((token) => token.text).join(""), content);
assert.deepEqual(tokens.map((token) => token.type), ["mention", "text", "link", "text"]);
assert.equal(tokens.some((token) => token.type === "link" && token.href.startsWith("javascript:")), false);
});

test("残缺网址保持为普通文本而不是站内相对链接", () => {
for (const content of ["www..", "https://.", "prefixwww.example.com"]) {
assert.deepEqual(tokenizeWebLinks(content), [{ type: "text", text: content }]);
}
});

test("消息链接使用新标签页并保留浏览器原生右键菜单", () => {
assert.match(mentionTextComponent, /class="message-link"/);
assert.match(mentionTextComponent, /target="_blank"/);
assert.match(mentionTextComponent, /rel="noopener noreferrer"/);
assert.match(mentionTextComponent, /@pointerdown\.stop/);
assert.match(mentionTextComponent, /@contextmenu\.stop/);
});
Loading