Files
Tom Moor 6a6987ec2d perf: Faster mention suggestions (#14583)
* perf: Faster mention suggestions

Limit each section of suggestions.mention to 1s so a slow query does not
delay the others, debounce mention and link editor requests, ignore stale
responses, and use title search in the link editor.

* fix: Include presentation in the mention suggestion time limits

* test: Use a fixed name in the collection member name filter test
2026-11-13 22:37:49 -05:00

339 lines
8.9 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { observer } from "mobx-react";
import {
ArrowIcon,
CloseIcon,
DocumentIcon,
OpenIcon,
ReturnIcon,
} from "outline-icons";
import type { Mark } from "prosemirror-model";
import type { EditorView } from "prosemirror-view";
import * as React from "react";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import Icon from "@shared/components/Icon";
import { hideScrollbars, s } from "@shared/styles";
import { isInternalUrl, sanitizeUrl } from "@shared/utils/urls";
import DocumentBreadcrumb from "~/components/DocumentBreadcrumb";
import Flex from "~/components/Flex";
import { ResizingHeightContainer } from "~/components/ResizingHeightContainer";
import Scrollable from "~/components/Scrollable";
import useDebouncedValue from "~/hooks/useDebouncedValue";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import Input from "./Input";
import SuggestionsMenuItem from "./SuggestionsMenuItem";
import ToolbarButton from "./ToolbarButton";
import Tooltip from "./Tooltip";
import useOnClickOutside from "~/hooks/useOnClickOutside";
import { useEditor } from "./EditorContext";
/** The time in milliseconds the query must stay the same before it is sent. */
const RequestDelay = 100;
type Props = {
mark?: Mark;
view: EditorView;
autoFocus?: boolean;
onLinkAdd: () => void;
onLinkUpdate: () => void;
onLinkRemove: () => void;
onEscape: () => void;
onClickOutside: (ev: MouseEvent | TouchEvent) => void;
onClickBack: () => void;
};
const LinkEditor: React.FC<Props> = ({
mark,
view,
autoFocus,
onLinkAdd,
onLinkUpdate,
onLinkRemove,
onEscape,
onClickOutside,
onClickBack,
}) => {
const { t } = useTranslation();
const getHref = () => sanitizeUrl(mark?.attrs.href) ?? "";
const initialValue = getHref();
const { commands } = useEditor();
const inputRef = useRef<HTMLInputElement>(null);
const wrapperRef = useRef<HTMLDivElement>(null);
const [query, setQuery] = useState(initialValue);
const [selectedIndex, setSelectedIndex] = useState(-1);
const { documents } = useStores();
const trimmedQuery = query.trim();
const results = trimmedQuery
? documents.findByQuery(trimmedQuery, { maxResults: 25 })
: [];
// Results from the store show at once, the server is only asked for more
// when the user stops typing.
const requestQuery = useDebouncedValue(trimmedQuery, RequestDelay);
const { request } = useRequest(
React.useCallback(
() =>
documents.searchTitles({
query: requestQuery,
limit: 25,
filters: [
{ field: "archivedAt", operator: "isNull" },
{ field: "publishedAt", operator: "isNotNull" },
],
}),
[documents, requestQuery]
)
);
useEffect(() => {
if (requestQuery) {
void request();
}
}, [requestQuery, request]);
// Focus imperatively rather than with the autoFocus attribute, which only
// applies on mount – the editor can already be open when focus is requested.
useEffect(() => {
if (autoFocus) {
inputRef.current?.focus();
inputRef.current?.select();
}
}, [autoFocus]);
useOnClickOutside(wrapperRef, (ev) => {
// If the link is totally empty or only spaces then remove the mark
if (!trimmedQuery) {
return removeLink();
}
// If the link in input is non-empty and same as it was when the editor opened, nothing to do
if (trimmedQuery === initialValue) {
onClickOutside(ev);
return;
}
if (!mark) {
return addLink(trimmedQuery);
}
updateLink(trimmedQuery);
});
const openLink = React.useCallback(() => {
commands["openLink"]();
}, [commands]);
const removeLink = React.useCallback(() => {
commands["removeLink"]();
onLinkRemove();
}, [commands, onLinkRemove]);
const updateLink = (link: string) => {
if (!link) {
return;
}
commands["updateLink"]({ href: sanitizeUrl(link) ?? "" });
onLinkUpdate();
};
const addLink = (link: string) => {
if (!link) {
return;
}
commands["addLink"]({ href: sanitizeUrl(link) ?? "" });
onLinkAdd();
};
const handleKeyDown = (event: React.KeyboardEvent) => {
switch (event.key) {
case "ArrowDown": {
event.preventDefault();
const maxIndex = results.length - 1;
setSelectedIndex((current) => (current >= maxIndex ? 0 : current + 1));
return;
}
case "ArrowUp": {
event.preventDefault();
const maxIndex = results.length - 1;
setSelectedIndex((current) => (current <= 0 ? maxIndex : current - 1));
return;
}
case "Enter": {
event.preventDefault();
if (selectedIndex >= 0 && results[selectedIndex]) {
const selectedDoc = results[selectedIndex];
if (!mark) {
addLink(selectedDoc.path);
} else {
updateLink(selectedDoc.path);
}
} else if (!trimmedQuery) {
removeLink();
} else if (!mark) {
addLink(trimmedQuery);
} else {
updateLink(trimmedQuery);
}
return;
}
case "Escape": {
event.preventDefault();
if (!initialValue) {
return removeLink();
}
onEscape();
return;
}
}
};
const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
const newValue = event.target.value;
if (newValue === query) {
return;
}
setQuery(newValue);
setSelectedIndex(-1);
};
const hasResults = !!results.length;
const isInternal = isInternalUrl(query);
const actions = [
{
tooltip: isInternal ? t("Go to link") : t("Open link"),
icon: isInternal ? <ArrowIcon /> : <OpenIcon />,
visible: true,
disabled: !query,
handler: openLink,
},
{
tooltip: t("Remove link"),
icon: <CloseIcon />,
visible: view.editable,
disabled: false,
handler: removeLink,
},
{
tooltip: t("Formatting controls"),
icon: <ReturnIcon />,
visible: view.editable,
disabled: false,
handler: onClickBack,
},
];
return (
<div ref={wrapperRef}>
<InputWrapper>
<Input
ref={inputRef}
value={query}
placeholder={`${t("Search or paste a link")}…`}
onKeyDown={handleKeyDown}
onChange={handleSearch}
onFocus={handleSearch}
readOnly={!view.editable}
/>
{actions.map((action, index) => {
if (!action.visible) {
return null;
}
return (
<Tooltip key={index} content={action.tooltip}>
<ToolbarButton
onClick={action.handler}
disabled={action.disabled}
>
{action.icon}
</ToolbarButton>
</Tooltip>
);
})}
</InputWrapper>
<SearchResults $hasResults={hasResults}>
<ResizingHeightContainer>
{hasResults && (
<>
{results.map((doc, index) => (
<SuggestionsMenuItem
onClick={() => {
if (!mark) {
addLink(doc.path);
} else {
updateLink(doc.path);
}
}}
onPointerMove={() => setSelectedIndex(index)}
selected={index === selectedIndex}
key={doc.id}
subtitle={
<DocumentBreadcrumb document={doc} onlyText maxDepth={2} />
}
title={doc.title}
icon={
doc.icon ? (
<Icon
value={doc.icon}
initial={doc.initial}
color={doc.color ?? undefined}
/>
) : (
<DocumentIcon />
)
}
/>
))}
</>
)}
</ResizingHeightContainer>
</SearchResults>
</div>
);
};
const InputWrapper = styled(Flex)`
pointer-events: all;
gap: 6px;
padding: 6px;
align-items: center;
`;
const SearchResults = styled(Scrollable)<{ $hasResults: boolean }>`
background: ${s("menuBackground")};
box-shadow: ${(props) => (props.$hasResults ? s("menuShadow") : "none")};
clip-path: inset(0px -100px -100px -100px);
position: absolute;
top: 100%;
width: 100%;
height: auto;
left: 0;
margin-top: -6px;
border-radius: 0 0 4px 4px;
padding: ${(props) => (props.$hasResults ? "6px" : "0")};
max-height: 240px;
pointer-events: all;
${hideScrollbars()}
@media (hover: none) and (pointer: coarse) {
position: fixed;
top: auto;
bottom: 46px;
border-radius: 0;
max-height: 50vh;
padding: 8px 8px 4px;
}
`;
export default observer(LinkEditor);