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_messages: Drop rows whose body is outside the selection.

Apoorva Pendsed06d30056e65
diff --git a/web/e2e-tests/copy-messages.test.ts b/web/e2e-tests/copy-messages.test.ts
index 5450bf6e54b..731e506382e 100644
--- a/web/e2e-tests/copy-messages.test.ts
+++ b/web/e2e-tests/copy-messages.test.ts
@@ -261,6 +261,118 @@ async function test_multiple_message_selection_with_partially_selected_bookend_m
assert.deepStrictEqual(actual_copied_lines, expected_copied_lines);
}
+type CopyRangeEndpoint = {
+ highlighted_part: "message_time" | "sender" | "content" | "reminder";
+ message: string;
+ // Only for "content": characters of the first text node left out of
+ // the selection, counted from the start for the start endpoint and
+ // from the end for the end endpoint.
+ text_node_offset?: number;
+};
+
+async function copy_custom_range(
+ page: Page,
+ start: CopyRangeEndpoint,
+ end: CopyRangeEndpoint,
+): Promise<{
+ default_prevented: boolean;
+ copied_lines: string[];
+ selection_text: string;
+}> {
+ return await page.evaluate(
+ (start: CopyRangeEndpoint, end: CopyRangeEndpoint) => {
+ function get_message_content_element(text: string): Element {
+ const node = [...document.querySelectorAll(".message-list .message_content")].find(
+ (candidate) => candidate.textContent?.trim() === text,
+ );
+ if (!node) {
+ throw new Error(`Expected message content: ${text}`);
+ }
+ return node;
+ }
+
+ function first_text_node(endpoint: CopyRangeEndpoint): Text {
+ const text = get_message_content_element(endpoint.message).querySelector(
+ "p",
+ )?.firstChild;
+ if (!(text instanceof Text)) {
+ throw new TypeError("Expected a Text node");
+ }
+ return text;
+ }
+
+ function endpoint_node(endpoint: CopyRangeEndpoint): Node {
+ const content = get_message_content_element(endpoint.message);
+ const row = content.closest(".message_row");
+ if (!row) {
+ throw new Error("Expected a message row");
+ }
+ if (endpoint.highlighted_part === "content") {
+ return content;
+ }
+ if (endpoint.highlighted_part === "sender") {
+ const sender = row.querySelector(".sender_name");
+ if (!sender) {
+ throw new Error("Expected a sender name");
+ }
+ return sender;
+ }
+ if (endpoint.highlighted_part === "reminder") {
+ const reminder = row.querySelector(".message-reminder");
+ if (!reminder) {
+ throw new Error("Expected a reminder");
+ }
+ return reminder;
+ }
+ const time = row.querySelector(".message-time");
+ if (!time) {
+ throw new Error("Expected a message timestamp");
+ }
+ return time;
+ }
+
+ const start_node = endpoint_node(start);
+ const end_node = endpoint_node(end);
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+ const range = document.createRange();
+ if (start.text_node_offset !== undefined) {
+ range.setStart(first_text_node(start), start.text_node_offset);
+ } else {
+ range.setStartBefore(start_node);
+ }
+ if (end.text_node_offset !== undefined) {
+ const end_text = first_text_node(end);
+ range.setEnd(end_text, end_text.length - end.text_node_offset);
+ } else {
+ range.setEndAfter(end_node);
+ }
+ selection.addRange(range);
+
+ const clipboard_data = new DataTransfer();
+ const copy_event = new ClipboardEvent("copy", {
+ bubbles: true,
+ cancelable: true,
+ clipboardData: clipboard_data,
+ });
+ document.dispatchEvent(copy_event);
+
+ const copied_html = clipboard_data.getData("text/html");
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(copied_html, "text/html");
+ return {
+ default_prevented: copy_event.defaultPrevented,
+ copied_lines: [...doc.body.children]
+ .map((el) => el.textContent.trim())
+ .filter((line) => line !== ""),
+ selection_text: window.getSelection()!.toString(),
+ };
+ },
+ start,
+ end,
+ );
+}
+
async function test_copying_selection_with_no_message_content(page: Page): Promise<void> {
// A recipient header plus the first message's sender name has no
// `.message_content`.
@@ -306,6 +418,138 @@ async function test_copying_selection_with_no_message_content(page: Page): Promi
assert.ok(result.selection_text.includes("Desdemona"));
}
+async function test_copying_me_timestamp_through_next_sender(page: Page): Promise<void> {
+ // /me timestamp through the next sender: no message body.
+ const result = await copy_custom_range(
+ page,
+ {highlighted_part: "message_time", message: "is posing for copy tests"},
+ {highlighted_part: "sender", message: "regular after me for copy tests"},
+ );
+ assert.equal(result.default_prevented, false);
+ assert.deepStrictEqual(result.copied_lines, []);
+ assert.ok(result.selection_text.includes("Desdemona"));
+}
+
+async function test_copying_me_timestamp_through_next_body(page: Page): Promise<void> {
+ // /me timestamp through the next message body.
+ const result = await copy_custom_range(
+ page,
+ {highlighted_part: "message_time", message: "is posing for copy tests"},
+ {highlighted_part: "content", message: "regular after me for copy tests"},
+ );
+ assert.equal(result.default_prevented, true);
+ assert.deepStrictEqual(result.copied_lines, ["Desdemona:", "regular after me for copy tests"]);
+}
+
+async function test_copying_me_timestamp_through_partial_next_body(page: Page): Promise<void> {
+ const result = await copy_custom_range(
+ page,
+ {highlighted_part: "message_time", message: "is posing for copy tests"},
+ {
+ highlighted_part: "content",
+ message: "regular after me for copy tests",
+ text_node_offset: 6,
+ },
+ );
+ assert.equal(result.default_prevented, true);
+ assert.deepStrictEqual(result.copied_lines, ["Desdemona:", "regular after me for copy..."]);
+}
+
+async function test_copying_me_timestamp_through_later_sender(page: Page): Promise<void> {
+ // /me timestamp through a later /me sender.
+ const result = await copy_custom_range(
+ page,
+ {highlighted_part: "message_time", message: "is posing for copy tests"},
+ {highlighted_part: "sender", message: "is posing again for copy tests"},
+ );
+ assert.equal(result.default_prevented, true);
+ assert.deepStrictEqual(result.copied_lines, [
+ "Desdemona:",
+ "regular after me for copy tests",
+ "Desdemona:",
+ "regular last after two mes",
+ ]);
+}
+
+async function test_copying_me_timestamp_through_later_body(page: Page): Promise<void> {
+ const result = await copy_custom_range(
+ page,
+ {highlighted_part: "message_time", message: "is posing for copy tests"},
+ {highlighted_part: "content", message: "regular last after two mes"},
+ );
+ assert.equal(result.default_prevented, true);
+ assert.deepStrictEqual(result.copied_lines, [
+ "Desdemona:",
+ "regular after me for copy tests",
+ "Desdemona:",
+ "regular last after two mes",
+ ]);
+}
+
+async function schedule_reminder_on_message(page: Page, content: string): Promise<void> {
+ await page.evaluate(async (content: string) => {
+ const node = [...document.querySelectorAll(".message-list .message_content")].find(
+ (candidate) => candidate.textContent?.trim() === content,
+ );
+ const message_id = node?.closest(".message_row")?.getAttribute("data-message-id");
+ const csrf = document.querySelector<HTMLInputElement>(
+ "input[name=csrfmiddlewaretoken]",
+ )?.value;
+ if (!message_id || !csrf) {
+ throw new Error("Expected message id and csrf token");
+ }
+ const res = await fetch("/json/reminders", {
+ method: "POST",
+ headers: {
+ "X-CSRFToken": csrf,
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ body: new URLSearchParams({
+ message_id,
+ scheduled_delivery_timestamp: String(Math.floor(Date.now() / 1000) + 86400),
+ }),
+ });
+ if (!res.ok) {
+ throw new Error(`Failed to schedule reminder: ${res.status}`);
+ }
+ }, content);
+ await page.waitForSelector(".message-list .message-reminder", {visible: true});
+}
+
+async function test_copying_from_reminder_through_next_body(page: Page): Promise<void> {
+ // Reminder text through the next message.
+ await schedule_reminder_on_message(page, "copy paste test F");
+ const result = await copy_custom_range(
+ page,
+ {highlighted_part: "reminder", message: "copy paste test F"},
+ {highlighted_part: "content", message: "copy paste test G"},
+ );
+ assert.equal(result.default_prevented, true);
+ assert.deepStrictEqual(result.copied_lines, ["Desdemona:", "copy paste test G"]);
+}
+
+async function test_copying_through_trailing_sender_name(page: Page): Promise<void> {
+ // Selection ends on a sender name.
+ const result = await copy_custom_range(
+ page,
+ {highlighted_part: "content", message: "is posing for copy tests"},
+ {highlighted_part: "sender", message: "regular after me for copy tests"},
+ );
+ assert.equal(result.default_prevented, true);
+ assert.deepStrictEqual(result.copied_lines, ["Desdemona:", "is posing for copy tests"]);
+}
+
+async function test_copying_repeated_text_suffix_through_next_sender(page: Page): Promise<void> {
+ // The selected suffix "copy copy" is also a prefix of the body.
+ const result = await copy_custom_range(
+ page,
+ {highlighted_part: "content", message: "copy copy copy", text_node_offset: 5},
+ {highlighted_part: "sender", message: "follows the repeated words"},
+ );
+ assert.equal(result.default_prevented, true);
+ assert.deepStrictEqual(result.copied_lines, ["Desdemona:", "...copy copy"]);
+}
+
async function copy_paste_test(page: Page): Promise<void> {
await common.log_in(page);
await common.send_multiple_messages(page, [
@@ -328,6 +572,38 @@ async function copy_paste_test(page: Page): Promise<void> {
{stream_name: "Verona", topic: "copy-paste-topic #3", content: "copy paste test F"},
{stream_name: "Verona", topic: "copy-paste-topic #3", content: "copy paste test G"},
+
+ {
+ stream_name: "Verona",
+ topic: "copy-paste-topic #4",
+ content: "/me is posing for copy tests",
+ },
+
+ {
+ stream_name: "Verona",
+ topic: "copy-paste-topic #4",
+ content: "regular after me for copy tests",
+ },
+
+ {
+ stream_name: "Verona",
+ topic: "copy-paste-topic #4",
+ content: "regular last after two mes",
+ },
+
+ {
+ stream_name: "Verona",
+ topic: "copy-paste-topic #4",
+ content: "/me is posing again for copy tests",
+ },
+
+ {stream_name: "Verona", topic: "copy-paste-topic #5", content: "copy copy copy"},
+
+ {
+ stream_name: "Verona",
+ topic: "copy-paste-topic #5",
+ content: "/me follows the repeated words",
+ },
]);
await page.click("#left-sidebar-navigation-list .top_left_all_messages");
@@ -340,6 +616,16 @@ async function copy_paste_test(page: Page): Promise<void> {
["copy paste test C", "copy paste test D", "copy paste test E"],
],
["Verona > copy-paste-topic #3", ["copy paste test F", "copy paste test G"]],
+ [
+ "Verona > copy-paste-topic #4",
+ [
+ "is posing for copy tests",
+ "regular after me for copy tests",
+ "regular last after two mes",
+ "is posing again for copy tests",
+ ],
+ ],
+ ["Verona > copy-paste-topic #5", ["copy copy copy", "follows the repeated words"]],
]);
console.log("Messages were sent successfully");
@@ -353,6 +639,14 @@ async function copy_paste_test(page: Page): Promise<void> {
await test_copying_messages_from_several_topics(page);
await test_timestamp_clipboard_has_datetime(page);
await test_copying_selection_with_no_message_content(page);
+ await test_copying_me_timestamp_through_next_sender(page);
+ await test_copying_me_timestamp_through_next_body(page);
+ await test_copying_me_timestamp_through_partial_next_body(page);
+ await test_copying_me_timestamp_through_later_sender(page);
+ await test_copying_me_timestamp_through_later_body(page);
+ await test_copying_from_reminder_through_next_body(page);
+ await test_copying_through_trailing_sender_name(page);
+ await test_copying_repeated_text_suffix_through_next_sender(page);
await test_multiple_message_selection_with_partially_selected_bookend_messages(page);
}
diff --git a/web/src/copy_messages.ts b/web/src/copy_messages.ts
index 6dbba4a9c3a..d130ab2df17 100644
--- a/web/src/copy_messages.ts
+++ b/web/src/copy_messages.ts
@@ -71,6 +71,50 @@ function get_selected_message_content_elements(): NodeListOf<HTMLElement> | unde
.querySelectorAll(".message_content");
}
+// First selected range start through last selected range end.
+// Firefox <147 splits a contiguous selection into several ranges
+// around `user-select: none` nodes.
+function selection_extent_range(): Range {
+ const selection = window.getSelection();
+ assert(selection !== null && selection.rangeCount > 0);
+ const first = selection.getRangeAt(0);
+ if (selection.rangeCount === 1) {
+ return first;
+ }
+ const last = selection.getRangeAt(selection.rangeCount - 1);
+ const extent = document.createRange();
+ extent.setStart(first.startContainer, first.startOffset);
+ extent.setEnd(last.endContainer, last.endOffset);
+ return extent;
+}
+
+function selection_covers_message_content($row: JQuery, range: Range): boolean {
+ const content = the($row).querySelector(".message_content");
+ assert(content !== null);
+ return range.intersectsNode(content);
+}
+
+// "end" when the selection starts after the previous message's
+// body, for example on a /me timestamp or reminder, and ends
+// in the middle of this message.
+// "start" when the range begins inside the first body.
+function bookend_ellipsis_side(range: Range, content: Element): RangeContainer {
+ return range.isPointInRange(content, 0) ? "end" : "start";
+}
+
+// Drop a bookend row whose .message_content is outside the selection.
+function drop_unselected_bookend_rows(copy_rows: JQuery[]): void {
+ const range = selection_extent_range();
+ const $first = copy_rows[0];
+ if ($first !== undefined && !selection_covers_message_content($first, range)) {
+ copy_rows.shift();
+ }
+ const $last = copy_rows.at(-1);
+ if ($last !== undefined && !selection_covers_message_content($last, range)) {
+ copy_rows.pop();
+ }
+}
+
// Returns the inner HTML of the `.message_content` element
// for the first or last message of a single range selection.
// The caller is expected to only pass the first or last message
@@ -144,9 +188,11 @@ function maybe_expand_selection_for_first_and_last_messages(
copy_rows: JQuery[],
range_count: number,
): void {
- // This is only meant for a multi-message selection involving
- // multiple ranges.
- assert(range_count > 1 && copy_rows.length > 1);
+ // Firefox <147 can emit multiple ranges for a single-row
+ // selection; expanding is only for a multi-row copy.
+ if (range_count <= 1 || copy_rows.length <= 1) {
+ return;
+ }
if (navigator.userAgent.includes("Chrome")) {
blueslip.error("Multiple ranges detected in Chrome for a multi-message selection.");
@@ -195,8 +241,14 @@ function construct_copy_div($div: JQuery, start_id: number, end_id: number): boo
let $first_message_element;
let $last_message_element;
const copy_rows = rows.visible_range(start_id, end_id);
- const range_count = window.getSelection()?.rangeCount;
- if (range_count && range_count > 1) {
+ const range_count = window.getSelection()?.rangeCount ?? 0;
+ // Trim before expanding a Firefox <147 multi-range selection,
+ // which can have rangeCount > 1 with fewer contentful rows.
+ drop_unselected_bookend_rows(copy_rows);
+ if (copy_rows.length === 0) {
+ return false;
+ }
+ if (range_count > 1) {
// Expand selection to select content from all the messages
// belonging to the multi-message selection.
// We do this only for Firefox where multi-message selections are
@@ -214,19 +266,6 @@ function construct_copy_div($div: JQuery, start_id: number, end_id: number): boo
// a single range for a multi-message selection.
const selected_message_content_elements = get_selected_message_content_elements();
assert(selected_message_content_elements !== undefined);
- // Case where the last message doesn't have any highlighted `.message_content`.
- // Here, end_id is set to id of the message whose username at the top
- // was highlighted, but has no highlighted `.message_content`.
- // (See analyze_selection for details.)
- // So the actually useful/contentful last message of this selection is
- // at copy_rows[copy_rows.length - 2]
- if (selected_message_content_elements.length === copy_rows.length - 1) {
- copy_rows.splice(-1, 1);
- if (copy_rows.length === 0) {
- // In case this just involved selecting the username of a message.
- return false;
- }
- }
assert(copy_rows[0] && copy_rows.at(-1));
const first_selected_message_content_element = the(copy_rows[0]).querySelector(
".message_content",
@@ -235,9 +274,16 @@ function construct_copy_div($div: JQuery, start_id: number, end_id: number): boo
".message_content",
);
assert(first_selected_message_content_element && last_selected_message_content_element);
+ const first_bookend_side =
+ selected_message_content_elements.length === 1
+ ? bookend_ellipsis_side(
+ selection_extent_range(),
+ first_selected_message_content_element,
+ )
+ : "start";
$first_message_element = $(
get_html_for_bookend_message_content(
- "start",
+ first_bookend_side,
first_selected_message_content_element,
selected_message_content_elements[0],
),