Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions resources/js/components/commit-composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ function CommitComposerBody({
<IssueCommandSuggestions
suggestions={issue.suggestions}
selected={issue.selected}
anchor={textareaRef}
onPick={(kind) => {
issue.start(kind, '');
focusBody(id);
Expand Down
77 changes: 70 additions & 7 deletions resources/js/components/issue-command.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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';
Expand Down Expand Up @@ -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<HTMLTextAreaElement | null>,
): SuggestionPosition | null {
const [position, setPosition] = useState<SuggestionPosition | null>(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<HTMLTextAreaElement | null>;
}) {
return (
const position = useSlashPosition(anchor);

if (position === null) {
return null;
}

return createPortal(
<div
data-command-suggestions
role="listbox"
aria-label="Commands"
className="mt-1 w-full max-w-sm rounded-md border bg-popover p-1 text-popover-foreground shadow-md"
style={position}
onMouseDown={(event) => 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];
Expand Down Expand Up @@ -305,10 +365,13 @@ export function IssueCommandSuggestions({
</button>
);
})}
<p className="px-2 pt-1 pb-0.5 font-mono text-xs text-muted-foreground">
↑↓ select · Tab or Enter pick · Esc dismiss
<p className="flex flex-wrap gap-x-1.5 px-2 pt-1 pb-0.5 font-mono text-xs text-muted-foreground">
<span className="whitespace-nowrap">↑↓ select</span>
<span className="whitespace-nowrap">· Tab or Enter pick</span>
<span className="whitespace-nowrap">· Esc dismiss</span>
</p>
</div>
</div>,
document.body,
);
}

Expand Down
89 changes: 7 additions & 82 deletions resources/js/components/mention-textarea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -37,7 +38,7 @@ type MentionResults = {

type Suggestions = MentionResults & { key: string };

type Position = ReturnType<typeof suggestionPosition>;
type Position = SuggestionPosition;

const debounce = 120;
const cache = new Map<string, MentionResults>();
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -364,7 +287,7 @@ export function MentionTextarea({
}

setTrigger(next);
setPosition(positionFor(textarea, next.start));
setPosition(suggestionPositionAt(textarea, next.start));
};

useEffect(() => {
Expand Down Expand Up @@ -432,7 +355,9 @@ export function MentionTextarea({

const reposition = () => {
if (textareaRef.current) {
setPosition(positionFor(textareaRef.current, trigger.start));
setPosition(
suggestionPositionAt(textareaRef.current, trigger.start),
);
}
};

Expand Down
87 changes: 87 additions & 0 deletions resources/js/lib/suggestion-position.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,90 @@ export function suggestionPosition(
: { top: character.bottom + gap }),
};
}

export type SuggestionPosition = ReturnType<typeof suggestionPosition>;

// 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,
);
}
13 changes: 13 additions & 0 deletions tests/Unit/ComposerDraft.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
Loading