From 6f49744ed5235169cda1a137d2da3100f34d1a68 Mon Sep 17 00:00:00 2001 From: Julien Bianchi Date: Sun, 22 Nov 2026 23:24:22 +0100 Subject: [PATCH 1/5] feat: expand /shrug and /tableflip into their text as they are typed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Typing /shrug or /tableflip at the start of the text or after a space, then a space or a new line, turns it into ¯\_(ツ)_/¯ or (╯°□°)╯︵ ┻━┻, as on Slack. It works wherever emoji shortcodes already do: commits, replies, quotes, poll options and remotes. Typing a slash suggests them, and a fresh commit draft lists them after /bug and /feature, so its menu stays the only one open. Code keeps the commands as typed. The expansions live in one table: adding an entry is enough to expand it and suggest it everywhere, and a test checks each command is a unique slug that no issue command uses. --- KNOWLEDGE_BASE.md | 4 +- resources/js/components/commit-composer.tsx | 5 +- resources/js/components/issue-command.tsx | 41 +++++-- resources/js/components/mention-textarea.tsx | 102 ++++++++++++++-- resources/js/lib/text-expansions.ts | 81 +++++++++++++ tests/Unit/ComposerDraft.test.tsx | 47 ++++++++ tests/Unit/OrgMentionSuggestions.test.tsx | 94 +++++++++++++++ tests/Unit/TextExpansions.test.tsx | 118 +++++++++++++++++++ 8 files changed, 466 insertions(+), 26 deletions(-) create mode 100644 resources/js/lib/text-expansions.ts create mode 100644 tests/Unit/TextExpansions.test.tsx diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index c860972480..b0615b46c5 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -263,6 +263,8 @@ Sources: [translation endpoint](app/Http/Controllers/CommitTranslationController Commit and reply text supports inline code in backticks and fenced code blocks with syntax highlighting, a **Wrap lines** toggle, and a copy control. A title after the language, as in ```` ```php title="app/Models/User.php" ````, labels the block in place of the language. Text outside code supports emoji shortcodes, clickable URLs, `@username` mentions, and `#hashtags`, which open commit search for signed-in members and stay plain text for guests. This is developer-oriented text formatting, not a full rich-text editor. +In commits, replies, quotes, poll options and remotes, `/shrug` and `/tableflip` typed at the start of the text or after a space become `¯\_(ツ)_/¯` and `(╯°□°)╯︵ ┻━┻` once a space or a new line follows. Typing `/` suggests them; in a fresh commit draft they are listed after `/bug` and `/feature`. Code keeps them as typed. They are expanded in the browser: text sent through the API stays as written. + The smiley button in the commit, reply and quote composers opens the same searchable emoji picker as reactions in remotes. Picking an emoji inserts it where the caret was, or over the selected text, and puts the caret right after it. In commits, replies, and remotes, start a line with `>` to render a quote block. Consecutive quoted lines stay together; an unquoted line ends the block. Quotes keep inline code, links, mentions, and emoji formatting. A `>` inside code or in the middle of a line stays literal. @@ -273,7 +275,7 @@ Typing **#123** in a composer looks up that exact issue or pull request in the / Write `color(#ff8a4c)` or `color(#fff)` outside code to show the hex value with a small color swatch. The `color(...)` markup stays in the draft and is hidden in the rendered commit. It accepts 3, 4, 6 or 8 hex digits. A bare `#` followed by a letter is a hashtag. On the web, if the text of a commit, reply, quote, or Remotes message contains a hashtag that could be a color, the composer shows the swatch syntax and offers to apply it. Colors that start with a digit can still show a swatch without the markup: `#000`, `#000000` and `#333333` are colors, while `#123` and `#333` stay plain text. The full-width `#` also works for automatic swatches, as in `#fff`. A swatch written with `color(...)` does not add the commit to a guild. -Sources: [body renderer](resources/js/components/commit-body.tsx), [emoji picker button](resources/js/components/emoji-picker.tsx), [colors](resources/js/lib/colors.ts), [code blocks](resources/js/components/code-block.tsx), [mention suggestions](app/Http/Controllers/MentionSuggestionController.php), [mention parsing](app/Services/Mentions.php). +Sources: [body renderer](resources/js/components/commit-body.tsx), [emoji picker button](resources/js/components/emoji-picker.tsx), [colors](resources/js/lib/colors.ts), [text expansions](resources/js/lib/text-expansions.ts), [code blocks](resources/js/components/code-block.tsx), [mention suggestions](app/Http/Controllers/MentionSuggestionController.php), [mention parsing](app/Services/Mentions.php). ### Draft previews diff --git a/resources/js/components/commit-composer.tsx b/resources/js/components/commit-composer.tsx index 1fd8cc5d82..92ce81bdf5 100644 --- a/resources/js/components/commit-composer.tsx +++ b/resources/js/components/commit-composer.tsx @@ -302,6 +302,7 @@ function CommitComposerBody({ rows={1} value={body} onValueChange={issue.change} + suggestsExpansions={!issue.ownsExpansions} onPaste={ poll === null ? attachments.onPaste : undefined } @@ -390,8 +391,8 @@ function CommitComposerBody({ { - issue.start(kind, ''); + onPick={(command) => { + issue.pick(command); focusBody(id); }} /> diff --git a/resources/js/components/issue-command.tsx b/resources/js/components/issue-command.tsx index 56b0513c75..5af16cd0e6 100644 --- a/resources/js/components/issue-command.tsx +++ b/resources/js/components/issue-command.tsx @@ -1,5 +1,5 @@ import { useHttp, usePage } from '@inertiajs/react'; -import { Bug, Lightbulb, X } from 'lucide-react'; +import { Bug, Lightbulb, Smile, X } from 'lucide-react'; import type { KeyboardEvent } from 'react'; import { useState } from 'react'; import { toast } from 'sonner'; @@ -16,8 +16,12 @@ import { typedCommand, } from '@/lib/issue-commands'; import { hasModKey } from '@/lib/keyboard'; +import type { TextExpansion } from '@/lib/text-expansions'; +import { suggestedExpansions } from '@/lib/text-expansions'; import { cn } from '@/lib/utils'; +export type ComposerCommand = IssueCommand | TextExpansion; + const hintDismissedKey = 'issue-command-hint-dismissed'; function isHintDismissed(): boolean { @@ -57,10 +61,13 @@ export function useIssueCommand({ >({ command: '', body: '' }); const command = issueCommands.find((candidate) => candidate.kind === kind) ?? null; + // While the draft is a lone command, this menu lists the text expansions too, so the field doesn't open its own. + const ownsExpansions = + enabled && kind === null && suggestedExpansions(body).length > 0; // A draft restored from the stash can be a lone slash: the menu only opens while the user is typing in it. - const suggestions = + const suggestions: ComposerCommand[] = enabled && kind === null && !dismissed && focused - ? suggestedCommands(body) + ? [...suggestedCommands(body), ...suggestedExpansions(body)] : []; const hint = enabled && kind === null && !hintDismissed ? hintedCommand(body) : null; @@ -71,6 +78,14 @@ export function useIssueCommand({ updateBody(rest); }; + const pick = (picked: ComposerCommand) => { + if ('kind' in picked) { + start(picked.kind, ''); + } else { + updateBody(`${picked.text} `); + } + }; + const change = (value: string) => { setDismissed(false); const typed = enabled && kind === null ? typedCommand(value) : null; @@ -164,7 +179,7 @@ export function useIssueCommand({ !hasModKey(event) ) { event.preventDefault(); - start(suggestions[selected % suggestions.length].kind, ''); + pick(suggestions[selected % suggestions.length]); return true; } @@ -202,6 +217,7 @@ export function useIssueCommand({ return { command, suggestions, + ownsExpansions, hint, dismissHint: () => { setHintDismissed(true); @@ -217,6 +233,7 @@ export function useIssueCommand({ focus: () => setFocused(true), blur: () => setFocused(false), start, + pick, exit: () => setKind(null), submit, handleKeyDown, @@ -264,9 +281,9 @@ export function IssueCommandSuggestions({ selected, onPick, }: { - suggestions: IssueCommand[]; + suggestions: ComposerCommand[]; selected: number; - onPick: (kind: IssueKind) => void; + onPick: (command: ComposerCommand) => void; }) { return (
{suggestions.map((command, index) => { - const Icon = icons[command.kind]; + const Icon = 'kind' in command ? icons[command.kind] : Smile; return ( ); diff --git a/resources/js/components/mention-textarea.tsx b/resources/js/components/mention-textarea.tsx index aa6a06bfe0..33bc4148a1 100644 --- a/resources/js/components/mention-textarea.tsx +++ b/resources/js/components/mention-textarea.tsx @@ -14,12 +14,17 @@ import type { EmojiSuggestion } from '@/lib/emoji'; import { emojifyInput, searchEmoji } from '@/lib/emoji'; import { issueReferenceBeforeCaret } from '@/lib/issue-reference'; import { suggestionPosition } from '@/lib/suggestion-position'; +import { + expandTextCommands, + expansionCommandBeforeCaret, + expansionsStartingWith, +} from '@/lib/text-expansions'; import { toastWhenThrottled } from '@/lib/throttle'; import { characterCount, cn, laneColor, limitCharacters } from '@/lib/utils'; import type { Organization, OrgMember, User } from '@/types'; type Trigger = { - kind: 'mention' | 'emoji' | 'issue' | 'guild'; + kind: 'mention' | 'emoji' | 'expansion' | 'issue' | 'guild'; start: number; query: string; }; @@ -86,6 +91,7 @@ function triggerAt( suggestsMentions: boolean, suggestsIssues: boolean, suggestsGuilds: boolean, + suggestsExpansions: boolean, ): Trigger | null { if (textarea.selectionStart !== textarea.selectionEnd) { return null; @@ -117,6 +123,14 @@ function triggerAt( }; } + const expansion = suggestsExpansions + ? expansionCommandBeforeCaret(before) + : null; + + if (expansion) { + return { kind: 'expansion', ...expansion }; + } + if (isTypingExplicitColor(before)) { return null; } @@ -263,8 +277,8 @@ function Highlighted({ text, query }: { text: string; query: string }) { /** * A textarea that suggests developers to mention as soon as "@" is typed, right under the "@", unless it doesn't - * suggest mentions, suggests emoji for the ":shortcode" being typed, and turns emoji shortcodes into emoji as they - * are typed. Within an org, it only suggests the org's members. + * suggest mentions, suggests emoji for the ":shortcode" being typed and text expansions for the "/command" being typed, and + * turns both into what they stand for as they are typed. Within an org, it only suggests the org's members. */ export function MentionTextarea({ ref, @@ -276,6 +290,7 @@ export function MentionTextarea({ maxLength, suggestsMentions = true, suggestsIssues = suggestsMentions, + suggestsExpansions = true, org, members, reply, @@ -287,6 +302,7 @@ export function MentionTextarea({ onValueChange: (value: string) => void; suggestsMentions?: boolean; suggestsIssues?: boolean; + suggestsExpansions?: boolean; org?: string; members?: OrgMember[]; reply?: string; @@ -336,6 +352,7 @@ export function MentionTextarea({ suggestsMentions, suggestsIssues, suggestsIssues && !!guilds?.length, + suggestsExpansions, ); if ( @@ -508,6 +525,11 @@ export function MentionTextarea({ const emojiQuery = trigger?.kind === 'emoji' ? trigger.query.toLowerCase() : ''; const emojis = emojiQuery === '' ? [] : searchEmoji(emojiQuery); + // The prop can turn off between a keystroke and the next render, so it is read here too, not only when tracking. + const expansions = + suggestsExpansions && trigger?.kind === 'expansion' + ? expansionsStartingWith(`/${trigger.query}`) + : []; const guildQuery = trigger?.kind === 'guild' ? trigger.query.toLowerCase() : ''; const matchingGuilds = @@ -534,7 +556,9 @@ export function MentionTextarea({ : 0 : trigger?.kind === 'emoji' ? emojis.length - : suggestions.length + organizations.length; + : trigger?.kind === 'expansion' + ? expansions.length + : suggestions.length + organizations.length; const selectedIndex = Math.min(activeIndex, Math.max(0, optionCount - 1)); const isOpen = trigger !== null && @@ -545,8 +569,10 @@ export function MentionTextarea({ ? issue !== null : trigger.kind === 'emoji' ? emojis.length > 0 - : suggestions.length + organizations.length > 0 || - query !== ''); + : trigger.kind === 'expansion' + ? expansions.length > 0 + : suggestions.length + organizations.length > 0 || + query !== ''); const insert = (text: string, separator: string) => { const textarea = textareaRef.current; @@ -633,6 +659,8 @@ export function MentionTextarea({ insert(`#${matchingGuilds[selectedIndex].handle}`, ' '); } else if (trigger?.kind === 'emoji') { selectEmoji(emojis[selectedIndex]); + } else if (trigger?.kind === 'expansion') { + insert(expansions[selectedIndex].text, ' '); } else { select( selectedIndex < suggestions.length @@ -670,10 +698,12 @@ export function MentionTextarea({ : trigger?.kind === 'emoji' ? emojis[selectedIndex] && `${id}-emoji-${emojis[selectedIndex].name}` - : selectedIndex < suggestions.length - ? `${id}-mention-${suggestions[selectedIndex].id}` - : organizations[selectedIndex - suggestions.length] && - `${id}-mention-${organizations[selectedIndex - suggestions.length].handle}`; + : trigger?.kind === 'expansion' + ? `${id}-expansion-${expansions[selectedIndex].name.slice(1)}` + : selectedIndex < suggestions.length + ? `${id}-mention-${suggestions[selectedIndex].id}` + : organizations[selectedIndex - suggestions.length] && + `${id}-mention-${organizations[selectedIndex - suggestions.length].handle}`; const isSearching = current?.key !== key; const listId = @@ -683,7 +713,9 @@ export function MentionTextarea({ ? `${id}-issues` : trigger?.kind === 'emoji' ? `${id}-emojis` - : `${id}-mentions`; + : trigger?.kind === 'expansion' + ? `${id}-expansions` + : `${id}-mentions`; return ( <> @@ -693,10 +725,19 @@ export function MentionTextarea({ value={value} onChange={(event) => { const target = event.currentTarget; - const { text, caret } = emojifyInput( + const emojified = emojifyInput( target.value, target.selectionStart ?? target.value.length, ); + const expanded = expandTextCommands( + emojified.text, + emojified.caret, + ); + const { text, caret } = + maxLength !== undefined && + characterCount(expanded.text) > maxLength + ? emojified + : expanded; const limited = maxLength === undefined @@ -831,6 +872,43 @@ export function MentionTextarea({ + ) : trigger?.kind === 'expansion' ? ( +
    + {expansions.map((expansion, index) => ( +
  • + setActiveIndex(index) + } + onClick={() => + insert(expansion.text, ' ') + } + className={cn( + 'flex cursor-pointer items-center gap-3 rounded-sm px-2.5 py-1.5', + { + 'bg-accent': + index === selectedIndex, + }, + )} + > + + {expansion.name} + + + {expansion.text} + +
  • + ))} +
) : trigger?.kind === 'emoji' ? (
    [name, text]), +); + +const commandPattern = new RegExp( + `(^|\\s)(${textExpansions.map(({ name }) => name).join('|')})(?=\\s)`, + 'g', +); + +export function expansionsStartingWith(typed: string): TextExpansion[] { + return textExpansions.filter(({ name }) => name.startsWith(typed)); +} + +/** + * The "/command" being typed in prose right before the caret, at the start of the text or after a space, while an + * expansion still starts with it: where its slash is, and what follows it. + */ +export function expansionCommandBeforeCaret( + before: string, +): { start: number; query: string } | null { + const match = (typedProse(before).at(-1) ?? '').match( + /(?:^|\s)(\/([a-z0-9-]*))$/, + ); + + return match && expansionsStartingWith(match[1]).length > 0 + ? { start: before.length - match[1].length, query: match[2] } + : null; +} + +/** + * The expansions a draft could still become while it is only a slash and the start of a command, like the issue + * commands. + */ +export function suggestedExpansions(body: string): TextExpansion[] { + return /^\/[a-z0-9-]*$/.test(body) ? expansionsStartingWith(body) : []; +} + +function expand(text: string): string { + if (!text.includes('/')) { + return text; + } + + return mapTypedProse(text, (prose) => + prose.replace( + commandPattern, + (_, before: string, name: string) => before + textByName.get(name), + ), + ); +} + +/** + * A command typed at the start of the text or after a space becomes its text once a space or a new line ends it, as on + * Slack. Code is left as typed. + */ +export function expandTextCommands( + text: string, + caret: number, +): { text: string; caret: number } { + const next = text.charAt(caret); + + return { + text: expand(text), + caret: expand(text.slice(0, caret) + next).length - next.length, + }; +} diff --git a/tests/Unit/ComposerDraft.test.tsx b/tests/Unit/ComposerDraft.test.tsx index 47f8ea7424..b613d9dc50 100644 --- a/tests/Unit/ComposerDraft.test.tsx +++ b/tests/Unit/ComposerDraft.test.tsx @@ -761,6 +761,53 @@ test('picking a suggestion with Enter starts an empty issue, and the shortcut op } }); +test('the command menu lists the text expansions after the issue commands, and picking one puts its text in the draft', () => { + draft.body = '/'; + focus(render()); + const view = render(); + const suggestions = view.fields.find( + (element) => element.type === IssueCommandSuggestions, + )!; + assert.deepEqual( + (suggestions.props.suggestions as { name: string }[]).map( + (command) => command.name, + ), + ['/feature', '/bug', '/shrug', '/tableflip'], + ); + const textarea = view.fields.find( + (element) => element.type === MentionTextarea, + )!; + assert.equal(textarea.props.suggestsExpansions, false); + + keyDown(render(), 'ArrowDown'); + keyDown(render(), 'ArrowDown'); + keyDown(render(), 'Enter'); + assert.deepEqual(draft.updateBody.mock.calls.at(-1), ['¯\\_(ツ)_/¯ ']); + + draft.body = '/ta'; + const picked = render().fields.find( + (element) => element.type === IssueCommandSuggestions, + )!; + vi.stubGlobal('requestAnimationFrame', () => 0); + + try { + (picked.props.onPick as (command: unknown) => void)( + (picked.props.suggestions as unknown[])[0], + ); + } finally { + vi.unstubAllGlobals(); + } + assert.deepEqual(draft.updateBody.mock.calls.at(-1), ['(╯°□°)╯︵ ┻━┻ ']); +}); + +test('the field suggests text expansions itself once the draft is more than a lone command', () => { + draft.body = 'it broke /'; + const textarea = render().fields.find( + (element) => element.type === MentionTextarea, + )!; + assert.equal(textarea.props.suggestsExpansions, true); +}); + test('a draft that mentions a bug suggests /bug, keeps the text when used, and can be dismissed', () => { draft.body = 'The search has a bug when going back'; let hint = render().fields.find( diff --git a/tests/Unit/OrgMentionSuggestions.test.tsx b/tests/Unit/OrgMentionSuggestions.test.tsx index 65102d241f..f6676059fd 100644 --- a/tests/Unit/OrgMentionSuggestions.test.tsx +++ b/tests/Unit/OrgMentionSuggestions.test.tsx @@ -179,6 +179,100 @@ test('does not suggest guilds inside code, URLs, partial handles or when preview assert.equal(state[0], null); }); +function selectAt(value: string, props: Record = {}) { + cursor = 0; + state[0] = null; + const textarea = elements( + MentionTextarea({ value, onValueChange: () => {}, ...props }), + ).find((element) => element.type === 'textarea')!; + (textarea.props.onSelect as (event: unknown) => void)({ + currentTarget: { + value, + selectionStart: value.length, + selectionEnd: value.length, + }, + }); + + return state[0]; +} + +test('suggests text expansions for the slash command being typed and inserts the text picked', () => { + state[0] = { kind: 'expansion', start: 3, query: 'sh' }; + cursor = 0; + effects = []; + const onValueChange = vi.fn(); + const fields = elements( + MentionTextarea({ value: 'ok /sh', onValueChange }), + ); + const options = fields.filter((element) => element.props.role === 'option'); + assert.deepEqual( + options.map((option) => option.props.id), + ['mentions-expansion-shrug'], + ); + const textarea = fields.find((element) => element.type === 'textarea')!; + const target = { + selectionStart: 6, + focus: vi.fn(), + setSelectionRange: vi.fn(), + }; + (textarea.props.ref as (element: unknown) => void)(target); + vi.stubGlobal('requestAnimationFrame', (callback: () => void) => + callback(), + ); + (options[0].props.onClick as () => void)(); + assert.deepEqual(onValueChange.mock.calls, [['ok ¯\\_(ツ)_/¯ ']]); + assert.deepEqual(target.setSelectionRange.mock.calls, [[13, 13]]); +}); + +test('keeps the text expansions closed as soon as the field opts out, even with a command already found', () => { + state[0] = { kind: 'expansion', start: 0, query: '' }; + cursor = 0; + effects = []; + const fields = elements( + MentionTextarea({ + value: '/', + onValueChange: () => {}, + suggestsExpansions: false, + }), + ); + assert.equal( + fields.filter((element) => element.props.role === 'option').length, + 0, + ); +}); + +test('leaves a command as typed when its text would go over the length limit', () => { + cursor = 0; + state[0] = null; + const onValueChange = vi.fn(); + const textarea = elements( + MentionTextarea({ value: '', onValueChange, maxLength: 12 }), + ).find((element) => element.type === 'textarea')!; + (textarea.props.onChange as (event: unknown) => void)({ + currentTarget: { + value: 'ab /shrug x', + selectionStart: 10, + selectionEnd: 10, + }, + nativeEvent: {}, + }); + assert.deepEqual(onValueChange.mock.calls, [['ab /shrug x']]); +}); + +test('does not suggest text expansions inside code, words or URLs, for unknown commands, or when the field opts out', () => { + for (const value of [ + '`/sh', + '```\n/sh', + 'and/sh', + 'https://example.com/sh', + '/deploy', + '/shrug ', + ]) { + assert.equal(selectAt(value), null, value); + } + assert.equal(selectAt('/sh', { suggestsExpansions: false }), null); +}); + test('suggests loaded org members immediately without scheduling a search request', () => { const fields = render([member('taylor'), member('jess', 'Jess', true)]); diff --git a/tests/Unit/TextExpansions.test.tsx b/tests/Unit/TextExpansions.test.tsx new file mode 100644 index 0000000000..be83acc902 --- /dev/null +++ b/tests/Unit/TextExpansions.test.tsx @@ -0,0 +1,118 @@ +/// +import assert from 'node:assert/strict'; +import { test } from 'vite-plus/test'; +import { issueCommands } from '../../resources/js/lib/issue-commands'; +import { + expandTextCommands, + expansionCommandBeforeCaret, + suggestedExpansions, + textExpansions, +} from '../../resources/js/lib/text-expansions'; + +test('each expansion has its own command, a slug no issue command uses, and a text to insert', () => { + const names = textExpansions.map(({ name }) => name); + + assert.equal(new Set(names).size, names.length); + + for (const { name, text } of textExpansions) { + assert.match(name, /^\/[a-z0-9]+(?:-[a-z0-9]+)*$/, name); + assert.ok( + !issueCommands.some((command) => command.name === name), + name, + ); + assert.ok(text !== '' && text.trim() === text, name); + } +}); + +test('finds the command being typed at the start of the text or after a space, while an expansion starts with it', () => { + assert.deepEqual(expansionCommandBeforeCaret('/'), { + start: 0, + query: '', + }); + assert.deepEqual(expansionCommandBeforeCaret('it broke\n/ta'), { + start: 9, + query: 'ta', + }); + for (const before of [ + '/deploy', + '/shrug ', + 'and/sh', + 'https://example.com/sh', + '`/sh', + '```\n/sh', + ]) { + assert.equal(expansionCommandBeforeCaret(before), null, before); + } +}); + +test('suggests expansions only while the draft is a slash and the start of a command', () => { + const commands = (body: string) => + suggestedExpansions(body).map(({ name }) => name); + + assert.deepEqual(commands('/'), ['/shrug', '/tableflip']); + assert.deepEqual(commands('/t'), ['/tableflip']); + assert.deepEqual(commands('/shrugs'), []); + assert.deepEqual(commands('ok /sh'), []); +}); + +test('turns a typed command into its text once a space or a new line follows it', () => { + assert.deepEqual(expandTextCommands('/shrug ', 7), { + text: '¯\\_(ツ)_/¯ ', + caret: 10, + }); + assert.deepEqual(expandTextCommands('/tableflip\n', 11), { + text: '(╯°□°)╯︵ ┻━┻\n', + caret: 13, + }); +}); + +test('turns a command typed after other words, and keeps the caret after the text', () => { + assert.deepEqual( + expandTextCommands('it broke again /tableflip later', 26), + { + text: 'it broke again (╯°□°)╯︵ ┻━┻ later', + caret: 28, + }, + ); +}); + +test('keeps the caret after the text when the command is typed before a space already there', () => { + assert.deepEqual(expandTextCommands('/shrug later', 6), { + text: '¯\\_(ツ)_/¯ later', + caret: 9, + }); +}); + +test('keeps the command being typed until a space or a new line ends it', () => { + assert.deepEqual(expandTextCommands('/shrug', 6), { + text: '/shrug', + caret: 6, + }); + assert.deepEqual(expandTextCommands('/shr ', 5), { + text: '/shr ', + caret: 5, + }); +}); + +test('leaves commands inside a word, a link or a longer command untouched', () => { + for (const text of [ + 'and/shrug ', + 'https://example.com/shrug ', + '/shrugging ', + '/shrug-off ', + '/tableflips ', + ]) { + assert.deepEqual(expandTextCommands(text, text.length), { + text, + caret: text.length, + }); + } +}); + +test('leaves commands in code untouched', () => { + const text = 'run `/shrug ` or\n```\n/tableflip \n```\n'; + assert.deepEqual(expandTextCommands(text, text.length), { + text, + caret: text.length, + }); +}); From 1f394ae8804bb1ff36810e5c804003de84409df6 Mon Sep 17 00:00:00 2001 From: Julien Bianchi Date: Mon, 23 Nov 2026 00:44:05 +0100 Subject: [PATCH 2/5] fix: move the caret after a command completed from inside it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Typing the h of /srug later turned it into ¯\_(ツ)_/¯ later, but left the caret inside the face: the caret was worked out from the text before it, where the command was not complete yet. Each replacement is now placed in the whole text, so a caret after a command moves with its text and one inside it goes to the text's end. mapTypedProse hands each prose part its offset for that. --- resources/js/lib/code.ts | 11 +++++-- resources/js/lib/text-expansions.ts | 48 +++++++++++++++++------------ tests/Unit/TextExpansions.test.tsx | 22 +++++++++++++ 3 files changed, 60 insertions(+), 21 deletions(-) diff --git a/resources/js/lib/code.ts b/resources/js/lib/code.ts index b819b20f4f..9c32dee905 100644 --- a/resources/js/lib/code.ts +++ b/resources/js/lib/code.ts @@ -93,10 +93,17 @@ export function withoutTypedCode(text: string): string { */ export function mapTypedProse( text: string, - callback: (prose: string) => string, + callback: (prose: string, offset: number) => string, ): string { + let offset = 0; + return splitCode(text, typedCodePattern) - .map((part, index) => (index % 2 === 0 ? callback(part) : part)) + .map((part, index) => { + const start = offset; + offset += part.length; + + return index % 2 === 0 ? callback(part, start) : part; + }) .join(''); } diff --git a/resources/js/lib/text-expansions.ts b/resources/js/lib/text-expansions.ts index 972bab69df..2e6a62d613 100644 --- a/resources/js/lib/text-expansions.ts +++ b/resources/js/lib/text-expansions.ts @@ -51,31 +51,41 @@ export function suggestedExpansions(body: string): TextExpansion[] { return /^\/[a-z0-9-]*$/.test(body) ? expansionsStartingWith(body) : []; } -function expand(text: string): string { - if (!text.includes('/')) { - return text; - } - - return mapTypedProse(text, (prose) => - prose.replace( - commandPattern, - (_, before: string, name: string) => before + textByName.get(name), - ), - ); -} - /** * A command typed at the start of the text or after a space becomes its text once a space or a new line ends it, as on - * Slack. Code is left as typed. + * Slack. Code is left as typed. A caret after a command moves with its text, and one inside it goes to the text's end. */ export function expandTextCommands( text: string, caret: number, ): { text: string; caret: number } { - const next = text.charAt(caret); + if (!text.includes('/')) { + return { text, caret }; + } + + let shift = 0; + let movedCaret = caret; + + const expanded = mapTypedProse(text, (prose, offset) => + prose.replace( + commandPattern, + (_, before: string, name: string, index: number) => { + const replacement = textByName.get(name) ?? name; + const start = offset + index + before.length; + const end = start + name.length; + + if (caret >= end) { + movedCaret += replacement.length - name.length; + } else if (caret > start) { + movedCaret = start + shift + replacement.length; + } + + shift += replacement.length - name.length; + + return before + replacement; + }, + ), + ); - return { - text: expand(text), - caret: expand(text.slice(0, caret) + next).length - next.length, - }; + return { text: expanded, caret: movedCaret }; } diff --git a/tests/Unit/TextExpansions.test.tsx b/tests/Unit/TextExpansions.test.tsx index be83acc902..e3a5139e7a 100644 --- a/tests/Unit/TextExpansions.test.tsx +++ b/tests/Unit/TextExpansions.test.tsx @@ -83,6 +83,28 @@ test('keeps the caret after the text when the command is typed before a space al }); }); +test('moves the caret after the text when the letter typed completes the command it is in', () => { + assert.deepEqual(expandTextCommands('/shrug later', 3), { + text: '¯\\_(ツ)_/¯ later', + caret: 9, + }); +}); + +test('shifts the caret by every text before it, code included', () => { + assert.deepEqual(expandTextCommands('/shrug and /tableflip ', 22), { + text: '¯\\_(ツ)_/¯ and (╯°□°)╯︵ ┻━┻ ', + caret: 27, + }); + assert.deepEqual(expandTextCommands('run `x` /shrug ', 15), { + text: 'run `x` ¯\\_(ツ)_/¯ ', + caret: 18, + }); + assert.deepEqual(expandTextCommands('/shrug then', 0), { + text: '¯\\_(ツ)_/¯ then', + caret: 0, + }); +}); + test('keeps the command being typed until a space or a new line ends it', () => { assert.deepEqual(expandTextCommands('/shrug', 6), { text: '/shrug', From 76be10b94594fcff64560ccc605845d238acc1bf Mon Sep 17 00:00:00 2001 From: Julien Bianchi Date: Mon, 23 Nov 2026 00:44:09 +0100 Subject: [PATCH 3/5] fix: keep the caret on a picked suggestion whose space did not fit Picking /shrug in ok /sh! with 13 characters allowed drops the space after the face to stay under the limit, but the caret still skipped it and landed after the !. It now skips the separator only when the text keeps one, added or already there. Mentions and guilds picked at the limit had the same off-by-one. --- resources/js/components/mention-textarea.tsx | 5 +++- tests/Unit/OrgMentionSuggestions.test.tsx | 24 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/resources/js/components/mention-textarea.tsx b/resources/js/components/mention-textarea.tsx index 33bc4148a1..fb35ffca33 100644 --- a/resources/js/components/mention-textarea.tsx +++ b/resources/js/components/mention-textarea.tsx @@ -595,9 +595,12 @@ export function MentionTextarea({ const after = value.slice(caret); const spacing = /^\s/u.test(after) ? '' : separator; let next = `${value.slice(0, trigger.start)}${text}${spacing}${after}`; + // The caret skips the separator only when the text keeps one: added here, or already there. + let skipped = separator.length; if (maxLength !== undefined && characterCount(next) > maxLength) { next = `${value.slice(0, trigger.start)}${text}${after}`; + skipped = spacing === '' ? skipped : 0; } if (maxLength !== undefined && characterCount(next) > maxLength) { @@ -609,7 +612,7 @@ export function MentionTextarea({ const nextCaret = trigger.kind === 'issue' ? textarea.selectionStart + next.length - value.length - : trigger.start + text.length + separator.length; + : trigger.start + text.length + skipped; onValueChange(next); close(); diff --git a/tests/Unit/OrgMentionSuggestions.test.tsx b/tests/Unit/OrgMentionSuggestions.test.tsx index f6676059fd..9fd62b8da7 100644 --- a/tests/Unit/OrgMentionSuggestions.test.tsx +++ b/tests/Unit/OrgMentionSuggestions.test.tsx @@ -224,6 +224,30 @@ test('suggests text expansions for the slash command being typed and inserts the assert.deepEqual(target.setSelectionRange.mock.calls, [[13, 13]]); }); +test('puts the caret right after the text picked when the space after it would go over the limit', () => { + state[0] = { kind: 'expansion', start: 3, query: 'sh' }; + cursor = 0; + effects = []; + const onValueChange = vi.fn(); + const fields = elements( + MentionTextarea({ value: 'ok /sh!', onValueChange, maxLength: 13 }), + ); + const option = fields.find((element) => element.props.role === 'option')!; + const textarea = fields.find((element) => element.type === 'textarea')!; + const target = { + selectionStart: 6, + focus: vi.fn(), + setSelectionRange: vi.fn(), + }; + (textarea.props.ref as (element: unknown) => void)(target); + vi.stubGlobal('requestAnimationFrame', (callback: () => void) => + callback(), + ); + (option.props.onClick as () => void)(); + assert.deepEqual(onValueChange.mock.calls, [['ok ¯\\_(ツ)_/¯!']]); + assert.deepEqual(target.setSelectionRange.mock.calls, [[12, 12]]); +}); + test('keeps the text expansions closed as soon as the field opts out, even with a command already found', () => { state[0] = { kind: 'expansion', start: 0, query: '' }; cursor = 0; From d77b10de828296dc3cc88e893b946be9dcc183a8 Mon Sep 17 00:00:00 2001 From: Julien Bianchi Date: Mon, 23 Nov 2026 08:07:13 +0100 Subject: [PATCH 4/5] fix: leave a command glued to code as typed A prose part can start right after inline code, so `x`/shrug expanded and its slash opened the suggestions, although the slash follows a backtick rather than a space. A command now has to start the text or follow a space in the whole text, not just in its prose part; `x` /shrug still expands. --- resources/js/lib/text-expansions.ts | 25 +++++++++++++++++++++---- tests/Unit/TextExpansions.test.tsx | 16 ++++++++++++++++ 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/resources/js/lib/text-expansions.ts b/resources/js/lib/text-expansions.ts index 2e6a62d613..5e21be3de9 100644 --- a/resources/js/lib/text-expansions.ts +++ b/resources/js/lib/text-expansions.ts @@ -38,11 +38,23 @@ export function expansionCommandBeforeCaret( /(?:^|\s)(\/([a-z0-9-]*))$/, ); - return match && expansionsStartingWith(match[1]).length > 0 - ? { start: before.length - match[1].length, query: match[2] } + const start = before.length - (match?.[1].length ?? 0); + + return match && + startsAtBoundary(before, start) && + expansionsStartingWith(match[1]).length > 0 + ? { start, query: match[2] } : null; } +/** + * Whether a slash starts the text or follows a space in it. A prose part can start right after code, so its own start + * is no boundary. + */ +function startsAtBoundary(text: string, slash: number): boolean { + return slash === 0 || /\s/u.test(text.charAt(slash - 1)); +} + /** * The expansions a draft could still become while it is only a slash and the start of a command, like the issue * commands. @@ -69,9 +81,14 @@ export function expandTextCommands( const expanded = mapTypedProse(text, (prose, offset) => prose.replace( commandPattern, - (_, before: string, name: string, index: number) => { - const replacement = textByName.get(name) ?? name; + (match: string, before: string, name: string, index: number) => { const start = offset + index + before.length; + + if (!startsAtBoundary(text, start)) { + return match; + } + + const replacement = textByName.get(name) ?? name; const end = start + name.length; if (caret >= end) { diff --git a/tests/Unit/TextExpansions.test.tsx b/tests/Unit/TextExpansions.test.tsx index e3a5139e7a..a65031f6ba 100644 --- a/tests/Unit/TextExpansions.test.tsx +++ b/tests/Unit/TextExpansions.test.tsx @@ -131,6 +131,22 @@ test('leaves commands inside a word, a link or a longer command untouched', () = } }); +test('leaves a command glued to code untouched, and expands one a space away from it', () => { + assert.deepEqual(expandTextCommands('`x`/shrug ', 10), { + text: '`x`/shrug ', + caret: 10, + }); + assert.deepEqual(expandTextCommands('`x` /shrug ', 11), { + text: '`x` ¯\\_(ツ)_/¯ ', + caret: 14, + }); + assert.equal(expansionCommandBeforeCaret('`x`/sh'), null); + assert.deepEqual(expansionCommandBeforeCaret('`x` /sh'), { + start: 4, + query: 'sh', + }); +}); + test('leaves commands in code untouched', () => { const text = 'run `/shrug ` or\n```\n/tableflip \n```\n'; assert.deepEqual(expandTextCommands(text, text.length), { From 7b2320f126c4c5e4fd136e115fc854eef7b846d9 Mon Sep 17 00:00:00 2001 From: Julien Bianchi Date: Mon, 23 Nov 2026 08:07:16 +0100 Subject: [PATCH 5/5] test: pin what text expansions do at a field's length limit A command whose text would go over the field's limit stays as typed, and expands as soon as there is room; one whose text lands exactly on the limit expands; picking one whose text does not fit leaves the draft alone. Checked in the browser on a poll option (50) and a remote message (2,000), where nothing is ever cut. The knowledge base says so. --- KNOWLEDGE_BASE.md | 2 +- tests/Unit/OrgMentionSuggestions.test.tsx | 39 +++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index b0615b46c5..4acc4fa7b3 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -263,7 +263,7 @@ Sources: [translation endpoint](app/Http/Controllers/CommitTranslationController Commit and reply text supports inline code in backticks and fenced code blocks with syntax highlighting, a **Wrap lines** toggle, and a copy control. A title after the language, as in ```` ```php title="app/Models/User.php" ````, labels the block in place of the language. Text outside code supports emoji shortcodes, clickable URLs, `@username` mentions, and `#hashtags`, which open commit search for signed-in members and stay plain text for guests. This is developer-oriented text formatting, not a full rich-text editor. -In commits, replies, quotes, poll options and remotes, `/shrug` and `/tableflip` typed at the start of the text or after a space become `¯\_(ツ)_/¯` and `(╯°□°)╯︵ ┻━┻` once a space or a new line follows. Typing `/` suggests them; in a fresh commit draft they are listed after `/bug` and `/feature`. Code keeps them as typed. They are expanded in the browser: text sent through the API stays as written. +In commits, replies, quotes, poll options and remotes, `/shrug` and `/tableflip` typed at the start of the text or after a space become `¯\_(ツ)_/¯` and `(╯°□°)╯︵ ┻━┻` once a space or a new line follows. Typing `/` suggests them; in a fresh commit draft they are listed after `/bug` and `/feature`. Code keeps them as typed, and so does a field whose length limit has no room left for the face; it is expanded as soon as there is. They are expanded in the browser: text sent through the API stays as written. The smiley button in the commit, reply and quote composers opens the same searchable emoji picker as reactions in remotes. Picking an emoji inserts it where the caret was, or over the selected text, and puts the caret right after it. diff --git a/tests/Unit/OrgMentionSuggestions.test.tsx b/tests/Unit/OrgMentionSuggestions.test.tsx index 9fd62b8da7..64a28a9aec 100644 --- a/tests/Unit/OrgMentionSuggestions.test.tsx +++ b/tests/Unit/OrgMentionSuggestions.test.tsx @@ -248,6 +248,45 @@ test('puts the caret right after the text picked when the space after it would g assert.deepEqual(target.setSelectionRange.mock.calls, [[12, 12]]); }); +test('expands a command whose text lands exactly on the length limit', () => { + cursor = 0; + state[0] = null; + const onValueChange = vi.fn(); + const textarea = elements( + MentionTextarea({ value: '', onValueChange, maxLength: 13 }), + ).find((element) => element.type === 'textarea')!; + vi.stubGlobal('requestAnimationFrame', () => 0); + (textarea.props.onChange as (event: unknown) => void)({ + currentTarget: { + value: 'ab /shrug ', + selectionStart: 10, + selectionEnd: 10, + }, + nativeEvent: {}, + }); + assert.deepEqual(onValueChange.mock.calls, [['ab ¯\\_(ツ)_/¯ ']]); +}); + +test('leaves the draft as it is when even the text picked would go over the limit', () => { + state[0] = { kind: 'expansion', start: 3, query: 'sh' }; + cursor = 0; + effects = []; + const onValueChange = vi.fn(); + const fields = elements( + MentionTextarea({ value: 'ok /sh', onValueChange, maxLength: 10 }), + ); + const option = fields.find((element) => element.props.role === 'option')!; + const textarea = fields.find((element) => element.type === 'textarea')!; + (textarea.props.ref as (element: unknown) => void)({ + selectionStart: 6, + focus: vi.fn(), + setSelectionRange: vi.fn(), + }); + (option.props.onClick as () => void)(); + assert.deepEqual(onValueChange.mock.calls, []); + assert.equal(state[0], null); +}); + test('keeps the text expansions closed as soon as the field opts out, even with a command already found', () => { state[0] = { kind: 'expansion', start: 0, query: '' }; cursor = 0;