Skip to content

Commit d810608

Browse files
wesbillmannpub1yxv5wk0u0fh6dwt925wntn7h397jvteyj4r87ttcd9xae7n2t3lqqj9jmm
andauthored
feat(desktop): keyboard shortcuts — ⌘⇧N new channel + ↑-to-edit last message (#809)
Signed-off-by: npub1yxv5wk0u0fh6dwt925wntn7h397jvteyj4r87ttcd9xae7n2t3lqqj9jmm <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub1yxv5wk0u0fh6dwt925wntn7h397jvteyj4r87ttcd9xae7n2t3lqqj9jmm <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co>
1 parent 39911e4 commit d810608

9 files changed

Lines changed: 292 additions & 4 deletions

File tree

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@ const overrides = new Map([
4343
["src/features/notifications/hooks.ts", 535], // notification settings + feed notification lifecycle + profile batch resolution + truncated-pubkey guard + badge state
4444
["src/features/home/ui/HomeView.tsx", 505], // inbox/feed orchestration + thread context + reply/delete flow + NIP-RS read-state projection wiring (useHomeInboxReadState)
4545
["src/features/messages/hooks.ts", 500], // message query/mutation hooks + optimistic updates
46-
["src/features/messages/ui/MessageComposer.tsx", 800], // media upload handlers (paste, drop, dialog) + channelId reset effect + edit mode (pre-fill, save, cancel, escape) + composer autofocus (#572) + Sprout code-block paste branch (round-trips copy-button output as a literal codeBlock so Markdown can't reshape it) + scroll-to-bottom on multi-line paste (#619) + Slack-style attachment-editable edits: seed pendingImeta from edit target, stash/restore user's draft pendingImeta across edit-mode entry/exit, re-append imeta markdown lines on edit-submit so renderer draws them
46+
["src/features/messages/lib/useRichTextEditor.ts", 560], // editor setup + 3 inline Tiptap keymap extensions (macEmacs/smartShiftEnter/submitOnEnter) + editorProps.handleKeyDown for ↑-to-edit + editable-toggle focus-restore (records isFocused before disable on send, re-focuses on re-enable so the WebView blur-on-disable doesn't strand focus on body). Split candidate: extract the 3 keymap extensions to a sibling module (tracked follow-up).
47+
["src/features/messages/ui/MessageComposer.tsx", 820], // media upload handlers (paste, drop, dialog) + channelId reset effect + edit mode (pre-fill, save, cancel, escape) + composer autofocus (#572) + Sprout code-block paste branch (round-trips copy-button output as a literal codeBlock so Markdown can't reshape it) + scroll-to-bottom on multi-line paste (#619) + Slack-style attachment-editable edits: seed pendingImeta from edit target, stash/restore user's draft pendingImeta across edit-mode entry/exit, re-append imeta markdown lines on edit-submit so renderer draws them
4748
["src/features/settings/ui/SettingsView.tsx", 600],
4849
["src/features/sidebar/ui/AppSidebar.tsx", 860], // channels + forums creation forms + Pulse nav
4950
["src/shared/api/relayClientSession.ts", 1040], // durable websocket session manager with reconnect/replay/recovery state + sendTypingIndicator + fetchChannelHistoryBefore + subscribeToChannelLive (huddle TTS) + subscribeToHuddleEvents (huddle indicator) + disconnect() for workspace switch teardown + fetchEvents/subscribeLive/publishEvent for NIP-RS read state + publishUserStatus/subscribeToUserStatusUpdates (NIP-38) + ConnectionState plumbing & stall-watchdog wiring for half-open WS detection (Warp orange-icon case) + terminal session latch (auth rejection no longer racing back to reconnecting) — emitter + watchdog + reconnect policy logic extracted to relayConnectionStateEmitter.ts / relayStallWatchdog.ts / relayReconnectPolicy.ts

‎desktop/src/app/AppShell.tsx‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ export function AppShell() {
175175
const [browseDialogType, setBrowseDialogType] =
176176
React.useState<BrowseDialogType>(null);
177177
const [isNewDmOpen, setIsNewDmOpen] = React.useState(false);
178+
const [isCreateChannelOpen, setIsCreateChannelOpen] = React.useState(false);
178179
const location = useLocation();
179180
const queryClient = useQueryClient();
180181
const {
@@ -522,6 +523,10 @@ export function AppShell() {
522523
setIsNewDmOpen(true);
523524
}, []);
524525

526+
const handleOpenCreateChannel = React.useCallback(() => {
527+
setIsCreateChannelOpen(true);
528+
}, []);
529+
525530
React.useLayoutEffect(() => {
526531
if (settingsOpen) {
527532
return;
@@ -545,6 +550,12 @@ export function AppShell() {
545550
return;
546551
}
547552

553+
if (key === "n" && event.shiftKey) {
554+
event.preventDefault();
555+
handleOpenCreateChannel();
556+
return;
557+
}
558+
548559
if (key === "o" && event.shiftKey) {
549560
event.preventDefault();
550561
handleOpenBrowseChannels();
@@ -565,6 +576,7 @@ export function AppShell() {
565576
}, [
566577
handleOpenBrowseChannels,
567578
handleOpenNewDm,
579+
handleOpenCreateChannel,
568580
handleOpenSearch,
569581
goHome,
570582
settingsOpen,
@@ -688,13 +700,15 @@ export function AppShell() {
688700
isLoading={channelsQuery.isLoading}
689701
isOpeningDm={openDmMutation.isPending}
690702
isNewDmOpen={isNewDmOpen}
703+
isCreateChannelOpen={isCreateChannelOpen}
691704
isPresencePending={presenceSession.isPending}
692705
onAddWorkspace={(workspace) => {
693706
const id = workspacesHook.addWorkspace(workspace);
694707
workspacesHook.switchWorkspace(id);
695708
}}
696709
onAddWorkspaceOpenChange={setIsAddWorkspaceOpen}
697710
onNewDmOpenChange={setIsNewDmOpen}
711+
onCreateChannelOpenChange={setIsCreateChannelOpen}
698712
onOpenAddWorkspace={() => setIsAddWorkspaceOpen(true)}
699713
onUpdateWorkspace={workspacesHook.updateWorkspace}
700714
onRemoveWorkspace={workspacesHook.removeWorkspace}

‎desktop/src/features/channels/ui/ChannelPane.tsx‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,50 @@ export const ChannelPane = React.memo(function ChannelPane({
175175
const mainEditTarget = editTarget && !isEditInThread ? editTarget : null;
176176
const threadEditTarget = editTarget && isEditInThread ? editTarget : null;
177177

178+
// ↑-to-edit resolvers. Find the most recent message authored by the current
179+
// user in the relevant scope and enter edit mode via `onEdit`. Editability
180+
// mirrors the action bar's gate (`message.pubkey === currentPubkey`); we
181+
// also skip optimistic `pending` messages, which have no persisted event id
182+
// to target. Both scopes are passed in chronological (oldest→newest) order,
183+
// so we select by newest `createdAt` and break ties toward the later array
184+
// position (`>=`) — `createdAt` is second-granularity, so a reply sent in
185+
// the same second as the message before it must still win. Returns true when
186+
// a target was found so MessageComposer can swallow the ArrowUp.
187+
const findLastOwnEditable = React.useCallback(
188+
(candidates: TimelineMessage[]): TimelineMessage | null => {
189+
if (!onEdit || !currentPubkey) return null;
190+
let best: TimelineMessage | null = null;
191+
for (const message of candidates) {
192+
if (message.pubkey !== currentPubkey || message.pending) continue;
193+
if (!best || message.createdAt >= best.createdAt) {
194+
best = message;
195+
}
196+
}
197+
return best;
198+
},
199+
[onEdit, currentPubkey],
200+
);
201+
202+
const handleEditLastOwnMainMessage = React.useCallback((): boolean => {
203+
const target = findLastOwnEditable(messages);
204+
if (!target || !onEdit) return false;
205+
onEdit(target);
206+
return true;
207+
}, [findLastOwnEditable, messages, onEdit]);
208+
209+
const handleEditLastOwnThreadMessage = React.useCallback((): boolean => {
210+
if (!onEdit) return false;
211+
// Thread scope = the open thread head plus its replies, in chronological
212+
// order. The head is oldest, so append it first.
213+
const scope: TimelineMessage[] = [];
214+
if (threadHeadMessage) scope.push(threadHeadMessage);
215+
for (const entry of threadMessages) scope.push(entry.message);
216+
const target = findLastOwnEditable(scope);
217+
if (!target) return false;
218+
onEdit(target);
219+
return true;
220+
}, [findLastOwnEditable, onEdit, threadHeadMessage, threadMessages]);
221+
178222
const isNonMemberView =
179223
activeChannel !== null &&
180224
!activeChannel.isMember &&
@@ -330,6 +374,7 @@ export const ChannelPane = React.memo(function ChannelPane({
330374
editTarget={mainEditTarget}
331375
isSending={isSending}
332376
onCancelEdit={onCancelEdit}
377+
onEditLastOwnMessage={handleEditLastOwnMainMessage}
333378
onEditSave={onEditSave}
334379
onSend={onSendMessage}
335380
profiles={profiles}
@@ -391,6 +436,7 @@ export const ChannelPane = React.memo(function ChannelPane({
391436
onClose={onCloseThread}
392437
onDelete={onDelete}
393438
onEdit={onEdit}
439+
onEditLastOwnMessage={handleEditLastOwnThreadMessage}
394440
onEditSave={onEditSave}
395441
onFollowThread={onFollowThread}
396442
onMarkUnread={onMarkUnread}

‎desktop/src/features/messages/lib/useRichTextEditor.ts‎

Lines changed: 82 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,20 @@ export type RichTextEditorOptions = {
4141
/** Called on plain Enter (submit). Handled inside Tiptap's extension system
4242
* so it fires *before* ProseMirror's default splitBlock behaviour. */
4343
onSubmit?: () => void;
44+
/**
45+
* Called on ArrowUp in an empty composer (Slack parity: edit your last
46+
* message). Handled inside ProseMirror's `editorProps.handleKeyDown` — the
47+
* raw DOM keydown hook that runs before any command/caret logic — so it
48+
* fires deterministically even immediately after a send while the editor
49+
* still holds DOM focus (where the keymap plugin and a wrapper-level
50+
* `onKeyDown` both fail to see the event because the WebView's
51+
* vertical-arrow handling consumes it first). The owner should locate the
52+
* most recent message authored by the current user within this composer's
53+
* scope and enter edit mode. Return `true` if a target was found and edit
54+
* mode was entered, so the keystroke is swallowed; return `false` to let
55+
* ArrowUp fall through to normal caret movement.
56+
*/
57+
onEditLastOwnMessage?: () => boolean;
4458
/** When true, plain Enter is passed through (e.g. to select an autocomplete item). */
4559
isAutocompleteOpen?: React.RefObject<boolean>;
4660
};
@@ -61,6 +75,7 @@ export function useRichTextEditor({
6175
mentionNames,
6276
channelNames,
6377
onSubmit,
78+
onEditLastOwnMessage,
6479
isAutocompleteOpen,
6580
}: RichTextEditorOptions) {
6681
const onUpdateRef = React.useRef(onUpdate);
@@ -69,6 +84,9 @@ export function useRichTextEditor({
6984
const onSubmitRef = React.useRef(onSubmit);
7085
onSubmitRef.current = onSubmit;
7186

87+
const onEditLastOwnMessageRef = React.useRef(onEditLastOwnMessage);
88+
onEditLastOwnMessageRef.current = onEditLastOwnMessage;
89+
7290
const placeholderRef = React.useRef(placeholder);
7391
placeholderRef.current = placeholder;
7492

@@ -286,6 +304,44 @@ export function useRichTextEditor({
286304
"min-h-0 resize-none overflow-y-hidden border-0 bg-transparent px-0 py-0 text-sm leading-6 md:leading-6 shadow-none focus-visible:ring-0 caret-foreground outline-hidden prose-sm max-w-none",
287305
"data-testid": "message-input",
288306
},
307+
// ArrowUp in an empty composer → edit your last message (Slack
308+
// parity). Handled here in ProseMirror's own DOM `keydown` hook —
309+
// NOT via `addKeyboardShortcuts` (the keymap plugin) and NOT via a
310+
// wrapper-level React `onKeyDown`.
311+
//
312+
// Why this layer specifically: immediately after a send the editor
313+
// still holds DOM focus and the doc was just cleared. In the app's
314+
// WebView, ProseMirror's keymap/vertical-arrow path does not reliably
315+
// route ArrowUp to our binding in that state — the keystroke is
316+
// effectively swallowed until the user clicks out and back (which is
317+
// exactly the reported bug). `handleKeyDown` is the first, lowest hook
318+
// ProseMirror exposes: it runs on the raw DOM keydown before any
319+
// command/caret logic, fires regardless of selection state, and works
320+
// the same across browser engines. Returning `true` consumes the key.
321+
handleKeyDown: (view, event) => {
322+
if (event.key !== "ArrowUp") return false;
323+
// Respect the same guards as before: no modifiers (let ⌥↑/⇧↑/etc.
324+
// through), autocomplete closed, a handler exists, and the composer
325+
// is empty (never steal the arrow from drafted text or an in-flight
326+
// edit, whose loaded body makes the doc non-empty).
327+
if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey)
328+
return false;
329+
if (isAutocompleteOpen?.current) return false;
330+
const handler = onEditLastOwnMessageRef.current;
331+
if (!handler) return false;
332+
// Emptiness is read straight off the live ProseMirror doc rather
333+
// than a captured `editor` ref — the `editor` instance isn't in
334+
// scope at config time (useEditor deps are `[]`), and the view's
335+
// state is always current. Empty = a single empty textblock with
336+
// no text content (mirrors Tiptap's `editor.isEmpty`).
337+
const { doc } = view.state;
338+
const isEmptyDoc =
339+
doc.childCount <= 1 && doc.textContent.length === 0;
340+
if (!isEmptyDoc) return false;
341+
// Consume only if a target was found and edit mode was entered;
342+
// otherwise let ArrowUp fall through to normal caret movement.
343+
return handler();
344+
},
289345
},
290346
onUpdate: ({ editor: ed }) => {
291347
const markdown = getMarkdownFromEditor(ed);
@@ -301,9 +357,33 @@ export function useRichTextEditor({
301357
);
302358

303359
// Toggle editable without destroying the editor instance.
360+
//
361+
// When the composer is disabled mid-send (`isSending` flips the `disabled`
362+
// prop true), ProseMirror sets the underlying element `contenteditable=false`
363+
// and the browser BLURS it — focus jumps to `document.body`. When the send
364+
// completes and the editor becomes editable again, focus does NOT return on
365+
// its own. That left the just-emptied composer focus-less, so the very next
366+
// ArrowUp (edit-last-message) never reached the editor's keydown hook and
367+
// did nothing until the user clicked back in. We restore focus here, scoped
368+
// to *this* editor instance (we only refocus if this editor was the one that
369+
// lost focus to the disable), so it can't steal focus from another composer.
370+
const hadFocusBeforeDisableRef = React.useRef(false);
304371
React.useEffect(() => {
305-
if (editor && editor.isEditable !== editable) {
306-
editor.setEditable(editable);
372+
if (!editor || editor.isEditable === editable) return;
373+
if (!editable) {
374+
// About to disable: remember whether we currently hold focus so we know
375+
// whether to restore it when re-enabled.
376+
hadFocusBeforeDisableRef.current = editor.isFocused;
377+
editor.setEditable(false);
378+
} else {
379+
editor.setEditable(true);
380+
// Re-enabled: if we owned focus before the disable blurred us, take it
381+
// back (preserving the current selection — `focus()` with no arg keeps
382+
// the existing selection rather than jumping to the end).
383+
if (hadFocusBeforeDisableRef.current) {
384+
hadFocusBeforeDisableRef.current = false;
385+
editor.commands.focus();
386+
}
307387
}
308388
}, [editor, editable]);
309389

‎desktop/src/features/messages/ui/MessageComposer.tsx‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,15 @@ type MessageComposerProps = {
6363
isSending?: boolean;
6464
onCancelEdit?: () => void;
6565
onCancelReply?: () => void;
66+
/**
67+
* Invoked when the user presses ↑ in an empty composer that is not already
68+
* in edit mode. The owner should locate the most recent message authored by
69+
* the current user within this composer's scope (main timeline, DM, or
70+
* thread) and enter edit mode for it. Return `true` if a target was found
71+
* and edit mode was entered, so the composer can swallow the keystroke;
72+
* return `false` to let the arrow key fall through normally.
73+
*/
74+
onEditLastOwnMessage?: () => boolean;
6675
onEditSave?: (content: string, mediaTags?: string[][]) => Promise<void>;
6776
onSend: (
6877
content: string,
@@ -92,6 +101,7 @@ export function MessageComposer({
92101
isSending = false,
93102
onCancelEdit,
94103
onCancelReply,
104+
onEditLastOwnMessage,
95105
onEditSave,
96106
onSend,
97107
placeholder,
@@ -145,12 +155,14 @@ export function MessageComposer({
145155
const isUploadingRef = React.useRef(media.isUploading);
146156
const onSendRef = React.useRef(onSend);
147157
const onEditSaveRef = React.useRef(onEditSave);
158+
const onEditLastOwnMessageRef = React.useRef(onEditLastOwnMessage);
148159
const editTargetRef = React.useRef(editTarget);
149160
disabledRef.current = disabled;
150161
isSendingRef.current = isSending;
151162
isUploadingRef.current = media.isUploading;
152163
onSendRef.current = onSend;
153164
onEditSaveRef.current = onEditSave;
165+
onEditLastOwnMessageRef.current = onEditLastOwnMessage;
154166
editTargetRef.current = editTarget;
155167

156168
const isAutocompleteOpenRef = React.useRef(false);
@@ -183,6 +195,13 @@ export function MessageComposer({
183195
mentionNames: mentions.knownNames,
184196
channelNames: channelLinks.knownChannelNames,
185197
onSubmit: () => submitMessageRef.current(),
198+
onEditLastOwnMessage: () => {
199+
// Never re-enter edit from an empty edit (e.g. image-only edit whose
200+
// text body is empty) — `editTarget` means we're already editing.
201+
if (editTargetRef.current) return false;
202+
const handler = onEditLastOwnMessageRef.current;
203+
return handler ? handler() : false;
204+
},
186205
isAutocompleteOpen: isAutocompleteOpenRef,
187206
onUpdate: ({ markdown, text }) => {
188207
setContent(markdown);

‎desktop/src/features/messages/ui/MessageThreadPanel.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ type MessageThreadPanelProps = {
4141
onClose: () => void;
4242
onDelete?: (message: TimelineMessage) => void;
4343
onEdit?: (message: TimelineMessage) => void;
44+
onEditLastOwnMessage?: () => boolean;
4445
onEditSave?: (content: string, mediaTags?: string[][]) => Promise<void>;
4546
onMarkUnread?: (message: TimelineMessage) => void;
4647
onExpandReplies: (message: TimelineMessage) => void;
@@ -98,6 +99,7 @@ export function MessageThreadPanel({
9899
onClose,
99100
onDelete,
100101
onEdit,
102+
onEditLastOwnMessage,
101103
onEditSave,
102104
onFollowThread,
103105
onMarkUnread,
@@ -353,6 +355,7 @@ export function MessageThreadPanel({
353355
isSending={isSending}
354356
onCancelEdit={onCancelEdit}
355357
onCancelReply={composerReplyTarget ? onCancelReply : undefined}
358+
onEditLastOwnMessage={onEditLastOwnMessage}
356359
onEditSave={onEditSave}
357360
onSend={onSend}
358361
placeholder={`Reply in thread to ${threadHead.author}`}

‎desktop/src/features/sidebar/ui/AppSidebar.tsx‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,8 @@ type AppSidebarProps = {
161161
isPresencePending?: boolean;
162162
isNewDmOpen?: boolean;
163163
onNewDmOpenChange?: (open: boolean) => void;
164+
isCreateChannelOpen?: boolean;
165+
onCreateChannelOpenChange?: (open: boolean) => void;
164166
};
165167

166168
// ---------------------------------------------------------------------------
@@ -410,6 +412,8 @@ export function AppSidebar({
410412
isPresencePending,
411413
isNewDmOpen: isNewDmOpenProp,
412414
onNewDmOpenChange,
415+
isCreateChannelOpen: isCreateChannelOpenProp,
416+
onCreateChannelOpenChange,
413417
}: AppSidebarProps) {
414418
const skeletonRows = ["first", "second", "third", "fourth", "fifth", "sixth"];
415419
const [isNewDmOpenInternal, setIsNewDmOpenInternal] = React.useState(false);
@@ -420,6 +424,17 @@ export function AppSidebar({
420424
const [profilePopoverOpen, setProfilePopoverOpen] = React.useState(false);
421425
const [createDialogKind, setCreateDialogKind] =
422426
React.useState<CreateChannelKind | null>(null);
427+
428+
// Allow the create-channel dialog to be opened from outside (e.g. the
429+
// ⌘⇧N global shortcut in AppShell), mirroring the controlled new-DM lift.
430+
// When the external flag flips on, open the "stream" create dialog; the
431+
// close direction is reported back via `onCreateChannelOpenChange` in the
432+
// dialog's `onOpenChange` below.
433+
React.useEffect(() => {
434+
if (isCreateChannelOpenProp) {
435+
setCreateDialogKind("stream");
436+
}
437+
}, [isCreateChannelOpenProp]);
423438
const [collapsedGroups, setCollapsedGroups] = React.useState<
424439
Record<CollapsibleSidebarGroup, boolean>
425440
>({
@@ -808,7 +823,14 @@ export function AppSidebar({
808823
channelKind={createDialogKind}
809824
isCreating={isCreatingAny}
810825
onOpenChange={(open) => {
811-
if (!open) setCreateDialogKind(null);
826+
if (!open) {
827+
// If a "stream" dialog driven by the external controller is
828+
// closing, report it back so AppShell's open state resets.
829+
if (createDialogKind === "stream") {
830+
onCreateChannelOpenChange?.(false);
831+
}
832+
setCreateDialogKind(null);
833+
}
812834
}}
813835
onCreate={handleCreateFromDialog}
814836
/>

0 commit comments

Comments
 (0)