Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
reload: Store and parse reload data more elegantly.
Evy Kassirerf5af06479ef5
diff --git a/web/src/drafts.ts b/web/src/drafts.tsindex b26b6695478..2c9bed7e16a 100644--- a/web/src/drafts.ts+++ b/web/src/drafts.ts@@ -433,7 +433,13 @@ export let update_draft = (opts: UpdateDraftOptions = {}): string | undefined =>const old_draft = draft_id === undefined ? undefined : draft_model.getDraft(draft_id);const no_notify = opts.no_notify ?? false;- const force_save = opts.force_save ?? false;+ // When message content is <= MINIMUM_MESSAGE_LENGTH_TO_SAVE_DRAFT,+ // we usually don't save it, but if there's some content and the+ // draft was already saved, we should save the shorter version+ // and shouldn't delete it below.+ const existing_draft_has_become_short =+ draft_id !== undefined && compose_state.message_content().length > 0;+ const force_save = opts.force_save ?? existing_draft_has_become_short;const draft = snapshot_message(force_save);if (draft === undefined) {diff --git a/web/src/hash_util.ts b/web/src/hash_util.tsindex 05932e8395b..29b407cbee4 100644--- a/web/src/hash_util.ts+++ b/web/src/hash_util.ts@@ -20,12 +20,12 @@ import type {UserGroup} from "./user_groups.ts";import {user_settings} from "./user_settings.ts";import * as util from "./util.ts";-export function build_reload_url(): string {+export function get_reload_hash(): string {let hash = window.location.hash;if (hash.startsWith("#")) {hash = hash.slice(1);}- return "+oldhash=" + encodeURIComponent(hash);+ return hash;}export function encode_operand(operator: string, operand: string): string {diff --git a/web/src/reload.ts b/web/src/reload.tsindex b555ec12a4f..e53749e4a29 100644--- a/web/src/reload.ts+++ b/web/src/reload.ts@@ -5,7 +5,6 @@ import * as z from "zod/mini";import * as blueslip from "./blueslip.ts";import * as channel from "./channel.ts";import * as compose_state from "./compose_state.ts";-import {csrf_token} from "./csrf.ts";import * as drafts from "./drafts.ts";import * as hash_util from "./hash_util.ts";import type {LocalStorage} from "./localstorage.ts";@@ -21,7 +20,14 @@ import * as util from "./util.ts";let server_reachable_check_failures = 0;-const token_metadata_schema = z.object({url: z.string(), timestamp: z.number()});+export const reload_metadata_schema = z.object({+ hash: z.string(),+ message_view_pointer: z.optional(z.number()),+ message_view_scroll_offset: z.optional(z.number()),+ compose_active_draft_id: z.optional(z.string()),+ compose_active_draft_send_immediately: z.optional(z.boolean()),+ timestamp: z.number(),+});const reload_hooks: (() => void)[] = [];@@ -35,7 +41,10 @@ function call_reload_hooks(): void {}}-function preserve_state(send_after_reload: boolean, save_compose: boolean): void {+function preserve_state(+ compose_active_draft_send_immediately: boolean,+ save_compose: boolean,+): void {if (!localstorage.supported()) {// If local storage is not supported by the browser, we can't// save the browser's position across reloads (since there's@@ -54,45 +63,32 @@ function preserve_state(send_after_reload: boolean, save_compose: boolean): voidreturn;}- let url = "#reload:send_after_reload=" + (send_after_reload ? "1" : "0");- assert(csrf_token !== undefined);- url += "+csrf_token=" + encodeURIComponent(csrf_token);-- const msg_type = compose_state.get_message_type();- if (save_compose && msg_type) {- if (msg_type === "stream") {- const stream_id = compose_state.stream_id();- url += "+msg_type=stream";- if (stream_id) {- url += "+stream_id=" + encodeURIComponent(stream_id);- }- url += "+topic=" + encodeURIComponent(compose_state.topic());- } else if (msg_type === "private") {- url += "+msg_type=private";- url +=- "+recipient=" +- encodeURIComponent(compose_state.private_message_recipient_emails());- }-- url += "+msg=" + encodeURIComponent(compose_state.message_content());- const draft_id = drafts.update_draft();- if (draft_id) {- url += "+draft_id=" + encodeURIComponent(draft_id);- }+ let draft_id: string | undefined;+ if (save_compose && compose_state.get_message_type()) {+ draft_id = drafts.update_draft({force_save: true});+ assert(draft_id !== undefined);}-+ let message_view_pointer: number | undefined;+ let message_view_scroll_offset: number | undefined;if (message_lists.current !== undefined) {const narrow_pointer = message_lists.current.selected_id();if (narrow_pointer !== -1) {- url += "+narrow_pointer=" + narrow_pointer;+ message_view_pointer = narrow_pointer;}const $narrow_row = message_lists.current.selected_row();if ($narrow_row.length > 0) {- url += "+narrow_offset=" + $narrow_row.get_offset_to_window().top;+ message_view_scroll_offset = $narrow_row.get_offset_to_window().top;}}- url += hash_util.build_reload_url();+ const reload_data: z.infer<typeof reload_metadata_schema> = {+ compose_active_draft_send_immediately,+ compose_active_draft_id: draft_id,+ message_view_pointer,+ message_view_scroll_offset,+ hash: hash_util.get_reload_hash(),+ timestamp: Date.now(),+ };// Delete unused states that have been around for a while.const ls = localstorage();@@ -103,25 +99,18 @@ function preserve_state(send_after_reload: boolean, save_compose: boolean): void// others) which is passed via the URL to the browser (post// reloading). The token is a key into local storage, where we// marshall and store the URL.- //- // TODO: Remove the now-unnecessary URL-encoding logic above and- // just pass the actual data structures through local storage.const token = util.random_int(0, 1024 * 1024 * 1024 * 1024);- const metadata: z.infer<typeof token_metadata_schema> = {- url,- timestamp: Date.now(),- };- ls.set("reload:" + token, metadata);+ ls.set("reload:" + token, reload_data);window.location.replace("#reload:" + token);}export function is_stale_refresh_token(token_metadata: unknown, now: number): boolean {- const parsed = token_metadata_schema.safeParse(token_metadata);- // TODO/compatibility: the metadata was changed from a string- // to a map containing the string and a timestamp. For now we'll- // delete all tokens that only contain the url. Remove this- // early return once you can no longer directly upgrade from- // Zulip 5.x to the current version.+ const parsed = reload_metadata_schema.safeParse(token_metadata);+ // TODO/compatibility(12.0): The metadata format was rewritten in+ // the 12.0 development branch in 2025. We garbage-collect reload+ // tokens in the old format if they are more than a week stale. We+ // can delete the parsing logic for the old format once it's no+ // longer possible to directly upgrade from 11.x to main.if (!parsed.success) {return true;}diff --git a/web/src/reload_setup.ts b/web/src/reload_setup.tsindex 1aafbb0e36b..da3e293ede0 100644--- a/web/src/reload_setup.ts+++ b/web/src/reload_setup.ts@@ -5,16 +5,18 @@ import * as activity from "./activity.ts";import * as blueslip from "./blueslip.ts";import * as compose from "./compose.ts";import * as compose_actions from "./compose_actions.ts";+import * as drafts from "./drafts.ts";import {localstorage} from "./localstorage.ts";import * as message_fetch from "./message_fetch.ts";import * as message_view from "./message_view.ts";import * as people from "./people.ts";+import {reload_metadata_schema} from "./reload.ts";// Check if we're doing a compose-preserving reload. This must be// done before the first call to get_events-// See `reload.preserve_state` for context on how this is built.-const reload_vars_schema = z.intersection(+// See history of `reload.preserve_state` for context on how this is built.+const legacy_reload_vars_schema = z.intersection(z.object({oldhash: z.string(),narrow_pointer: z.optional(z.string()),@@ -42,7 +44,6 @@ export function initialize(): void {return;}const hash_fragment = window.location.hash.slice("#".length);- const trigger = "reload";// Using the token, recover the saved pre-reload data from local// storage. Afterwards, we clear the reload entry from local@@ -55,11 +56,57 @@ export function initialize(): void {// exist, but be log it so that it's available for future// debugging if an exception happens later.blueslip.info("Invalid hash change reload token");- message_view.changehash("", trigger);+ message_view.changehash("", "reload");return;}ls.remove(hash_fragment);+ const parsed = reload_metadata_schema.safeParse(fragment);+ if (parsed.success) {+ // IMPORTANT: Most changes to this function's behavior should+ // also update load_from_legacy_data.+ const data = parsed.data;+ if (data.compose_active_draft_id !== undefined) {+ const draft = drafts.draft_model.getDraft(data.compose_active_draft_id);+ if (draft === false) {+ blueslip.warn("Tried to restore a draft that didn't exist.");+ } else {+ compose_actions.start({...draft, message_type: draft.type});+ if (data.compose_active_draft_send_immediately) {+ compose.finish();+ }+ }+ }++ // We only restore pointer and offset for the current narrow, even if+ // there are narrows that were cached before the reload, they are no+ // longer cached after the reload. We could possibly store the pointer+ // and offset for these narrows but it might lead to a confusing+ // experience if the user gets back to these narrow much later (maybe days)+ // and finds them at a random position in the narrow which they didn't+ // navigate to while they were trying to just get to the latest unread+ // message in that narrow which will now take more effort to find.+ message_fetch.set_initial_pointer_and_offset({+ narrow_pointer: data.message_view_pointer,+ narrow_offset: data.message_view_scroll_offset,+ });++ activity.set_new_user_input(false);+ message_view.changehash(data.hash, "reload");+ } else {+ load_from_legacy_data(fragment);+ }+}++function load_from_legacy_data(fragment: unknown): void {+ // IMPORTANT: This function mostly duplicates initialize with+ // different parsing logic. Be careful to avoid fixing only one+ // code path.+ //+ // TODO/compatibility(12.0): This legacy code path can be deleted+ // once it is no longer possible to directly upgrade from 11.x to+ // main.+ //// TODO/compatibility: `fragment` was changed from a string// to a map containing the string and a timestamp. For now we'll// delete all tokens that only contain the url. Remove the@@ -85,7 +132,7 @@ export function initialize(): void {raw_vars[pair[0]!] = decodeURIComponent(pair[1]!);}- const vars = reload_vars_schema.parse(raw_vars);+ const vars = legacy_reload_vars_schema.parse(raw_vars);if (vars.msg !== undefined) {const send_now = vars.send_after_reload === "1";@@ -134,5 +181,5 @@ export function initialize(): void {});activity.set_new_user_input(false);- message_view.changehash(vars.oldhash, trigger);+ message_view.changehash(vars.oldhash, "reload");}diff --git a/web/tests/hash_util.test.cjs b/web/tests/hash_util.test.cjsindex ce86a5a7874..2bdb05ce212 100644--- a/web/tests/hash_util.test.cjs+++ b/web/tests/hash_util.test.cjs@@ -99,18 +99,18 @@ run_test("test_is_same_server_message_link", () => {}});-run_test("build_reload_url", () => {+run_test("get_reload_hash", () => {window.location.hash = "#settings/profile";- assert.equal(hash_util.build_reload_url(), "+oldhash=settings%2Fprofile");+ assert.equal(hash_util.get_reload_hash(), "settings/profile");window.location.hash = "#test";- assert.equal(hash_util.build_reload_url(), "+oldhash=test");+ assert.equal(hash_util.get_reload_hash(), "test");window.location.hash = "#";- assert.equal(hash_util.build_reload_url(), "+oldhash=");+ assert.equal(hash_util.get_reload_hash(), "");window.location.hash = "";- assert.equal(hash_util.build_reload_url(), "+oldhash=");+ assert.equal(hash_util.get_reload_hash(), "");});run_test("test is_editing_stream", () => {diff --git a/web/tests/reload.test.cjs b/web/tests/reload.test.cjsindex 09861da1a5e..ac9b58f0b75 100644--- a/web/tests/reload.test.cjs+++ b/web/tests/reload.test.cjs@@ -10,14 +10,14 @@ window.addEventListener = noop;const reload = zrequire("reload");run_test("old_metadata_string_is_stale", () => {- assert.ok(reload.is_stale_refresh_token("#reload:234234235234", Date.now()), true);+ assert.ok(reload.is_stale_refresh_token({reload_data: {hash: ""}}, Date.now()), true);});run_test("recent_token_is_not_stale ", () => {assert.ok(!reload.is_stale_refresh_token({- url: "#reload:234234235234",+ hash: "",timestamp: Date.parse("21 Jan 2022 00:00:00 GMT"),},Date.parse("23 Jan 2022 00:00:00 GMT"),@@ -29,7 +29,7 @@ run_test("old_token_is_stale ", () => {assert.ok(reload.is_stale_refresh_token({- url: "#reload:234234235234",+ hash: "",timestamp: Date.parse("13 Jan 2022 00:00:00 GMT"),},Date.parse("23 Jan 2022 00:00:00 GMT"),