From b85795aeb39ee30f339746749af63dfd054aca60 Mon Sep 17 00:00:00 2001 From: Julien Bianchi Date: Mon, 23 Nov 2026 00:11:58 +0100 Subject: [PATCH] fix: float the command menu over the composer instead of pushing it down Typing / in a fresh commit draft opened the /feature and /bug menu in the composer's flow, so the actions under it and the rest of the page jumped down, and back up when it closed. The mention, emoji, issue and guild suggestions float over the page instead. The menu now floats the same way: rendered in a portal, fixed under the slash, moved along when the page scrolls or resizes, and opened above it near the bottom of the viewport. In the composer dialog it can go past the dialog's edge rather than being clipped by it. The code that places the field's suggestions moves to lib/suggestion-position so both share it, and the key hints wrap between hints at its narrower width. --- resources/js/components/commit-composer.tsx | 1 + resources/js/components/issue-command.tsx | 77 ++++++++++- resources/js/components/mention-textarea.tsx | 89 +----------- resources/js/lib/suggestion-position.ts | 87 ++++++++++++ tests/Unit/ComposerDraft.test.tsx | 13 ++ tests/Unit/IssueCommandSuggestions.test.tsx | 135 +++++++++++++++++++ 6 files changed, 313 insertions(+), 89 deletions(-) create mode 100644 tests/Unit/IssueCommandSuggestions.test.tsx diff --git a/resources/js/components/commit-composer.tsx b/resources/js/components/commit-composer.tsx index 1fd8cc5d82..e031f6f56c 100644 --- a/resources/js/components/commit-composer.tsx +++ b/resources/js/components/commit-composer.tsx @@ -390,6 +390,7 @@ function CommitComposerBody({ { issue.start(kind, ''); focusBody(id); diff --git a/resources/js/components/issue-command.tsx b/resources/js/components/issue-command.tsx index 56b0513c75..59e0ddc3ca 100644 --- a/resources/js/components/issue-command.tsx +++ b/resources/js/components/issue-command.tsx @@ -1,7 +1,8 @@ import { useHttp, usePage } from '@inertiajs/react'; import { Bug, Lightbulb, X } from 'lucide-react'; -import type { KeyboardEvent } from 'react'; -import { useState } from 'react'; +import type { KeyboardEvent, RefObject } from 'react'; +import { useLayoutEffect, useState } from 'react'; +import { createPortal } from 'react-dom'; import { toast } from 'sonner'; import { store } from '@/actions/App/Http/Controllers/IssueController'; import { showTimeout, timeoutFrom } from '@/components/timeout-dialog'; @@ -16,6 +17,8 @@ import { typedCommand, } from '@/lib/issue-commands'; import { hasModKey } from '@/lib/keyboard'; +import type { SuggestionPosition } from '@/lib/suggestion-position'; +import { suggestionPositionAt } from '@/lib/suggestion-position'; import { cn } from '@/lib/utils'; const hintDismissedKey = 'issue-command-hint-dismissed'; @@ -259,21 +262,78 @@ export function IssueCommandBadge({ ); } +/** + * Where the menu floats: under the slash that starts the draft, kept there while the page scrolls or resizes. + */ +function useSlashPosition( + anchor: RefObject, +): SuggestionPosition | null { + const [position, setPosition] = useState(null); + + useLayoutEffect(() => { + const textarea = anchor.current; + + if (!textarea) { + return; + } + + const reposition = () => setPosition(suggestionPositionAt(textarea, 0)); + + reposition(); + window.addEventListener('scroll', reposition, { + capture: true, + passive: true, + }); + window.addEventListener('resize', reposition); + const viewport = window.visualViewport; + viewport?.addEventListener('resize', reposition); + viewport?.addEventListener('scroll', reposition); + // A dialog opening on a restored slash is still zooming in when the menu first measures it. + document.addEventListener('animationend', reposition, true); + + return () => { + window.removeEventListener('scroll', reposition, { + capture: true, + }); + window.removeEventListener('resize', reposition); + viewport?.removeEventListener('resize', reposition); + viewport?.removeEventListener('scroll', reposition); + document.removeEventListener('animationend', reposition, true); + }; + }, [anchor]); + + return position; +} + +/** + * The commands a draft that is a lone slash could become, floating over the composer like the other suggestions so + * nothing moves when it opens. + */ export function IssueCommandSuggestions({ suggestions, selected, onPick, + anchor, }: { suggestions: IssueCommand[]; selected: number; onPick: (kind: IssueKind) => void; + anchor: RefObject; }) { - return ( + const position = useSlashPosition(anchor); + + if (position === null) { + return null; + } + + return createPortal(
event.preventDefault()} + className="pointer-events-auto fixed z-50 overflow-y-auto overscroll-contain rounded-lg border bg-popover p-1.5 text-popover-foreground shadow-[0_12px_32px_-12px_rgb(0_0_0/0.35)] motion-safe:animate-in motion-safe:fade-in-0 motion-safe:zoom-in-95" > {suggestions.map((command, index) => { const Icon = icons[command.kind]; @@ -305,10 +365,13 @@ export function IssueCommandSuggestions({ ); })} -

- ↑↓ select · Tab or Enter pick · Esc dismiss +

+ ↑↓ select + · Tab or Enter pick + · Esc dismiss

-
+ , + document.body, ); } diff --git a/resources/js/components/mention-textarea.tsx b/resources/js/components/mention-textarea.tsx index aa6a06bfe0..d08cc6665e 100644 --- a/resources/js/components/mention-textarea.tsx +++ b/resources/js/components/mention-textarea.tsx @@ -13,7 +13,8 @@ import { isTypingExplicitColor } from '@/lib/colors'; 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 type { SuggestionPosition } from '@/lib/suggestion-position'; +import { suggestionPositionAt } from '@/lib/suggestion-position'; import { toastWhenThrottled } from '@/lib/throttle'; import { characterCount, cn, laneColor, limitCharacters } from '@/lib/utils'; import type { Organization, OrgMember, User } from '@/types'; @@ -37,7 +38,7 @@ type MentionResults = { type Suggestions = MentionResults & { key: string }; -type Position = ReturnType; +type Position = SuggestionPosition; const debounce = 120; const cache = new Map(); @@ -54,33 +55,6 @@ const mentionBeforeCaretPattern = const emojiBeforeCaretPattern = /(?:^|[^\p{L}\p{N}_:])(:([A-Za-z0-9_+-]{2,}))$/u; -// Every style that changes where text wraps, so the mirror below wraps exactly like the textarea. -const mirroredProperties = [ - 'box-sizing', - 'width', - 'border-top-width', - 'border-right-width', - 'border-bottom-width', - 'border-left-width', - 'padding-top', - 'padding-right', - 'padding-bottom', - 'padding-left', - 'font-family', - 'font-size', - 'font-weight', - 'font-style', - 'font-stretch', - 'font-feature-settings', - 'font-variant', - 'line-height', - 'letter-spacing', - 'word-spacing', - 'text-transform', - 'text-indent', - 'tab-size', -]; - function triggerAt( textarea: HTMLTextAreaElement, suggestsMentions: boolean, @@ -138,57 +112,6 @@ function triggerAt( : null; } -/** - * Where a character of the textarea is drawn, measured on a hidden copy of it that wraps the same way. - */ -function characterRect(textarea: HTMLTextAreaElement, index: number) { - const style = window.getComputedStyle(textarea); - const mirror = document.createElement('div'); - const marker = document.createElement('span'); - - mirroredProperties.forEach((property) => - mirror.style.setProperty(property, style.getPropertyValue(property)), - ); - mirror.style.position = 'absolute'; - mirror.style.visibility = 'hidden'; - mirror.style.top = '0'; - mirror.style.left = '-9999px'; - mirror.style.whiteSpace = 'pre-wrap'; - mirror.style.overflowWrap = 'break-word'; - - mirror.textContent = textarea.value.slice(0, index); - marker.textContent = textarea.value.slice(index) || '.'; - mirror.appendChild(marker); - document.body.appendChild(mirror); - - const rect = textarea.getBoundingClientRect(); - const lineHeight = - Number.parseFloat(style.lineHeight) || - Number.parseFloat(style.fontSize) * 1.4; - const top = rect.top + marker.offsetTop - textarea.scrollTop; - const left = rect.left + marker.offsetLeft - textarea.scrollLeft; - - mirror.remove(); - - return { top, left, bottom: top + lineHeight }; -} - -function positionFor(textarea: HTMLTextAreaElement, index: number): Position { - const character = characterRect(textarea, index); - const viewport = window.visualViewport; - - return suggestionPosition( - character, - { - left: viewport?.offsetLeft ?? 0, - top: viewport?.offsetTop ?? 0, - width: viewport?.width ?? window.innerWidth, - height: viewport?.height ?? window.innerHeight, - }, - window.innerHeight, - ); -} - async function fetchSuggestions( query: string, org: string | undefined, @@ -364,7 +287,7 @@ export function MentionTextarea({ } setTrigger(next); - setPosition(positionFor(textarea, next.start)); + setPosition(suggestionPositionAt(textarea, next.start)); }; useEffect(() => { @@ -432,7 +355,9 @@ export function MentionTextarea({ const reposition = () => { if (textareaRef.current) { - setPosition(positionFor(textareaRef.current, trigger.start)); + setPosition( + suggestionPositionAt(textareaRef.current, trigger.start), + ); } }; diff --git a/resources/js/lib/suggestion-position.ts b/resources/js/lib/suggestion-position.ts index bb0f683af2..fda0c0b65b 100644 --- a/resources/js/lib/suggestion-position.ts +++ b/resources/js/lib/suggestion-position.ts @@ -29,3 +29,90 @@ export function suggestionPosition( : { top: character.bottom + gap }), }; } + +export type SuggestionPosition = ReturnType; + +// Every style that changes where text wraps, so the mirror below wraps exactly like the textarea. +const mirroredProperties = [ + 'box-sizing', + 'width', + 'border-top-width', + 'border-right-width', + 'border-bottom-width', + 'border-left-width', + 'padding-top', + 'padding-right', + 'padding-bottom', + 'padding-left', + 'font-family', + 'font-size', + 'font-weight', + 'font-style', + 'font-stretch', + 'font-feature-settings', + 'font-variant', + 'line-height', + 'letter-spacing', + 'word-spacing', + 'text-transform', + 'text-indent', + 'tab-size', +]; + +/** + * Where a character of the textarea is drawn, measured on a hidden copy of it that wraps the same way. + */ +function characterRect(textarea: HTMLTextAreaElement, index: number) { + const style = window.getComputedStyle(textarea); + const mirror = document.createElement('div'); + const marker = document.createElement('span'); + + mirroredProperties.forEach((property) => + mirror.style.setProperty(property, style.getPropertyValue(property)), + ); + mirror.style.position = 'absolute'; + mirror.style.visibility = 'hidden'; + mirror.style.top = '0'; + mirror.style.left = '-9999px'; + mirror.style.whiteSpace = 'pre-wrap'; + mirror.style.overflowWrap = 'break-word'; + + mirror.textContent = textarea.value.slice(0, index); + marker.textContent = textarea.value.slice(index) || '.'; + mirror.appendChild(marker); + document.body.appendChild(mirror); + + const rect = textarea.getBoundingClientRect(); + const lineHeight = + Number.parseFloat(style.lineHeight) || + Number.parseFloat(style.fontSize) * 1.4; + const top = rect.top + marker.offsetTop - textarea.scrollTop; + const left = rect.left + marker.offsetLeft - textarea.scrollLeft; + + mirror.remove(); + + return { top, left, bottom: top + lineHeight }; +} + +/** + * Where suggestions for the text at a character of the textarea float: right under it, or above it near the bottom of + * the visible viewport. + */ +export function suggestionPositionAt( + textarea: HTMLTextAreaElement, + index: number, +): SuggestionPosition { + const character = characterRect(textarea, index); + const viewport = window.visualViewport; + + return suggestionPosition( + character, + { + left: viewport?.offsetLeft ?? 0, + top: viewport?.offsetTop ?? 0, + width: viewport?.width ?? window.innerWidth, + height: viewport?.height ?? window.innerHeight, + }, + window.innerHeight, + ); +} diff --git a/tests/Unit/ComposerDraft.test.tsx b/tests/Unit/ComposerDraft.test.tsx index 47f8ea7424..0c8fb92238 100644 --- a/tests/Unit/ComposerDraft.test.tsx +++ b/tests/Unit/ComposerDraft.test.tsx @@ -663,6 +663,19 @@ test('a restored slash only opens the command menu while the composer is focused assert.equal(hasSuggestions(), false); }); +test('the command menu floats from the field it belongs to', () => { + draft.body = '/'; + focus(render()); + const view = render(); + const suggestions = view.fields.find( + (element) => element.type === IssueCommandSuggestions, + )!; + const textarea = view.fields.find( + (element) => element.type === MentionTextarea, + )!; + assert.equal(suggestions.props.anchor, textarea.props.ref); +}); + test('typing a command and a space turns the draft into an issue, and backspace turns it back into a commit', () => { draft.body = '/bu'; focus(render()); diff --git a/tests/Unit/IssueCommandSuggestions.test.tsx b/tests/Unit/IssueCommandSuggestions.test.tsx new file mode 100644 index 0000000000..d7a9666c3a --- /dev/null +++ b/tests/Unit/IssueCommandSuggestions.test.tsx @@ -0,0 +1,135 @@ +/// +import assert from 'node:assert/strict'; +import * as React from 'react'; +import type { ReactElement, ReactNode } from 'react'; +import { beforeEach, test, vi } from 'vite-plus/test'; + +let state: unknown[]; +let cursor = 0; +let effects: (() => void | (() => void))[]; +const position = { left: 10, top: 120, width: 288, maxHeight: 320 }; +const positionAt = vi.fn(() => position); +const listeners = new Map void>(); +const removed: string[] = []; + +vi.doMock('react', () => ({ + ...React, + useLayoutEffect: (effect: () => void | (() => void)) => + effects.push(effect), + useState: (initial: unknown) => { + const index = cursor++; + if (!(index in state)) state[index] = initial; + return [ + state[index], + (value: unknown) => { + state[index] = value; + }, + ]; + }, +})); +vi.doMock('react-dom', () => ({ + createPortal: (children: unknown) => children, +})); +vi.doMock('@inertiajs/react', () => ({ + useHttp: () => ({}), + usePage: () => ({ props: {} }), +})); +vi.doMock('../../resources/js/lib/suggestion-position', () => ({ + suggestionPositionAt: positionAt, +})); + +const { IssueCommandSuggestions } = + await import('../../resources/js/components/issue-command'); +const { issueCommands } = await import('../../resources/js/lib/issue-commands'); + +type Element = ReactElement>; +function elements(node: ReactNode): Element[] { + if (!React.isValidElement(node)) return []; + const element = node as Element; + return [ + element, + ...React.Children.toArray(element.props.children as ReactNode).flatMap( + elements, + ), + ]; +} + +function render(textarea: unknown) { + cursor = 0; + return IssueCommandSuggestions({ + suggestions: issueCommands, + selected: 0, + onPick: () => {}, + anchor: { current: textarea as HTMLTextAreaElement | null }, + }); +} + +beforeEach(() => { + state = []; + effects = []; + listeners.clear(); + removed.length = 0; + positionAt.mockClear(); + vi.stubGlobal('document', { + body: {}, + addEventListener: (type: string, listener: () => void) => + listeners.set(`document:${type}`, listener), + removeEventListener: (type: string) => removed.push(`document:${type}`), + }); + vi.stubGlobal('window', { + addEventListener: (type: string, listener: () => void) => + listeners.set(type, listener), + removeEventListener: (type: string) => removed.push(type), + visualViewport: null, + }); +}); + +test('floats over the composer under the slash, like the other suggestions, instead of pushing its actions down', () => { + const textarea = { value: '/' }; + assert.equal(render(textarea), null); + + const cleanups = effects.map((effect) => effect()); + assert.deepEqual(positionAt.mock.calls, [[textarea, 0]]); + + const [menu, ...rest] = elements(render(textarea)); + assert.equal(menu.props['data-command-suggestions'], true); + assert.equal(menu.props.role, 'listbox'); + assert.deepEqual(menu.props.style, position); + assert.match(String(menu.props.className), /\bfixed\b/); + assert.deepEqual( + rest + .filter((element) => element.props.role === 'option') + .map((option) => option.props['aria-selected']), + [true, false], + ); + assert.deepEqual( + rest + .filter((element) => element.type === 'span') + .map((label) => label.props.children) + .filter((text) => typeof text === 'string' && text.startsWith('/')), + ['/feature', '/bug'], + ); + + const preventDefault = vi.fn(); + (menu.props.onMouseDown as (event: unknown) => void)({ preventDefault }); + assert.equal(preventDefault.mock.calls.length, 1); + + listeners.get('scroll')!(); + listeners.get('resize')!(); + listeners.get('document:animationend')!(); + assert.equal(positionAt.mock.calls.length, 4); + + cleanups.forEach((cleanup) => cleanup?.()); + assert.deepEqual(removed.toSorted(), [ + 'document:animationend', + 'resize', + 'scroll', + ]); +}); + +test('stays closed until the field it belongs to is there', () => { + assert.equal(render(null), null); + effects.forEach((effect) => effect()); + assert.equal(render(null), null); + assert.equal(positionAt.mock.calls.length, 0); +});