Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
popover_menus_data: Add algorithm for scroll-to-date suggestions.
Alya Abbott01b79ee102d9
diff --git a/web/src/popover_menus_data.ts b/web/src/popover_menus_data.tsindex 6f7555e26fe..ac4de30548a 100644--- a/web/src/popover_menus_data.ts+++ b/web/src/popover_menus_data.ts@@ -10,6 +10,7 @@ import {$t} from "./i18n.ts";import * as message_delete from "./message_delete.ts";import * as message_edit from "./message_edit.ts";import * as message_lists from "./message_lists.ts";+import type {Message} from "./message_store.ts";import * as narrow_state from "./narrow_state.ts";import {page_params} from "./page_params.ts";import * as people from "./people.ts";@@ -21,6 +22,7 @@ import * as starred_messages from "./starred_messages.ts";import {current_user, realm, realm_billing} from "./state_data.ts";import * as stream_data from "./stream_data.ts";import * as sub_store from "./sub_store.ts";+import * as timerender from "./timerender.ts";import {num_unread_for_topic} from "./unread.ts";import {user_settings} from "./user_settings.ts";import * as user_status from "./user_status.ts";@@ -456,3 +458,194 @@ function is_topic_definitely_empty(stream_id: number, topic: string): boolean {return true;}++const MAX_SUGGESTED_DATES = 4;+// When picking a date near each slice boundary, search this+// many positions in each direction for a better choice.+const SEARCH_RADIUS = 2;++type DateGroup = {+ date_string: string;+ timestamp: number;+ preceding_quiet_days: number;+ message_count: number;+};++export type ScrollToDateSuggestion = {+ label: string;+ iso_date_string: string;+};++// Cache the formatter to avoid creating a new Intl.DateTimeFormat+// on every call. Invalidated when the display timezone changes.+let date_key_formatter: Intl.DateTimeFormat | undefined;+let date_key_timezone: string | undefined;++function get_date_key(timestamp: number): string {+ // Group by calendar day in the user's display timezone, so that+ // grouping is consistent with the date labels shown in the popover.+ if (date_key_formatter === undefined || date_key_timezone !== timerender.display_time_zone) {+ date_key_timezone = timerender.display_time_zone;+ date_key_formatter = new Intl.DateTimeFormat("en-US", {+ timeZone: date_key_timezone,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ }+ const parts = date_key_formatter.formatToParts(new Date(timestamp * 1000));+ const year = parts.find((part) => part.type === "year")!.value;+ const month = parts.find((part) => part.type === "month")!.value;+ const day = parts.find((part) => part.type === "day")!.value;+ return `${year}-${month}-${day}`;+}++// Compute the gap in days between two YYYY-MM-DD date strings.+// Since these are already calendar dates in the display timezone,+// we parse them as UTC to avoid browser-local timezone issues.+function date_string_gap_days(prev_key: string, curr_key: string): number {+ const prev_ms = Date.parse(prev_key + "T00:00:00Z");+ const curr_ms = Date.parse(curr_key + "T00:00:00Z");+ return Math.round((curr_ms - prev_ms) / 86_400_000);+}++// Format a date for display: "February 12" for the current year,+// "February 12, 2025" for older years.+function format_date_label(timestamp: number, now_year: string): string {+ const date = new Date(timestamp * 1000);+ const date_year = get_date_key(timestamp).slice(0, 4);+ if (date_year === now_year) {+ return timerender.get_localized_date_or_time_for_format(date, "long_dayofyear");+ }+ return timerender.get_localized_date_or_time_for_format(date, "long_dayofyear_year");+}++// Group messages by calendar date, tracking the days of silence+// before each date and the number of messages on that date.+function build_date_groups(messages: Message[]): DateGroup[] {+ const groups: DateGroup[] = [];+ let current_group: DateGroup | undefined;++ for (const message of messages) {+ const date_key = get_date_key(message.timestamp);+ if (current_group?.date_string !== date_key) {+ const preceding_quiet_days =+ current_group === undefined+ ? 0+ : date_string_gap_days(current_group.date_string, date_key);+ current_group = {+ date_string: date_key,+ timestamp: message.timestamp,+ preceding_quiet_days,+ message_count: 0,+ };+ groups.push(current_group);+ }+ current_group.message_count += 1;+ }++ return groups;+}++// Compute cumulative message counts from per-group counts.+// cumulative[i] is the total messages in groups 0..i (inclusive).+function compute_cumulative_counts(groups: DateGroup[]): number[] {+ const cumulative: number[] = [];+ let total = 0;+ for (const group of groups) {+ total += group.message_count;+ cumulative.push(total);+ }+ return cumulative;+}++// Find the index in cumulative whose value is closest to target.+function closest_index(cumulative: number[], target: number): number {+ let best = 0;+ let best_distance = Math.abs(cumulative[0]! - target);+ for (let i = 1; i < cumulative.length; i += 1) {+ const distance = Math.abs(cumulative[i]! - target);+ if (distance < best_distance) {+ best = i;+ best_distance = distance;+ }+ }+ return best;+}++// Compute up to MAX_SUGGESTED_DATES dates to offer in the+// "Scroll to" popover, drawn from the locally cached messages.+//+// Algorithm: divide the message volume into equal slices, then+// for each slice boundary, prefer a nearby date with a long+// silence before it (the start of a new conversation burst).+export function get_scroll_to_date_suggestions(messages: Message[]): ScrollToDateSuggestion[] {+ if (messages.length === 0) {+ return [];+ }++ const date_groups = build_date_groups(messages);++ // Exclude today — the user is likely already there.+ const today_key = get_date_key(Date.now() / 1000);+ const filtered_groups = date_groups.filter((group) => group.date_string !== today_key);++ if (filtered_groups.length === 0) {+ return [];+ }++ const now_year = today_key.slice(0, 4);++ // If there are few enough unique dates, just suggest all of them.+ if (filtered_groups.length <= MAX_SUGGESTED_DATES) {+ return filtered_groups.map((group) => ({+ label: format_date_label(group.timestamp, now_year),+ iso_date_string: new Date(group.timestamp * 1000).toISOString(),+ }));+ }++ const cumulative = compute_cumulative_counts(filtered_groups);+ const total = cumulative.at(-1)!;++ const selected_indices = new Set<number>();++ // Split the message volume into equal slices (e.g. 20%, 40%,+ // 60%, 80%) and pick one date near each boundary.+ for (let slice = 1; slice <= MAX_SUGGESTED_DATES; slice += 1) {+ const slice_breakpoint = (total * slice) / (MAX_SUGGESTED_DATES + 1);+ const nearest = closest_index(cumulative, slice_breakpoint);++ // Look at nearby dates (±SEARCH_RADIUS) and prefer the+ // one with the longest quiet period before it, since+ // that marks where a conversation restarted.+ const search_start = Math.max(0, nearest - SEARCH_RADIUS);+ const search_end = Math.min(filtered_groups.length - 1, nearest + SEARCH_RADIUS);++ let best = nearest;+ // If the nearest date was already picked, treat its+ // silence as -1 so any other candidate will win.+ let longest_silence = selected_indices.has(nearest)+ ? -1+ : filtered_groups[nearest]!.preceding_quiet_days;+ // Among nearby dates not already picked, find the one+ // with the longest quiet period before it.+ for (let i = search_start; i <= search_end; i += 1) {+ if (+ !selected_indices.has(i) &&+ filtered_groups[i]!.preceding_quiet_days > longest_silence+ ) {+ best = i;+ longest_silence = filtered_groups[i]!.preceding_quiet_days;+ }+ }++ selected_indices.add(best);+ }++ // Sort since selected_indices is a set.+ const sorted_indices = [...selected_indices].toSorted((a, b) => a - b);+ return sorted_indices.map((i) => ({+ label: format_date_label(filtered_groups[i]!.timestamp, now_year),+ iso_date_string: new Date(filtered_groups[i]!.timestamp * 1000).toISOString(),+ }));+}diff --git a/web/tests/popover_menus_data.test.cjs b/web/tests/popover_menus_data.test.cjsindex bdba4eadbe4..d3ce896e020 100644--- a/web/tests/popover_menus_data.test.cjs+++ b/web/tests/popover_menus_data.test.cjs@@ -68,6 +68,28 @@ mock_esm("../src/group_permission_settings", {};},});+mock_esm("../src/timerender", {+ display_time_zone: "UTC",+ get_localized_date_or_time_for_format(date) {+ // Return a simple date string for testing.+ const d = new Date(date);+ const months = [+ "January",+ "February",+ "March",+ "April",+ "May",+ "June",+ "July",+ "August",+ "September",+ "October",+ "November",+ "December",+ ];+ return `${months[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`;+ },+});const current_user = {};set_current_user(current_user);@@ -306,3 +328,100 @@ test("not_my_message_view_source_and_move", ({override}) => {assert.equal(response.editability_menu_item, undefined);assert.equal(response.move_message_menu_item, "translated: Move messages");});++// Helper to create a minimal message object with a given timestamp.+function make_message(id, timestamp) {+ return {id, timestamp};+}++function date_timestamp(date_string) {+ return new Date(date_string + "T12:00:00").getTime() / 1000;+}++run_test("get_scroll_to_date_suggestions - empty messages", () => {+ const result = popover_menus_data.get_scroll_to_date_suggestions([]);+ assert.deepEqual(result, []);+});++run_test("get_scroll_to_date_suggestions - all messages today", () => {+ const today = new Date();+ const today_ts = today.getTime() / 1000;+ const messages = [make_message(1, today_ts), make_message(2, today_ts + 60)];+ const result = popover_menus_data.get_scroll_to_date_suggestions(messages);+ assert.deepEqual(result, []);+});++run_test("get_scroll_to_date_suggestions - few unique dates", () => {+ // With 3 unique dates (all in the past), all should be suggested.+ const messages = [+ make_message(1, date_timestamp("2025-01-10")),+ make_message(2, date_timestamp("2025-01-10")),+ make_message(3, date_timestamp("2025-02-15")),+ make_message(4, date_timestamp("2025-03-20")),+ ];+ const result = popover_menus_data.get_scroll_to_date_suggestions(messages);+ assert.equal(result.length, 3);+ // Verify chronological order.+ assert.ok(result[0].iso_date_string < result[1].iso_date_string);+ assert.ok(result[1].iso_date_string < result[2].iso_date_string);+});++run_test("get_scroll_to_date_suggestions - many dates with gaps", () => {+ // Simulate a conversation with bursts separated by gaps.+ // Burst 1: Jan 5-7 (9 messages)+ // Gap: 20 days+ // Burst 2: Jan 27-28 (8 messages)+ // Gap: 15 days+ // Burst 3: Feb 12-14 (10 messages)+ // Gap: 25 days+ // Burst 4: Mar 11-12 (8 messages)+ const messages = [];+ let id = 1;+ // 4 bursts of conversation separated by multi-week gaps.+ for (const [count, date] of [+ // Burst 1+ [3, "2025-01-05"],+ [3, "2025-01-06"],+ [3, "2025-01-07"],+ // Burst 2+ [4, "2025-01-27"],+ [4, "2025-01-28"],+ // Burst 3+ [4, "2025-02-12"],+ [3, "2025-02-13"],+ [3, "2025-02-14"],+ // Burst 4+ [4, "2025-03-11"],+ [4, "2025-03-12"],+ ]) {+ for (let i = 0; i < count; i += 1) {+ messages.push(make_message(id, date_timestamp(date)));+ id += 1;+ }+ }++ const result = popover_menus_data.get_scroll_to_date_suggestions(messages);+ // We have 10 unique dates across 4 bursts; expect 3-4 suggestions.+ assert.ok(result.length >= 3 && result.length <= 4);+ // Verify chronological order.+ for (let i = 1; i < result.length; i += 1) {+ assert.ok(result[i - 1].iso_date_string < result[i].iso_date_string);+ }+ // The algorithm should prefer dates at the start of bursts (after gaps).+ // Jan 27 has a 20-day gap before it, Feb 12 has a 15-day gap,+ // Mar 11 has a 25-day gap — these should appear as suggestions.+ const iso_dates = result.map((s) => s.iso_date_string.slice(0, 10));+ // Burst-start dates (Jan 27, Feb 12, Mar 11) should be well represented.+ const burst_starts = new Set(["2025-01-27", "2025-02-12", "2025-03-11"]);+ const burst_start_count = iso_dates.filter((d) => burst_starts.has(d)).length;+ assert.ok(burst_start_count >= 2, `Expected >=2 burst starts, got ${burst_start_count}`);+});++run_test("get_scroll_to_date_suggestions - single date in the past", () => {+ const messages = [+ make_message(1, date_timestamp("2025-06-15")),+ make_message(2, date_timestamp("2025-06-15")),+ ];+ const result = popover_menus_data.get_scroll_to_date_suggestions(messages);+ assert.equal(result.length, 1);+});