Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
compose_ui: Reverse linkify on paste.
Shubham Padiafa8b76e076ec
diff --git a/web/src/compose_paste.ts b/web/src/compose_paste.tsindex 80feebf2c75..0d11352efd0 100644--- a/web/src/compose_paste.ts+++ b/web/src/compose_paste.ts@@ -643,6 +643,18 @@ function add_text_and_select(text: string, $textarea: JQuery<HTMLTextAreaElementtextarea.setSelectionRange(init_cursor_pos, new_cursor_pos);}+function replace_pasted_text(+ $textarea: JQuery<HTMLTextAreaElement>,+ pasted_text: string,+ replacement_text: string,+): void {+ // To ensure you can get the actual pasted URL back via the browser+ // undo feature, we first paste the URL in, then select it, and then+ // replace it with the nicer markdown syntax.+ add_text_and_select(pasted_text, $textarea);+ compose_ui.insert_and_scroll_into_view(replacement_text, $textarea);+}+export function try_stream_topic_syntax_text(text: string): string | null {const stream_topic = hash_util.decode_stream_topic_from_url(text);@@ -799,15 +811,23 @@ export function paste_handler(if (syntax_text) {event.preventDefault();event.stopPropagation();- // To ensure you can get the actual pasted URL back via the browser- // undo feature, we first paste the URL in, then select it, and then- // replace it with the nicer markdown syntax.- add_text_and_select(trimmed_paste_text, $textarea);- compose_ui.insert_and_scroll_into_view(syntax_text + " ", $textarea);+ replace_pasted_text($textarea, trimmed_paste_text, syntax_text + " ");}return;}}+ // Keep this outside the `isUrl(trimmed_paste_text)` code just above.+ // `reverse_linkify_text` can still transform URL-like text inside a larger+ // string that is not itself a valid URL, based on our configured url patterns.+ if (!compose_ui.cursor_inside_code_block($textarea) && !compose_ui.shift_pressed) {+ const reversed_text = compose_ui.reverse_linkify_text(trimmed_paste_text);+ if (reversed_text) {+ event.preventDefault();+ event.stopPropagation();+ replace_pasted_text($textarea, trimmed_paste_text, reversed_text);+ return;+ }+ }// We do not paste formatted markdown when inside a code block.// Unlike Chrome, Firefox doesn't automatically paste plainly on using Ctrl+Shift+V,// hence we need to handle it ourselves, by checking if shift key is pressed, and onlydiff --git a/web/src/compose_ui.ts b/web/src/compose_ui.tsindex bebcdc09f0f..53f1d46f1d3 100644--- a/web/src/compose_ui.ts+++ b/web/src/compose_ui.ts@@ -11,6 +11,7 @@ import {setFieldText,wrapFieldSelection,} from "text-field-edit";+import type Template from "uri-template-lite";import * as z from "zod/mini";import type {Typeahead} from "./bootstrap_typeahead.ts";@@ -20,6 +21,7 @@ import * as common from "./common.ts";import * as compose_state from "./compose_state.ts";import type {TypeaheadSuggestion} from "./composebox_typeahead.ts";import {$t, $t_html} from "./i18n.ts";+import * as linkifiers from "./linkifiers.ts";import * as loading from "./loading.ts";import * as markdown from "./markdown.ts";import * as people from "./people.ts";@@ -685,6 +687,114 @@ export function position_inside_code_block(content: string, position: number): breturn [...code_blocks].some((code_block) => code_block?.textContent?.includes(unique_insert));}+// A function with the same name implements this on the Python side.+// Please replicate any changes here to that function as well.+function expand_reverse_template(+ reverse_template: string,+ variables: Record<string, string>,+): string {+ const output: string[] = [];+ let index = 0;+ while (index < reverse_template.length) {+ if (reverse_template.startsWith("{{", index)) {+ output.push("{");+ index += 2;+ } else if (reverse_template.startsWith("}}", index)) {+ output.push("}");+ index += 2;+ } else if (reverse_template[index] === "{") {+ const end_index = reverse_template.indexOf("}", index + 1);+ // This should not fail with a valid reverse_template.+ assert(end_index !== -1);++ const name = reverse_template.slice(index + 1, end_index);+ // This should not fail with a valid reverse_template.+ assert(name !== "");++ const value = variables[name];+ // This should not fail with a valid reverse_template.+ assert(value !== undefined);++ output.push(value);+ index = end_index + 1;+ } else {+ output.push(reverse_template[index]!);+ index += 1;+ }+ }+ return output.join("");+}++function expand_url_template_from_match(+ match: RegExpExecArray,+ url_template: Template,+ group_number_to_name: Record<number, string>,+): string | null {+ const context: Record<string, string> = {};+ const capturing_groups = match.slice(1).entries();+ for (const [index, capturing_group] of capturing_groups) {+ const name = group_number_to_name[index + 1];+ if (!name) {+ return null;+ }+ context[name] = capturing_group;+ }+ return url_template.expand(context);+}++function reverse_linkify_segment(segment: string): string | null {+ const linkifier_map = linkifiers.get_linkifier_map();+ for (const [pattern, {url_template, group_number_to_name, reverse_template}] of linkifier_map) {+ if (!reverse_template) {+ continue;+ }++ const template_context = url_template.match(segment);+ if (!template_context) {+ continue;+ }++ const reversed_text = expand_reverse_template(reverse_template, template_context);+ pattern.lastIndex = 0;+ const match = pattern.exec(reversed_text);+ if (!match) {+ continue;+ }++ // Validate that expanding the captured groups round-trips to the original URL.+ const expanded_url = expand_url_template_from_match(+ match,+ url_template,+ group_number_to_name,+ );+ if (expanded_url !== segment) {+ continue;+ }+ return reversed_text;+ }+ return null;+}++export function reverse_linkify_text(text: string): string | null {+ // We keep the spaces around in a capturing group so we can join it later.+ const segments = text.split(/(\s+)/);+ let changed = false;++ for (let i = 0; i < segments.length; i += 1) {+ const segment = segments[i]!;+ if (segment.trim() === "") {+ continue;+ }+ const replacement = reverse_linkify_segment(segment) ?? segment;+ if (replacement !== segment) {+ changed = true;+ segments[i] = replacement;+ }+ }++ return changed ? segments.join("") : null;+}+export let format_text = ($textarea: JQuery<HTMLTextAreaElement>,type: string,diff --git a/web/src/linkifiers.ts b/web/src/linkifiers.tsindex e8741564378..dc0cfa83ac0 100644--- a/web/src/linkifiers.ts+++ b/web/src/linkifiers.ts@@ -6,7 +6,11 @@ import type {realm_linkifier_schema} from "./state_data.ts";type LinkifierMap = Map<RegExp,- {url_template: Template; group_number_to_name: Record<number, string>}+ {+ url_template: Template;+ group_number_to_name: Record<number, string>;+ reverse_template: string | null;+ }>;const linkifier_map: LinkifierMap = new Map();@@ -101,6 +105,7 @@ export function update_linkifier_rules(linkifiers: Linkifier[]): void {linkifier_map.set(regex, {url_template,group_number_to_name,+ reverse_template: linkifier.reverse_template ?? null,});}}diff --git a/web/tests/compose_ui.test.cjs b/web/tests/compose_ui.test.cjsindex fa5c307afdb..da471a8ca0a 100644--- a/web/tests/compose_ui.test.cjs+++ b/web/tests/compose_ui.test.cjs@@ -25,6 +25,7 @@ mock_esm("../src/message_lists", {});const compose_ui = zrequire("compose_ui");+const linkifiers = zrequire("linkifiers");const stream_data = zrequire("stream_data");const people = zrequire("people");const user_status = zrequire("user_status");@@ -271,6 +272,63 @@ run_test("compute_placeholder_text", ({override}) => {);});+run_test("reverse_linkify_text", () => {+ linkifiers.update_linkifier_rules([+ {+ id: 1,+ pattern: "#(?P<id>\\d+)",+ url_template: "https://tracker.example.com/issue/{id}",+ reverse_template: "#{id}",+ },+ ]);+ assert.equal(compose_ui.reverse_linkify_text("https://tracker.example.com/issue/42"), "#42");+ assert.equal(+ compose_ui.reverse_linkify_text(+ "Links https://tracker.example.com/issue/42 and https://tracker.example.com/issue/43",+ ),+ "Links #42 and #43",+ );+ // Typo in rest of the URL.+ assert.equal(compose_ui.reverse_linkify_text("https://tracker.example.com/issues/42"), null);+ // {id} is absent is the URL.+ assert.equal(compose_ui.reverse_linkify_text("https://tracker.example.com/issues/"), null);++ // Check non HTTP schemes to make sure we don't creep in any HTTP specific+ // code by mistake.+ linkifiers.update_linkifier_rules([+ {+ id: 2,+ pattern: "#(?P<id>\\d+)",+ url_template: "zulip://issue/{id}",+ reverse_template: "#{id}",+ },+ ]);+ assert.equal(compose_ui.reverse_linkify_text("zulip://issue/42"), "#42");++ // Use `{{` to escape `{`.+ linkifiers.update_linkifier_rules([+ {+ id: 3,+ pattern: "\\{(?P<id>\\d+)\\}",+ url_template: "https://tracker.example.com/issue/{id}",+ reverse_template: "{{{id}}}",+ },+ ]);+ assert.equal(compose_ui.reverse_linkify_text("https://tracker.example.com/issue/42"), "{42}");++ // Ignore reverse template that would not round-trip back to the URL.+ linkifiers.update_linkifier_rules([+ {+ id: 4,+ pattern: "#(?P<id>.+)",+ url_template: "https://tracker.example.com/issue/{+id}",+ reverse_template: "#{id}",+ },+ ]);+ assert.equal(compose_ui.reverse_linkify_text("https://tracker.example.com/issue/a%2Fb"), null);+ assert.equal(compose_ui.reverse_linkify_text("https://tracker.example.com/issue/a/b"), "#a/b");+});+run_test("quote_message", ({override, override_rewire}) => {const devel_stream = make_stream({subscribed: false,diff --git a/zerver/models/linkifiers.py b/zerver/models/linkifiers.pyindex 9b4dad210ed..92ea581e1f4 100644--- a/zerver/models/linkifiers.py+++ b/zerver/models/linkifiers.py@@ -25,6 +25,8 @@ def normalize_optional_text(value: str | None) -> str | None:return value or None+# A function with the same name implements this on the JS side.+# Please replicate any changes here to that function as well.def expand_reverse_template(reverse_template: str, match: "re2._Match[str]", group_set: set[str]) -> str: