diff --git a/.bb/plugins.json b/.bb/plugins.json index ecd7eab5..6cc7d055 100644 --- a/.bb/plugins.json +++ b/.bb/plugins.json @@ -20,6 +20,7 @@ { "name": "slack", "source": "./plugins/slack" }, { "name": "review-watch", "source": "./plugins/review-watch" }, { "name": "pr-board", "source": "./plugins/pr-board" }, - { "name": "voice-transcription", "source": "./plugins/voice-transcription" } + { "name": "voice-transcription", "source": "./plugins/voice-transcription" }, + { "name": "tmux-vim", "source": "./plugins/tmux-vim" } ] } diff --git a/.github/workflows/plugins.yaml b/.github/workflows/plugins.yaml index 6b47b3f7..f0cb8854 100644 --- a/.github/workflows/plugins.yaml +++ b/.github/workflows/plugins.yaml @@ -17,7 +17,7 @@ jobs: strategy: fail-fast: false matrix: - plugin: [devbox-provider, github-watcher, html-preview, image-copy, kubernetes-provider, pr-board, pr-inbox, review-watch, stewards, team-setup, thread-briefs, workstreams] + plugin: [devbox-provider, github-watcher, html-preview, image-copy, kubernetes-provider, pr-board, pr-inbox, review-watch, stewards, team-setup, thread-briefs, tmux-vim, workstreams] defaults: run: working-directory: plugins/${{ matrix.plugin }} diff --git a/README.md b/README.md index e43fa386..e356b814 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ Plugins for [bb](https://getbb.app), maintained by Bit Complete. | [review-watch](plugins/review-watch) | Queues the GitHub pull requests that need your review and opens a thread for one when you press Start | | [pr-board](plugins/pr-board) | A plain-language board of your open GitHub pull requests: what can merge, what needs you, and who you wait on | | [voice-transcription](plugins/voice-transcription) | Adds a voice-input service that transcribes through any OpenAI-compatible `/audio/transcriptions` endpoint from the server process | +| [tmux-vim](plugins/tmux-vim) | A tmux-style prefix key and vim-style keys for panes, threads and the sidebar, with a thread chooser, copy mode and pane resizing | Install one: diff --git a/plugins/tmux-vim/.gitignore b/plugins/tmux-vim/.gitignore new file mode 100644 index 00000000..1eae0cf6 --- /dev/null +++ b/plugins/tmux-vim/.gitignore @@ -0,0 +1,2 @@ +dist/ +node_modules/ diff --git a/plugins/tmux-vim/PLUGIN_OVERVIEW.md b/plugins/tmux-vim/PLUGIN_OVERVIEW.md new file mode 100644 index 00000000..4f84ce4f --- /dev/null +++ b/plugins/tmux-vim/PLUGIN_OVERVIEW.md @@ -0,0 +1,61 @@ +Move around bb without the mouse, using the keys you already know from tmux +and vim. + +## What you get + +- A **prefix key** (default `Ctrl-a`) followed by one key: `h` `j` `k` `l` to + move between panes, `Option-h` `j` `k` `l` to resize the focused pane (the + same keys work again without the prefix for a second), `v` or `s` to open a + thread, or start a new one, in a new pane to the right or below, `w` to open + one in the current pane, `c` for a new thread in the current pane, `z` to + zoom, `x` to close, `1` to `9`, `n` and `p` to switch threads, `?` for help. +- `Ctrl-h/j/k/l` to move between panes and into the sidebar without the prefix. +- **Browsing keys** while you are not typing: `j` `k` `Ctrl-d` `Ctrl-u` `gg` + `G` to scroll, `/` to find, `:` for the command palette, `H` `L` to switch + threads, `i` to type a message, `Space e` to toggle the sidebar, `,ff` for + the thread chooser and `,fg` for thread search. +- A **copy mode** like tmux's, for selecting conversation text without the + mouse: enter it with `v` or with the prefix then `[`, move with `h` `j` `k` + `l`, `w` `b` `e`, `0` `$`, `gg` `G` and more, press `v` to start selecting, + `y` to copy and `Escape` to leave. +- **Copy on select** (on by default): text you select with the mouse in a + conversation is copied when you release the button. The setting + `copyOnSelect` turns it off. +- A **thread chooser** popup and **sidebar keys**: `j` `k` to move, `Enter`, + `v` or `s` to open the thread here, to the right or below. When the chooser + was opened to split, its first row is **New thread**: `Enter` on it, or `c` + from any row, starts a new thread in the new pane. + +## How it works + +One key listener decides for every key press whether the cursor is in a text +field, the terminal, a dialog or a menu, and leaves the key alone there. Only +the prefix key and `Ctrl-h/j/k/l` are taken while you type; press the prefix +twice to send it through. The prefix key, the leader key, the timeouts and +where the keys apply can be changed under Settings, Installed plugins, or with +`bb plugin config tmux-vim set `. + +Copying puts on the clipboard (where copied text waits until you paste it) +what `Cmd-C` would, because the plugin runs the browser's own Copy command. +If the browser refuses, the text is copied without formatting instead. Copy +mode works in conversations only, and a keyboard selection is lost when bb +unloads that part of a long conversation. + +The plugin needs no account or network access. Several actions rely on bb's +page structure, last checked against the source code of bb 0.50.1, and may +need an update after a bb upgrade. Keys do not work while the cursor is inside +the embedded browser page, and "open below" also opens the thread in your +other bb windows. bb gives plugins no way to open a new pane with the New +thread screen in it, so a new thread in a new pane shows one of your existing +threads there for a moment before the New thread screen replaces it. bb's Back +button shows that thread again. bb has no call for resizing a pane either, so +the plugin imitates a mouse drag on the line between two panes; the steps are +coarse because bb pulls that line onto an even split when it comes close, and +nothing is resized while a pane is zoomed. The default keys were chosen for +macOS; on Windows and Linux `Ctrl-j`, `Ctrl-k`, `Ctrl-d` and `Ctrl-a` take +over shortcuts of bb itself unless you change the settings. + +## For agents + +The bundled `tmux-vim` skill lists the keys, the settings and the known limits, +so an agent can answer questions about this plugin or change a setting for you. diff --git a/plugins/tmux-vim/README.md b/plugins/tmux-vim/README.md new file mode 100644 index 00000000..3fcb9fde --- /dev/null +++ b/plugins/tmux-vim/README.md @@ -0,0 +1,894 @@ +# Tmux + Vim keys for bb + +A bb plugin (an add-on that bb loads next to its own code) that lets you drive +bb from the keyboard the way you drive tmux and vim: + +- a tmux-style **prefix key** (default `Ctrl-a`) followed by one more key, for + moving between panes, resizing them, splitting, zooming, closing and + switching threads; +- `Ctrl-h/j/k/l` to move between panes and into the sidebar without the prefix; +- vim-style **browsing keys** (`j`, `k`, `gg`, `G`, `/`, `:` and more) that are + active only while you are not typing; +- a **copy mode** like the one in tmux: move a cursor through a conversation + with the keyboard, select text with `v` and copy it with `y`; +- **copy on select**: text you select with the mouse in a conversation is + copied as soon as you release the button; +- a **thread chooser**, a popup that lists your threads so you can open one in + the current pane or in a new pane, or start a new thread in a new pane. + +It was written against bb desktop 0.49.0 and last checked against the source +code of bb desktop 0.50.1 (see "Tied to bb's inner workings" under "Known +limits" for what that check covered). The default keys were chosen for macOS; +on Windows and Linux some of them take over shortcuts of bb itself (see "Known +limits"). + +## Words used here + +- **Thread**: one conversation with an agent. +- **Pane**: one of the side-by-side or stacked areas that each show a thread. + bb allows up to 8 panes. +- **Focused pane**: the pane bb treats as current. New threads open there. +- **Divider**: the thin line between two panes. Dragging it with the mouse + makes one pane bigger and the other smaller. +- **Sidebar**: the thread list on the left. +- **Message box**: the text field where you type a message to the agent (bb + calls it the composer). +- **Prefix key**: a key you press first to tell the plugin "the next key is a + command". It is how tmux works. A small pill showing the prefix appears at the + bottom of the window while the plugin waits for the next key. +- **Leader key**: the first key of a longer vim-style sequence, here `,`. +- **Command palette**: bb's searchable list of commands. +- **Clipboard**: where the computer keeps copied text until you paste it. +- **Selection**: the highlighted text that a copy takes. +- **Copy mode**: a state in which the keys move a cursor through the text of a + conversation instead of scrolling it, so you can select and copy without the + mouse. tmux has the same thing under the same name. + +## Keys + +### After the prefix + +Press `Ctrl-a`, release it, then press the key. The plugin waits 3 seconds for +the second key (setting `prefixTimeoutMs`). These work everywhere except inside +a dialog, a menu or the embedded browser page. + +| Keys | What happens | +| --- | --- | +| `Ctrl-a` `h` or `Left` | Focus the pane to the left. From the leftmost pane, or with a single pane, focus the sidebar thread list. | +| `Ctrl-a` `j` or `Down` | Focus the pane below. | +| `Ctrl-a` `k` or `Up` | Focus the pane above. | +| `Ctrl-a` `l` or `Right` | Focus the pane to the right. | +| `Ctrl-a` `v` | Open the thread chooser. The thread you pick opens in a new pane to the right of the focused pane. The first row, New thread, starts a new thread in that new pane instead. | +| `Ctrl-a` `s` | Open the thread chooser. The thread you pick opens in a new pane below. The first row, New thread, starts a new thread in that new pane instead. | +| `Ctrl-a` `w` | Open the thread chooser. The thread you pick opens in the focused pane. | +| `Ctrl-a` `c` | Start a new thread in the focused pane. If another pane already shows the New thread screen, bb moves to that pane instead. | +| `Ctrl-a` `z` | Zoom the focused pane to fill the split area, or undo the zoom. | +| `Ctrl-a` `x` | Close the focused pane. In the pane you land in, the cursor goes where it was when you left that pane (see "Without the prefix" below). | +| `Ctrl-a` `Option-h` | Resize the focused pane by moving its divider to the left (see "Resizing panes" below). | +| `Ctrl-a` `Option-j` | Resize the focused pane by moving its divider down. | +| `Ctrl-a` `Option-k` | Resize the focused pane by moving its divider up. | +| `Ctrl-a` `Option-l` | Resize the focused pane by moving its divider to the right. | +| `Ctrl-a` `1` to `9` | Jump to thread 1 to 9 (see "Thread order" below). | +| `Ctrl-a` `n` | Go to the next thread. Wraps around at the end. | +| `Ctrl-a` `p` | Go to the previous thread. Wraps around at the start. | +| `Ctrl-a` `[` | Enter copy mode in the focused pane (see "Copy mode" below). | +| `Ctrl-a` `?` | Show the key help. | +| `Ctrl-a` `Ctrl-a` | Send `Ctrl-a` itself to the terminal or text field that has focus. | +| `Ctrl-a` `Escape` | Cancel the prefix. | + +Any other key after the prefix cancels the prefix and is not passed on. A +dead key, or a key that an input method turns into text, cancels the prefix as +well, but that key is passed on (see "Dead keys" under "Resizing panes"). + +### Resizing panes + +`Ctrl-a` then `Option-h`, `Option-j`, `Option-k` or `Option-l` moves a divider +by 48 pixels (setting `resizeStepPx`). On Windows and Linux the key is Alt. +Holding Shift as well makes no difference. + +- **Which divider moves.** As in tmux, `Option-h` and `Option-l` move the + divider on the right edge of the focused pane, and `Option-j` and `Option-k` + the one on its bottom edge. A pane at the right end or at the bottom has no + such divider, so the one on its left or top edge moves instead. The key + only says which way the divider goes. Example: with two panes side by side, + `Option-l` makes the left pane wider when the left pane is focused, and + makes the right pane narrower when the right pane is focused. When the + focused pane has no divider that can go that way, for example `Option-j` + with panes that are only side by side, nothing happens. +- **Repeating.** For one second after a resize (setting `repeatTimeoutMs`) + the four keys work again without the prefix, as repeatable keys do in tmux, + and every resize starts that second again. The prefix pill stays on screen + for as long as this lasts. You can also hold the key down. Any other key + ends it at once and is then handled as usual, so nothing you type is lost. + Without the prefix and outside that second, `Option-h/j/k/l` are never + taken: in a text field they type their usual characters. + The second only starts when the focused pane has a divider that the key + moves. A divider that is already as far that way as bb lets it go counts, + so you can still press the opposite key without the prefix. When there is + no such divider (a single pane, a zoomed pane, or `Option-j` with panes + that are only side by side), the pill disappears at once and the four keys + type their usual characters again. + +Known limits of resizing: + +- **The steps are coarse.** While a divider is dragged, bb pulls it onto the + line that splits its row or column evenly as soon as it comes within 12 + pixels of that line. A step that ends there is therefore up to 12 pixels + longer or shorter than you asked for. This is also why `resizeStepPx` + cannot be set below 32: a step has to be clearly longer than the reach of + that pull. A press that bb would pull straight back to where the divider + already is does nothing. +- **Nothing happens while a pane is zoomed.** bb hides the dividers then, and + a message says so. Undo the zoom with `Ctrl-a` `z` first. With a single pane + a message says that there is nothing to resize. +- **Nothing happens while the conversation is hidden.** bb lets you widen + the side panel of a thread until its conversation is hidden. The panes are + then still there but have no width, so the plugin leaves them alone and + shows no message. +- **Sizes follow bb's own minimums.** bb wants every pane to have 15 percent + or more of its row (panes side by side) or of its column (stacked panes). + Once a pane is that small, the key that would shrink it further does + nothing: no message is shown and bb is sent nothing. Example: with three + panes side by side in a row of 1200 pixels, a pane stops at 180 pixels. + A step that would go past that size stops at it, so it can be shorter than + `resizeStepPx`. + The plugin has to keep to this size itself. During a mouse drag bb only + holds a pane at 15 percent of the two panes beside the divider, which is + less in a row of three or more panes. The next time any divider of that + row moves, bb brings the pane back up to 15 percent of the row and takes + the room from the other panes, so dividers that nobody touched move. Three + things follow from that: + - A pane that a mouse drag left below 15 percent of its row is brought + back by bb on the next resize in that row, also one from the keyboard, + and another divider moves to make room. That is bb's doing. + - A divider can stop up to 13 pixels short of the smallest size. That + happens where bb's even-split line lies just past that size and would + pull the divider over it. + - In a row or column of seven or eight panes no pane can have 15 percent. + bb then makes the other panes of that row equal again whenever a divider + in it moves, with the mouse as well. +- **It imitates a mouse drag.** bb has no shortcut, command or plugin call + for resizing a pane. So the plugin sends bb's divider the same three events + a mouse drag would: a press, a move and a release. A bb update can break + this. If bb's code fails on those events and the pane has not changed, a + message says that resizing did not work in this version of bb. It is shown + once until the window is reloaded. This was checked by reading bb's source + code, not by running the desktop app. +- **bb sees a mouse press.** It reacts as it does to a click on a divider: + thread rows that you selected in the sidebar (Shift-click or Cmd-click) are + no longer selected afterwards, and an open suggestion popup of the message + box (the list that appears after you type `@` or `/`) closes, as it does + on any click outside the message box. A press that moves nothing, because + the pane is at its smallest size or has no divider that way, sends bb no + mouse press and has neither effect. +- **A held key needs the repeat to start in time.** A keyboard waits a moment + before it starts repeating a held key. If that wait is longer than + `repeatTimeoutMs`, holding the key resizes only once. Raise the setting or + press the key again. +- **Dead keys.** On a keyboard layout where one of these Option combinations + is a dead key (a key that waits for the next letter to put an accent on + it), the plugin does not see that key and cannot resize in that direction. + A dead key pressed after the prefix, or during the second in which the + keys repeat, cancels the prefix or ends that second: the pill disappears + and the keys you press next are typed as usual. That matters when a finger + slips onto a dead key next to `h`, `j`, `k` or `l`. The dead key itself + still reaches the text field, because the plugin cannot take it back. The + same goes for a key that an input method (for example one for Japanese) + turns into text. +- **On a Mac the resize keys go by the place of the key, not by its + letter.** With Option held, a key types a symbol and not its letter, so + the plugin cannot read the letter. It goes by where the key is: the four + places where `h`, `j`, `k` and `l` are on a US keyboard. On a layout that + puts those letters elsewhere, such as Dvorak or Colemak, press the keys in + those four places. Example: on Dvorak the key that types `h` sits where + `j` is on a US keyboard, so Option with that key resizes down. On Windows + and Linux, Alt leaves the letter as it is, so there the keys follow the + letters. Every other key of the plugin follows the letters everywhere. + +### Without the prefix + +| Keys | What happens | +| --- | --- | +| `Ctrl-h` | Focus the pane to the left, or the sidebar from the leftmost pane. | +| `Ctrl-j` | Focus the pane below. | +| `Ctrl-k` | Focus the pane above. | +| `Ctrl-l` | Focus the pane to the right. | + +By default these work everywhere except inside the terminal, where the shell +keeps them (setting `ctrlHjkl`). They are off inside dialogs and menus. + +Each pane remembers whether you were typing when you left it, the way every +tmux pane keeps the mode of the vim that runs in it. This README calls the two +states insert mode (the cursor is in the text field of the pane's message +box) and browsing mode (it is not, so the browsing keys below work). + +- **A pane you left in insert mode.** When a key of this plugin brings you + back to it, the cursor is in its message box again and you can go on + typing. Example: you write a message in the left pane, press `Ctrl-l` to + read something in the right pane, and press `Ctrl-h`. The cursor is back in + the message box of the left pane. +- **A pane you left in browsing mode, or have not been in yet.** The cursor + rests on the pane itself, not in the message box, so the browsing keys + work at once. Press `i` to type. + +What counts is where the cursor was when you left the pane, however you left +it: with a key of this plugin, with a click on another pane or on the +sidebar, by opening a dialog or by switching to another window. `Escape` in +the message box, a click on the conversation of the same pane, or entering +copy mode from the message box takes the cursor out of the message box +first, so the pane is then in browsing mode. The same goes for a pane you +come back to without going into its message box. Example: you type in the +left pane, click the conversation of the right pane, and click the +conversation of the left pane again. You are now browsing in the left pane, +so that is what it remembers when you leave it the next time. + +Only the text field of the message box is insert mode. On the buttons beside +it, such as Send, Stop or the model picker, the browsing keys work, so a pane +you leave from one of them is in browsing mode. The small editor that bb +opens in place when you change a message you already sent, or one that is +still queued, is not the message box either: a pane you leave from there is +in browsing mode too. + +Closing a pane follows the same rule. After `Ctrl-a` `x` the cursor is in the +message box of the pane you land in if you left that pane in insert mode, +and on the pane itself otherwise. + +The memory belongs to the thread that the pane shows: + +- When the pane is switched to another thread, that thread starts in browsing + mode. +- When a thread is no longer shown in any pane, what was remembered for it is + dropped. It starts in browsing mode when you open it again. +- When a thread ends up in another pane, for example after you dragged one + pane onto the middle of another to swap the two, it starts in browsing mode + there. +- Nothing is remembered across a reload of the window, or while the plugin + is unloaded. + +Four details: + +- While bb shows a question of the agent in place of the message box, the + message box cannot take the cursor. The cursor then rests on the pane, and + the pane counts as browsing from then on: when you come back to it later, + the cursor rests on the pane again until you press `i` or click the message + box. +- The plugin puts the cursor back by giving it to the text field itself. + The text cursor is then meant to be at the place in your draft where you + were typing, with any text you had selected there still selected. The + browser only keeps that place while its selection is still in the draft. + It is not after you clicked or selected text somewhere else in the + meantime, or used copy mode, and after bb has drawn the message box anew, + for example for the pane that stays when `Ctrl-a` `x` closes the other of + two panes. The plugin then asks bb to put the cursor in the message box, + and bb always puts the text cursor at the end of your draft. This part was + checked by reading bb's code and by tests against a copy of bb's page. It + was not tried in the running desktop app, and those tests cannot show what + a real browser does with the text cursor. +- bb puts the cursor in the message box of a thread by itself when the thread + appears. When bb starts with several panes, the cursor therefore passes + through one message box after the other. A pane that the cursor only passed + through that way, with no key or mouse press of yours in between, does not + count as left in insert mode. +- With the setting `focusAfterPaneMove` set to `composer`, nothing is + remembered: the cursor always goes to the message box. + +With two or more panes, the focused pane has a thin border around the whole +pane. It follows the pane bb treats as current, so it stays while you type in +the message box and after you leave it with `Escape`. + +A thread that a key of this plugin puts in a pane (`Ctrl-a` `1` to `9`, `n`, +`p`, `H`, `L`, the chooser, the sidebar keys) starts in browsing mode: the +cursor rests on the pane. bb itself puts the cursor in the message box a +moment after a thread appears, so the plugin moves it back to the pane until +the message box has been there for about a second and a half. A click, `i`, +`Tab` or a bb shortcut with Ctrl, Alt or Cmd ends that at once. When the +thread is already shown in another pane, the same keys do not open it again: +they move you to that pane, and the cursor goes where it was when you left +that pane. When you open a thread with the mouse, the plugin does not step in +and the cursor ends in the message box as usual. + +### Browsing + +These need the setting `vimKeys` (on by default). They act only when the +cursor is **not** in a text field, the message box, the terminal, a dialog or a +menu, so they never get in the way of typing. + +| Keys | What happens | +| --- | --- | +| `j` / `k` | Scroll the conversation down / up by `scrollStepPx` pixels. Hold the key to keep scrolling. | +| `Ctrl-d` / `Ctrl-u` | Scroll down / up half a page. | +| `gg` | Scroll to the top of the conversation. | +| `G` | Scroll to the bottom of the conversation. | +| `/` | Open bb's find-in-thread bar (desktop app only). | +| `i` | Put the cursor in the message box of the focused pane. | +| `v` | Enter copy mode (see "Copy mode" below). | +| `:` | Open bb's command palette. | +| `H` / `L` | Go to the previous / next thread. | +| `Space` `e` | Show or hide the sidebar. | +| `,` `f` `f` | Open the thread chooser (the thread opens in the focused pane). | +| `,` `f` `g` | Open bb's thread search. | + +The scrolling keys, `/` and `v` need a pane that shows a thread. On the New +thread screen only `i`, `:`, `H`, `L`, `Space e`, `,ff` and `,fg` are active. On +Settings and plugin pages none of the browsing keys are active, and the pane +moves do nothing there because no pane is on screen (`Ctrl-h` still goes to +the sidebar). Multi-key sequences such as `gg` wait 1 second for the next key +(setting `sequenceTimeoutMs`). + +A held key repeats only for scrolling, for moving through the sidebar, for +moving the cursor in copy mode and for resizing a pane. Any other key you +hold after the prefix, or the key that closed the chooser or the key help, is +not typed into whatever has the cursor next. + +To leave the message box and get back to the browsing keys, press `Escape`. +That is bb's own behaviour, not this plugin's: `Escape` first closes an open +suggestion menu, and otherwise takes the cursor out of the message box. While +you are editing a message you already sent, `Escape` cancels the edit instead. + +### Copy mode + +Copy mode lets you select and copy text of a conversation with the keyboard. +It follows tmux's copy mode with vi keys: `v` starts the selection, `y` copies +it and leaves, `Escape` leaves without copying. + +To enter it, press `v` while you are browsing a conversation (this needs +`vimKeys`), or `Ctrl-a` `[`, which also works from the message box and with +`vimKeys` off. A small pill at the bottom of the window shows `COPY`, and a +block marks the cursor. +If you had selected text in that conversation and the end of that selection is +on screen, the cursor starts there. Otherwise it starts at the beginning of +the last line you can see, as in tmux. When you enter from the message box, +the terminal or the sidebar, the keyboard focus moves to the pane, so the next +keys are not typed there. + +| Keys | What happens | +| --- | --- | +| `h` / `l` or `Left` / `Right` | Move one character left / right. | +| `j` / `k` or `Down` / `Up` | Move one line down / up. | +| `w` | Move to the start of the next word. | +| `b` | Move to the start of the previous word. | +| `e` | Move to the end of the word. | +| `0` or `^` | Move to the start of the line. | +| `$` | Move to the end of the line. | +| `{` / `}` | Move to the previous / next paragraph. | +| `gg` / `G` | Move to the first / last text of the conversation. | +| `H` / `M` / `L` | Move to the top / middle / bottom line you can see. | +| `Ctrl-d` / `Ctrl-u` | Move half a page down / up. | +| `v` | Start selecting at the cursor. The pill changes to `VISUAL`. Press `v` again to drop the selection and stay in copy mode. | +| `y` or `Enter` | Copy the selection and leave copy mode. A message says "Selection copied". | +| `Escape` or `q` | Leave copy mode without copying. The selection is cleared. | + +While you are selecting, every move stretches the selection from the place +where you pressed `v` to the cursor. The conversation scrolls by itself when +the cursor leaves the part you can see. The cursor never leaves the +conversation of the pane where you entered copy mode. + +`y` before `v` copies nothing and tells you to press `v` first. + +The block marks the character that comes after the cursor. That character is +not part of the selection until the cursor has moved past it. This differs +from tmux and vim, where `v` followed at once by `y` copies one character: +here it copies nothing and tells you to move the cursor first. Press `l` once +to take the character under the block. + +While copy mode is on: + +- Any other key without Ctrl, Alt or Cmd does nothing, so a slip of the finger + does not scroll, switch threads or type. +- Keys with Ctrl, Alt or Cmd go to bb as usual. `Cmd-C` still copies the + selection. +- The prefix key and `Ctrl-h/j/k/l` work as usual and end copy mode. +- On a focused button or link, `Space` and `Enter` still press it. Use `y` to + copy there. + +Copy mode ends by itself when you press a mouse button, when the window loses +focus or is hidden, when another key of this plugin does something else (a +pane move, a resize, the chooser, a thread switch, the key help), when the +cursor goes +into a text field, the terminal or a dialog, when the pane stops showing a +conversation, and when the plugin is paused or unloaded. It also ends, without +a message, when bb itself shows another thread in the pane, for example after +bb's own shortcut for the next thread: the next key you press then works as a +browsing key again. + +bb shows its own small "Add to chat" menu next to text selected inside one +message. It appears for a keyboard selection too. Clicking it ends copy mode +and keeps the selection, so the button gets the text you selected, as it does +after a mouse selection. + +### In the sidebar + +These are active while a thread row in the sidebar has keyboard focus, which +is what `Ctrl-h` or `Ctrl-a` `h` gives you. A focused row gets a visible +outline. + +A row that you clicked with the mouse does not count: it is treated as an +ordinary link, so `j` and `k` keep scrolling the conversation, and `Enter` and +`Escape` go to bb. Press `Ctrl-h` to move into the sidebar from there. While +rows are selected (bb's multi-selection with Shift-click or Cmd-click), the +first `Escape` goes to bb and clears the selection. + +| Keys | What happens | +| --- | --- | +| `j` / `k` or `Ctrl-j` / `Ctrl-k` | Move to the next / previous thread row. | +| `gg` / `G` | Move to the first / last thread row. | +| `Enter` | Open that thread in the focused pane. | +| `v` | Open that thread in a new pane to the right. | +| `s` | Open that thread in a new pane below. | +| `l`, `Escape` or `Ctrl-l` | Go back to the focused pane. | + +Going to the sidebar and back follows the same rule as a move between panes. +If the cursor was in the message box when you pressed `Ctrl-h` (or `Ctrl-a` +`h`), it is in the message box again after `l`, `Escape` or `Ctrl-l`. If it +was not, it rests on the pane. `Enter`, `v` and `s` open a thread, which +starts in browsing mode unless it is already shown in a pane (see "Without +the prefix" above). + +With `vimKeys` on, `:`, `H`, `L`, `Space e`, `,ff` and `,fg` work here too. + +### In the thread chooser + +The chooser lists every thread that is not archived, most recent activity +first. Its first line says what `Enter` will do. Marks at the end of a row +show `focused pane`, `in a pane`, `running`, `unread` and `child thread`. +bb shows a thread in at most one pane, so picking a thread that is already +in a pane moves you to that pane. + +When the chooser was opened to split (`Ctrl-a` `v` or `Ctrl-a` `s`), the list +starts with one extra row, **New thread**. It is the highlighted row when the +chooser opens, so `Enter` at once starts a new thread in a new pane. The row +is hidden while the filter field holds text, so `Enter` after filtering still +opens the first matching thread. The chooser opened with `Ctrl-a` `w` or `,ff` +never has this row, and `c` does nothing there: `Ctrl-a` `c` already starts a +new thread in the focused pane. + +| Keys | What happens | +| --- | --- | +| `j`, `Down` or `Ctrl-n` | Move down the list. | +| `k`, `Up` or `Ctrl-p` | Move up the list. | +| `gg` / `G` | First / last row. | +| `Enter` | Open the highlighted thread the way the chooser was opened (this pane, right or below). On the New thread row: start a new thread in a new pane, to the right or below as the chooser was opened. | +| `v` | Open the highlighted thread in a new pane to the right. On the New thread row: start a new thread there. | +| `s` | Open the highlighted thread in a new pane below. On the New thread row: start a new thread there. | +| `c` | Only after `Ctrl-a` `v` or `Ctrl-a` `s`: start a new thread in a new pane, to the right or below as the chooser was opened, whichever row is highlighted. | +| `/` | Move to the filter field and type to filter by title or project name. | +| `Escape` or `q` | Close the chooser. | + +While the filter field has focus: type to filter, `Down` / `Up` or `Ctrl-n` / +`Ctrl-p` move, `Enter` opens the highlighted thread, and `Escape` returns to the +list and keeps the filter text. `c` is typed as text there. While the field is +empty the New thread row is still in the list, and `Enter` on it starts a new +thread. + +#### How a new thread gets its own pane + +bb gives plugins no call that opens a new pane with the New thread screen in +it. bb itself can do that (hold Cmd or Ctrl and click New thread in the +sidebar), but the calls a plugin may use only open a new pane with an existing +thread in it. So the plugin takes two steps: + +1. It opens the new pane with one of your threads in it. That thread only + stands in for a moment; this README calls it the placeholder thread. +2. As soon as bb shows the new pane, the plugin turns that pane into the New + thread screen and puts the cursor in its message box, as `Ctrl-a` `c` does. + +The placeholder is a thread that is not shown in any pane. bb marks a thread +as read once it is on screen, and again when new activity arrives while it is +on screen. So the plugin picks the thread that loses the least by being shown +for a moment, in this order: + +1. the most recent thread that has no unread messages and is not running; +2. a running thread that has no unread messages; +3. any other thread, which then has unread messages. + +What this means in practice is listed under "Known limits". + +### In the key help + +`Ctrl-a` `?` opens a list of every key with your current settings applied. +`j` / `k` scroll it, and `Escape` or `q` closes it. On a Mac it calls the Alt +key Option, as this README does, and on Windows and Linux it calls it Alt. +For the resize keys it also says for how long they work without the prefix. + +## Copying with the mouse + +When you select text in a conversation with the mouse and release the button, +the plugin copies it and shows "Selection copied". tmux does the same when its +mouse mode is on. A double click on a word and a triple click on a paragraph +count as well. + +- Only text of a conversation is copied this way. Text in the message box, in + other text fields, in the terminal and in dialogs is left alone. +- Only a selection that this press of the mouse button made or changed is + copied, and the press has to start on the conversation. A selection that was + already there stays as it is when you click somewhere that leaves it alone, + such as the sidebar or a button. That goes for text you selected from the + keyboard, for text selected while the plugin was paused, and for the word + that a right click selects on macOS: none of them is copied by a later + click. +- The clipboard holds what `Cmd-C` would have put there, because the plugin + runs the browser's own Copy command and bb decides what a copy of message + text contains. +- The selection stays highlighted, so bb's "Add to chat" menu still works. + Clicking it does not copy a second time. +- Nothing is copied while the plugin is paused or `enabled` is off. + +Turn this off with the setting `copyOnSelect`. + +## Thread order + +`Ctrl-a` `1` to `9`, `Ctrl-a` `n` / `p` and `H` / `L` need an order for your +threads. With the setting `threadOrder` set to `sidebar` (the default) they +follow the sidebar from top to bottom, so thread 1 is the first row of the +sidebar. With `recent` they follow the chooser's order, most recent activity +first. If the sidebar cannot be read (for example on a Settings page), the +plugin uses the last order it read, and falls back to `recent` when it has +none. + +## Command palette commands + +The plugin adds three commands to bb's command palette. They have no keyboard +shortcut of their own; you can give them one in bb's keyboard settings. + +- **Tmux Vim: Open thread chooser** - the same as `Ctrl-a` `w`. +- **Tmux Vim: Show keys** - the same as `Ctrl-a` `?`. +- **Tmux Vim: Pause or resume keys in this window** - turns every key of this + plugin off, or on again, in the current window only. Pausing also ends copy + mode and stops the mouse copy. A short message tells you which state you are + now in. Use it when the keys get in your way. The + pause also ends when the window is reloaded, and when the plugin is unloaded + and loaded again (`bb plugin disable` then `enable`, or `bb plugin reload` + after its code changed). `bb plugin reload` with unchanged code does not + restart the plugin in open windows, so the pause stays. + +To turn the plugin's keys off in every window, switch off the `enabled` +setting instead. + +## Settings + +Change a setting in bb under Settings, Installed plugins, Tmux + Vim keys, or +from a terminal: + +``` +bb plugin config tmux-vim # show the current values +bb plugin config tmux-vim set # change one +bb plugin config tmux-vim set prefixKey ctrl+b +bb plugin config tmux-vim set ctrlHjkl not-typing +bb plugin config tmux-vim unset prefixKey # back to the default +``` + +Changes reach the open windows right away; no reload is needed. + +| Key | Default | Allowed values | What it does | +| --- | --- | --- | --- | +| `enabled` | `true` | `true`, `false` | Turns every key of this plugin on or off. | +| `prefixKey` | `ctrl+a` | A key with Ctrl, Alt or Cmd, or a function key | The prefix key. Write it like `ctrl+b`, `Ctrl-B`, `C-b`, `alt+x`, `cmd+k` or `f12`. A plain key such as `a` is refused and `ctrl+a` is used, because a plain prefix would be taken away from typing. A prefix on `alt+h`, `alt+j`, `alt+k` or `alt+l` takes that key away from resizing, because the prefix pressed twice sends the key itself: resize that way with Shift held as well (`Option-Shift-h` and so on). The key help then lists only the form that works. | +| `prefixTimeoutMs` | `3000` | 300 to 60000 | How long, in milliseconds, the prefix waits for the next key. | +| `sequenceTimeoutMs` | `1000` | 200 to 10000 | How long a sequence such as `gg` or `,ff` waits for its next key. | +| `ctrlHjkl` | `all-but-terminal` | `all-but-terminal`, `everywhere`, `not-typing`, `off` | Where `Ctrl-h/j/k/l` move between panes. `not-typing` leaves them alone in text fields, the message box and the terminal. | +| `vimKeys` | `true` | `true`, `false` | Turns the browsing keys on or off. The prefix keys, `Ctrl-h/j/k/l` and the sidebar's own keys (`j`, `k`, `gg`, `G`, `Enter`, `v`, `s`, `l`, `Escape`) stay on. | +| `leaderKey` | `,` | One key | The first key of `,ff` and `,fg`. Write `space` for the space bar. A key that already does something on its own (`j`, `k`, `G`, `/`, `:`, `H`, `L`, `i`, `v`, `s`, `l`, `Enter`, `Escape`) is refused and `,` is used. | +| `threadOrder` | `sidebar` | `sidebar`, `recent` | The order used by `1` to `9`, `n` / `p` and `H` / `L`. | +| `focusAfterPaneMove` | `pane` | `pane`, `composer` | Where the cursor goes after you move to a pane. `pane`: on the pane, so the browsing keys work at once, except in a pane that you left while typing, where it goes back to the message box. `composer`: always in the message box. | +| `scrollStepPx` | `80` | 10 to 2000 | How many pixels `j` and `k` scroll. | +| `copyOnSelect` | `true` | `true`, `false` | Copies conversation text as soon as you finish selecting it with the mouse. Copy mode works either way. | +| `resizeStepPx` | `48` | 32 to 400 | How many pixels one resize moves a divider. | +| `repeatTimeoutMs` | `1000` | 200 to 5000 | How long, in milliseconds, `Option-h/j/k/l` keep resizing without the prefix after a resize. | + +In `prefixKey` the modifier names are `ctrl` (or `control`), `alt` (or +`option`), `cmd` (or `command`, `meta`) and `shift`. The short forms are `C-` +for Ctrl, `M-` for Alt, `D-` for Cmd and `S-` for Shift. + +## Where the keys stay out of the way + +The plugin looks at where the cursor is before it handles a key: + +- In a **dialog, menu or popup** it handles nothing, so those keep their own + keys. The chooser and the key help are dialogs with their own keys. The one + exception is bb's "Add to chat" menu next to selected text: it never takes + the cursor, so the keys go on working while it shows. bb shows that menu for + text selected in a conversation, in the terminal, in a file preview and in + the diff view. +- In the **terminal** only the prefix key is taken (and `Ctrl-h/j/k/l` if you + set `ctrlHjkl` to `everywhere`). Press the prefix twice to send it to the + shell. +- In the **message box and other text fields** only the prefix key and + `Ctrl-h/j/k/l` are taken. Everything else is typed as usual. +- For **one second after a resize**, `Option-h/j/k/l` resize again, also in + a text field or the terminal (see "Resizing panes"). A key pressed inside a + dialog, a menu or the embedded browser page ends that second early, and so + does a dead key. The prefix pill shows for as long as it lasts. A press + that found no divider to move does not start that second. +- On a **focused button or link**, `Space` and `Enter` still press it. +- **Until bb has loaded your settings** (a moment after a window opens, and on + screens outside bb's main layout, such as its setup guide) the plugin + handles no key at all and copies nothing, so it never acts on defaults you + changed. The same holds when bb cannot read the settings at all, which + happens while the server part of the plugin is not running. Once the + settings have arrived, the plugin keeps using the last ones it got. + +## Known limits + +- **Embedded browser.** While the cursor is inside a web page in bb's Browser + tab, or inside any other embedded frame, no key reaches the plugin. Click + outside the page first. +- **The chooser can be hidden by the Browser tab.** The Browser tab is drawn on + top of everything else in the window. The chooser moves to the left of it, + but if the Browser tab fills most of the window the chooser can be covered. + `Escape` still closes it. +- **Split below affects other windows.** `Ctrl-a` `s` (and `s` in the sidebar + and chooser) uses bb's public "open in a pane below" call, which bb sends to + every open bb window and device. Each of them opens the thread too. Splitting + to the right stays in the current window. A new thread below goes through + the same call, so your other bb windows get a new pane with the placeholder + thread in it, and it stays there: only the window you pressed the key in + turns that pane into the New thread screen. +- **A new thread in a new pane shows another thread first.** For a moment the + new pane shows the placeholder thread (see "How a new thread gets its own + pane"). If every thread that could be the placeholder is unread, the one + that is used can lose its unread mark. If the only read threads left are + running, one of them is used, and activity that arrives in the moment it is + shown is marked as read. The plugin waits 1.5 seconds for a pane to the + right and 3 seconds for a pane below. If the pane has not shown up by then, + a message says "Could not open the new pane." and nothing more happens; a + pane that arrives later keeps the placeholder thread. If bb's server refuses + to open the pane below, the message is "Could not open the new pane below." + and the plugin stops waiting at once. +- **bb's Back button shows the placeholder thread.** Each of the two steps + adds an entry to bb's Back and Forward history, and the plugin has no call + that avoids it. So right after a new thread in a new pane, bb's Back button + shows the placeholder thread in the pane that has the focus, which is the + new pane unless you moved to another one. Forward brings the New thread + screen back. +- **The placeholder thread shows its conversation again.** bb lets you widen + the side panel of a thread until its conversation is hidden. The call that + opens a pane to the right always brings the conversation back, and bb + remembers that for the thread. So a placeholder thread whose conversation + you had hidden shows it again the next time you open it. A pane below does + not have this effect. +- **A New thread screen that appears while the plugin waits.** If another pane + turns into the New thread screen before the new pane is ready, for example + because you pressed `Ctrl-a` `c` in that moment, bb moves you to that + screen, the new pane keeps the placeholder thread and a message says so. +- **No new pane from Settings or the Plugins page.** Such a page shows no + panes. bb keeps your panes hidden behind it, and the plugin cannot see what + they show. The New thread row therefore opens nothing there and says "This + page shows no panes, so no new pane was opened." Go back to a thread first, + or press `Ctrl-a` `c`. +- **Only one New thread screen.** bb shows the New thread screen in at most + one pane of a window. If a pane already shows it, the New thread row opens + no pane: you are moved to that pane, the cursor goes to its message box and + a message says why. +- **A new thread when every thread is already in a pane.** Then there is no + placeholder (this is also the case when the focused pane shows your only + thread). The plugin swaps instead: the focused pane becomes the New thread + screen and the thread it showed moves to the new pane. You get the new pane + either way, but the New thread screen sits where the thread was and the + thread sits in the new pane. With a split below, your other bb windows open + that thread in a pane below too, or move to the pane that already shows it. + If the focused pane shows no thread either, for example a plugin page, a + message says that there is no thread to open the new pane with. + The swap takes the thread out of its pane before the new pane exists. If + the new pane then cannot be opened (bb's server refused, or the pane did not + show up in time), the plugin puts the thread back in its pane and the + message ends with "The thread is back in its pane." It does not put the + thread back while you are typing, or when another pane has the focus by + then, because that would replace what you are looking at. The message then + ends with "The thread that was in the pane is closed. Open it again from + the sidebar." You get the same message when you press a mouse button before + the plugin could ask for the new pane: the press stops the swap, as it stops + every wait for a new pane. +- **Zoom follows focus.** bb keeps the zoom on whichever pane has focus. If you + move to another pane while zoomed, that pane becomes the zoomed one. The + plugin undoes the zoom before it splits a pane. +- **Collapsed sidebar groups are skipped.** With `threadOrder` set to + `sidebar`, threads inside a collapsed group, or moved under "More", are not + reached by `1` to `9`, `n` / `p` or `H` / `L`. The chooser still lists them. +- **`Ctrl-h/j/k/l` replace text editing keys.** In text fields these keys + normally edit text (for example `Ctrl-k` deletes to the end of the line on + macOS). Set `ctrlHjkl` to `not-typing` to keep them for editing. With + `ctrlHjkl` set to `off`, `Ctrl-j`, `Ctrl-k` and `Ctrl-l` are off in the + sidebar too; `j`, `k`, `l` and `Escape` still work there. +- **Windows and Linux.** bb's own shortcuts use Cmd on macOS and Ctrl + elsewhere, so on Windows and Linux the default keys of this plugin collide + with them. The plugin sees the key first and bb's shortcut does not run: + `Ctrl-k` (bb: thread search) and `Ctrl-j` (bb: show or hide the side panel) + move between panes instead, everywhere except in the terminal; `Ctrl-l` + (bb: go to the address bar of the Browser tab) does the same in the Browser + tab's toolbar; `Ctrl-d` (the git plugin: toggle diff) scrolls half a page + while you are not typing; and the first `Ctrl-a` in a text field arms the + prefix instead of selecting all (press it twice). To keep bb's shortcuts, + set `ctrlHjkl` to `off` and move `prefixKey` to a free key such as `ctrl+b`. + `Ctrl-d` and `Ctrl-u` can only be given back by turning `vimKeys` off, or by + binding bb's commands to other keys in bb's keyboard settings. +- **`Space` waits.** While the browsing keys are active, `Space` is the start + of `Space e`, so on its own it does nothing. +- **Some keys depend on bb's own shortcuts.** `:` and `,fg` work by triggering + bb's keyboard shortcut for that command, because bb offers no other way to + run it. If you removed that shortcut in bb's keyboard settings, the plugin + tells you the key cannot work. `/` needs the desktop app. +- **Copy mode only works in conversations.** It selects the conversation of + the focused pane and nothing else: not the terminal, the message box, the + side panel, Settings or plugin pages. Where the focused pane shows no + conversation, such as the New thread screen, `Ctrl-a` `[` shows a message + and `v` does nothing. The mouse copy is limited to conversation text as + well. +- **Copy mode moves the way the browser does.** The plugin moves the cursor + with the browser's own text navigation + ([Selection.modify](https://developer.mozilla.org/en-US/docs/Web/API/Selection/modify)). + What counts as a word for `w`, `b` and `e`, or as a paragraph for `{` and + `}`, follows the browser's rules, which differ from vim's in places (for + example around punctuation). `0` and `^` both go to the start of the line. + Before `v`, `j` and `k` do not remember the column you started in after + crossing a shorter line. +- **A selection can be lost in a long conversation.** bb only keeps the + messages near the visible part loaded. `gg` and `G` therefore reach the first + and last text that is loaded; press them again to go further. If the place + where you pressed `v`, or the text under the cursor, is unloaded or redrawn + (as in a message that is still being written), copy mode ends and a message + says the selection was lost. +- **bb's "Add to chat" menu shows up for keyboard selections.** It appears + next to any text selected inside one message, as it does after a mouse + selection. While it shows, bb switches off its own keyboard shortcuts, and + `Escape` does not help: bb shows the menu again as soon as the key is + released. `:`, `,fg` and `/` work by triggering those shortcuts, so when + bb refuses one of them because of that menu, the plugin drops the selection, + waits a moment for bb to close the menu and tries again. The text you + selected is no longer highlighted afterwards. Text selected in the terminal + cannot be dropped this way; there the three keys still show a message until + you click to clear the selection. +- **Characters typed with Option.** On some keyboard layouts `[`, `{` or `}` + need the Option key (on a German Mac keyboard they are Option-5, Option-8 + and Option-9). The plugin accepts such a key press as the character it + types, but only when that character is one of its keys and the Option + combination itself is not. Every other Option combination is passed on to + bb as a shortcut, also in copy mode. On Windows and Linux this applies to + characters typed with AltGr; Alt alone always counts as a shortcut there. + `^` is a dead key on some layouts (it waits for the next letter); use `0` + instead. The four resize keys, `Option-h/j/k/l`, are taken only after the + prefix and in the second after a resize; at any other time they are passed + on like every other Option combination. +- **Copying uses an old browser command.** To put on the clipboard what + `Cmd-C` would, the plugin calls the browser's Copy command + ([document.execCommand](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand)), + which browsers mark as deprecated (kept for old pages, may be removed one + day). If the browser refuses it, the plugin copies through bb's plugin API + instead, which gives plain text without formatting. If both fail, a message + says "Could not copy the selection". +- **The cursor block can be off in places.** At the end of a line it is a thin + bar. Inside a code block that scrolls sideways it can be drawn over the text + next to the block, and it only follows the text again on the next key or + scroll after the page layout shifts. +- **At most 8 panes.** bb's limit. The plugin tells you instead of replacing a + pane. +- **Narrow windows.** Below 768 pixels wide bb shows a single pane and turns + the sidebar into a drawer that behaves like a dialog, so there are no panes + to move between and the sidebar keys do not work there. The New thread row + of the chooser opens nothing there and says that the window is too narrow, + because bb would show the placeholder thread in place of what you were + looking at. Use `Ctrl-a` `c` instead. +- **Restart.** bb saves your pane layout itself. On a fresh start the desktop + app opens the New thread screen, which replaces the thread of the pane that + had focus when you quit; the plugin reopens that one thread once. bb loads + plugins a moment after that screen appears, so the plugin only does this + while you have not clicked or typed in the window yet. If you have, it + leaves the New thread screen alone, so that it never takes the screen away + while you are writing a message. If the plugin was switched off for a while + and is switched on again while the New thread screen is showing in a window + you have not touched yet, it can reopen the thread it last remembered. + Only the first bb window is repaired: a second window or browser tab that + you open while another one is open keeps its New thread screen. To tell, + the plugin uses the browser's Web Locks API. That API is missing on a page + that is served neither over HTTPS nor from localhost; there every new window + is treated as the first one and gets the repair. With several windows open + at quit, all of them share one remembered layout, the one that changed last. +- **Tied to bb's inner workings.** bb has no public API for several of these + actions (closing a pane, focusing a pane, resizing a pane, scrolling, + reading the sidebar order), so the plugin reads bb's page structure and + clicks bb's own buttons. Those details were first read from bb 0.49.0, + except the ones for resizing and the mark that tells the message box of a + pane from the editor of a sent message, which were read from bb 0.50.1. + For bb 0.50.1 + they were checked by reading its source code and comparing it with 0.49.0: + every name in `src/constants.ts` is still there and means the same. One thing + bb does differently in 0.50.1 matters here and is handled: it loads plugins + only after the first screen is shown (see "Restart" above). The same check + showed that bb puts its "Add to chat" menu on the page itself when the + selected text is in the terminal, a file preview or the diff view, which the + plugin now allows for. All of this can change in any bb release. After a bb + upgrade some keys may stop working until `src/constants.ts` is updated. When + the plugin cannot find the parts of bb it needs, it writes one warning to + the developer console, and a key that fails shows a short message. The + check for 0.50.1 was done by reading code, and the automated tests run + against a copy of bb's page structure, not against the running desktop app. + +## Install, reload and remove + +Installing a plugin lets its code run inside bb with full trust, so only +install it from a source you trust. From the bb-plugins repository: + +``` +bb plugin install git:https://github.com/bitcomplete/bb-plugins.git@main --plugin tmux-vim +``` + +Or from a checkout of this folder: + +``` +npm install # once, fetches the build and test tools +bb plugin install . # asks for confirmation, then loads the plugin +``` + +If the folder lives inside a bb-managed workspace, `bb plugin install` prints a +note: bb will later copy the plugin into its own data folder and run it from +there. Keep the source somewhere outside bb's data folder to avoid that. + +After changing the source: + +``` +bb plugin reload tmux-vim # rebuild and reload in every open window +bb plugin dev # or: rebuild and reload on every save +``` + +To stop using it: + +``` +bb plugin disable tmux-vim # unload it, keep the settings +bb plugin enable tmux-vim # load it again +bb plugin remove tmux-vim # remove it and delete its settings +``` + +`bb plugin remove` leaves this source folder on disk. + +## For developers + +Run these four checks before installing or after any change: + +``` +npx tsc --noEmit # type check +npx vitest run --config vitest.config.ts # unit and integration tests +bb plugin build # bundle into dist/ +bb plugin types --check # SDK version matches the running bb +``` + +How the code is laid out: + +- `app.tsx` registers the three parts bb needs to know about: the content + script, the app overlay and the palette commands. A **content script** is + plain page code that bb runs once per window. An **app overlay** is a React + component that bb mounts once per window. +- `src/content-script.ts` is the single key listener. For each key press it + asks `src/focus-context.ts` where the cursor is, lets the state machine in + `src/machine.ts` decide, and passes the result to `src/actions.ts`. +- `src/keys.ts` turns a key press into a name such as `C-a`, and + `src/keymap.ts` builds the key tables from the settings. +- `src/pane-mode.ts` remembers which panes were left while typing, and the + text field the cursor was in. It listens for the cursor entering and + leaving the text field of a message box, and for the cursor or a mouse + press landing elsewhere in a pane. `src/pane-focus.ts` asks it where the + cursor belongs after a pane move. +- `src/actions.ts`, `src/pane-focus.ts` and `src/open-thread.ts` carry out the + actions. `src/new-thread.ts` starts a new thread in a new pane for the + chooser: it opens the placeholder thread, waits for bb to show the new pane + and then turns it into the New thread screen. It also puts the thread back + when a swap cannot finish. `src/dom-actions.ts` and + `src/bb-commands.ts` hold everything that depends on bb's page structure and + shortcuts. +- `src/pane-resize.ts` resizes a pane: it finds the divider next to the + focused pane, works out how far bb lets that divider go, and sends it the + events of a mouse drag. +- `src/copy-mode.ts` is the copy mode engine: it keeps the cursor and the + place where the selection started, moves them with the browser's + `Selection.modify`, and works out where to draw the cursor block. + `src/clipboard.ts` does the copying, and `src/copy-on-select.ts` is the mouse + feature. +- `src/overlay/` is the visible part: the prefix pill, the copy mode pill and + cursor block, the chooser, the key help and the messages. + `src/overlay/BridgePublisher.tsx` copies the values of bb's React hooks into + `src/bridge.ts`, where the plain functions above read them. +- `src/restore.ts` and `src/overlay/cold-start.ts` reopen the lost thread after + a restart. `src/overlay/window-presence.ts` tells whether another bb window + is open. +- `src/constants.ts` holds every selector, event name and command id that was + read from bb's source. It is the first file to check after a bb upgrade. +- `server.ts` declares the settings. `app.test.tsx` runs the whole plugin + against a copy of bb's page structure. diff --git a/plugins/tmux-vim/app.css b/plugins/tmux-vim/app.css new file mode 100644 index 00000000..4b880a97 --- /dev/null +++ b/plugins/tmux-vim/app.css @@ -0,0 +1,23 @@ +/* + * Global, not scoped to the plugin. The selectors mirror SELECTORS.sidebarRow, + * SELECTORS.focusedThreadPane and SELECTORS.paneFocusScrim in + * src/constants.ts, and src/overlay/app-css.test.ts fails when they drift + * apart. + * + * The pane border follows bb's own focused-pane mark, not keyboard focus, so + * it stays while the cursor is in the message box. It is drawn on bb's overlay + * for the pane, because an outline on the pane itself is covered by the pane's + * header and content and its top edge sits under the window's title strip. + * The overlay of the focused pane is see-through, so lifting it above the + * pane header (z-index 21 in bb) changes nothing else. + */ + +a[data-sidebar-thread-shortcut-target][data-sidebar-thread-id]:focus-visible { + outline: 2px solid var(--ring); + outline-offset: -2px; +} + +[data-split-pane-id][data-focused="true"]:not([aria-hidden="true"]):not([data-sidebar-split-container] *) > [data-pane-focus-scrim] { + z-index: 26; + box-shadow: inset 0 0 0 1px var(--ring); +} diff --git a/plugins/tmux-vim/app.test.tsx b/plugins/tmux-vim/app.test.tsx new file mode 100644 index 00000000..23b1368d --- /dev/null +++ b/plugins/tmux-vim/app.test.tsx @@ -0,0 +1,3512 @@ +// @vitest-environment jsdom +import type { PluginSidebarSplitLayout } from "@get-bb/plugin-sdk/app"; +import { collectPluginAppRegistrations } from "@get-bb/plugin-sdk/internal/plugin-app-collector"; +import { experimental_makePanelController } from "@get-bb/plugin-sdk/testing"; +import { + loadPluginApp, + mountPluginContentScripts, + renderSlot, + type MountedPluginContentScripts, + type PluginSdkTestFakes, + type RenderedSlot, +} from "@get-bb/plugin-sdk/testing/app"; +import { + act, + cleanup, + fireEvent, + screen, + waitFor, +} from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + findBinding, + setKeybindings, + type AppKeybinding, +} from "./src/bb-commands"; +import { getBridge, getUiState, resetStore, setBridge } from "./src/bridge"; +import { + BB_COMMANDS, + PLUGIN_LOCKS, + PLUGIN_STORAGE_KEYS, +} from "./src/constants"; +import { noteSidebarPointerDown } from "./src/dom-actions"; +import { cancelPendingNewThread } from "./src/new-thread"; +import { + installFakeLocks, + makeProject, + makeThread, + removeFakeLocks, +} from "./src/overlay/test-support"; +import { cancelPendingFocus } from "./src/pane-focus"; +import { resetPaneResize } from "./src/pane-resize"; +import { resetThreadOrderCache } from "./src/thread-order"; + +const app = await loadPluginApp(() => import("./app")); +const { default: definition } = await import("./app"); +const commands = collectPluginAppRegistrations(definition).commandPaletteActions; + +const IDLE_THREAD = { + status: "idle", + createdAt: 1, + parentThreadId: null, + isUnread: false, +} as const; + +const THREADS = [ + makeThread("thr-1", { + ...IDLE_THREAD, + displayTitle: "Alpha", + latestAttentionAt: 300, + }), + makeThread("thr-2", { + ...IDLE_THREAD, + displayTitle: "Beta", + latestAttentionAt: 200, + }), + makeThread("thr-3", { + ...IDLE_THREAD, + displayTitle: "Gamma", + latestAttentionAt: 100, + }), +]; + +const PROJECTS = [makeProject("proj-1", "Website")]; + +const TWO_PANES: PluginSidebarSplitLayout = { + panes: [ + { + paneId: "pane-1", + threadId: "thr-1", + isFocused: true, + rect: { x: 0, y: 0, width: 0.5, height: 1 }, + }, + { + paneId: "pane-2", + threadId: "thr-2", + isFocused: false, + rect: { x: 0.5, y: 0, width: 0.5, height: 1 }, + }, + ], +}; + +const THREAD_ROUTE = "/projects/proj-1/threads/thr-1"; +const NEW_THREAD_ROUTE = "/"; + +// A copy of the bb 0.50.1 markup the plugin reads: the sidebar with its thread +// rows, two thread panes, a message box, a terminal and an unrelated text field. +const BB_PAGE = ` +
+
+
+ Alpha + Beta + Gamma +
+
+
+ +
+
+ +
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+ +`; + +const PLAIN_KEYS = [ + "j", + "k", + "g", + "G", + "/", + ":", + "H", + "L", + "i", + " ", + ",", + "f", + "e", + "1", + "?", + "v", + "s", + "x", + "Enter", + "Escape", + "Backspace", + "Tab", + "ArrowLeft", +]; + +const TYPING_CHORDS: KeyboardEventInit[] = [ + { key: "d", ctrlKey: true }, + { key: "u", ctrlKey: true }, + { key: "c", ctrlKey: true }, + { key: "k", metaKey: true }, + { key: "ArrowLeft", altKey: true }, +]; + +const HJKL = ["h", "j", "k", "l"]; + +// Three messages of one line each, as ThreadTimelineRows.tsx lays them out +// inside the conversation scroller. +const CONVERSATION = ` +
+

alpha beta gamma

+

delta epsilon

+

zeta eta theta

+
+`; + +// Nine messages of one line each, enough to tell the top, the middle and the +// bottom of the view apart. +const LONG_CONVERSATION = ` +
+ ${["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] + .map( + (word, index) => + `

message ${word}

`, + ) + .join("")} +
+`; + +// bb's "Add to chat" menu as TimelineSelectionMenu.tsx renders it: a Radix +// popover shown next to selected text. In a conversation it sits inside the +// scroller. For the terminal, a file preview and the diff view it sits on the +// page body. +const BB_SELECTION_MENU = ` +
+
+ +
+
+`; + +// Another bb popover, as NotificationCenter.tsx renders it on the page body. +const BB_OTHER_POPOVER = ` +
+
+ +
+
+`; + +// bb's own test for an open dialog, from AppCommandProvider.tsx. +const BB_OPEN_MODAL = + '[aria-modal="true"]:not([inert]):not([inert] *):not([data-state="closed"]), [role="dialog"][data-state="open"]:not([inert]):not([inert] *)'; + +const NOTHING_SELECTED_NOTICE = + "Nothing is selected yet. Move the cursor, then press y to copy"; + +const CHAR_WIDTH = 8; +const LINE_HEIGHT = 20; +const TEXT_LEFT = 40; +const FIRST_LINE_TOP = 100; +const COPIED_NOTICE = "Selection copied"; + +let page: HTMLElement; +let view: RenderedSlot; +let mounted: MountedPluginContentScripts; +let pageListeners: AbortController; +let threadsOpen: ReturnType; +let threadsPaneAction: ReturnType; +let consoleError: ReturnType; +let consoleWarn: ReturnType; +let execCommand: ReturnType boolean>>; +let copiedTexts: string[]; + +function fixture(testId: string): HTMLElement { + const element = page.querySelector(`[data-testid="${testId}"]`); + if (element === null) throw new Error(`fixture ${testId} is missing`); + return element; +} + +function sidebarRow(threadId: string): HTMLElement { + const row = page.querySelector( + `[data-sidebar-thread-id="${threadId}"]`, + ); + if (row === null) throw new Error(`sidebar row ${threadId} is missing`); + return row; +} + +function pane(paneId: string): HTMLElement { + const element = page.querySelector( + `[data-split-pane-id="${paneId}"]`, + ); + if (element === null) throw new Error(`pane ${paneId} is missing`); + return element; +} + +function focusedPaneViewport(): HTMLElement { + const viewport = pane("pane-1").querySelector( + "[data-page-scroll-viewport]", + ); + if (viewport === null) throw new Error("the timeline viewport is missing"); + return viewport; +} + +function press( + init: KeyboardEventInit, + target: EventTarget = document.body, +): KeyboardEvent { + const event = new KeyboardEvent("keydown", { + bubbles: true, + cancelable: true, + ...init, + }); + act(() => { + target.dispatchEvent(event); + }); + return event; +} + +function pressKey(key: string, target?: EventTarget): KeyboardEvent { + return press({ key }, target); +} + +function pressCtrl(key: string, target?: EventTarget): KeyboardEvent { + return press({ key, ctrlKey: true }, target); +} + +// settings: null stands for a bb that has no values for the plugin, which is +// what it reports while the server part of the plugin is not running. +interface OverlayOptions { + layout?: PluginSidebarSplitLayout | null; + contextThreadId?: string | null; + composerThreadId?: string; + settings?: Record | null; + keybindings?: readonly AppKeybinding[]; +} + +function renderOverlay(options: OverlayOptions = {}): void { + const layout = options.layout === undefined ? TWO_PANES : options.layout; + const contextThreadId = + options.contextThreadId === undefined ? "thr-1" : options.contextThreadId; + const keybindings = options.keybindings ?? []; + threadsOpen = vi.fn(async () => ({ delivered: 1 })); + threadsPaneAction = vi.fn(async () => ({ delivered: 1 })); + const sdk = { + system: { config: async () => ({ keybindings }) }, + subscribe: () => () => {}, + threads: { open: threadsOpen, paneAction: threadsPaneAction }, + } as unknown as PluginSdkTestFakes; + view = renderSlot( + app.appOverlays[0], + {}, + { + sidebarThreads: { threads: THREADS, projects: PROJECTS }, + sidebarSplitLayout: layout ?? undefined, + context: { projectId: "proj-1", threadId: contextThreadId }, + composer: { + scope: { kind: "thread", threadId: options.composerThreadId ?? "thr-1" }, + }, + settings: options.settings === null ? undefined : (options.settings ?? {}), + sdk, + }, + ); +} + +function storedSnapshot(): { savedAt: number } | null { + const raw = window.localStorage.getItem(PLUGIN_STORAGE_KEYS.layoutSnapshot); + return raw === null ? null : JSON.parse(raw); +} + +async function mountContentScripts(): Promise { + mounted = await mountPluginContentScripts(app, { pluginId: "tmux-vim" }); +} + +async function mountPlugin(options: OverlayOptions = {}): Promise { + renderOverlay(options); + await mountContentScripts(); +} + +// The test harness cannot change the layout after a navigation the way bb +// does, so the new layout is published straight into the bridge. +function bbFocusesThread(threadId: string): void { + const bridge = getBridge(); + if (bridge === null) throw new Error("the bridge was not published"); + const showsThread = bridge.layout?.panes.some( + (layoutPane) => layoutPane.threadId === threadId, + ); + const panes = bridge.layout?.panes.map((layoutPane) => { + if (showsThread) { + return { ...layoutPane, isFocused: layoutPane.threadId === threadId }; + } + return layoutPane.isFocused ? { ...layoutPane, threadId } : layoutPane; + }); + setBridge({ + ...bridge, + context: { ...bridge.context, threadId }, + layout: panes === undefined ? null : { panes }, + }); + for (const layoutPane of panes ?? []) { + pane(layoutPane.paneId).setAttribute( + "data-focused", + String(layoutPane.isFocused), + ); + } +} + +// As above: the layout bb has once it opened the thread in a new pane and +// focused that pane. +function bbOpensPane(threadId: string): void { + const bridge = getBridge(); + if (bridge === null) throw new Error("the bridge was not published"); + const panes = (bridge.layout?.panes ?? []).map((layoutPane) => ({ + ...layoutPane, + isFocused: false, + })); + const newPane = { + paneId: "pane-new", + threadId, + isFocused: true, + rect: { x: 0, y: 0.5, width: 1, height: 0.5 }, + }; + setBridge({ + ...bridge, + context: { ...bridge.context, threadId }, + layout: { panes: [...panes, newPane] }, + }); +} + +// As above: the layout bb has once the focused pane shows the New thread +// screen in place of its thread. +function bbShowsNewThreadScreenInFocusedPane(): void { + const bridge = getBridge(); + if (bridge === null) throw new Error("the bridge was not published"); + const panes = (bridge.layout?.panes ?? []).map((layoutPane) => + layoutPane.isFocused ? { ...layoutPane, threadId: null } : layoutPane, + ); + setBridge({ + ...bridge, + context: { ...bridge.context, threadId: null }, + layout: { panes }, + }); +} + +function afterFrames(count: number): Promise { + return new Promise((resolve) => { + const tick = (left: number): void => { + if (left === 0) { + resolve(); + return; + } + requestAnimationFrame(() => tick(left - 1)); + }; + tick(count); + }); +} + +function clickWithMouse(element: HTMLElement): void { + element.dispatchEvent(new Event("pointerdown", { bubbles: true })); + element.focus(); +} + +function bbShortcut(command: string, key: string): AppKeybinding { + return { + command, + desktopOnly: false, + shortcut: { + key, + mod: false, + meta: false, + control: false, + alt: true, + shift: false, + }, + when: { all: [], none: [] }, + }; +} + +// Stands in for bb's own shortcut handler: it claims the Alt shortcut of each +// binding, as bb does for a command it ran, and records the command id. +function listenForBbShortcuts(bindings: readonly AppKeybinding[]): string[] { + const ran: string[] = []; + window.addEventListener( + "keydown", + (event) => { + const binding = bindings.find( + ({ shortcut }) => event.altKey && event.key === shortcut.key, + ); + if (binding === undefined) return; + event.preventDefault(); + ran.push(binding.command); + }, + { signal: pageListeners.signal }, + ); + return ran; +} + +async function mountPluginWithBbShortcuts( + bindings: readonly AppKeybinding[], +): Promise { + await mountPlugin({ keybindings: bindings }); + await waitFor(() => + expect(findBinding(bindings[0].command)).not.toBeNull(), + ); + return listenForBbShortcuts(bindings); +} + +function onEvent(element: HTMLElement, type: string): ReturnType { + const listener = vi.fn(); + element.addEventListener(type, listener, { signal: pageListeners.signal }); + return listener; +} + +function setScrollMetrics( + viewport: HTMLElement, + metrics: { clientHeight: number; scrollHeight: number }, +): void { + for (const [name, value] of Object.entries(metrics)) { + Object.defineProperty(viewport, name, { configurable: true, value }); + } +} + +async function runCommand(id: string): Promise { + const command = commands.find((candidate) => candidate.id === id); + if (command?.target !== "app") throw new Error(`no app command ${id}`); + await act(async () => { + await command.run({ + threadId: "thr-1", + projectId: "proj-1", + experimental_panel: experimental_makePanelController(), + }); + }); +} + +function chooserList(): HTMLElement { + return screen.getByRole("listbox", { name: "Threads" }); +} + +function pageSelection(): Selection { + const selection = document.getSelection(); + if (selection === null) throw new Error("the document has no selection"); + return selection; +} + +function lineText(testId: string): Text { + const text = fixture(testId).firstChild; + if (!(text instanceof Text)) throw new Error(`line ${testId} has no text`); + return text; +} + +function conversationLines(): Text[] { + const lines = focusedPaneViewport().querySelectorAll("[data-timeline-row-id] p"); + return Array.from(lines, (line) => line.firstChild).filter( + (node): node is Text => node instanceof Text, + ); +} + +// jsdom has no layout, so every message is one line of fixed-width characters. +function fakeClientRects(this: Range): DOMRect[] { + const index = conversationLines().indexOf(this.startContainer as Text); + if (index === -1) return []; + const length = + this.endContainer === this.startContainer + ? this.endOffset - this.startOffset + : 0; + return [ + new DOMRect( + TEXT_LEFT + this.startOffset * CHAR_WIDTH, + FIRST_LINE_TOP + index * LINE_HEIGHT, + length * CHAR_WIDTH, + LINE_HEIGHT, + ), + ]; +} + +function fakeCaretPositionFromPoint( + x: number, + y: number, +): { offsetNode: Node; offset: number } | null { + if (y < FIRST_LINE_TOP) return null; + const line = conversationLines()[Math.floor((y - FIRST_LINE_TOP) / LINE_HEIGHT)]; + if (line === undefined) return null; + const offset = Math.round((x - TEXT_LEFT) / CHAR_WIDTH); + return { offsetNode: line, offset: Math.min(line.length, Math.max(0, offset)) }; +} + +function wordSpans(line: Text): { start: number; end: number }[] { + return Array.from(line.data.matchAll(/\S+/g), (match) => ({ + start: match.index, + end: match.index + match[0].length, + })); +} + +// As macOS does it: forward to the end of a word, backward to its start. +function wordStep(line: Text, offset: number, step: 1 | -1): number | null { + const words = wordSpans(line); + if (step === 1) return words.find((word) => word.end > offset)?.end ?? null; + return words.filter((word) => word.start < offset).at(-1)?.start ?? null; +} + +// Stands in for the browser's Selection.modify. Every message is one line and +// one paragraph. A step that has nowhere to go does nothing, as in a browser. +function fakeModify( + this: Selection, + _alter?: string, + direction?: string, + granularity?: string, +): void { + const lines = conversationLines(); + const index = lines.indexOf(this.focusNode as Text); + if (index === -1) return; + const line = lines[index]; + const step = direction === "forward" || direction === "right" ? 1 : -1; + const next = lines[index + step]; + if (granularity === "character") { + const offset = this.focusOffset + step; + if (offset >= 0 && offset <= line.length) this.extend(line, offset); + return; + } + if (granularity === "word") { + const offset = wordStep(line, this.focusOffset, step); + if (offset !== null) this.extend(line, offset); + return; + } + if (granularity === "lineboundary") { + this.extend(line, step === 1 ? line.length : 0); + return; + } + if (granularity === "paragraph") { + if (next !== undefined) this.extend(next, 0); + return; + } + if (granularity !== "line") { + throw new Error(`the fake browser does not move by ${granularity}`); + } + if (next !== undefined) this.extend(next, Math.min(this.focusOffset, next.length)); +} + +function define(target: object, name: string, value: unknown): void { + Object.defineProperty(target, name, { + configurable: true, + writable: true, + value, + }); +} + +// What jsdom lacks for selecting and copying: Selection.modify, the lookup of +// text at a point, the rectangles of a range and the copy command. +function installBrowserFakes(): void { + const viewport = focusedPaneViewport(); + viewport.innerHTML = CONVERSATION; + viewport.getBoundingClientRect = () => new DOMRect(0, 0, 800, 400); + copiedTexts = []; + execCommand = vi.fn((_command: string) => { + copiedTexts.push(pageSelection().toString()); + return true; + }); + define(Selection.prototype, "modify", fakeModify); + define(Range.prototype, "getClientRects", fakeClientRects); + define(document, "caretPositionFromPoint", fakeCaretPositionFromPoint); + define(document, "execCommand", execCommand); +} + +function removeBrowserFakes(): void { + pageSelection().removeAllRanges(); + Reflect.deleteProperty(Selection.prototype, "modify"); + Reflect.deleteProperty(Range.prototype, "getClientRects"); + Reflect.deleteProperty(document, "caretPositionFromPoint"); + Reflect.deleteProperty(document, "execCommand"); +} + +function cursorPlace(): string { + const { focusNode, focusOffset } = pageSelection(); + return `${focusNode?.parentElement?.dataset.testid ?? "nowhere"}:${focusOffset}`; +} + +function cursorBlock(): Record<"left" | "top" | "width" | "height", string> { + const { left, top, width, height } = screen.getByTestId("copy-cursor").style; + return { left, top, width, height }; +} + +function modePill(): string | null { + return screen.queryByRole("status")?.textContent ?? null; +} + +function showBbSelectionMenu(): HTMLElement { + focusedPaneViewport().insertAdjacentHTML("beforeend", BB_SELECTION_MENU); + return fixture("add-to-chat"); +} + +// What bb does when its pane shows another thread: PageShell is keyed by the +// thread id in ThreadScreen.tsx, so the scroller is a new element. +function bbShowsAnotherThread(): HTMLElement { + const fresh = document.createElement("div"); + fresh.setAttribute("data-page-scroll-viewport", ""); + fresh.innerHTML = LONG_CONVERSATION; + fresh.getBoundingClientRect = () => new DOMRect(0, 0, 800, 400); + focusedPaneViewport().replaceWith(fresh); + return fresh; +} + +// The browser's record of whether the window was clicked or typed in since it +// loaded (navigator.userActivation), which jsdom does not have. +function setWindowUsed(hasBeenActive: boolean): void { + Object.defineProperty(navigator, "userActivation", { + configurable: true, + value: { hasBeenActive, isActive: false }, + }); +} + +function pressPointer(element: HTMLElement): void { + act(() => { + element.dispatchEvent(new Event("pointerdown", { bubbles: true })); + }); +} + +function nextTask(): Promise { + return act(() => new Promise((resolve) => setTimeout(resolve, 0))); +} + +function pressMouseOn(element: Element, init: MouseEventInit = {}): void { + element.dispatchEvent( + new MouseEvent("mousedown", { bubbles: true, button: 0, ...init }), + ); +} + +// The plugin reads the selection one task after the button is released. +async function releaseMouseOn( + element: Element, + init: MouseEventInit = {}, +): Promise { + element.dispatchEvent( + new MouseEvent("mouseup", { bubbles: true, button: 0, ...init }), + ); + await nextTask(); + await nextTask(); +} + +// A drag over the text: the button goes down on it, the browser selects, and +// the button is released. +async function selectWithMouse( + text: Text, + start: number, + end: number, +): Promise { + const element = text.parentElement ?? document.body; + pressMouseOn(element); + pageSelection().setBaseAndExtent(text, start, text, end); + await releaseMouseOn(element); +} + +async function clickWithButton(element: Element): Promise { + pressMouseOn(element); + await releaseMouseOn(element); +} + +function chooserTitles(): (string | null)[] { + return screen + .getAllByRole("option") + .map((option) => option.firstElementChild?.textContent ?? null); +} + +beforeEach(() => { + window.history.replaceState(null, "", THREAD_ROUTE); + consoleError = vi.spyOn(console, "error"); + consoleWarn = vi.spyOn(console, "warn"); + // jsdom reports no window focus while an element is losing the cursor. A + // browser reports it for as long as the window is the active one. + vi.spyOn(document, "hasFocus").mockReturnValue(true); + pageListeners = new AbortController(); + page = document.createElement("div"); + page.innerHTML = BB_PAGE; + document.body.append(page); +}); + +afterEach(async () => { + if (mounted !== undefined && !mounted.inspection.disposed) { + await mounted.lifecycle.dispose(); + } + expect(consoleError.mock.calls).toEqual([]); + expect(consoleWarn.mock.calls).toEqual([]); + vi.useRealTimers(); + vi.restoreAllMocks(); + pageListeners.abort(); + cancelPendingFocus(); + cancelPendingNewThread(); + resetPaneResize(); + noteSidebarPointerDown(null); + cleanup(); + resetStore(); + resetThreadOrderCache(); + setKeybindings(null); + removeFakeLocks(); + Reflect.deleteProperty(navigator, "userActivation"); + window.localStorage.clear(); + document.body.replaceChildren(); +}); + +describe("registration", () => { + it("registers one content script and one app overlay", () => { + expect(app.contentScripts.map((script) => script.id)).toEqual(["keys"]); + expect(app.appOverlays.map((overlay) => overlay.id)).toEqual(["overlay"]); + }); + + it("registers three palette commands without a default shortcut", () => { + expect( + commands.map(({ id, title, target, defaultShortcut }) => ({ + id, + title, + target, + defaultShortcut, + })), + ).toEqual([ + { + id: "open-thread-chooser", + title: "Tmux Vim: Open thread chooser", + target: "app", + defaultShortcut: null, + }, + { + id: "show-keys", + title: "Tmux Vim: Show keys", + target: "app", + defaultShortcut: null, + }, + { + id: "toggle-paused", + title: "Tmux Vim: Pause or resume keys in this window", + target: "app", + defaultShortcut: null, + }, + ]); + }); +}); + +describe("prefix keys", () => { + it("opens the thread chooser on Ctrl-a then w and opens the chosen thread", async () => { + await mountPlugin(); + + const prefix = pressCtrl("a"); + expect(prefix.defaultPrevented).toBe(true); + expect(getUiState().prefixArmed).toBe(true); + expect(screen.getByRole("status").textContent).toBe("Ctrl-a"); + + const key = pressKey("w"); + expect(key.defaultPrevented).toBe(true); + expect(getUiState().prefixArmed).toBe(false); + expect(getUiState().chooser).toEqual({ open: true, placement: "replace" }); + expect(screen.getByRole("dialog", { name: "Thread chooser" })).toBeTruthy(); + expect(chooserTitles()).toEqual(["Alpha", "Beta", "Gamma"]); + + pressKey("G", chooserList()); + pressKey("Enter", chooserList()); + + expect(getUiState().chooser).toEqual({ open: false }); + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-3" }, + ]); + }); + + it("opens a thread in a pane below on Ctrl-a then s", async () => { + await mountPlugin(); + + pressCtrl("a"); + pressKey("s"); + expect(getUiState().chooser).toEqual({ open: true, placement: "down" }); + + pressKey("G", chooserList()); + pressKey("Enter", chooserList()); + + expect(threadsOpen).toHaveBeenCalledWith({ + threadId: "thr-3", + split: "down", + file: null, + }); + expect(view.inspection.navigateCalls).toEqual([]); + }); + + it("starts a new thread on Ctrl-a then c", async () => { + await mountPlugin(); + + pressCtrl("a"); + const key = pressKey("c"); + + expect(key.defaultPrevented).toBe(true); + expect(view.inspection.navigateCalls).toEqual([ + { method: "toCompose", options: { focusPrompt: true } }, + ]); + }); + + it("lets the second Ctrl-a through to the page", async () => { + await mountPlugin(); + + const first = pressCtrl("a"); + const second = pressCtrl("a"); + + expect(first.defaultPrevented).toBe(true); + expect(second.defaultPrevented).toBe(false); + expect(getUiState().prefixArmed).toBe(false); + expect(pressKey("w").defaultPrevented).toBe(false); + expect(getUiState().chooser).toEqual({ open: false }); + }); + + it("shows the key help on Ctrl-a then ?", async () => { + await mountPlugin(); + + pressCtrl("a"); + pressKey("?"); + + const help = screen.getByRole("dialog", { name: "Tmux + Vim keys" }); + expect(help.textContent).toContain("After the prefix"); + expect(help.textContent).toContain("Ctrl-a 1-9"); + }); +}); + +describe("typing", () => { + it.each(["notes", "composer", "terminal-input"])( + "leaves keys typed in the %s field alone", + async (testId) => { + await mountPlugin(); + const field = fixture(testId); + + for (const key of PLAIN_KEYS) { + expect(pressKey(key, field).defaultPrevented, key).toBe(false); + } + for (const chord of TYPING_CHORDS) { + expect(press(chord, field).defaultPrevented, chord.key).toBe(false); + } + expect(view.inspection.navigateCalls).toEqual([]); + expect(getUiState().chooser).toEqual({ open: false }); + }, + ); + + it.each(["notes", "composer", "terminal-input"])( + "arms the prefix on Ctrl-a in the %s field and passes the second Ctrl-a", + async (testId) => { + await mountPlugin(); + const field = fixture(testId); + + expect(pressCtrl("a", field).defaultPrevented).toBe(true); + expect(getUiState().prefixArmed).toBe(true); + expect(pressCtrl("a", field).defaultPrevented).toBe(false); + expect(getUiState().prefixArmed).toBe(false); + }, + ); + + it.each(["notes", "composer"])( + "takes Ctrl+h/j/k/l in the %s field for pane moves", + async (testId) => { + await mountPlugin(); + const field = fixture(testId); + + for (const key of HJKL) { + expect(pressCtrl(key, field).defaultPrevented, key).toBe(true); + } + }, + ); + + it("leaves Ctrl+h/j/k/l to the shell inside the terminal", async () => { + await mountPlugin(); + const terminalInput = fixture("terminal-input"); + + for (const key of HJKL) { + expect(pressCtrl(key, terminalInput).defaultPrevented, key).toBe(false); + } + expect(view.inspection.navigateCalls).toEqual([]); + }); +}); + +describe("pane and sidebar moves", () => { + it("moves to the pane on the right on Ctrl-l", async () => { + await mountPlugin(); + const pointerDowns: EventTarget[] = []; + pane("pane-2").addEventListener("pointerdown", (event) => { + if (event.target !== null) pointerDowns.push(event.target); + }); + + expect(pressCtrl("l").defaultPrevented).toBe(true); + + expect(pointerDowns).toEqual([pane("pane-2")]); + await waitFor(() => + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-2" }, + ]), + ); + }); + + it("enters the sidebar on Ctrl-h from the leftmost pane and drives it with vim keys", async () => { + await mountPlugin(); + + expect(pressCtrl("h").defaultPrevented).toBe(true); + expect(document.activeElement).toBe(sidebarRow("thr-1")); + + expect(pressKey("j", sidebarRow("thr-1")).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(sidebarRow("thr-2")); + + expect(pressKey("G", sidebarRow("thr-2")).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(sidebarRow("thr-3")); + + expect(pressKey("Enter", sidebarRow("thr-3")).defaultPrevented).toBe(true); + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-3" }, + ]); + + expect(pressKey("l", sidebarRow("thr-3")).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(pane("pane-1")); + }); + + it("jumps to the second thread in sidebar order on Ctrl-a then 2", async () => { + await mountPlugin(); + + pressCtrl("a"); + pressKey("2"); + + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-2" }, + ]); + }); +}); + +describe("browsing keys", () => { + it("scrolls the focused pane's conversation on j and k", async () => { + await mountPlugin(); + const viewport = focusedPaneViewport(); + const wheelDeltas: number[] = []; + viewport.addEventListener("wheel", (event) => { + wheelDeltas.push((event as WheelEvent).deltaY); + }); + + const down = pressKey("j"); + expect(down.defaultPrevented).toBe(true); + expect(viewport.scrollTop).toBe(80); + + const up = pressKey("k"); + expect(up.defaultPrevented).toBe(true); + expect(viewport.scrollTop).toBe(0); + expect(wheelDeltas).toEqual([80, -80]); + }); + + it("opens the chooser on the leader sequence , f f", async () => { + await mountPlugin(); + + for (const key of [",", "f", "f"]) { + expect(pressKey(key).defaultPrevented, key).toBe(true); + } + + expect(getUiState().chooser).toEqual({ open: true, placement: "replace" }); + }); +}); + +describe("palette commands", () => { + it("opens the chooser and the key help", async () => { + await mountPlugin(); + + await runCommand("open-thread-chooser"); + expect(screen.getByRole("dialog", { name: "Thread chooser" })).toBeTruthy(); + pressKey("q", chooserList()); + expect(getUiState().chooser).toEqual({ open: false }); + + await runCommand("show-keys"); + expect(getUiState().helpOpen).toBe(true); + }); + + it("pauses and resumes the keys and says which state it is in", async () => { + await mountPlugin(); + + await runCommand("toggle-paused"); + expect(getUiState().paused).toBe(true); + expect(getUiState().notice?.text).toContain("paused"); + expect(pressCtrl("a").defaultPrevented).toBe(false); + expect(pressKey("j").defaultPrevented).toBe(false); + expect(getUiState().prefixArmed).toBe(false); + + await runCommand("toggle-paused"); + expect(getUiState().paused).toBe(false); + expect(getUiState().notice?.text).toContain("on again"); + expect(pressCtrl("a").defaultPrevented).toBe(true); + }); +}); + +describe("cold start", () => { + const SNAPSHOT_AT_QUIT = { + version: 1, + savedAt: 1, + focusedThreadId: "thr-1", + panes: [ + { paneId: "pane-1", threadId: "thr-1", isFocused: true }, + { paneId: "pane-2", threadId: "thr-2", isFocused: false }, + ], + }; + const LAYOUT_AFTER_COLD_START: PluginSidebarSplitLayout = { + panes: TWO_PANES.panes.map((layoutPane) => + layoutPane.isFocused ? { ...layoutPane, threadId: null } : layoutPane, + ), + }; + + it("reopens the thread that the New thread screen replaced", () => { + window.history.replaceState(null, "", NEW_THREAD_ROUTE); + window.localStorage.setItem( + PLUGIN_STORAGE_KEYS.layoutSnapshot, + JSON.stringify(SNAPSHOT_AT_QUIT), + ); + + renderOverlay({ layout: LAYOUT_AFTER_COLD_START, contextThreadId: null }); + + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-1" }, + ]); + }); + + it("reopens it in the only bb window once the browser has said so", async () => { + installFakeLocks(); + window.history.replaceState(null, "", NEW_THREAD_ROUTE); + window.localStorage.setItem( + PLUGIN_STORAGE_KEYS.layoutSnapshot, + JSON.stringify(SNAPSHOT_AT_QUIT), + ); + + renderOverlay({ layout: LAYOUT_AFTER_COLD_START, contextThreadId: null }); + + await waitFor(() => + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-1" }, + ]), + ); + }); + + it("leaves a new window on the New thread screen while another bb window is open", async () => { + installFakeLocks([ + { name: PLUGIN_LOCKS.openWindow, clientId: "first-window" }, + ]); + window.history.replaceState(null, "", NEW_THREAD_ROUTE); + window.localStorage.setItem( + PLUGIN_STORAGE_KEYS.layoutSnapshot, + JSON.stringify(SNAPSHOT_AT_QUIT), + ); + + renderOverlay({ layout: LAYOUT_AFTER_COLD_START, contextThreadId: null }); + + await waitFor(() => + expect(storedSnapshot()?.savedAt).not.toBe(SNAPSHOT_AT_QUIT.savedAt), + ); + expect(view.inspection.navigateCalls).toEqual([]); + }); + + it("only records the layout when nothing was lost", () => { + renderOverlay(); + + expect(view.inspection.navigateCalls).toEqual([]); + expect(storedSnapshot()).toMatchObject({ + focusedThreadId: "thr-1", + panes: SNAPSHOT_AT_QUIT.panes, + }); + }); + + it("reopens the thread in a window that has not been clicked or typed in yet", () => { + setWindowUsed(false); + window.history.replaceState(null, "", NEW_THREAD_ROUTE); + window.localStorage.setItem( + PLUGIN_STORAGE_KEYS.layoutSnapshot, + JSON.stringify(SNAPSHOT_AT_QUIT), + ); + + renderOverlay({ layout: LAYOUT_AFTER_COLD_START, contextThreadId: null }); + + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-1" }, + ]); + }); + + it("leaves the New thread screen alone once the user has clicked or typed in the window", () => { + setWindowUsed(true); + window.history.replaceState(null, "", NEW_THREAD_ROUTE); + window.localStorage.setItem( + PLUGIN_STORAGE_KEYS.layoutSnapshot, + JSON.stringify(SNAPSHOT_AT_QUIT), + ); + + renderOverlay({ layout: LAYOUT_AFTER_COLD_START, contextThreadId: null }); + + expect(view.inspection.navigateCalls).toEqual([]); + expect(storedSnapshot()).toMatchObject({ + focusedThreadId: null, + panes: [ + { paneId: "pane-1", threadId: null, isFocused: true }, + { paneId: "pane-2", threadId: "thr-2", isFocused: false }, + ], + }); + }); +}); + +describe("more prefix keys", () => { + it("moves with the arrow keys after the prefix", async () => { + await mountPlugin(); + const pointerDown = onEvent(pane("pane-2"), "pointerdown"); + + pressCtrl("a"); + expect(pressKey("ArrowRight").defaultPrevented).toBe(true); + + expect(pointerDown).toHaveBeenCalledTimes(1); + }); + + it("closes the focused pane on Ctrl-a x with bb's own button", async () => { + await mountPlugin(); + const click = onEvent(fixture("close-pane"), "click"); + + pressCtrl("a"); + pressKey("x"); + + expect(click).toHaveBeenCalledTimes(1); + expect(getUiState().notice).toBeNull(); + }); + + it("zooms on Ctrl-a z through bb's own shortcut", async () => { + const ran = await mountPluginWithBbShortcuts([ + bbShortcut(BB_COMMANDS.paneMaximizeToggle, "e"), + ]); + + pressCtrl("a"); + pressKey("z"); + + expect(ran).toEqual([BB_COMMANDS.paneMaximizeToggle]); + expect(threadsPaneAction).not.toHaveBeenCalled(); + expect(getUiState().notice).toBeNull(); + }); + + it("goes to the next and the previous thread on Ctrl-a n and p, wrapping around", async () => { + await mountPlugin(); + + pressCtrl("a"); + pressKey("n"); + pressCtrl("a"); + pressKey("p"); + + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-2" }, + { method: "toThread", threadId: "thr-3" }, + ]); + }); + + it("cancels the prefix on Escape", async () => { + await mountPlugin(); + + pressCtrl("a"); + expect(pressKey("Escape").defaultPrevented).toBe(true); + + expect(getUiState().prefixArmed).toBe(false); + expect(pressKey("w").defaultPrevented).toBe(false); + expect(getUiState().chooser).toEqual({ open: false }); + }); + + it("cancels the prefix when the next key does not come in time", async () => { + await mountPlugin(); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + + pressCtrl("a"); + act(() => { + vi.advanceTimersByTime(2999); + }); + expect(getUiState().prefixArmed).toBe(true); + act(() => { + vi.advanceTimersByTime(2); + }); + + expect(getUiState().prefixArmed).toBe(false); + expect(screen.queryByRole("status")).toBeNull(); + expect(pressKey("w").defaultPrevented).toBe(false); + }); +}); + +describe("resizing panes", () => { + // The divider bb draws between two panes that are side by side, as + // SplitDivider in SplitThreadArea.tsx renders it. SplitTree in the same file + // marks the row that holds the panes and the divider as a grid root. + const BB_DIVIDER = ` +
+ +
+ `; + + // What Option-h, j, k and l type on a US Mac keyboard. + const OPTION_CHARACTERS: Record = { + h: "\u02d9", + j: "\u2206", + k: "\u02da", + l: "\u00ac", + }; + + let drags: string[]; + + function pressOption( + letter: string, + target?: EventTarget, + init: KeyboardEventInit = {}, + ): KeyboardEvent { + return press( + { + key: OPTION_CHARACTERS[letter], + code: `Key${letter.toUpperCase()}`, + altKey: true, + ...init, + }, + target, + ); + } + + function dragTo(x: number): string[] { + return [ + `pointerdown at ${x},300 pointer 1 buttons 1`, + `pointermove at ${x},300 pointer 1 buttons 1`, + `pointerup at ${x},300 pointer 1 buttons 0`, + ]; + } + + // jsdom has no layout, so the boxes are set here: the left pane, the + // divider of 1 pixel and the right pane, in a row of 1001 pixels. + function layOutPanes(leftWidth: number, rightWidth = 1000 - leftWidth): void { + const row = pane("pane-1").parentElement; + if (row === null) throw new Error("the panes have no row"); + const rowWidth = leftWidth + 1 + rightWidth; + row.getBoundingClientRect = () => new DOMRect(0, 0, rowWidth, 600); + pane("pane-1").getBoundingClientRect = () => new DOMRect(0, 0, leftWidth, 600); + fixture("divider").getBoundingClientRect = () => new DOMRect(leftWidth, 0, 1, 600); + pane("pane-2").getBoundingClientRect = () => + new DOMRect(leftWidth + 1, 0, rightWidth, 600); + } + + beforeEach(() => { + pane("pane-1").insertAdjacentHTML("afterend", BB_DIVIDER); + pane("pane-1").parentElement?.setAttribute("data-split-resize-grid-root", ""); + layOutPanes(500); + drags = []; + for (const type of ["pointerdown", "pointermove", "pointerup"]) { + fixture("divider-hit-target").addEventListener( + type, + (event) => { + const { clientX, clientY, pointerId, buttons } = event as PointerEvent; + drags.push( + `${type} at ${clientX},${clientY} pointer ${pointerId} buttons ${buttons}`, + ); + }, + { signal: pageListeners.signal }, + ); + } + }); + + it("drags the divider on the right of the focused pane on Ctrl-a then Option-l, and again on Option-l alone", async () => { + await mountPlugin(); + const focusPresses = onEvent(pane("pane-2"), "pointerdown"); + + pressCtrl("a"); + expect(pressOption("l").defaultPrevented).toBe(true); + expect(drags).toEqual(dragTo(548.5)); + expect(getUiState().prefixArmed).toBe(true); + expect(modePill()).toBe("Ctrl-a"); + + expect(pressOption("l").defaultPrevented).toBe(true); + expect(pressOption("l", undefined, { repeat: true }).defaultPrevented).toBe( + true, + ); + expect(pressOption("h", undefined, { shiftKey: true }).defaultPrevented).toBe( + true, + ); + expect(drags).toEqual([ + ...dragTo(548.5), + ...dragTo(548.5), + ...dragTo(548.5), + ...dragTo(452.5), + ]); + + expect(getUiState().prefixArmed).toBe(true); + expect(getUiState().notice).toBeNull(); + expect(focusPresses).not.toHaveBeenCalled(); + expect(view.inspection.navigateCalls).toEqual([]); + }); + + it("leaves Option-h/j/k/l to typing without the prefix and once the repeat window is over", async () => { + await mountPlugin({ settings: { resizeStepPx: 100, repeatTimeoutMs: 400 } }); + const notes = fixture("notes"); + + for (const letter of HJKL) { + expect(pressOption(letter, notes).defaultPrevented, letter).toBe(false); + expect( + pressOption(letter, notes, { shiftKey: true }).defaultPrevented, + letter, + ).toBe(false); + } + expect(drags).toEqual([]); + + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + pressCtrl("a", notes); + expect(pressOption("l", notes).defaultPrevented).toBe(true); + expect(drags).toEqual(dragTo(600.5)); + act(() => { + vi.advanceTimersByTime(399); + }); + expect(getUiState().prefixArmed).toBe(true); + act(() => { + vi.advanceTimersByTime(2); + }); + expect(getUiState().prefixArmed).toBe(false); + expect(screen.queryByRole("status")).toBeNull(); + expect(pressOption("l", notes).defaultPrevented).toBe(false); + + pressCtrl("a", notes); + pressOption("j", notes); + expect(pressKey("x", notes).defaultPrevented).toBe(false); + expect(pressOption("l", notes).defaultPrevented).toBe(false); + expect(drags).toEqual(dragTo(600.5)); + expect(getUiState().notice).toBeNull(); + }); + + it("opens no repeat window when the pane has no divider that can go that way", async () => { + await mountPlugin(); + const notes = fixture("notes"); + + pressCtrl("a", notes); + expect(modePill()).toBe("Ctrl-a"); + expect(pressOption("j", notes).defaultPrevented).toBe(true); + + expect(getUiState().prefixArmed).toBe(false); + expect(modePill()).toBeNull(); + expect(pressOption("j", notes, { repeat: true }).defaultPrevented).toBe(true); + for (const letter of HJKL) { + expect(pressOption(letter, notes).defaultPrevented, letter).toBe(false); + } + expect(drags).toEqual([]); + expect(getUiState().notice).toBeNull(); + }); + + it("says once that there is only one pane, opens no repeat window and types the next Option key", async () => { + pane("pane-2").remove(); + fixture("divider").remove(); + pane("pane-1").removeAttribute("data-focused"); + await mountPlugin({ layout: null }); + const notes = fixture("notes"); + + pressCtrl("a", notes); + expect(pressOption("l", notes).defaultPrevented).toBe(true); + const notice = getUiState().notice; + expect(notice?.text).toBe("There is only one pane, so there is nothing to resize."); + expect(getUiState().prefixArmed).toBe(false); + expect(modePill()).toBeNull(); + + expect(pressOption("l", notes, { repeat: true }).defaultPrevented).toBe(true); + expect(pressOption("l", notes).defaultPrevented).toBe(false); + expect(pressOption("k", notes).defaultPrevented).toBe(false); + expect(getUiState().notice).toBe(notice); + }); + + it("sends bb nothing at the smallest pane size, and still takes the key that goes the other way", async () => { + layOutPanes(150); + await mountPlugin(); + const notes = fixture("notes"); + + pressCtrl("a", notes); + expect(pressOption("h", notes).defaultPrevented).toBe(true); + expect(pressOption("h", notes, { repeat: true }).defaultPrevented).toBe(true); + expect(drags).toEqual([]); + expect(getUiState().prefixArmed).toBe(true); + + expect(pressOption("l", notes).defaultPrevented).toBe(true); + expect(drags).toEqual(dragTo(198.5)); + expect(getUiState().notice).toBeNull(); + }); + + it("stops a long step at the smallest pane size", async () => { + await mountPlugin({ settings: { resizeStepPx: 400 } }); + + pressCtrl("a"); + pressOption("h"); + expect(drags).toEqual(dragTo(150.5)); + }); + + it("leaves the panes alone while bb hides the conversation area", async () => { + layOutPanes(0, 0); + await mountPlugin(); + const notes = fixture("notes"); + + pressCtrl("a", notes); + expect(pressOption("l", notes).defaultPrevented).toBe(true); + + expect(drags).toEqual([]); + expect(getUiState().prefixArmed).toBe(false); + expect(pressOption("l", notes).defaultPrevented).toBe(false); + expect(getUiState().notice).toBeNull(); + }); + + // What Option-u is on a US Mac keyboard: a dead key, which waits for the + // next letter to put an accent on it. + it.each<[string, KeyboardEventInit]>([ + ["a dead key", { key: "Dead", code: "KeyU", altKey: true }], + ["a dead key that the browser reports as key 229", { key: "Dead", code: "KeyU", altKey: true, keyCode: 229 }], + ])("ends the prefix on %s, so the next key is typed and closes no pane", async (_name, deadKey) => { + await mountPlugin(); + const notes = fixture("notes"); + const closeClick = onEvent(fixture("close-pane"), "click"); + + pressCtrl("a", notes); + expect(press(deadKey, notes).defaultPrevented).toBe(false); + + expect(getUiState().prefixArmed).toBe(false); + expect(modePill()).toBeNull(); + expect(pressKey("x", notes).defaultPrevented).toBe(false); + expect(pressKey("Backspace", notes).defaultPrevented).toBe(false); + expect(closeClick).not.toHaveBeenCalled(); + }); + + it("ends the repeat window on a dead key as well", async () => { + await mountPlugin(); + const notes = fixture("notes"); + + pressCtrl("a", notes); + pressOption("l", notes); + expect(getUiState().prefixArmed).toBe(true); + press({ key: "Dead", code: "KeyU", altKey: true }, notes); + + expect(getUiState().prefixArmed).toBe(false); + expect(pressOption("l", notes).defaultPrevented).toBe(false); + expect(drags).toEqual(dragTo(548.5)); + }); + + it("names the resize keys Option in the key help on a Mac and says that they repeat", async () => { + vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); + await mountPlugin(); + + pressCtrl("a"); + pressKey("?"); + + const help = screen.getByRole("dialog", { name: "Tmux + Vim keys" }); + expect(help.textContent).toContain("Ctrl-a Option-h / Option-Shift-h"); + expect(help.textContent).toContain( + "Resize this pane by moving its divider to the left. Then the key works without the prefix for 1 second", + ); + expect(help.textContent).not.toContain("Alt-"); + }); + + it("drops the resize key that the prefix takes from the key help and keeps its Shift form working", async () => { + await mountPlugin({ settings: { prefixKey: "alt+h" } }); + const notes = fixture("notes"); + + expect(pressOption("h", notes).defaultPrevented).toBe(true); + expect(pressOption("h", notes).defaultPrevented).toBe(false); + expect(drags).toEqual([]); + + pressOption("h", notes); + expect(pressOption("h", notes, { shiftKey: true }).defaultPrevented).toBe(true); + expect(drags).toEqual(dragTo(452.5)); + + pressOption("h"); + pressKey("?"); + const help = screen.getByRole("dialog", { name: "Tmux + Vim keys" }); + expect(help.textContent).toContain("Alt-h Alt-Shift-h"); + expect(help.textContent).not.toContain("Alt-h Alt-h / Alt-Shift-h"); + }); +}); + +describe("after a thread is opened", () => { + async function openThirdThread(): Promise { + pressCtrl("a"); + pressKey("3"); + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-3" }, + ]); + bbFocusesThread("thr-3"); + await afterFrames(3); + } + + it("keeps the cursor on the pane when bb puts it in the thread's message box a moment later", async () => { + await mountPlugin(); + await openThirdThread(); + expect(document.activeElement).toBe(pane("pane-1")); + + fixture("composer").focus(); + + expect(document.activeElement).toBe(pane("pane-1")); + expect(pressKey("j", pane("pane-1")).defaultPrevented).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(80); + }); + + it("lets a click put the cursor in the message box at once", async () => { + await mountPlugin(); + await openThirdThread(); + + clickWithMouse(fixture("composer")); + + expect(document.activeElement).toBe(fixture("composer")); + }); + + it("lets a bb shortcut put the cursor in the message box at once", async () => { + await mountPlugin(); + await openThirdThread(); + + const shortcut = press({ key: "c", metaKey: true, shiftKey: true }); + fixture("composer").focus(); + + expect(shortcut.defaultPrevented).toBe(false); + expect(document.activeElement).toBe(fixture("composer")); + }); + + it("puts the cursor in the message box on i and leaves it there", async () => { + await mountPlugin(); + pressCtrl("a"); + pressKey("1"); + await afterFrames(3); + expect(document.activeElement).toBe(pane("pane-1")); + + expect(pressKey("i", pane("pane-1")).defaultPrevented).toBe(true); + fixture("composer").focus(); + + expect(view.inspection.composer.focusCount).toBe(1); + expect(document.activeElement).toBe(fixture("composer")); + }); + + it("puts the cursor in the message box by itself when focusAfterPaneMove is composer", async () => { + await mountPlugin({ settings: { focusAfterPaneMove: "composer" } }); + + pressCtrl("a"); + pressKey("1"); + + await waitFor(() => expect(view.inspection.composer.focusCount).toBe(1)); + }); +}); + +describe("a pane that was left while typing", () => { + // The test harness only counts how often the plugin asked bb for the cursor + // in the message box. bb answers a moment later by putting it there. + function bbPutsCursorInMessageBox(): void { + fixture("composer").focus(); + } + + // bb takes the cursor out of the message box on Escape with a plain blur(). + function pressEscapeInMessageBox(): void { + expect(pressKey("Escape", fixture("composer")).defaultPrevented).toBe(false); + fixture("composer").blur(); + } + + async function moveToPane(key: string, threadId: string): Promise { + expect( + pressCtrl(key, document.activeElement ?? document.body).defaultPrevented, + ).toBe(true); + bbFocusesThread(threadId); + await afterFrames(3); + } + + it("puts the cursor back in the message box after Ctrl-l to the next pane and Ctrl-h back", async () => { + await mountPlugin(); + fixture("composer").focus(); + + await moveToPane("l", "thr-2"); + expect(document.activeElement).toBe(pane("pane-2")); + expect(view.inspection.composer.focusCount).toBe(0); + + await moveToPane("h", "thr-1"); + expect(view.inspection.composer.focusCount).toBe(1); + bbPutsCursorInMessageBox(); + await afterFrames(2); + + expect(document.activeElement).toBe(fixture("composer")); + expect(pressKey("j", fixture("composer")).defaultPrevented).toBe(false); + }); + + it("puts the cursor on the pane after Escape took it out of the message box before the move", async () => { + await mountPlugin(); + fixture("composer").focus(); + pressEscapeInMessageBox(); + + await moveToPane("l", "thr-2"); + await moveToPane("h", "thr-1"); + expect(document.activeElement).toBe(pane("pane-1")); + expect(view.inspection.composer.focusCount).toBe(0); + + bbPutsCursorInMessageBox(); + + expect(document.activeElement).toBe(pane("pane-1")); + expect(pressKey("j", pane("pane-1")).defaultPrevented).toBe(true); + }); + + it.each([{ key: "l" }, { key: "Escape" }, { key: "l", ctrlKey: true }])( + "puts the cursor back in the message box on the way back from the sidebar with $key", + async (leave) => { + await mountPlugin(); + fixture("composer").focus(); + + expect(pressCtrl("h", fixture("composer")).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(sidebarRow("thr-1")); + + expect(press(leave, sidebarRow("thr-1")).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(pane("pane-1")); + expect(view.inspection.composer.focusCount).toBe(1); + bbPutsCursorInMessageBox(); + + expect(document.activeElement).toBe(fixture("composer")); + }, + ); + + it("puts the cursor on the pane on the way back from the sidebar after Escape in the message box", async () => { + await mountPlugin(); + fixture("composer").focus(); + pressEscapeInMessageBox(); + + pressCtrl("h"); + pressKey("l", sidebarRow("thr-1")); + + expect(document.activeElement).toBe(pane("pane-1")); + expect(view.inspection.composer.focusCount).toBe(0); + }); + + it("puts the cursor back in the message box on a jump to the thread from another pane", async () => { + await mountPlugin(); + fixture("composer").focus(); + await moveToPane("l", "thr-2"); + + pressCtrl("a", pane("pane-2")); + pressKey("1", pane("pane-2")); + bbFocusesThread("thr-1"); + await afterFrames(3); + + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-1" }, + ]); + expect(view.inspection.composer.focusCount).toBe(1); + }); + + it("starts another thread in the same pane on the pane, and forgets the first thread for when it is opened again", async () => { + await mountPlugin(); + fixture("composer").focus(); + + pressCtrl("a", fixture("composer")); + pressKey("3", fixture("composer")); + bbFocusesThread("thr-3"); + await afterFrames(3); + expect(document.activeElement).toBe(pane("pane-1")); + + pressCtrl("a", pane("pane-1")); + pressKey("1", pane("pane-1")); + bbFocusesThread("thr-1"); + await afterFrames(3); + expect(document.activeElement).toBe(pane("pane-1")); + + pressCtrl("h", pane("pane-1")); + pressKey("l", sidebarRow("thr-1")); + + expect(document.activeElement).toBe(pane("pane-1")); + expect(view.inspection.composer.focusCount).toBe(0); + }); + + // A browser leaves the selection in the draft when the cursor goes to an + // element that is no text field. jsdom moves the selection on every + // focus(), so it is put back where the browser would have left it. + function browserKeepsTextCursorIn(editor: HTMLElement): void { + pageSelection().setBaseAndExtent(editor, 0, editor, 0); + } + + // A click on a conversation: bb focuses that pane, and the browser puts + // the cursor on the pane element. + function clickConversationOf(paneId: string, threadId: string): void { + const conversation = pane(paneId).querySelector( + "[data-page-scroll-viewport]", + ); + if (conversation === null) throw new Error("the pane has no conversation"); + pressPointer(conversation); + bbFocusesThread(threadId); + pane(paneId).focus(); + } + + it("focuses the text field itself on the way back while the text cursor is still in the draft, so bb does not move it to the end", async () => { + await mountPlugin(); + fixture("composer").focus(); + await moveToPane("l", "thr-2"); + browserKeepsTextCursorIn(fixture("composer")); + + await moveToPane("h", "thr-1"); + + expect(document.activeElement).toBe(fixture("composer")); + expect(view.inspection.composer.focusCount).toBe(0); + expect(pressKey("j", fixture("composer")).defaultPrevented).toBe(false); + + await moveToPane("l", "thr-2"); + browserKeepsTextCursorIn(fixture("composer")); + await moveToPane("h", "thr-1"); + expect(document.activeElement).toBe(fixture("composer")); + }); + + it("puts the cursor on the pane after the user came back to it with a click on its conversation", async () => { + await mountPlugin(); + fixture("composer").focus(); + clickConversationOf("pane-2", "thr-2"); + clickConversationOf("pane-1", "thr-1"); + expect(document.activeElement).toBe(pane("pane-1")); + expect(pressKey("j", pane("pane-1")).defaultPrevented).toBe(true); + + await moveToPane("l", "thr-2"); + browserKeepsTextCursorIn(fixture("composer")); + await moveToPane("h", "thr-1"); + + expect(document.activeElement).toBe(pane("pane-1")); + expect(view.inspection.composer.focusCount).toBe(0); + bbPutsCursorInMessageBox(); + expect(document.activeElement).toBe(pane("pane-1")); + expect(pressKey("j", pane("pane-1")).defaultPrevented).toBe(true); + }); + + it("puts the cursor on the pane after the user left it from the Send button, where the browsing keys work", async () => { + await mountPlugin(); + const send = document.createElement("button"); + fixture("composer").after(send); + fixture("composer").focus(); + clickWithMouse(send); + expect(pressKey("j", send).defaultPrevented).toBe(true); + + await moveToPane("l", "thr-2"); + browserKeepsTextCursorIn(fixture("composer")); + await moveToPane("h", "thr-1"); + + expect(document.activeElement).toBe(pane("pane-1")); + expect(view.inspection.composer.focusCount).toBe(0); + }); + + // bb shows a question of the agent in place of the message box, which is + // hidden meanwhile (hidden={hasPendingInteraction} in FollowUpPromptBox.tsx). + // A hidden element cannot take the cursor in a browser. + it("rests on the pane while bb hides the message box, and on the next return as well", async () => { + await mountPlugin(); + fixture("composer").focus(); + await moveToPane("l", "thr-2"); + browserKeepsTextCursorIn(fixture("composer")); + const hidden = vi.spyOn(fixture("composer"), "focus").mockImplementation(() => {}); + + await moveToPane("h", "thr-1"); + expect(document.activeElement).toBe(pane("pane-1")); + expect(view.inspection.composer.focusCount).toBe(1); + + hidden.mockRestore(); + expect(pressKey("j", pane("pane-1")).defaultPrevented).toBe(true); + await moveToPane("l", "thr-2"); + browserKeepsTextCursorIn(fixture("composer")); + await moveToPane("h", "thr-1"); + + expect(document.activeElement).toBe(pane("pane-1")); + expect(view.inspection.composer.focusCount).toBe(1); + expect(pressKey("j", pane("pane-1")).defaultPrevented).toBe(true); + }); + + it("puts the cursor on the pane after Escape that followed a click on a thread row within half a second", async () => { + await mountPlugin(); + clickWithMouse(sidebarRow("thr-1")); + bbPutsCursorInMessageBox(); + pressEscapeInMessageBox(); + + pressCtrl("h"); + expect(document.activeElement).toBe(sidebarRow("thr-1")); + pressKey("l", sidebarRow("thr-1")); + + expect(document.activeElement).toBe(pane("pane-1")); + expect(view.inspection.composer.focusCount).toBe(0); + }); + + // bb's zoom follows the focused pane: the pane that is left gets hidden, + // and the browser takes the cursor away from a hidden element. + it("puts the cursor back in the message box of a zoomed pane that was hidden while the user was in the next pane", async () => { + await mountPlugin(); + fixture("composer").focus(); + + expect(pressCtrl("l", fixture("composer")).defaultPrevented).toBe(true); + pane("pane-1").setAttribute("aria-hidden", "true"); + fixture("composer").blur(); + bbFocusesThread("thr-2"); + await afterFrames(3); + expect(document.activeElement).toBe(pane("pane-2")); + + expect(pressCtrl("h", pane("pane-2")).defaultPrevented).toBe(true); + pane("pane-2").setAttribute("aria-hidden", "true"); + pane("pane-1").removeAttribute("aria-hidden"); + bbFocusesThread("thr-1"); + await afterFrames(3); + + expect(view.inspection.composer.focusCount).toBe(1); + bbPutsCursorInMessageBox(); + expect(document.activeElement).toBe(fixture("composer")); + }); +}); + +// bb's closePane (SplitThreadArea.tsx) sets the layout first and navigates +// second, and the navigation is rendered later. So the pane that stays is +// the single pane at once, while the route still names the closed thread. +describe("closing a pane with Ctrl-a x", () => { + function addMessageBoxToSecondPane(): HTMLElement { + pane("pane-2") + .querySelector("[data-thread-window]") + ?.insertAdjacentHTML( + "beforeend", + '
', + ); + return fixture("composer-2"); + } + + function bbClosesFirstPane(): void { + const bridge = getBridge(); + if (bridge === null) throw new Error("the bridge was not published"); + pane("pane-1").remove(); + pane("pane-2").removeAttribute("tabindex"); + pane("pane-2").removeAttribute("data-focused"); + setBridge({ ...bridge, layout: null }); + } + + function bbRouteFollows(): void { + const bridge = getBridge(); + if (bridge === null) throw new Error("the bridge was not published"); + setBridge({ ...bridge, context: { ...bridge.context, threadId: "thr-2" } }); + } + + function closeFirstPaneFrom(target: HTMLElement): void { + fixture("close-pane").addEventListener("click", bbClosesFirstPane, { + signal: pageListeners.signal, + }); + pressCtrl("a", target); + expect(pressKey("x", target).defaultPrevented).toBe(true); + expect(getBridge()?.layout).toBeNull(); + expect(getBridge()?.context.threadId).toBe("thr-1"); + } + + async function typeInSecondPaneAndMoveToFirst(): Promise { + const messageBox = addMessageBoxToSecondPane(); + bbFocusesThread("thr-2"); + clickWithMouse(messageBox); + expect(pressCtrl("h", messageBox).defaultPrevented).toBe(true); + bbFocusesThread("thr-1"); + await afterFrames(3); + expect(document.activeElement).toBe(pane("pane-1")); + return messageBox; + } + + it("lands in the message box of the pane that stays when that pane was left while typing, once the route names its thread", async () => { + await mountPlugin({ composerThreadId: "thr-2" }); + const messageBox = await typeInSecondPaneAndMoveToFirst(); + + closeFirstPaneFrom(pane("pane-1")); + await afterFrames(3); + expect(view.inspection.composer.focusCount).toBe(0); + + bbRouteFollows(); + await afterFrames(3); + expect(view.inspection.composer.focusCount).toBe(1); + messageBox.focus(); + + expect(document.activeElement).toBe(messageBox); + expect(pressKey("j", messageBox).defaultPrevented).toBe(false); + }); + + it("leaves the cursor in that message box when bb put it there while the route was still behind", async () => { + await mountPlugin({ composerThreadId: "thr-2" }); + const messageBox = await typeInSecondPaneAndMoveToFirst(); + + closeFirstPaneFrom(pane("pane-1")); + messageBox.focus(); + await afterFrames(3); + bbRouteFollows(); + await afterFrames(3); + + expect(document.activeElement).toBe(messageBox); + expect(pressKey("j", messageBox).defaultPrevented).toBe(false); + }); + + it("rests on the pane that stays when the cursor was in the message box of the closed pane", async () => { + await mountPlugin({ composerThreadId: "thr-2" }); + const messageBox = addMessageBoxToSecondPane(); + fixture("composer").focus(); + + closeFirstPaneFrom(fixture("composer")); + await afterFrames(3); + bbRouteFollows(); + await afterFrames(3); + expect(view.inspection.composer.focusCount).toBe(0); + + messageBox.focus(); + expect(document.activeElement).toBe(document.body); + expect(pressKey("j").defaultPrevented).toBe(true); + }); +}); + +describe("held keys", () => { + it("keeps scrolling while j is held", async () => { + await mountPlugin(); + + pressKey("j"); + const repeat = press({ key: "j", repeat: true }); + + expect(repeat.defaultPrevented).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(160); + }); + + it("does not start scrolling when the key after the prefix is held", async () => { + await mountPlugin(); + + pressCtrl("a"); + pressKey("j"); + const repeat = press({ key: "j", repeat: true }); + + expect(repeat.defaultPrevented).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(0); + }); + + it("does not type the key that closed the key help into the message box", async () => { + await mountPlugin(); + const composer = fixture("composer"); + composer.focus(); + pressCtrl("a", composer); + pressKey("?", composer); + const help = screen.getByRole("dialog", { name: "Tmux + Vim keys" }); + expect(help.contains(document.activeElement)).toBe(true); + + pressKey("q", document.activeElement ?? help); + await waitFor(() => expect(document.activeElement).toBe(composer)); + const repeat = press({ key: "q", repeat: true }, composer); + + expect(repeat.defaultPrevented).toBe(true); + expect(pressKey("q", composer).defaultPrevented).toBe(false); + }); + + it("does not send a draft with the Enter that chose a thread", async () => { + await mountPlugin(); + const composer = fixture("composer"); + composer.focus(); + pressCtrl("a", composer); + pressKey("w", composer); + + pressKey("Enter", chooserList()); + const repeat = press({ key: "Enter", repeat: true }, composer); + + expect(getUiState().chooser).toEqual({ open: false }); + expect(repeat.defaultPrevented).toBe(true); + }); + + it.each(["Enter", "c"])( + "does not type the held %s that started a new thread from the chooser into the message box", + async (key) => { + await mountPlugin(); + const composer = fixture("composer"); + composer.focus(); + pressCtrl("a", composer); + pressKey("v", composer); + + pressKey(key, chooserList()); + const repeat = press({ key, repeat: true }, composer); + + expect(getUiState().chooser).toEqual({ open: false }); + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-3", options: { split: true } }, + ]); + expect(repeat.defaultPrevented).toBe(true); + }, + ); +}); + +describe("more sidebar keys", () => { + it("leaves a thread row that was clicked to bb and keeps the browsing keys on the conversation", async () => { + await mountPlugin(); + const row = sidebarRow("thr-2"); + clickWithMouse(row); + + expect(pressKey("j", row).defaultPrevented).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(80); + expect(document.activeElement).toBe(row); + expect(pressKey("Escape", row).defaultPrevented).toBe(false); + expect(pressKey("Enter", row).defaultPrevented).toBe(false); + expect(view.inspection.navigateCalls).toEqual([]); + + expect(pressCtrl("h", row).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(sidebarRow("thr-1")); + expect(pressKey("j", sidebarRow("thr-1")).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(row); + expect(pressKey("k", row).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(sidebarRow("thr-1")); + }); + + it("leaves Escape to bb while thread rows are selected", async () => { + await mountPlugin(); + pressCtrl("h"); + const row = sidebarRow("thr-1"); + sidebarRow("thr-2").setAttribute("data-sidebar-thread-selected", ""); + + expect(pressKey("Escape", row).defaultPrevented).toBe(false); + expect(document.activeElement).toBe(row); + + sidebarRow("thr-2").removeAttribute("data-sidebar-thread-selected"); + expect(pressKey("Escape", row).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(pane("pane-1")); + }); + + it("moves with Ctrl-j and Ctrl-k, splits with v and s, and returns with Ctrl-l", async () => { + await mountPlugin(); + pressCtrl("h"); + + pressCtrl("j", sidebarRow("thr-1")); + pressCtrl("j", sidebarRow("thr-2")); + expect(document.activeElement).toBe(sidebarRow("thr-3")); + pressCtrl("k", sidebarRow("thr-3")); + expect(document.activeElement).toBe(sidebarRow("thr-2")); + pressKey("G", sidebarRow("thr-2")); + + expect(pressKey("v", sidebarRow("thr-3")).defaultPrevented).toBe(true); + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-3", options: { split: true } }, + ]); + expect(pressKey("s", sidebarRow("thr-3")).defaultPrevented).toBe(true); + expect(threadsOpen).toHaveBeenCalledWith({ + threadId: "thr-3", + split: "down", + file: null, + }); + + expect(pressCtrl("l", sidebarRow("thr-3")).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(pane("pane-1")); + }); +}); + +describe("more browsing keys", () => { + it("scrolls half a page on Ctrl-d and Ctrl-u and to the ends on G and gg", async () => { + await mountPlugin(); + const viewport = focusedPaneViewport(); + setScrollMetrics(viewport, { clientHeight: 400, scrollHeight: 2000 }); + + pressCtrl("d"); + expect(viewport.scrollTop).toBe(200); + pressCtrl("u"); + expect(viewport.scrollTop).toBe(0); + press({ key: "G", shiftKey: true }); + expect(viewport.scrollTop).toBe(2000); + pressKey("g"); + expect(viewport.scrollTop).toBe(2000); + pressKey("g"); + expect(viewport.scrollTop).toBe(0); + }); + + it("switches threads on L and H", async () => { + await mountPlugin(); + + expect(press({ key: "L", shiftKey: true }).defaultPrevented).toBe(true); + expect(press({ key: "H", shiftKey: true }).defaultPrevented).toBe(true); + + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-2" }, + { method: "toThread", threadId: "thr-3" }, + ]); + }); + + it("opens bb's find, command palette and thread search through bb's shortcuts", async () => { + const ran = await mountPluginWithBbShortcuts([ + bbShortcut(BB_COMMANDS.windowFind, "f"), + bbShortcut(BB_COMMANDS.paletteOpen, "p"), + bbShortcut(BB_COMMANDS.threadSearch, "k"), + ]); + + pressKey("/"); + press({ key: ":", shiftKey: true }); + for (const key of [",", "f", "g"]) pressKey(key); + + expect(ran).toEqual([ + BB_COMMANDS.windowFind, + BB_COMMANDS.paletteOpen, + BB_COMMANDS.threadSearch, + ]); + expect(getUiState().notice).toBeNull(); + }); + + // bb runs none of its shortcuts while a dialog is open, and its menu for + // selected message text counts as one. It closes that menu when the + // selection is gone. + it("drops a mouse selection so that bb opens the command palette behind its selection menu", async () => { + installBrowserFakes(); + const binding = bbShortcut(BB_COMMANDS.paletteOpen, "p"); + await mountPlugin({ keybindings: [binding] }); + await waitFor(() => expect(findBinding(binding.command)).not.toBeNull()); + const ran: string[] = []; + window.addEventListener( + "keydown", + (event) => { + if (!event.altKey || event.key !== "p") return; + if (document.querySelector(BB_OPEN_MODAL) !== null) return; + event.preventDefault(); + ran.push(binding.command); + }, + { signal: pageListeners.signal }, + ); + await selectWithMouse(lineText("line-1"), 0, 5); + const menu = showBbSelectionMenu().closest("[data-radix-popper-content-wrapper]"); + document.addEventListener( + "selectionchange", + () => { + if (pageSelection().rangeCount === 0) menu?.remove(); + }, + { signal: pageListeners.signal }, + ); + + expect(press({ key: ":", shiftKey: true }).defaultPrevented).toBe(true); + expect(ran).toEqual([]); + + await waitFor(() => expect(ran).toEqual([BB_COMMANDS.paletteOpen])); + expect(pageSelection().rangeCount).toBe(0); + expect(getUiState().notice?.text).toBe(COPIED_NOTICE); + removeBrowserFakes(); + }); + + it("says so when bb has no shortcut that could open the command palette", async () => { + await mountPlugin(); + + expect(press({ key: ":", shiftKey: true }).defaultPrevented).toBe(true); + + expect(getUiState().notice?.text).toContain("bb has no shortcut bound"); + }); + + it("shows or hides the sidebar on Space e with bb's own button", async () => { + await mountPlugin(); + const trigger = page.querySelector('[data-sidebar="trigger"]'); + if (trigger === null) throw new Error("the sidebar trigger is missing"); + const click = onEvent(trigger, "click"); + + expect(pressKey(" ").defaultPrevented).toBe(true); + expect(pressKey("e").defaultPrevented).toBe(true); + + expect(click).toHaveBeenCalledTimes(1); + }); +}); + +describe("more chooser keys", () => { + it("filters on /, returns to the list on Escape and opens to the right on v", async () => { + await mountPlugin(); + pressCtrl("a"); + pressKey("w"); + + pressKey("/", chooserList()); + const filter = screen.getByRole("combobox", { + name: "Filter threads by title", + }); + expect(document.activeElement).toBe(filter); + fireEvent.change(filter, { target: { value: "gam" } }); + expect(chooserTitles()).toEqual(["Gamma"]); + pressKey("Escape", filter); + expect(document.activeElement).toBe(chooserList()); + + pressKey("v", chooserList()); + + expect(getUiState().chooser).toEqual({ open: false }); + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-3", options: { split: true } }, + ]); + }); + + it("moves with j, k and Ctrl-n and jumps to the pane of a thread that is already open", async () => { + await mountPlugin(); + for (const key of [",", "f", "f"]) pressKey(key); + expect(screen.getAllByRole("option")[1].textContent).toContain("in a pane"); + + pressKey("j", chooserList()); + pressKey("j", chooserList()); + pressKey("k", chooserList()); + pressCtrl("n", chooserList()); + pressCtrl("p", chooserList()); + pressKey("s", chooserList()); + + expect(threadsOpen).not.toHaveBeenCalled(); + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-2" }, + ]); + }); +}); + +describe("a new thread from the chooser", () => { + const PLACEHOLDER_TO_THE_RIGHT = { + method: "toThread", + threadId: "thr-3", + options: { split: true }, + }; + const NEW_THREAD_SCREEN = { + method: "toCompose", + options: { focusPrompt: true }, + }; + + it("opens a pane to the right on Ctrl-a then v then Enter and turns it into the New thread screen", async () => { + await mountPlugin(); + pressCtrl("a"); + pressKey("v"); + expect(chooserTitles()).toEqual(["New thread", "Alpha", "Beta", "Gamma"]); + + pressKey("Enter", chooserList()); + + expect(getUiState().chooser).toEqual({ open: false }); + expect(view.inspection.navigateCalls).toEqual([PLACEHOLDER_TO_THE_RIGHT]); + + await afterFrames(2); + expect(view.inspection.navigateCalls).toEqual([PLACEHOLDER_TO_THE_RIGHT]); + + bbOpensPane("thr-3"); + await afterFrames(2); + + expect(view.inspection.navigateCalls).toEqual([ + PLACEHOLDER_TO_THE_RIGHT, + NEW_THREAD_SCREEN, + ]); + expect(getUiState().notice).toBeNull(); + }); + + it("opens a pane below on Ctrl-a then s then c, from a thread row, and stops waiting when the mouse is pressed", async () => { + await mountPlugin(); + pressCtrl("a"); + pressKey("s"); + pressKey("j", chooserList()); + + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + + const key = pressKey("c", chooserList()); + + expect(key.defaultPrevented).toBe(true); + expect(getUiState().chooser).toEqual({ open: false }); + expect(threadsOpen).toHaveBeenCalledWith({ + threadId: "thr-3", + split: "down", + file: null, + }); + + document.body.dispatchEvent(new Event("pointerdown", { bubbles: true })); + bbOpensPane("thr-3"); + act(() => { + vi.advanceTimersByTime(3000); + }); + expect(getUiState().notice).toBeNull(); + vi.useRealTimers(); + await afterFrames(2); + + expect(view.inspection.navigateCalls).toEqual([]); + expect(getUiState().notice).toBeNull(); + }); + + it("says that the new pane was not opened when its 3 seconds pass without a mouse press", async () => { + await mountPlugin(); + pressCtrl("a"); + pressKey("s"); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + + pressKey("Enter", chooserList()); + act(() => { + vi.advanceTimersByTime(3000); + }); + + expect(getUiState().notice?.text).toBe("Could not open the new pane."); + }); + + it("moves to the New thread screen that Ctrl-a then c made during the wait and says that the new pane kept its thread", async () => { + await mountPlugin(); + pressCtrl("a"); + pressKey("s"); + pressKey("Enter", chooserList()); + expect(threadsOpen).toHaveBeenCalledTimes(1); + + pressCtrl("a"); + pressKey("c"); + expect(view.inspection.navigateCalls).toEqual([NEW_THREAD_SCREEN]); + bbShowsNewThreadScreenInFocusedPane(); + bbOpensPane("thr-3"); + await afterFrames(2); + + expect(view.inspection.navigateCalls).toEqual([ + NEW_THREAD_SCREEN, + NEW_THREAD_SCREEN, + ]); + expect(getUiState().notice?.text).toBe( + "bb shows the New thread screen in one pane only, so you were moved to it. The new pane kept the thread it opened with.", + ); + }); + + it("lets the New thread row of a chooser that is opened again during the wait replace the first request", async () => { + await mountPlugin(); + pressCtrl("a"); + pressKey("s"); + pressKey("Enter", chooserList()); + expect(threadsOpen).toHaveBeenCalledTimes(1); + + pressCtrl("a"); + pressKey("v"); + expect(chooserTitles()).toEqual(["New thread", "Alpha", "Beta", "Gamma"]); + pressKey("Enter", chooserList()); + expect(view.inspection.navigateCalls).toEqual([PLACEHOLDER_TO_THE_RIGHT]); + bbOpensPane("thr-3"); + await afterFrames(3); + + expect(threadsOpen).toHaveBeenCalledTimes(1); + expect(view.inspection.navigateCalls).toEqual([ + PLACEHOLDER_TO_THE_RIGHT, + NEW_THREAD_SCREEN, + ]); + expect(getUiState().notice).toBeNull(); + }); + + it("says that the thread is closed when the mouse is pressed while every thread is in a pane and the new pane was not asked for yet", async () => { + await mountPlugin({ + layout: { + panes: [ + ...TWO_PANES.panes, + { + paneId: "pane-3", + threadId: "thr-3", + isFocused: false, + rect: { x: 0, y: 0.5, width: 1, height: 0.5 }, + }, + ], + }, + }); + pressCtrl("a"); + pressKey("v"); + + pressKey("Enter", chooserList()); + expect(view.inspection.navigateCalls).toHaveLength(1); + expect(view.inspection.navigateCalls[0]).toMatchObject({ method: "toCompose" }); + + document.body.dispatchEvent(new Event("pointerdown", { bubbles: true })); + expect(getUiState().notice).toBeNull(); + bbShowsNewThreadScreenInFocusedPane(); + await afterFrames(2); + + expect(view.inspection.navigateCalls).toHaveLength(1); + expect(getUiState().notice?.text).toBe( + "Could not open the new pane. The thread that was in the pane is closed. Open it again from the sidebar.", + ); + }); + + it("moves to the pane that already shows the New thread screen and says why", async () => { + pane("pane-2").innerHTML = "
"; + await mountPlugin({ + layout: { + panes: [ + TWO_PANES.panes[0], + { ...TWO_PANES.panes[1], threadId: null }, + ], + }, + }); + pressCtrl("a"); + pressKey("v"); + + pressKey("Enter", chooserList()); + + expect(view.inspection.navigateCalls).toEqual([NEW_THREAD_SCREEN]); + expect(getUiState().notice?.text).toBe( + "bb shows the New thread screen in one pane only, so you were moved to it.", + ); + }); + + it("offers no new thread on Ctrl-a then w, where c is left alone", async () => { + await mountPlugin(); + pressCtrl("a"); + pressKey("w"); + expect(chooserTitles()).toEqual(["Alpha", "Beta", "Gamma"]); + + const key = pressKey("c", chooserList()); + + expect(key.defaultPrevented).toBe(false); + expect(getUiState().chooser).toEqual({ open: true, placement: "replace" }); + expect(view.inspection.navigateCalls).toEqual([]); + }); +}); + +// What bb 0.50.1 renders for a single pane (SecondaryPanelLayout.tsx): the +// pane element keeps its id, but has neither the focused mark nor a +// tabindex, so it cannot take the cursor. +describe("with a single pane", () => { + beforeEach(() => { + pane("pane-2").remove(); + pane("pane-1").removeAttribute("data-focused"); + pane("pane-1").removeAttribute("tabindex"); + }); + + it("scrolls, enters the sidebar on Ctrl-h and has no other pane to move to", async () => { + await mountPlugin({ layout: null }); + + expect(pressKey("j").defaultPrevented).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(80); + + expect(pressCtrl("l").defaultPrevented).toBe(true); + await afterFrames(2); + expect(view.inspection.navigateCalls).toEqual([]); + + pressCtrl("h"); + expect(document.activeElement).toBe(sidebarRow("thr-1")); + pressKey("l", sidebarRow("thr-1")); + expect(document.activeElement).toBe(document.body); + expect(pressKey("j").defaultPrevented).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(160); + }); + + it("goes back from the sidebar to the message box that had the cursor, and to the pane after Escape", async () => { + await mountPlugin({ layout: null }); + fixture("composer").focus(); + + expect(pressCtrl("h", fixture("composer")).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(sidebarRow("thr-1")); + pageSelection().setBaseAndExtent(fixture("composer"), 0, fixture("composer"), 0); + pressKey("l", sidebarRow("thr-1")); + expect(document.activeElement).toBe(fixture("composer")); + expect(view.inspection.composer.focusCount).toBe(0); + + expect(pressKey("Escape", fixture("composer")).defaultPrevented).toBe(false); + fixture("composer").blur(); + pressCtrl("h"); + pressKey("l", sidebarRow("thr-1")); + expect(document.activeElement).toBe(document.body); + expect(view.inspection.composer.focusCount).toBe(0); + }); + + it("rests on the pane after a click on the conversation brought the user back from the sidebar", async () => { + await mountPlugin({ layout: null }); + fixture("composer").focus(); + clickWithMouse(sidebarRow("thr-1")); + pressPointer(focusedPaneViewport()); + sidebarRow("thr-1").blur(); + expect(pressKey("j").defaultPrevented).toBe(true); + + pressCtrl("h"); + pressKey("l", sidebarRow("thr-1")); + + expect(document.activeElement).toBe(document.body); + expect(view.inspection.composer.focusCount).toBe(0); + }); + + it("marks the open thread in the chooser and splits to the right from it", async () => { + await mountPlugin({ layout: null }); + + pressCtrl("a"); + pressKey("v"); + expect(screen.getAllByRole("option")[1].textContent).toContain( + "focused pane", + ); + pressKey("j", chooserList()); + pressKey("j", chooserList()); + pressKey("Enter", chooserList()); + + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: "thr-2", options: { split: true } }, + ]); + }); + + it("does nothing on the zoom and close keys", async () => { + await mountPlugin({ layout: null }); + const click = onEvent(fixture("close-pane"), "click"); + + pressCtrl("a"); + pressKey("x"); + pressCtrl("a"); + pressKey("z"); + + expect(click).not.toHaveBeenCalled(); + expect(threadsPaneAction).not.toHaveBeenCalled(); + expect(getUiState().notice).toBeNull(); + }); +}); + +describe("on a page that shows no panes, such as Settings", () => { + function showSettingsPage(): HTMLInputElement { + const field = document.createElement("input"); + page.querySelector("main")?.replaceChildren(field); + field.focus(); + return field; + } + + it("stays on the page when a pane key is pressed in a text field", async () => { + await mountPlugin(); + const field = showSettingsPage(); + + expect(pressCtrl("l", field).defaultPrevented).toBe(true); + await afterFrames(2); + + expect(view.inspection.navigateCalls).toEqual([]); + expect(document.activeElement).toBe(field); + expect(pressKey("j", field).defaultPrevented).toBe(false); + }); + + it("does not zoom the panes of other bb windows", async () => { + await mountPlugin(); + showSettingsPage(); + + pressCtrl("a"); + pressKey("z"); + + expect(threadsPaneAction).not.toHaveBeenCalled(); + expect(getUiState().notice?.text).toBe("Could not zoom this pane."); + }); + + it.each([ + ["v", "Enter"], + ["s", "c"], + ])( + "opens no pane for a new thread on Ctrl-a then %s then %s, stays on the page and says why", + async (splitKey, newThreadKey) => { + await mountPlugin(); + const field = showSettingsPage(); + pressCtrl("a", field); + pressKey(splitKey, field); + expect(chooserTitles()).toEqual(["New thread", "Alpha", "Beta", "Gamma"]); + + pressKey(newThreadKey, chooserList()); + await afterFrames(2); + + expect(getUiState().chooser).toEqual({ open: false }); + expect(view.inspection.navigateCalls).toEqual([]); + expect(threadsOpen).not.toHaveBeenCalled(); + expect(getUiState().notice?.text).toBe( + "This page shows no panes, so no new pane was opened.", + ); + expect(document.activeElement).toBe(field); + }, + ); +}); + +describe("settings", () => { + it("handles no key while the plugin is switched off", async () => { + await mountPlugin({ settings: { enabled: false } }); + + expect(pressCtrl("a").defaultPrevented).toBe(false); + expect(pressKey("j").defaultPrevented).toBe(false); + expect(pressCtrl("l").defaultPrevented).toBe(false); + expect(getUiState().prefixArmed).toBe(false); + }); + + it("uses the configured prefix key", async () => { + await mountPlugin({ settings: { prefixKey: "ctrl+b" } }); + + expect(pressCtrl("a").defaultPrevented).toBe(false); + expect(pressCtrl("b").defaultPrevented).toBe(true); + expect(screen.getByRole("status").textContent).toBe("Ctrl-b"); + pressKey("w"); + + expect(getUiState().chooser).toEqual({ open: true, placement: "replace" }); + }); + + it("keeps the prefix and the sidebar keys when vimKeys is off", async () => { + await mountPlugin({ settings: { vimKeys: false } }); + + expect(pressKey("j").defaultPrevented).toBe(false); + expect(press({ key: "L", shiftKey: true }).defaultPrevented).toBe(false); + expect(focusedPaneViewport().scrollTop).toBe(0); + + pressCtrl("h"); + expect(pressKey("j", sidebarRow("thr-1")).defaultPrevented).toBe(true); + expect(document.activeElement).toBe(sidebarRow("thr-2")); + expect(pressCtrl("a").defaultPrevented).toBe(true); + }); + + it.each([ + ["off", { notes: false, "terminal-input": false }], + ["not-typing", { notes: false, "terminal-input": false }], + ["all-but-terminal", { notes: true, "terminal-input": false }], + ["everywhere", { notes: true, "terminal-input": true }], + ] as const)("takes Ctrl-l as ctrlHjkl %s says", async (mode, expected) => { + await mountPlugin({ settings: { ctrlHjkl: mode } }); + + expect(pressCtrl("l").defaultPrevented).toBe(mode !== "off"); + for (const [testId, taken] of Object.entries(expected)) { + expect(pressCtrl("l", fixture(testId)).defaultPrevented, testId).toBe( + taken, + ); + } + }); + + it.each([ + ["sidebar", "thr-1"], + ["recent", "thr-2"], + ])("numbers the threads in %s order", async (threadOrder, secondThread) => { + const list = sidebarRow("thr-3").parentElement; + list?.prepend(sidebarRow("thr-3")); + await mountPlugin({ settings: { threadOrder } }); + + pressCtrl("a"); + pressKey("2"); + + expect(view.inspection.navigateCalls).toEqual([ + { method: "toThread", threadId: secondThread }, + ]); + }); +}); + +describe("loading and unloading", () => { + it("handles no key before the overlay has published the user's settings", async () => { + await mountContentScripts(); + + expect(pressCtrl("a").defaultPrevented).toBe(false); + expect(pressKey("j").defaultPrevented).toBe(false); + expect(pressCtrl("l").defaultPrevented).toBe(false); + expect(getUiState().prefixArmed).toBe(false); + }); + + it("handles no key and copies nothing while bb has no values for the settings", async () => { + installBrowserFakes(); + await mountPlugin({ settings: null }); + + expect(getBridge()).toBeNull(); + expect(pressCtrl("a").defaultPrevented).toBe(false); + expect(pressKey("j").defaultPrevented).toBe(false); + expect(pressKey("v").defaultPrevented).toBe(false); + await selectWithMouse(lineText("line-1"), 0, 5); + + expect(execCommand).not.toHaveBeenCalled(); + expect(mounted.inspection.experimental_clipboardWrites).toEqual([]); + expect(getUiState().notice).toBeNull(); + removeBrowserFakes(); + }); + + it("does not carry a pause or an open popup over to the next time the plugin is loaded", async () => { + await mountPlugin(); + await runCommand("toggle-paused"); + await runCommand("show-keys"); + expect(getUiState()).toMatchObject({ paused: true, helpOpen: true }); + + await act(async () => { + await mounted.lifecycle.dispose(); + }); + expect(getUiState()).toMatchObject({ paused: false, helpOpen: false }); + await mountContentScripts(); + + expect(pressCtrl("a").defaultPrevented).toBe(true); + expect(screen.queryByRole("dialog")).toBeNull(); + }); +}); + +describe("dispose", () => { + it("prevents no key once the content script is disposed", async () => { + await mountPlugin(); + expect(mounted.inspection.mountedIds).toEqual(["keys"]); + pressCtrl("a"); + expect(getUiState().prefixArmed).toBe(true); + + await act(async () => { + await mounted.lifecycle.dispose(); + }); + + expect(getUiState().prefixArmed).toBe(false); + expect(pressCtrl("a").defaultPrevented).toBe(false); + expect(pressKey("j").defaultPrevented).toBe(false); + expect(pressKey("w").defaultPrevented).toBe(false); + for (const key of HJKL) { + expect(pressCtrl(key).defaultPrevented, key).toBe(false); + } + expect(getUiState().chooser).toEqual({ open: false }); + expect(view.inspection.navigateCalls).toEqual([]); + }); +}); + +describe("copy mode", () => { + beforeEach(installBrowserFakes); + afterEach(removeBrowserFakes); + + it("enters on v while browsing a conversation and shows the COPY pill and the cursor", async () => { + await mountPlugin(); + + expect(pressKey("v").defaultPrevented).toBe(true); + + expect(getUiState().copyMode).toMatchObject({ active: true, selecting: false }); + expect(modePill()).toBe("COPY"); + expect(cursorPlace()).toBe("line-3:0"); + expect(pageSelection().isCollapsed).toBe(true); + expect(cursorBlock()).toEqual({ + left: "40px", + top: "140px", + width: "8px", + height: "20px", + }); + }); + + it("moves the cursor on k, l, j and h instead of scrolling", async () => { + await mountPlugin(); + pressKey("v"); + + expect(pressKey("k").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-2:0"); + expect(cursorBlock()).toMatchObject({ left: "40px", top: "120px" }); + + expect(pressKey("l").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-2:1"); + expect(cursorBlock()).toMatchObject({ left: "48px", top: "120px" }); + + expect(pressKey("j").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:1"); + + expect(pressKey("h").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:0"); + expect(pageSelection().isCollapsed).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(0); + }); + + it("moves with the arrow keys and to the ends of a line on 0 and $", async () => { + await mountPlugin(); + pressKey("v"); + + pressKey("ArrowUp"); + pressKey("ArrowRight"); + expect(cursorPlace()).toBe("line-2:1"); + press({ key: "$", shiftKey: true }); + expect(cursorPlace()).toBe("line-2:13"); + expect(cursorBlock()).toMatchObject({ left: "144px", width: "2px" }); + pressKey("0"); + expect(cursorPlace()).toBe("line-2:0"); + pressKey("ArrowDown"); + pressKey("ArrowLeft"); + expect(cursorPlace()).toBe("line-3:0"); + }); + + it("moves by word on w, e and b and to the start of the line on ^", async () => { + await mountPlugin(); + pressKey("v"); + + expect(pressKey("w").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:5"); + expect(pressKey("e").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:8"); + expect(pressKey("w").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:9"); + expect(pressKey("b").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:5"); + expect(press({ key: "^", shiftKey: true }).defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:0"); + expect(pageSelection().isCollapsed).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(0); + }); + + it("moves by paragraph on { and }", async () => { + await mountPlugin(); + pressKey("v"); + pressKey("l"); + + expect(press({ key: "{", shiftKey: true }).defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-2:0"); + expect(press({ key: "{", shiftKey: true }).defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-1:0"); + expect(press({ key: "}", shiftKey: true }).defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-2:0"); + expect(view.inspection.navigateCalls).toEqual([]); + }); + + it("moves to the first and the last text on gg and G", async () => { + await mountPlugin(); + pressKey("v"); + + expect(pressKey("g").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:0"); + expect(pressKey("g").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-1:0"); + expect(press({ key: "G", shiftKey: true }).defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:14"); + expect(pageSelection().isCollapsed).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(0); + }); + + it("moves to the top, middle and bottom line of the view on H, M and L", async () => { + await mountPlugin(); + focusedPaneViewport().innerHTML = LONG_CONVERSATION; + pressKey("v"); + expect(cursorPlace()).toBe("line-9:0"); + + expect(press({ key: "H", shiftKey: true }).defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-1:0"); + expect(press({ key: "M", shiftKey: true }).defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-5:0"); + expect(press({ key: "L", shiftKey: true }).defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-9:0"); + expect(view.inspection.navigateCalls).toEqual([]); + }); + + it("selects with the word, paragraph and screen keys once v started selecting", async () => { + await mountPlugin(); + pressKey("v"); + pressKey("v"); + + pressKey("e"); + expect(pageSelection().toString()).toBe("zeta"); + pressKey("w"); + expect(pageSelection().toString()).toBe("zeta "); + press({ key: "{", shiftKey: true }); + expect(cursorPlace()).toBe("line-2:0"); + press({ key: "H", shiftKey: true }); + expect(cursorPlace()).toBe("line-1:0"); + expect(modePill()).toBe("VISUAL"); + + pressKey("y"); + await waitFor(() => expect(getUiState().notice?.text).toBe(COPIED_NOTICE)); + expect(copiedTexts).toHaveLength(1); + expect(copiedTexts[0].replace(/\s+/g, " ")).toBe("alpha beta gamma delta epsilon "); + }); + + it("keeps moving while a movement key is held", async () => { + await mountPlugin(); + pressKey("v"); + + pressKey("l"); + const repeat = press({ key: "l", repeat: true }); + + expect(repeat.defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:2"); + }); + + it.each(["y", "Enter"])( + "selects from v to the cursor and copies it on %s with the browser's copy command", + async (copyKey) => { + await mountPlugin(); + pressKey("v"); + pressKey("k"); + + expect(pressKey("v").defaultPrevented).toBe(true); + expect(modePill()).toBe("VISUAL"); + expect(getUiState().copyMode).toMatchObject({ selecting: true }); + press({ key: "$", shiftKey: true }); + expect(pageSelection().toString()).toBe("delta epsilon"); + expect(cursorPlace()).toBe("line-2:13"); + + expect(pressKey(copyKey).defaultPrevented).toBe(true); + + expect(execCommand.mock.calls).toEqual([["copy"]]); + expect(copiedTexts).toEqual(["delta epsilon"]); + await waitFor(() => expect(getUiState().notice?.text).toBe(COPIED_NOTICE)); + expect(getUiState().copyMode).toEqual({ active: false }); + expect(pageSelection().rangeCount).toBe(0); + expect(modePill()).toBeNull(); + expect(screen.queryByTestId("copy-cursor")).toBeNull(); + expect(mounted.inspection.experimental_clipboardWrites).toEqual([]); + }, + ); + + it("drops the selection on a second v and stays in copy mode", async () => { + await mountPlugin(); + pressKey("v"); + pressKey("v"); + pressKey("l"); + expect(pageSelection().toString()).toBe("z"); + + pressKey("v"); + + expect(modePill()).toBe("COPY"); + expect(pageSelection().isCollapsed).toBe(true); + expect(cursorPlace()).toBe("line-3:1"); + }); + + it("says how to select when y is pressed before v and stays in copy mode", async () => { + await mountPlugin(); + pressKey("v"); + + expect(pressKey("y").defaultPrevented).toBe(true); + + await waitFor(() => + expect(getUiState().notice?.text).toBe( + "Press v to start selecting, then y to copy", + ), + ); + expect(execCommand).not.toHaveBeenCalled(); + expect(modePill()).toBe("COPY"); + }); + + it("asks for a move, not for v, when y is pressed right after v started selecting", async () => { + await mountPlugin(); + pressKey("v"); + pressKey("v"); + + expect(pressKey("y").defaultPrevented).toBe(true); + + await waitFor(() => + expect(getUiState().notice?.text).toBe(NOTHING_SELECTED_NOTICE), + ); + expect(copiedTexts).toEqual([]); + expect(mounted.inspection.experimental_clipboardWrites).toEqual([]); + expect(modePill()).toBe("VISUAL"); + + pressKey("l"); + pressKey("y"); + await waitFor(() => expect(getUiState().notice?.text).toBe(COPIED_NOTICE)); + expect(copiedTexts).toEqual(["z"]); + }); + + it("falls back to bb's plain-text copy when the browser refuses its copy command", async () => { + await mountPlugin(); + execCommand.mockReturnValue(false); + pressKey("v"); + pressKey("v"); + press({ key: "$", shiftKey: true }); + + pressKey("y"); + + await waitFor(() => expect(getUiState().notice?.text).toBe(COPIED_NOTICE)); + expect(mounted.inspection.experimental_clipboardWrites).toEqual([ + { text: "zeta eta theta" }, + ]); + expect(getUiState().copyMode).toEqual({ active: false }); + }); + + it.each(["Escape", "q"])( + "leaves on %s and clears the selection without copying", + async (leaveKey) => { + await mountPlugin(); + pressKey("v"); + pressKey("v"); + pressKey("l"); + expect(pageSelection().toString()).toBe("z"); + + expect(pressKey(leaveKey).defaultPrevented).toBe(true); + + expect(getUiState().copyMode).toEqual({ active: false }); + expect(pageSelection().rangeCount).toBe(0); + expect(modePill()).toBeNull(); + expect(execCommand).not.toHaveBeenCalled(); + expect(getUiState().notice).toBeNull(); + expect(pressKey("j").defaultPrevented).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(80); + }, + ); + + it("swallows a key that means nothing in copy mode", async () => { + await mountPlugin(); + pressKey("v"); + + for (const key of ["z", "i", "/", ":", " ", "Tab", "1", "Backspace"]) { + expect(pressKey(key).defaultPrevented, key).toBe(true); + } + + expect(cursorPlace()).toBe("line-3:0"); + expect(getUiState().copyMode).toMatchObject({ active: true, selecting: false }); + expect(view.inspection.composer.focusCount).toBe(0); + expect(focusedPaneViewport().scrollTop).toBe(0); + expect(getUiState().notice).toBeNull(); + }); + + it("leaves Cmd+C and other shortcuts with Cmd or Alt to the browser and bb", async () => { + await mountPlugin(); + pressKey("v"); + pressKey("v"); + pressKey("l"); + + expect(press({ key: "c", metaKey: true }).defaultPrevented).toBe(false); + expect(press({ key: "k", metaKey: true }).defaultPrevented).toBe(false); + expect(press({ key: "ArrowLeft", altKey: true }).defaultPrevented).toBe(false); + + expect(modePill()).toBe("VISUAL"); + expect(pageSelection().toString()).toBe("z"); + }); + + it("moves half a page on Ctrl-d and Ctrl-u instead of scrolling", async () => { + await mountPlugin(); + pressKey("v"); + + expect(pressCtrl("u").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-1:0"); + expect(pressCtrl("d").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:0"); + expect(focusedPaneViewport().scrollTop).toBe(0); + }); + + it("leaves copy mode on the prefix then h, which goes to the sidebar as usual", async () => { + await mountPlugin(); + pressKey("v"); + + expect(pressCtrl("a").defaultPrevented).toBe(true); + expect(getUiState().copyMode).toMatchObject({ active: true }); + expect(pressKey("h").defaultPrevented).toBe(true); + + expect(getUiState().copyMode).toEqual({ active: false }); + expect(modePill()).toBeNull(); + expect(document.activeElement).toBe(sidebarRow("thr-1")); + }); + + it("leaves copy mode on Ctrl-l, which moves to the pane on the right as usual", async () => { + await mountPlugin(); + const pointerDown = onEvent(pane("pane-2"), "pointerdown"); + pressKey("v"); + + expect(pressCtrl("l").defaultPrevented).toBe(true); + + expect(getUiState().copyMode).toEqual({ active: false }); + expect(pointerDown).toHaveBeenCalledTimes(1); + }); + + it("leaves copy mode and clears the selection on a pointer press", async () => { + await mountPlugin(); + pressKey("v"); + pressKey("v"); + pressKey("l"); + + pressPointer(fixture("line-1")); + + expect(getUiState().copyMode).toEqual({ active: false }); + expect(pageSelection().rangeCount).toBe(0); + expect(modePill()).toBeNull(); + }); + + it("leaves copy mode when the window loses focus", async () => { + await mountPlugin(); + pressKey("v"); + + act(() => { + window.dispatchEvent(new Event("blur")); + }); + + expect(getUiState().copyMode).toEqual({ active: false }); + }); + + it("leaves copy mode when the cursor goes into the message box", async () => { + await mountPlugin(); + pressKey("v"); + const composer = fixture("composer"); + composer.focus(); + + expect(pressKey("j", composer).defaultPrevented).toBe(false); + + expect(getUiState().copyMode).toEqual({ active: false }); + }); + + it("leaves copy mode at once when the keys are paused", async () => { + await mountPlugin(); + pressKey("v"); + + await runCommand("toggle-paused"); + + expect(getUiState().copyMode).toEqual({ active: false }); + expect(modePill()).toBeNull(); + }); + + it("leaves copy mode when the plugin is unloaded", async () => { + await mountPlugin(); + pressKey("v"); + pressKey("v"); + pressKey("l"); + + await act(async () => { + await mounted.lifecycle.dispose(); + }); + + expect(getUiState().copyMode).toEqual({ active: false }); + expect(pageSelection().rangeCount).toBe(0); + expect(pressKey("v").defaultPrevented).toBe(false); + }); + + it("leaves copy mode, without a notice, on the first key after bb showed another thread in the pane", async () => { + await mountPlugin(); + pressKey("v"); + pressKey("v"); + pressKey("l"); + expect(press({ key: "}", metaKey: true, shiftKey: true }).defaultPrevented).toBe(false); + const viewport = bbShowsAnotherThread(); + + expect(pressKey("j").defaultPrevented).toBe(true); + + expect(getUiState().copyMode).toEqual({ active: false }); + expect(modePill()).toBeNull(); + expect(getUiState().notice).toBeNull(); + expect(viewport.scrollTop).toBe(80); + }); + + it("leaves copy mode, without a notice, when the new thread scrolls", async () => { + await mountPlugin(); + pressKey("v"); + const viewport = bbShowsAnotherThread(); + + act(() => { + viewport.dispatchEvent(new Event("scroll")); + }); + await act(() => afterFrames(2)); + + expect(getUiState().copyMode).toEqual({ active: false }); + expect(modePill()).toBeNull(); + expect(getUiState().notice).toBeNull(); + }); + + it.each(["notes", "composer", "terminal-input"])( + "types v in the %s field instead of entering copy mode", + async (testId) => { + await mountPlugin(); + + expect(pressKey("v", fixture(testId)).defaultPrevented).toBe(false); + + expect(getUiState().copyMode).toEqual({ active: false }); + }, + ); + + it("enters on the prefix then [ from the message box and takes the cursor out of it", async () => { + await mountPlugin(); + const composer = fixture("composer"); + composer.focus(); + + pressCtrl("a", composer); + expect(pressKey("[", composer).defaultPrevented).toBe(true); + + expect(modePill()).toBe("COPY"); + expect(document.activeElement).toBe(pane("pane-1")); + expect(pressKey("k", pane("pane-1")).defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-2:0"); + }); + + it("enters on the prefix then [ while vimKeys is off, where v does nothing", async () => { + await mountPlugin({ settings: { vimKeys: false } }); + + expect(pressKey("v").defaultPrevented).toBe(false); + expect(getUiState().copyMode).toEqual({ active: false }); + + pressCtrl("a"); + pressKey("["); + expect(modePill()).toBe("COPY"); + expect(pressKey("k").defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-2:0"); + }); + + // A German Mac keyboard: Option-5 types "[", Option-8 "{" and Option-9 "}". + it("takes [, { and } typed with Option on a Mac keyboard layout that needs it", async () => { + vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); + await mountPlugin({ settings: { vimKeys: false } }); + + pressCtrl("a"); + expect(press({ key: "[", code: "Digit5", altKey: true }).defaultPrevented).toBe(true); + expect(modePill()).toBe("COPY"); + expect(cursorPlace()).toBe("line-3:0"); + + expect(press({ key: "{", code: "Digit8", altKey: true }).defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-2:0"); + expect(press({ key: "}", code: "Digit9", altKey: true }).defaultPrevented).toBe(true); + expect(cursorPlace()).toBe("line-3:0"); + }); + + it("still passes Option shortcuts that type no key of the plugin on to bb in copy mode", async () => { + vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); + await mountPlugin(); + pressKey("v"); + + expect(press({ key: "@", code: "KeyL", altKey: true }).defaultPrevented).toBe(false); + expect(press({ key: "≈", code: "KeyX", altKey: true }).defaultPrevented).toBe(false); + expect(press({ key: "|", code: "Digit7", altKey: true }).defaultPrevented).toBe(false); + + expect(modePill()).toBe("COPY"); + expect(cursorPlace()).toBe("line-3:0"); + }); + + it("treats Alt with [ as a shortcut on Windows and Linux, where Alt types nothing", async () => { + vi.spyOn(navigator, "platform", "get").mockReturnValue("Win32"); + await mountPlugin(); + + pressCtrl("a"); + expect(press({ key: "[", code: "BracketLeft", altKey: true }).defaultPrevented).toBe(true); + + expect(getUiState().prefixArmed).toBe(false); + expect(getUiState().copyMode).toEqual({ active: false }); + }); + + it("says so when the conversation has no text to select", async () => { + await mountPlugin(); + focusedPaneViewport().replaceChildren(); + + expect(pressKey("v").defaultPrevented).toBe(true); + + expect(getUiState().copyMode).toEqual({ active: false }); + expect(getUiState().notice?.text).toBe( + "There is no conversation text to select here", + ); + }); + + it("lists the copy mode keys in the key help", async () => { + await mountPlugin(); + + pressCtrl("a"); + pressKey("?"); + + const help = screen.getByRole("dialog", { name: "Tmux + Vim keys" }); + expect(help.textContent).toContain("Copy mode"); + expect(help.textContent).toContain("Start selecting, or drop the selection"); + expect(help.textContent).toContain("Ctrl-a ["); + }); +}); + +describe("copy mode next to bb's selection menu", () => { + beforeEach(installBrowserFakes); + afterEach(removeBrowserFakes); + + it("goes on selecting and copies while bb shows its menu for the selection", async () => { + await mountPlugin(); + pressKey("v"); + pressKey("v"); + pressKey("l"); + showBbSelectionMenu(); + + expect(pressKey("l").defaultPrevented).toBe(true); + expect(pageSelection().toString()).toBe("ze"); + expect(modePill()).toBe("VISUAL"); + + expect(pressKey("y").defaultPrevented).toBe(true); + expect(copiedTexts).toEqual(["ze"]); + await waitFor(() => expect(getUiState().notice?.text).toBe(COPIED_NOTICE)); + expect(getUiState().copyMode).toEqual({ active: false }); + }); + + it("starts at the end of a mouse selection although bb shows its menu for it", async () => { + await mountPlugin(); + const line = lineText("line-1"); + pageSelection().setBaseAndExtent(line, 0, line, 5); + showBbSelectionMenu(); + + expect(pressKey("v").defaultPrevented).toBe(true); + + expect(modePill()).toBe("COPY"); + expect(cursorPlace()).toBe("line-1:5"); + expect(pageSelection().isCollapsed).toBe(true); + }); + + it("keeps the prefix and the browsing keys working while the menu shows", async () => { + await mountPlugin(); + const line = lineText("line-1"); + pageSelection().setBaseAndExtent(line, 0, line, 5); + showBbSelectionMenu(); + + expect(pressKey("j").defaultPrevented).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(80); + expect(pressCtrl("a").defaultPrevented).toBe(true); + expect(pressKey("w").defaultPrevented).toBe(true); + expect(getUiState().chooser).toEqual({ open: true, placement: "replace" }); + }); + + it("leaves the selection to bb's Add to chat button when that is pressed", async () => { + await mountPlugin(); + pressKey("v"); + pressKey("v"); + press({ key: "$", shiftKey: true }); + const addToChat = showBbSelectionMenu(); + + pressPointer(addToChat); + + expect(getUiState().copyMode).toEqual({ active: false }); + expect(modePill()).toBeNull(); + expect(pageSelection().toString()).toBe("zeta eta theta"); + }); + + it("stays out of the way while the cursor is on the menu's own button", async () => { + await mountPlugin(); + const addToChat = showBbSelectionMenu(); + addToChat.focus(); + + expect(pressKey("j", addToChat).defaultPrevented).toBe(false); + expect(pressCtrl("a", addToChat).defaultPrevented).toBe(false); + }); + + it("keeps the prefix working in the terminal while bb shows its menu for selected terminal output", async () => { + await mountPlugin(); + const terminal = fixture("terminal-input"); + const pointerDown = onEvent(pane("pane-2"), "pointerdown"); + terminal.focus(); + document.body.insertAdjacentHTML("beforeend", BB_SELECTION_MENU); + + expect(pressCtrl("a", terminal).defaultPrevented).toBe(true); + expect(getUiState().prefixArmed).toBe(true); + expect(pressKey("l", terminal).defaultPrevented).toBe(true); + + expect(pointerDown).toHaveBeenCalledTimes(1); + }); + + it("keeps the browsing keys and copy mode working while the menu shows on the page body, as for a file preview", async () => { + await mountPlugin(); + document.body.insertAdjacentHTML("beforeend", BB_SELECTION_MENU); + + expect(pressKey("j").defaultPrevented).toBe(true); + expect(focusedPaneViewport().scrollTop).toBe(80); + expect(pressCtrl("l").defaultPrevented).toBe(true); + expect(pressKey("v").defaultPrevented).toBe(true); + expect(modePill()).toBe("COPY"); + }); + + it("still handles no key while another popover of bb is open on the page body", async () => { + await mountPlugin(); + document.body.insertAdjacentHTML("beforeend", BB_OTHER_POPOVER); + + expect(pressKey("j").defaultPrevented).toBe(false); + expect(pressCtrl("a").defaultPrevented).toBe(false); + expect(pressCtrl("l").defaultPrevented).toBe(false); + expect(pressKey("v").defaultPrevented).toBe(false); + expect(getUiState().copyMode).toEqual({ active: false }); + }); +}); + +describe("copying with the mouse", () => { + beforeEach(installBrowserFakes); + afterEach(removeBrowserFakes); + + it("copies conversation text as soon as the mouse button is released", async () => { + await mountPlugin(); + + await selectWithMouse(lineText("line-1"), 0, 5); + + expect(execCommand.mock.calls).toEqual([["copy"]]); + expect(copiedTexts).toEqual(["alpha"]); + await waitFor(() => expect(getUiState().notice?.text).toBe(COPIED_NOTICE)); + expect(pageSelection().toString()).toBe("alpha"); + expect(getUiState().copyMode).toEqual({ active: false }); + }); + + it("does not copy the same selection again on a click on bb's selection menu", async () => { + await mountPlugin(); + await selectWithMouse(lineText("line-1"), 0, 5); + + await clickWithButton(showBbSelectionMenu()); + + expect(copiedTexts).toEqual(["alpha"]); + }); + + it("copies nothing on a click in the sidebar or on a button while conversation text is selected", async () => { + await mountPlugin(); + const line = lineText("line-1"); + pageSelection().setBaseAndExtent(line, 0, line, 5); + await nextTask(); + + await clickWithButton(sidebarRow("thr-2")); + await clickWithButton(fixture("close-pane")); + await releaseMouseOn(document.body); + + expect(pageSelection().toString()).toBe("alpha"); + expect(execCommand).not.toHaveBeenCalled(); + expect(mounted.inspection.experimental_clipboardWrites).toEqual([]); + expect(getUiState().notice).toBeNull(); + }); + + it("copies nothing for the word a right click selects, nor on the next click in the sidebar", async () => { + await mountPlugin(); + const line = lineText("line-1"); + const paragraph = fixture("line-1"); + + pressMouseOn(paragraph, { button: 2 }); + pageSelection().setBaseAndExtent(line, 0, line, 5); + paragraph.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, button: 2 })); + await releaseMouseOn(paragraph, { button: 2 }); + await clickWithButton(sidebarRow("thr-2")); + + expect(pageSelection().toString()).toBe("alpha"); + expect(execCommand).not.toHaveBeenCalled(); + expect(getUiState().notice).toBeNull(); + }); + + it("copies nothing for a copy mode selection when bb's menu is pressed and the button is released beside it", async () => { + await mountPlugin(); + pressKey("v"); + pressKey("v"); + press({ key: "$", shiftKey: true }); + const addToChat = showBbSelectionMenu(); + + pressPointer(addToChat); + pressMouseOn(addToChat); + await releaseMouseOn(fixture("line-3")); + + expect(getUiState().copyMode).toEqual({ active: false }); + expect(pageSelection().toString()).toBe("zeta eta theta"); + expect(execCommand).not.toHaveBeenCalled(); + expect(getUiState().notice).toBeNull(); + }); + + it("copies again once the selection has changed", async () => { + await mountPlugin(); + await selectWithMouse(lineText("line-1"), 0, 5); + + await selectWithMouse(lineText("line-2"), 0, 5); + + expect(copiedTexts).toEqual(["alpha", "delta"]); + }); + + it("does not copy text selected in the message box", async () => { + await mountPlugin(); + const composer = fixture("composer"); + composer.textContent = "draft words"; + + await selectWithMouse(composer.firstChild as Text, 0, 5); + + expect(pageSelection().toString()).toBe("draft"); + expect(execCommand).not.toHaveBeenCalled(); + expect(mounted.inspection.experimental_clipboardWrites).toEqual([]); + expect(getUiState().notice).toBeNull(); + }); + + it("does not copy text selected outside a conversation", async () => { + await mountPlugin(); + + await selectWithMouse(sidebarRow("thr-1").firstChild as Text, 0, 5); + + expect(pageSelection().toString()).toBe("Alpha"); + expect(execCommand).not.toHaveBeenCalled(); + expect(getUiState().notice).toBeNull(); + }); + + it("copies nothing when copyOnSelect is off", async () => { + await mountPlugin({ settings: { copyOnSelect: false } }); + + await selectWithMouse(lineText("line-1"), 0, 5); + + expect(execCommand).not.toHaveBeenCalled(); + expect(mounted.inspection.experimental_clipboardWrites).toEqual([]); + expect(getUiState().notice).toBeNull(); + }); + + it("copies nothing while the keys are paused, nor on the first click after they are resumed", async () => { + await mountPlugin(); + await runCommand("toggle-paused"); + + await selectWithMouse(lineText("line-1"), 0, 5); + + expect(execCommand).not.toHaveBeenCalled(); + expect(getUiState().notice?.text).toContain("paused"); + + await runCommand("toggle-paused"); + await clickWithButton(sidebarRow("thr-2")); + + expect(pageSelection().toString()).toBe("alpha"); + expect(execCommand).not.toHaveBeenCalled(); + expect(getUiState().notice?.text).toContain("on again"); + }); + + it("copies nothing while the plugin is switched off", async () => { + await mountPlugin({ settings: { enabled: false } }); + + await selectWithMouse(lineText("line-1"), 0, 5); + + expect(pageSelection().toString()).toBe("alpha"); + expect(execCommand).not.toHaveBeenCalled(); + expect(mounted.inspection.experimental_clipboardWrites).toEqual([]); + expect(getUiState().notice).toBeNull(); + }); + + it("copies nothing on a plain click, which selects nothing", async () => { + await mountPlugin(); + const paragraph = fixture("line-1"); + + pressMouseOn(paragraph); + pageSelection().collapse(lineText("line-1"), 3); + await releaseMouseOn(paragraph); + + expect(execCommand).not.toHaveBeenCalled(); + expect(getUiState().notice).toBeNull(); + }); + + it("falls back to bb's plain-text copy when the browser refuses its copy command", async () => { + await mountPlugin(); + execCommand.mockReturnValue(false); + + await selectWithMouse(lineText("line-1"), 0, 5); + + await waitFor(() => expect(getUiState().notice?.text).toBe(COPIED_NOTICE)); + expect(mounted.inspection.experimental_clipboardWrites).toEqual([ + { text: "alpha" }, + ]); + }); + + it("copies nothing once the plugin is unloaded", async () => { + await mountPlugin(); + await act(async () => { + await mounted.lifecycle.dispose(); + }); + + await selectWithMouse(lineText("line-1"), 0, 5); + + expect(execCommand).not.toHaveBeenCalled(); + }); +}); diff --git a/plugins/tmux-vim/app.tsx b/plugins/tmux-vim/app.tsx new file mode 100644 index 00000000..553b099b --- /dev/null +++ b/plugins/tmux-vim/app.tsx @@ -0,0 +1,17 @@ +import { definePluginApp } from "@get-bb/plugin-sdk/app"; +import "./app.css"; +import { PALETTE_COMMANDS } from "./src/commands"; +import { mountKeyHandler } from "./src/content-script"; +import { TmuxVimOverlay } from "./src/overlay/Overlay"; + +export default definePluginApp((app) => { + app.contentScripts.register({ + id: "keys", + mount: (context) => mountKeyHandler(context), + }); + app.slots.experimental_appOverlay({ + id: "overlay", + component: TmuxVimOverlay, + }); + for (const command of PALETTE_COMMANDS) app.commands.register(command); +}); diff --git a/plugins/tmux-vim/components.json b/plugins/tmux-vim/components.json new file mode 100644 index 00000000..d720305b --- /dev/null +++ b/plugins/tmux-vim/components.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "tsx": true, + "tailwind": { + "config": "", + "css": "app.css", + "baseColor": "neutral", + "cssVariables": true + }, + "aliases": { + "components": "@/components", + "ui": "@/components/ui", + "lib": "@/lib", + "utils": "@/lib/utils", + "hooks": "@/hooks" + }, + "registries": { + "@bb": "https://raw.githubusercontent.com/get-bb/bb/desktop-v0.49.0/packages/plugin-registry/r/{name}.json" + } +} diff --git a/plugins/tmux-vim/components/ui/button.tsx b/plugins/tmux-vim/components/ui/button.tsx new file mode 100644 index 00000000..1d049e67 --- /dev/null +++ b/plugins/tmux-vim/components/ui/button.tsx @@ -0,0 +1,59 @@ +import * as React from "react"; +import { Slot } from "@radix-ui/react-slot"; +import { cva, type VariantProps } from "class-variance-authority"; + +import { cn } from "../../lib/utils"; +import { CONTROL_HOVER_TRANSITION } from "./motion.js"; + +const buttonVariants = cva( + `inline-flex cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ${CONTROL_HOVER_TRANSITION} focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_[data-icon-root]]:pointer-events-none [&_[data-icon-root]]:size-4 [&_[data-icon-root]]:shrink-0`, + { + variants: { + variant: { + default: "bg-foreground text-background hover:bg-foreground/90", + destructive: + "bg-destructive text-destructive-foreground hover:bg-destructive/90", + outline: + "border border-input bg-transparent hover:bg-state-hover hover:text-foreground", + secondary: + "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: + "hover:bg-state-hover hover:text-foreground aria-pressed:bg-state-active aria-pressed:text-foreground aria-pressed:hover:bg-state-active data-[state=open]:bg-state-active data-[state=open]:text-foreground data-[state=open]:hover:bg-state-active", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-9 px-4 py-2", + sm: "h-8 rounded-md px-3 text-xs", + lg: "h-10 rounded-md px-8", + icon: "h-9 w-9", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + }, +); + +export interface ButtonProps + extends + Omit, "title">, + VariantProps { + asChild?: boolean; +} + +const Button = React.forwardRef( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button"; + return ( + + ); + }, +); +Button.displayName = "Button"; + +export { Button, buttonVariants }; diff --git a/plugins/tmux-vim/components/ui/coarse-pointer-sizing.ts b/plugins/tmux-vim/components/ui/coarse-pointer-sizing.ts new file mode 100644 index 00000000..30ff2d28 --- /dev/null +++ b/plugins/tmux-vim/components/ui/coarse-pointer-sizing.ts @@ -0,0 +1,66 @@ +export const COARSE_POINTER_TEXT_BASE_CLASS = + "text-sm max-md:pointer-coarse:text-base"; + +export const COARSE_POINTER_TEXT_SM_CLASS = + "text-xs max-md:pointer-coarse:text-sm"; + +export const COARSE_POINTER_ICON_SIZE_CLASS = + "size-4 max-md:pointer-coarse:size-5"; + +export const COARSE_POINTER_ICON_SIZE_SHRINK_CLASS = + "size-4 shrink-0 max-md:pointer-coarse:size-5"; + +export const COARSE_POINTER_COMPACT_ICON_SIZE_CLASS = + "size-3.5 max-md:pointer-coarse:size-5"; + +export const COARSE_POINTER_COMPACT_ICON_SIZE_SHRINK_CLASS = + "size-3.5 shrink-0 max-md:pointer-coarse:size-5"; + +export const COARSE_POINTER_DOT_SIZE_CLASS = + "size-1.5 max-md:pointer-coarse:size-2"; + +export const COARSE_POINTER_GLYPH_BOX_CLASS = + "h-4 w-4 max-md:pointer-coarse:h-5 max-md:pointer-coarse:w-5"; + +export const COARSE_POINTER_CHECK_SLOT_CLASS = + "h-3.5 w-3.5 max-md:pointer-coarse:h-5 max-md:pointer-coarse:w-5"; + +const HEADER_ICON_BUTTON_BOX_CLASS = + "h-[28px] w-[28px] rounded-md p-0 max-md:pointer-coarse:h-[36px] max-md:pointer-coarse:w-[36px]"; + +export const COARSE_POINTER_HEADER_ICON_BUTTON_CLASS = `${HEADER_ICON_BUTTON_BOX_CLASS} [&_[data-icon-root]]:size-[16px] max-md:pointer-coarse:[&_[data-icon-root]]:size-[20px]`; + +export const COARSE_POINTER_HEADER_REDUCED_GLYPH_ICON_BUTTON_CLASS = `${HEADER_ICON_BUTTON_BOX_CLASS} [&_[data-icon-root]]:size-[13px] max-md:pointer-coarse:[&_[data-icon-root]]:size-[16px]`; + +export const COARSE_POINTER_COMPACT_ICON_BUTTON_CLASS = + "h-7 w-7 rounded-md p-0 [&_[data-icon-root]]:size-3.5 max-md:pointer-coarse:h-9 max-md:pointer-coarse:w-9 max-md:pointer-coarse:[&_[data-icon-root]]:size-5"; + +export const COARSE_POINTER_CHILD_ICON_BUTTON_CLASS = + "h-8 w-8 justify-center p-0 [&>[data-icon-root]]:size-4 max-md:pointer-coarse:h-9 max-md:pointer-coarse:w-9 max-md:pointer-coarse:[&>[data-icon-root]]:size-5"; + +export const COARSE_POINTER_TOOLBAR_ACTION_BUTTON_CLASS = + "h-7 rounded-md border-border bg-transparent px-2 text-xs font-medium text-foreground shadow-none hover:bg-state-hover hover:text-foreground max-md:pointer-coarse:h-9"; + +export const COARSE_POINTER_PROMPT_ACTION_BUTTON_CLASS = + "h-8 px-2 transition-all max-md:pointer-coarse:h-10 max-md:pointer-coarse:px-3"; + +export const COARSE_POINTER_PROMPT_ICON_ACTION_BUTTON_CLASS = + "size-auto h-8 px-2 transition-all max-md:pointer-coarse:h-10 max-md:pointer-coarse:px-3"; + +export const COARSE_POINTER_PROMPT_COMBO_BUTTON_CLASS = + "h-8 w-8 rounded-l-none border-l border-l-primary-foreground/20 px-0 transition-all hover:border-l-primary-foreground/30 max-md:pointer-coarse:h-10 max-md:pointer-coarse:w-10"; + +export const COARSE_POINTER_INPUT_HEIGHT_CLASS = + "h-9 max-md:pointer-coarse:h-10"; + +export const COARSE_POINTER_COMPACT_ROW_HEIGHT_CLASS = + "h-7 max-md:pointer-coarse:h-9"; + +export const COARSE_POINTER_ROW_HEIGHT_CLASS = + "h-[var(--bb-sidebar-row-height)] max-md:pointer-coarse:h-[var(--bb-sidebar-row-height-coarse)]"; + +export const COARSE_POINTER_PROVIDER_TAB_SIZE_CLASS = + "h-7 w-6 max-md:pointer-coarse:h-9 max-md:pointer-coarse:w-9"; + +export const COARSE_POINTER_ROW_ACTION_SIZE_CLASS = + "h-7 w-7 max-md:pointer-coarse:h-9 max-md:pointer-coarse:w-9"; diff --git a/plugins/tmux-vim/components/ui/dialog.tsx b/plugins/tmux-vim/components/ui/dialog.tsx new file mode 100644 index 00000000..fb4faa0b --- /dev/null +++ b/plugins/tmux-vim/components/ui/dialog.tsx @@ -0,0 +1,453 @@ +import * as React from "react"; +import * as DialogPrimitive from "@radix-ui/react-dialog"; +import { Slot } from "@radix-ui/react-slot"; + +import { cn } from "../../lib/utils"; +import { usePortalScopeProps } from "../../lib/portal-scope"; +import { useBrowserDimmingModal } from "../../hooks/useBrowserDimmingModal"; +import { + type ResponsiveOverlayContextValue, + useResponsiveRoot, + MobileTrigger, + ResponsiveDrawerShell, + stripRadixContentProps, +} from "./responsive-overlay.js"; +import { + blurActiveKeyboardInputBeforeOverlayOpen, + getOverlayTriggerClassName, + preventOverlayTriggerSelection, +} from "./overlay-trigger.js"; +import { Icon } from "../../components/ui/icon.js"; + +interface ResponsiveDialogContextValue extends ResponsiveOverlayContextValue { + titleId: string; + descriptionId: string; + registerTitleId: (id: string) => () => void; + registerDescriptionId: (id: string) => () => void; +} + +const ResponsiveDialogContext = + React.createContext({ + isCompactViewport: false, + open: false, + onOpenChange: () => {}, + titleId: "", + descriptionId: "", + registerTitleId: () => () => {}, + registerDescriptionId: () => () => {}, + }); + +function useResponsiveDialog() { + return React.useContext(ResponsiveDialogContext); +} + +function Dialog({ + children, + open: controlledOpen, + onOpenChange: controlledOnChange, + ...props +}: React.ComponentProps) { + const responsiveRoot = useResponsiveRoot(controlledOpen, controlledOnChange); + const generatedTitleId = React.useId(); + const generatedDescriptionId = React.useId(); + const [titleId, setTitleId] = React.useState(generatedTitleId); + const [descriptionId, setDescriptionId] = React.useState( + generatedDescriptionId, + ); + const registerTitleId = React.useCallback( + (id: string) => { + setTitleId(id); + return () => setTitleId(generatedTitleId); + }, + [generatedTitleId], + ); + const registerDescriptionId = React.useCallback( + (id: string) => { + setDescriptionId(id); + return () => setDescriptionId(generatedDescriptionId); + }, + [generatedDescriptionId], + ); + const ctx = React.useMemo( + () => ({ + ...responsiveRoot, + titleId, + descriptionId, + registerTitleId, + registerDescriptionId, + }), + [ + descriptionId, + registerDescriptionId, + registerTitleId, + responsiveRoot, + titleId, + ], + ); + + const body = ctx.isCompactViewport ? ( + children + ) : ( + + {children} + + ); + + return ( + + {body} + + ); +} + +const DialogTrigger = React.forwardRef< + HTMLButtonElement, + React.ComponentPropsWithoutRef +>(({ asChild, children, className, ...props }, ref) => { + const { isCompactViewport, open, onOpenChange } = useResponsiveDialog(); + + if (isCompactViewport) { + return ( + + {children} + + ); + } + + return ( + { + if (!open) { + blurActiveKeyboardInputBeforeOverlayOpen(); + } + preventOverlayTriggerSelection(event); + }} + {...props} + > + {children} + + ); +}); +DialogTrigger.displayName = "DialogTrigger"; + +interface DialogCloseProps extends React.ButtonHTMLAttributes { + asChild?: boolean; +} + +const DialogClose = React.forwardRef( + ({ asChild, onClick, children, ...props }, ref) => { + const { isCompactViewport, onOpenChange } = useResponsiveDialog(); + + if (isCompactViewport) { + const Comp = asChild ? Slot : "button"; + const handleClick: React.MouseEventHandler = ( + event, + ) => { + onClick?.(event); + if (!event.defaultPrevented) { + onOpenChange(false); + } + }; + return ( + + {children} + + ); + } + + return ( + + {children} + + ); + }, +); +DialogClose.displayName = "DialogClose"; + +const DialogOverlay = React.forwardRef< + React.ComponentRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogOverlay.displayName = DialogPrimitive.Overlay.displayName; + +function useChildrenRetainedWhileClosing( + open: boolean, + children: React.ReactNode, +) { + const [wasOpen, setWasOpen] = React.useState(open); + const [closing, setClosing] = React.useState(false); + const [lastOpenChildren, setLastOpenChildren] = + React.useState(open ? children : null); + if (wasOpen !== open) { + setWasOpen(open); + setClosing(!open); + } + if (open && lastOpenChildren !== children) setLastOpenChildren(children); + const finishClosing = React.useCallback(() => { + setClosing(false); + setLastOpenChildren(null); + }, []); + return { + content: !open && closing ? lastOpenChildren : children, + finishClosing, + }; +} + +type DialogContentProps = React.ComponentPropsWithoutRef< + typeof DialogPrimitive.Content +> & { + onAfterCloseAutoFocus?: () => void; + hideCloseButton?: boolean; + compactContentClassName?: string; +}; + +const DialogContent = React.forwardRef( + ( + { + className, + children, + hideCloseButton = false, + compactContentClassName, + onAfterCloseAutoFocus, + onCloseAutoFocus, + ...props + }, + ref, + ) => { + const { isCompactViewport, open, onOpenChange, titleId, descriptionId } = + useResponsiveDialog(); + useBrowserDimmingModal(open); + const scopeProps = usePortalScopeProps(); + const { content, finishClosing } = useChildrenRetainedWhileClosing( + open, + children, + ); + + if (isCompactViewport) { + const domProps = stripRadixContentProps(props); + return ( + { + if (!settledOpen) finishClosing(); + }} + onEscapeKeyDown={props.onEscapeKeyDown} + onPointerDownOutside={props.onPointerDownOutside} + onInteractOutside={props.onInteractOutside} + labelledBy={titleId} + describedBy={descriptionId} + > +
+ {content} +
+
+ ); + } + + return ( + + + { + finishClosing(); + onCloseAutoFocus?.(event); + queueMicrotask(() => onAfterCloseAutoFocus?.()); + }} + className={cn( + "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg grid-cols-[minmax(0,1fr)] translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-sm duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 sm:rounded-lg", + className, + )} + {...props} + > + {content} + {hideCloseButton ? null : ( + + + Close + + )} + + + ); + }, +); +DialogContent.displayName = "DialogContent"; + +const DialogHeader = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +DialogHeader.displayName = "DialogHeader"; + +const DialogFooter = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +DialogFooter.displayName = "DialogFooter"; + +const DialogTitle = React.forwardRef< + HTMLHeadingElement, + React.ComponentPropsWithoutRef +>(({ asChild, className, id, children, ...props }, ref) => { + const { isCompactViewport, titleId, registerTitleId } = useResponsiveDialog(); + const resolvedId = id ?? titleId; + React.useLayoutEffect(() => { + if (!isCompactViewport) { + return; + } + return registerTitleId(resolvedId); + }, [isCompactViewport, registerTitleId, resolvedId]); + + if (isCompactViewport) { + const titleProps = { + id: resolvedId, + className: cn( + "text-base font-semibold leading-none tracking-tight", + className, + ), + ...props, + }; + if (asChild) { + return ( + + {children} + + ); + } + return ( +

+ {children} +

+ ); + } + return ( + + {children} + + ); +}); +DialogTitle.displayName = "DialogTitle"; + +const DialogDescription = React.forwardRef< + React.ComponentRef, + React.ComponentPropsWithoutRef +>(({ asChild, className, id, children, ...props }, ref) => { + const { isCompactViewport, descriptionId, registerDescriptionId } = + useResponsiveDialog(); + const resolvedId = id ?? descriptionId; + React.useLayoutEffect(() => { + if (!isCompactViewport) { + return; + } + return registerDescriptionId(resolvedId); + }, [isCompactViewport, registerDescriptionId, resolvedId]); + + if (isCompactViewport) { + const descriptionProps = { + id: resolvedId, + className: cn("text-sm text-muted-foreground", className), + ...props, + }; + if (asChild) { + return ( + + {children} + + ); + } + return ( +

+ {children} +

+ ); + } + return ( + + {children} + + ); +}); +DialogDescription.displayName = DialogPrimitive.Description.displayName; + +export { + Dialog, + DialogOverlay, + DialogTrigger, + DialogClose, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +}; diff --git a/plugins/tmux-vim/components/ui/hooks/use-compact-viewport.tsx b/plugins/tmux-vim/components/ui/hooks/use-compact-viewport.tsx new file mode 100644 index 00000000..e2adfaef --- /dev/null +++ b/plugins/tmux-vim/components/ui/hooks/use-compact-viewport.tsx @@ -0,0 +1,37 @@ +import { + createContext, + createElement, + useContext, + type ReactNode, +} from "react"; + +import { useMediaQuery } from "./use-media-query.js"; + +export const COMPACT_VIEWPORT_QUERY = "(max-width: 767px)"; + +const CompactViewportOverrideContext = createContext(null); + +interface CompactViewportOverrideProviderProps { + children: ReactNode; + isCompactViewport: boolean; +} + +export function CompactViewportOverrideProvider({ + children, + isCompactViewport, +}: CompactViewportOverrideProviderProps) { + return createElement( + CompactViewportOverrideContext.Provider, + { value: isCompactViewport }, + children, + ); +} + +export function useIsCompactViewport(): boolean { + const override = useContext(CompactViewportOverrideContext); + const isCompactViewport = useMediaQuery(COMPACT_VIEWPORT_QUERY); + if (override !== null) { + return override; + } + return isCompactViewport; +} diff --git a/plugins/tmux-vim/components/ui/hooks/use-media-query.ts b/plugins/tmux-vim/components/ui/hooks/use-media-query.ts new file mode 100644 index 00000000..076b07ac --- /dev/null +++ b/plugins/tmux-vim/components/ui/hooks/use-media-query.ts @@ -0,0 +1,70 @@ +import { useSyncExternalStore } from "react"; + +export const DARK_COLOR_SCHEME_QUERY = "(prefers-color-scheme: dark)"; +export const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)"; + +type MediaQueryRef = { + mql: MediaQueryList; + subscribe: (notify: () => void) => () => void; +}; + +const mediaQueryCache = new Map(); + +function createMediaQueryRef(query: string): MediaQueryRef | null { + if (typeof window === "undefined" || !window.matchMedia) return null; + + let ref = mediaQueryCache.get(query); + if (ref) return ref; + + const mql = window.matchMedia(query); + const listeners = new Set<() => void>(); + const onChange = () => { + for (const listener of listeners) listener(); + }; + + ref = { + mql, + subscribe(notify) { + const wasEmpty = listeners.size === 0; + listeners.add(notify); + if (wasEmpty) { + mql.addEventListener("change", onChange); + } + return () => { + listeners.delete(notify); + if (listeners.size === 0) { + mql.removeEventListener("change", onChange); + mediaQueryCache.delete(query); + } + }; + }, + }; + mediaQueryCache.set(query, ref); + return ref; +} + +export function subscribeMediaQuery( + query: string, + notify: () => void, +): () => void { + return createMediaQueryRef(query)?.subscribe(notify) ?? (() => {}); +} + +export function getMediaQuerySnapshot(query: string): boolean { + if (typeof window === "undefined" || !window.matchMedia) return false; + return ( + mediaQueryCache.get(query)?.mql.matches ?? window.matchMedia(query).matches + ); +} + +export function useMediaQuery(query: string): boolean { + return useSyncExternalStore( + (notify) => subscribeMediaQuery(query, notify), + () => getMediaQuerySnapshot(query), + () => false, + ); +} + +export function usePrefersReducedMotion(): boolean { + return useMediaQuery(REDUCED_MOTION_QUERY); +} diff --git a/plugins/tmux-vim/components/ui/hooks/use-pointer-coarse.ts b/plugins/tmux-vim/components/ui/hooks/use-pointer-coarse.ts new file mode 100644 index 00000000..7c123c51 --- /dev/null +++ b/plugins/tmux-vim/components/ui/hooks/use-pointer-coarse.ts @@ -0,0 +1,7 @@ +import { useMediaQuery } from "./use-media-query.js"; + +export const POINTER_COARSE_QUERY = "(pointer: coarse)"; + +export function usePointerCoarse(): boolean { + return useMediaQuery(POINTER_COARSE_QUERY); +} diff --git a/plugins/tmux-vim/components/ui/icon.tsx b/plugins/tmux-vim/components/ui/icon.tsx new file mode 100644 index 00000000..1bb8fb0c --- /dev/null +++ b/plugins/tmux-vim/components/ui/icon.tsx @@ -0,0 +1,8 @@ +import { + experimental_Icon, + type ExperimentalIconProps, +} from "@get-bb/plugin-sdk/app"; + +export type IconName = string; +export type IconProps = ExperimentalIconProps; +export const Icon = experimental_Icon; diff --git a/plugins/tmux-vim/components/ui/input.tsx b/plugins/tmux-vim/components/ui/input.tsx new file mode 100644 index 00000000..ccb7295a --- /dev/null +++ b/plugins/tmux-vim/components/ui/input.tsx @@ -0,0 +1,30 @@ +import * as React from "react"; + +import { + COARSE_POINTER_INPUT_HEIGHT_CLASS, + COARSE_POINTER_TEXT_BASE_CLASS, +} from "./coarse-pointer-sizing.js"; +import { cn } from "../../lib/utils"; +import { CONTROL_HOVER_TRANSITION } from "./motion.js"; + +const Input = React.forwardRef>( + ({ className, type, ...props }, ref) => { + return ( + + ); + }, +); +Input.displayName = "Input"; + +export { Input }; diff --git a/plugins/tmux-vim/components/ui/motion.ts b/plugins/tmux-vim/components/ui/motion.ts new file mode 100644 index 00000000..caaa329c --- /dev/null +++ b/plugins/tmux-vim/components/ui/motion.ts @@ -0,0 +1,4 @@ +export const CONTROL_HOVER_TRANSITION = + "transition-colors duration-150 hover:duration-0"; + +export const LIST_HOVER_TRANSITION = "transition-none"; diff --git a/plugins/tmux-vim/components/ui/overlay-trigger.ts b/plugins/tmux-vim/components/ui/overlay-trigger.ts new file mode 100644 index 00000000..cf0bff66 --- /dev/null +++ b/plugins/tmux-vim/components/ui/overlay-trigger.ts @@ -0,0 +1,84 @@ +import type { MouseEvent } from "react"; +import { cn } from "../../lib/utils"; + +const OVERLAY_TRIGGER_CLASS_NAME = "select-none"; + +type OverlayTriggerClassNameResolver = (className?: string) => string; + +const NON_TEXT_INPUT_TYPES = new Set([ + "button", + "checkbox", + "file", + "hidden", + "image", + "radio", + "range", + "reset", + "submit", +]); + +export const getOverlayTriggerClassName: OverlayTriggerClassNameResolver = ( + className, +) => cn(OVERLAY_TRIGGER_CLASS_NAME, className); + +function isKeyboardInputElement(element: Element): element is HTMLElement { + if (element instanceof HTMLTextAreaElement) return true; + if (element instanceof HTMLInputElement) { + return ( + !element.disabled && + !element.readOnly && + !NON_TEXT_INPUT_TYPES.has(element.type) + ); + } + if (!(element instanceof HTMLElement)) return false; + + return ( + element.isContentEditable || + element.closest("[contenteditable='true']") !== null + ); +} + +export function blurActiveKeyboardInputWithin(container: Element | null): void { + if (typeof document === "undefined") return; + + const activeElement = document.activeElement; + if (!activeElement || !isKeyboardInputElement(activeElement)) return; + if (container !== null && !container.contains(activeElement)) return; + + activeElement.blur(); +} + +export function blurActiveKeyboardInputBeforeOverlayOpen(): void { + blurActiveKeyboardInputWithin(null); +} + +export function blurActiveKeyboardInputBeforeOverlayClose(): void { + blurActiveKeyboardInputWithin(null); +} + +export function preventOverlayTriggerSelection(event: MouseEvent): void { + event.preventDefault(); +} + +let lastInputModality: "pointer" | "keyboard" = "pointer"; + +if (typeof document !== "undefined") { + document.addEventListener( + "keydown", + () => { + lastInputModality = "keyboard"; + }, + { capture: true }, + ); + document.addEventListener( + "pointerdown", + () => { + lastInputModality = "pointer"; + }, + { capture: true }, + ); +} + +export function isLastInputKeyboard(): boolean { + return lastInputModality === "keyboard"; +} diff --git a/plugins/tmux-vim/components/ui/responsive-overlay.tsx b/plugins/tmux-vim/components/ui/responsive-overlay.tsx new file mode 100644 index 00000000..fb01ed7f --- /dev/null +++ b/plugins/tmux-vim/components/ui/responsive-overlay.tsx @@ -0,0 +1,895 @@ +import * as React from "react"; +import { createPortal } from "react-dom"; +import { Slot } from "@radix-ui/react-slot"; + +import { + blurActiveKeyboardInputBeforeOverlayOpen, + blurActiveKeyboardInputBeforeOverlayClose, + blurActiveKeyboardInputWithin, + getOverlayTriggerClassName, + preventOverlayTriggerSelection, +} from "./overlay-trigger.js"; +import { useIsCompactViewport } from "./hooks/use-compact-viewport.js"; +import { usePointerCoarse } from "./hooks/use-pointer-coarse.js"; +import { usePortalScopeProps } from "../../lib/portal-scope.js"; +import { cn } from "../../lib/utils.js"; + +export interface ResponsiveOverlayContextValue { + isCompactViewport: boolean; + open: boolean; + onOpenChange: (open: boolean) => void; +} + +const RESPONSIVE_DRAWER_REALIZE_FALLBACK_MS = 120; + +export const COMPACT_SHEET_CONTENT_STYLE: React.CSSProperties = { + width: "auto", + minWidth: "auto", + maxWidth: "none", +}; + +const DRAWER_KEYBOARD_INSET_PROPERTY = "--bb-drawer-keyboard-inset"; +const DRAWER_KEYBOARD_MIN_OVERLAP_PX = 80; + +function resetDrawerKeyboardStyles(drawerElement: HTMLElement | null): void { + if (drawerElement === null) return; + + drawerElement.style.height = ""; + drawerElement.style.bottom = ""; + drawerElement.style.removeProperty(DRAWER_KEYBOARD_INSET_PROPERTY); +} + +export function measureDrawerKeyboardOverlap({ + layoutViewportHeight, + visualViewportHeight, + visualViewportOffsetTop, +}: { + layoutViewportHeight: number; + visualViewportHeight: number; + visualViewportOffsetTop: number; +}): number { + const overlap = Math.round( + layoutViewportHeight - (visualViewportHeight + visualViewportOffsetTop), + ); + return overlap >= DRAWER_KEYBOARD_MIN_OVERLAP_PX ? overlap : 0; +} + +function useDrawerKeyboardInset( + panelRef: React.RefObject, + open: boolean, +): void { + React.useEffect(() => { + const panel = panelRef.current; + const visualViewport = window.visualViewport; + if (panel === null || !open || !visualViewport) return; + + let animationFrame: number | null = null; + const applyInset = () => { + animationFrame = null; + if (visualViewport.scale !== 1) { + resetDrawerKeyboardStyles(panel); + return; + } + const overlap = measureDrawerKeyboardOverlap({ + layoutViewportHeight: panel.ownerDocument.documentElement.clientHeight, + visualViewportHeight: visualViewport.height, + visualViewportOffsetTop: visualViewport.offsetTop, + }); + if (overlap === 0) { + panel.style.bottom = ""; + panel.style.removeProperty(DRAWER_KEYBOARD_INSET_PROPERTY); + return; + } + panel.style.bottom = `${overlap}px`; + panel.style.setProperty(DRAWER_KEYBOARD_INSET_PROPERTY, `${overlap}px`); + }; + const scheduleUpdate = () => { + if (animationFrame !== null) { + window.cancelAnimationFrame(animationFrame); + } + animationFrame = window.requestAnimationFrame(applyInset); + }; + + applyInset(); + visualViewport.addEventListener("resize", scheduleUpdate); + visualViewport.addEventListener("scroll", scheduleUpdate); + + return () => { + visualViewport.removeEventListener("resize", scheduleUpdate); + visualViewport.removeEventListener("scroll", scheduleUpdate); + if (animationFrame !== null) { + window.cancelAnimationFrame(animationFrame); + } + resetDrawerKeyboardStyles(panel); + }; + }, [open, panelRef]); +} + +export function useResponsiveOverlayBehavior() { + const presentation = useIsCompactViewport() ? "drawer" : "floating"; + const isPointerCoarse = usePointerCoarse(); + + return { + presentation, + supportsHover: presentation === "floating" && !isPointerCoarse, + }; +} + +export function useResponsiveRoot( + controlledOpen: boolean | undefined, + controlledOnChange: ((open: boolean) => void) | undefined, + defaultOpen: boolean = false, +): ResponsiveOverlayContextValue { + const { presentation } = useResponsiveOverlayBehavior(); + const isCompactViewport = presentation === "drawer"; + const [internalOpen, setInternalOpen] = React.useState(defaultOpen); + const isControlled = controlledOpen !== undefined; + const open = isControlled ? controlledOpen : internalOpen; + + const onOpenChange = React.useCallback( + (next: boolean) => { + if (open && !next && isCompactViewport) { + blurActiveKeyboardInputBeforeOverlayClose(); + } + if (!isControlled) { + setInternalOpen(next); + } + controlledOnChange?.(next); + }, + [isCompactViewport, isControlled, controlledOnChange, open], + ); + + return React.useMemo( + () => ({ isCompactViewport, open, onOpenChange }), + [isCompactViewport, open, onOpenChange], + ); +} + +interface MobileTriggerProps { + asChild?: boolean; + open: boolean; + onOpenChange: (open: boolean) => void; + haspopup: "menu" | "dialog"; + children: React.ReactNode; + onClick?: React.MouseEventHandler; +} + +export const MobileTrigger = React.forwardRef< + HTMLButtonElement, + MobileTriggerProps & + Omit< + React.ButtonHTMLAttributes, + keyof MobileTriggerProps + > +>( + ( + { + asChild, + open, + onOpenChange, + haspopup, + onClick, + children, + className, + ...domProps + }, + ref, + ) => { + const triggerClassName = getOverlayTriggerClassName(className); + const handleClick: React.MouseEventHandler = (e) => { + onClick?.(e); + if (!e.defaultPrevented) { + if (!open) { + blurActiveKeyboardInputBeforeOverlayOpen(); + } + onOpenChange(!open); + } + }; + + const ariaProps = { + "aria-expanded": open, + "aria-haspopup": haspopup, + "data-state": open ? "open" : "closed", + } as const; + + if (asChild) { + return ( + + {children} + + ); + } + + return ( + + ); + }, +); +MobileTrigger.displayName = "MobileTrigger"; + +const RADIX_CONTENT_PROP_NAMES = [ + "side", + "sideOffset", + "align", + "alignOffset", + "collisionPadding", + "collisionBoundary", + "arrowPadding", + "sticky", + "hideWhenDetached", + "avoidCollisions", + "onOpenAutoFocus", + "onCloseAutoFocus", + "onEscapeKeyDown", + "onPointerDownOutside", + "onFocusOutside", + "onInteractOutside", +] as const; + +type RadixContentPropName = (typeof RADIX_CONTENT_PROP_NAMES)[number]; + +const RADIX_CONTENT_KEYS: ReadonlySet = new Set( + RADIX_CONTENT_PROP_NAMES, +); + +export function stripRadixContentProps>( + props: T, +): Omit { + const result = {} as Record; + for (const key of Object.keys(props)) { + if (!RADIX_CONTENT_KEYS.has(key)) { + result[key] = props[key]; + } + } + return result as Omit; +} + +type DrawerPointerDownOutsideEvent = CustomEvent<{ + originalEvent: PointerEvent; +}>; + +interface DrawerDismissalHandlers { + onEscapeKeyDown?: (event: KeyboardEvent) => void; + onPointerDownOutside?: (event: DrawerPointerDownOutsideEvent) => void; + onInteractOutside?: (event: DrawerPointerDownOutsideEvent) => void; +} + +interface ResponsiveDrawerShellProps extends DrawerDismissalHandlers { + open: boolean; + onOpenChange: (open: boolean) => void; + closeOnBackdropClick?: boolean; + onAfterCloseAutoFocus?: () => void; + srLabel?: string; + labelledBy?: string; + describedBy?: string; + contentClassName?: string; + onContentAnimationEnd?: (open: boolean) => void; + children: React.ReactNode; +} + +export function useResponsiveDrawerRealization({ + open, + enabled = true, +}: { + open: boolean; + enabled?: boolean; +}): { isContentRealized: boolean; realizeContent: () => void } { + const [isContentRealized, setIsContentRealized] = React.useState(false); + const realizeContent = React.useCallback( + () => setIsContentRealized(true), + [], + ); + + React.useEffect(() => { + if (!enabled || !open || isContentRealized) { + return; + } + + let firstFrame: number | null = null; + let secondFrame: number | null = null; + firstFrame = window.requestAnimationFrame(() => { + firstFrame = null; + secondFrame = window.requestAnimationFrame(() => { + secondFrame = null; + realizeContent(); + }); + }); + const fallback = window.setTimeout( + realizeContent, + RESPONSIVE_DRAWER_REALIZE_FALLBACK_MS, + ); + + return () => { + if (firstFrame !== null) { + window.cancelAnimationFrame(firstFrame); + } + if (secondFrame !== null) { + window.cancelAnimationFrame(secondFrame); + } + window.clearTimeout(fallback); + }; + }, [enabled, isContentRealized, open, realizeContent]); + + return { + isContentRealized: enabled && isContentRealized, + realizeContent, + }; +} + +export function ResponsiveDrawerShell({ + open, + onOpenChange, + onAfterCloseAutoFocus, + closeOnBackdropClick = true, + srLabel, + labelledBy, + describedBy, + contentClassName, + onContentAnimationEnd, + onEscapeKeyDown, + onPointerDownOutside, + onInteractOutside, + children, +}: ResponsiveDrawerShellProps) { + const { isContentRealized } = useResponsiveDrawerRealization({ open }); + + if (!open && !isContentRealized) { + return null; + } + + return ( + + {isContentRealized ? ( + children + ) : ( +