Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

copy_paste: Preserve timestamps across copy-paste.

apoorva55ddde841194
diff --git a/web/e2e-tests/copy-messages.test.ts b/web/e2e-tests/copy-messages.test.ts
index c9028adbaee..92b57d673c4 100644
--- a/web/e2e-tests/copy-messages.test.ts
+++ b/web/e2e-tests/copy-messages.test.ts
@@ -125,9 +125,57 @@ async function test_copying_messages_from_several_topics(page: Page): Promise<vo
assert.deepStrictEqual(actual_copied_lines, expected_copied_lines);
}
+async function test_timestamp_clipboard_has_datetime(page: Page): Promise<void> {
+ // Verify that copying a rendered timestamp injects <span data-datetime> into the
+ // selection HTML so Chrome's clipboard serializer cannot silently drop the datetime.
+ const copied_html = await page.evaluate(() => {
+ const time_el = document.querySelector<HTMLElement>(
+ '.message-list time[datetime="2026-05-23T17:30:00Z"]',
+ );
+ if (!time_el) {
+ return null;
+ }
+ const range = document.createRange();
+ range.selectNodeContents(time_el);
+ window.getSelection()!.removeAllRanges();
+ window.getSelection()!.addRange(range);
+
+ // Dispatch copy: copy_handler runs improve_time_selection_range, which
+ // injects <span data-datetime> into the DOM and expands the range to
+ // cover the full <time>. For a single-message selection copy_handler
+ // returns false (browser handles clipboard natively), so the DataTransfer
+ // stays empty — but the selection range now contains the mutated DOM.
+ document.dispatchEvent(
+ new ClipboardEvent("copy", {
+ bubbles: true,
+ cancelable: true,
+ clipboardData: new DataTransfer(),
+ }),
+ );
+
+ // Serialize the mutated, expanded selection: this is what Chrome writes
+ // to the clipboard. Even when Chrome strips <time>, <span data-datetime>
+ // survives as a plain span and the paste handler can recover <time:ISO>.
+ const div = document.createElement("div");
+ div.append(window.getSelection()!.getRangeAt(0).cloneContents());
+ return div.innerHTML;
+ });
+
+ assert.ok(
+ copied_html?.includes('data-datetime="2026-05-23T17:30:00Z"'),
+ `Expected data-datetime="2026-05-23T17:30:00Z" in clipboard HTML, got: ${copied_html}`,
+ );
+}
+
async function copy_paste_test(page: Page): Promise<void> {
await common.log_in(page);
await common.send_multiple_messages(page, [
+ {
+ stream_name: "Verona",
+ topic: "copy-paste-topic #0",
+ content: "<time:2026-05-23T17:30:00Z>",
+ },
+
{stream_name: "Verona", topic: "copy-paste-topic #1", content: "copy paste test A"},
{stream_name: "Verona", topic: "copy-paste-topic #1", content: "copy paste test B"},
@@ -146,6 +194,7 @@ async function copy_paste_test(page: Page): Promise<void> {
await page.click("#left-sidebar-navigation-list .top_left_all_messages");
const message_list_id = await common.get_current_msg_list_id(page, true);
await common.check_messages_sent(page, message_list_id, [
+ ["Verona > copy-paste-topic #0", ["Sat, May 23, 2026, 5:30 PM"]],
["Verona > copy-paste-topic #1", ["copy paste test A", "copy paste test B"]],
[
"Verona > copy-paste-topic #2",
@@ -163,6 +212,7 @@ async function copy_paste_test(page: Page): Promise<void> {
await test_copying_last_from_prev_all_from_next(page);
await test_copying_all_from_prev_first_from_next(page);
await test_copying_messages_from_several_topics(page);
+ await test_timestamp_clipboard_has_datetime(page);
}
await common.run_test(copy_paste_test);
diff --git a/web/src/compose_paste.ts b/web/src/compose_paste.ts
index 69b23951b6b..f28432eeac0 100644
--- a/web/src/compose_paste.ts
+++ b/web/src/compose_paste.ts
@@ -257,7 +257,7 @@ export function paste_handler_converter(
const has_single_child_with_valid_text = has_single_textful_child_node(copied_html_fragment);
- const outer_elements_to_retain = ["PRE", "UL", "OL", "A", "CODE"];
+ const outer_elements_to_retain = ["PRE", "UL", "OL", "A", "CODE", "TIME"];
// If the entire selection copied is within a single HTML element (like an
// `h1`), we don't want to retain its styling, except when it is needed to
// identify the intended structure of the copied content.
@@ -303,6 +303,31 @@ export function paste_handler_converter(
return "~~" + content + "~~";
},
});
+ turndownService.addRule("timestamp", {
+ filter(node) {
+ // Require .timestamp-content-wrapper to distinguish Zulip timestamps
+ // from arbitrary <time datetime> elements on other websites.
+ if (
+ node.nodeName === "TIME" &&
+ node.hasAttribute("datetime") &&
+ node.querySelector(".timestamp-content-wrapper") !== null
+ ) {
+ return true;
+ }
+ // Fallback when Chrome's clipboard serializer strips the
+ // <time> wrapper: the copy handler stashes the datetime on
+ // the .timestamp-content-wrapper span as `data-datetime`.
+ if (node.hasAttribute("data-datetime") && node.closest("time") === null) {
+ return true;
+ }
+ return false;
+ },
+ replacement(_content, node) {
+ assert(node instanceof HTMLElement);
+ const datetime = node.getAttribute("datetime") ?? node.getAttribute("data-datetime");
+ return `<time:${datetime}>`;
+ },
+ });
turndownService.addRule("links", {
filter: ["a"],
replacement(content, node) {
diff --git a/web/src/copy_messages.ts b/web/src/copy_messages.ts
index 53a22c90e8c..f4ca939e7ce 100644
--- a/web/src/copy_messages.ts
+++ b/web/src/copy_messages.ts
@@ -162,6 +162,51 @@ function expand_range_based_on_katex_parent(
}
}
+function improve_time_selection_range(range: Range): void {
+ const start_element = get_nearest_html_element(range.startContainer);
+ const end_element = get_nearest_html_element(range.endContainer);
+ if (!start_element || !end_element) {
+ return;
+ }
+
+ const start_time = start_element.closest("time");
+ const end_time = end_element.closest("time");
+
+ if (!start_time && !end_time) {
+ return;
+ }
+
+ // Chrome strips <time> and .timestamp-content-wrapper from the
+ // paste HTML, so wrap the date text in a <span data-datetime> that
+ // the paste handler can read.
+ for (const time of new Set([start_time, end_time])) {
+ if (!time) {
+ continue;
+ }
+ const datetime = time.getAttribute("datetime");
+ const wrapper = time.querySelector(".timestamp-content-wrapper");
+ if (!datetime || !wrapper) {
+ continue;
+ }
+ for (const child of wrapper.childNodes) {
+ if (child.nodeType === Node.TEXT_NODE && child.nodeValue?.trim()) {
+ const span = document.createElement("span");
+ span.setAttribute("data-datetime", datetime);
+ child.replaceWith(span);
+ span.append(child);
+ break;
+ }
+ }
+ }
+
+ if (start_time) {
+ range.setStartBefore(start_time);
+ }
+ if (end_time) {
+ range.setEndAfter(end_time);
+ }
+}
+
/*
Our paste behavior for KaTeX relies on processing the MathML
annotations generated by KaTeX in `<annotation>` tags. This
@@ -292,6 +337,7 @@ export function copy_handler(ev: ClipboardEvent): boolean {
// we process all ranges individually.
let custom_handle_copy = false;
for (let i = 0; i < selection.rangeCount; i += 1) {
+ improve_time_selection_range(selection.getRangeAt(i));
improve_katex_selection_range(selection.getRangeAt(i));
if (maybe_update_range_for_code_blocks(selection.getRangeAt(i), ev)) {
diff --git a/web/tests/compose_paste.test.cjs b/web/tests/compose_paste.test.cjs
index 5f3c461bebc..0dc8a151006 100644
--- a/web/tests/compose_paste.test.cjs
+++ b/web/tests/compose_paste.test.cjs
@@ -570,6 +570,24 @@ run_test("paste_handler_converter", () => {
'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta http-equiv="Content-Style-Type" content="text/css"><title></title><meta name="Generator" content="Cocoa HTML Writer"><meta name="CocoaVersion" content="2575.4"><style type="text/css">p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #000000}span.s1 {font-variant-ligatures: no-common-ligatures}</style></head><body><p class="p1"><span class="s1">insertions</span></p></body></html>';
assert.equal(compose_paste.paste_handler_converter(input), "insertions");
+ // Zulip timestamp followed by text.
+ input =
+ '<meta charset=\'utf-8\'><time datetime="2026-05-29T16:30:00Z" style="background: rgba(0, 0, 0, 0.2); border-radius: 3px; box-shadow: rgba(0, 0, 0, 0.4) 0px 0px 0px 1px; white-space: nowrap; margin: 0px 2px; font-size: 0.95em; color: rgb(222, 222, 222); font-family: &quot;Source Sans 3 VF&quot;, sans-serif;"><span class="timestamp-content-wrapper" style="font-size: 1.0526em; padding: 0px 0.2em; display: inline-flex; align-items: baseline; gap: 3px;"><span></span>May 29, 2026, 10:00 PM</span></time><span style="color: rgb(222, 222, 222); display: inline !important; float: none;"><span> </span>good better<span> </span></span>';
+ assert.equal(
+ compose_paste.paste_handler_converter(input),
+ "<time:2026-05-29T16:30:00Z> good better",
+ );
+
+ // Chrome-stripped timestamp: Chrome's clipboard serializer removes the <time>
+ // wrapper, leaving only the clock icon <i> and the <span data-datetime> fallback.
+ input =
+ '<meta charset=\'utf-8\'><br class="Apple-interchange-newline"><i class="zulip-icon zulip-icon-clock markdown-timestamp-icon" style="text-transform: none; font-size: 15.9995px; line-height: 15.9995px; text-decoration-line: inherit; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; display: inline-block; speak: none; font-family: zulip-icons !important; font-style: normal !important; font-weight: 400; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: normal !important; font-variant-east-asian: normal !important; font-variant-alternates: normal !important; font-variant-position: normal !important; font-variant-emoji: normal !important; align-self: center; color: rgb(222, 222, 222); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: nowrap; background-color: rgba(0, 0, 0, 0.2);"></i><span data-datetime="2026-05-23T17:30:00Z" style="color: rgb(222, 222, 222); font-family: &quot;Source Sans 3 VF&quot;, sans-serif; font-size: 15.9995px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: nowrap; background-color: rgba(0, 0, 0, 0.2); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Sat, May 23, 2026, 11:00 PM</span>';
+ assert.equal(compose_paste.paste_handler_converter(input), "<time:2026-05-23T17:30:00Z>");
+
+ // Non-Zulip <time datetime> elements, should not be converted.
+ input = "<meta charset='utf-8'><time datetime=\"2024-06-01T09:00:00Z\">June 1, 2024</time>";
+ assert.equal(compose_paste.paste_handler_converter(input), "June 1, 2024");
+
// Math block tests
/*