Files
outline/app/editor/components/LinkEditor.tsx
T
Tom Moor 3039f0723c feat: Update link editor toolbar layout (#14781)
Move the back button to the start, use the new unlink icon, and show an
Apply button when the URL has changed.
2026-11-27 09:34:24 -05:00

366 lines
9.6 KiB
TypeScript
Raw 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,
BackIcon,
DocumentIcon,
OpenIcon,
UnlinkIcon,
} 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 { Inner } from "~/components/Button";
import ButtonSmall from "~/components/ButtonSmall";
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 ToolbarSeparator from "./ToolbarSeparator";
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 applyLink = () => {
if (!trimmedQuery) {
removeLink();
} else if (!mark) {
addLink(trimmedQuery);
} else {
updateLink(trimmedQuery);
}
};
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 {
applyLink();
}
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: t("Remove link"),
icon: <UnlinkIcon />,
visible: view.editable,
disabled: false,
handler: removeLink,
},
{
tooltip: isInternal ? t("Go to link") : t("Open link"),
icon: isInternal ? <ArrowIcon /> : <OpenIcon />,
visible: true,
disabled: !query,
handler: openLink,
},
];
const isChanged =
view.editable && !!trimmedQuery && trimmedQuery !== initialValue;
return (
<div ref={wrapperRef}>
<InputWrapper>
{view.editable && (
<Tooltip content={t("Formatting controls")}>
<ToolbarButton onClick={onClickBack}>
<BackIcon />
</ToolbarButton>
</Tooltip>
)}
<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>
);
})}
{isChanged && (
<>
<ToolbarSeparator />
<ApplyButton onClick={applyLink}>{t("Apply")}</ApplyButton>
</>
)}
</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>
);
};
// Match the toolbar button height so the toolbar does not grow.
const ApplyButton = styled(ButtonSmall)`
height: 24px;
${Inner} {
line-height: 24px;
min-height: 24px;
}
`;
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);