From d2ea65da10c7a4738f65431269f1f3e86098d82c Mon Sep 17 00:00:00 2001 From: N-Shar-ma Date: Mon, 6 Feb 2023 16:54:57 +0530 Subject: [PATCH] compose: Clean code to fix `up` hotkey to edit previous message. This is a follow up to 875ad8e implementing a better approach. We call `cursor_at_start_of_whitespace_in_compose` from `focus_in_empty_compose` itself if and when needed. --- static/js/compose_state.js | 24 +++++++++++++----------- static/js/hotkey.js | 3 +-- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/static/js/compose_state.js b/static/js/compose_state.js index d8f5ffaf59..651fdfd18d 100644 --- a/static/js/compose_state.js +++ b/static/js/compose_state.js @@ -86,24 +86,26 @@ export const message_content = get_or_set("compose-textarea", true); const untrimmed_message_content = get_or_set("compose-textarea", true, true); -export function cursor_at_start_of_whitespace_in_compose() { - // First check if the compose box is focused. TODO: Maybe we - // should make `consider_start_of_whitespace_message_empty` a - // parameter to `focus_in_empty_compose` instead. - const focused_element_id = document.activeElement.id; - if (focused_element_id !== "compose-textarea") { - return false; - } - +function cursor_at_start_of_whitespace_in_compose() { const cursor_position = $("#compose-textarea").caret(); return message_content() === "" && cursor_position === 0; } -export function focus_in_empty_compose() { +export function focus_in_empty_compose(consider_start_of_whitespace_message_empty = false) { // A user trying to press arrow keys in an empty compose is mostly // likely trying to navigate messages. This helper function // decides whether the compose box is empty for this purpose. - if (!composing() || untrimmed_message_content() !== "") { + if (!composing()) { + return false; + } + + // We treat the compose box as empty if it's completely empty, or + // if the caller requested, if it contains only whitespace and we're + // at the start of te compose box. + const treat_compose_as_empty = + untrimmed_message_content() === "" || + (consider_start_of_whitespace_message_empty && cursor_at_start_of_whitespace_in_compose()); + if (!treat_compose_as_empty) { return false; } diff --git a/static/js/hotkey.js b/static/js/hotkey.js index 9ec56943f2..af618a7a21 100644 --- a/static/js/hotkey.js +++ b/static/js/hotkey.js @@ -732,8 +732,7 @@ export function process_hotkey(e, hotkey) { ((event_name === "down_arrow" || event_name === "page_down" || event_name === "end") && compose_state.focus_in_empty_compose()) || ((event_name === "up_arrow" || event_name === "page_up" || event_name === "home") && - (compose_state.focus_in_empty_compose() || - compose_state.cursor_at_start_of_whitespace_in_compose())) + compose_state.focus_in_empty_compose(true)) ) { compose_actions.cancel(); // don't return, as we still want it to be picked up by the code below