diff --git a/Dockerfile b/Dockerfile
index f05c05a291..e704d2e430 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -6,7 +6,7 @@ ARG APP_PATH
WORKDIR $APP_PATH
# ---
-FROM node:26.13.0-slim AS runner
+FROM node:26.13.1-slim AS runner
LABEL org.opencontainers.image.source="https://github.com/outline/outline"
diff --git a/Dockerfile.base b/Dockerfile.base
index 2ea5c1d12c..3267b7cd08 100644
--- a/Dockerfile.base
+++ b/Dockerfile.base
@@ -1,5 +1,5 @@
ARG APP_PATH=/opt/outline
-FROM node:26.13.0 AS deps
+FROM node:26.13.1 AS deps
ARG APP_PATH
WORKDIR $APP_PATH
diff --git a/app/components/Menu/ContextMenu.tsx b/app/components/Menu/ContextMenu.tsx
index e9f734b4be..8c209b8996 100644
--- a/app/components/Menu/ContextMenu.tsx
+++ b/app/components/Menu/ContextMenu.tsx
@@ -4,6 +4,7 @@ import useActionContext from "~/hooks/useActionContext";
import useMobile from "~/hooks/useMobile";
import type { ActionFactory, ActionVariant, ActionWithChildren } from "~/types";
import { preventDefault } from "~/utils/events";
+import { MenuFilter, MenuFilterEmpty, useMenuFilter } from "./MenuFilter";
import { toMenuItems } from "./transformer";
import { observer } from "mobx-react";
import { useComputed } from "~/hooks/useComputed";
@@ -31,6 +32,13 @@ export const ContextMenu = observer(
const actionContext = useActionContext({
isMenu: true,
});
+ const {
+ query,
+ setQuery,
+ handleKeyDownCapture,
+ handleEscapeKeyDown,
+ reset: resetFilter,
+ } = useMenuFilter();
// Menu items are only built while the menu is open.
const menuItems = useComputed(() => {
@@ -54,12 +62,13 @@ export const ContextMenu = observer(
(open: boolean) => {
setOpen(open);
if (open) {
+ resetFilter();
onOpen?.();
} else {
onClose?.();
}
},
- [onOpen, onClose]
+ [onOpen, onClose, resetFilter]
);
const enablePointerEvents = React.useCallback(() => {
@@ -86,7 +95,7 @@ export const ContextMenu = observer(
return <>{children}>;
}
- const content = open ? toMenuItems(menuItems) : null;
+ const content = open ? toMenuItems(menuItems, query) : null;
return (
@@ -97,8 +106,11 @@ export const ContextMenu = observer(
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
onCloseAutoFocus={preventDefault}
+ onEscapeKeyDown={handleEscapeKeyDown}
+ onKeyDownCapture={handleKeyDownCapture}
>
- {content}
+
+ {content ?? (query ? : null)}
diff --git a/app/components/Menu/DropdownMenu.tsx b/app/components/Menu/DropdownMenu.tsx
index 313e1629b0..9a5036c772 100644
--- a/app/components/Menu/DropdownMenu.tsx
+++ b/app/components/Menu/DropdownMenu.tsx
@@ -20,6 +20,7 @@ import type {
MenuItem,
MenuItemWithChildren,
} from "~/types";
+import { MenuFilter, MenuFilterEmpty, useMenuFilter } from "./MenuFilter";
import { toMenuItems, toMobileMenuItems } from "./transformer";
import { observer } from "mobx-react";
import { useComputed } from "~/hooks/useComputed";
@@ -65,6 +66,13 @@ export const DropdownMenu = observer(function DropdownMenu({
const actionContext = useActionContext({
isMenu: true,
});
+ const {
+ query,
+ setQuery,
+ handleKeyDownCapture,
+ handleEscapeKeyDown,
+ reset: resetFilter,
+ } = useMenuFilter();
const menuItems = useComputed(() => {
if (!open) {
@@ -93,12 +101,13 @@ export const DropdownMenu = observer(function DropdownMenu({
(open: boolean) => {
setOpen(open);
if (open) {
+ resetFilter();
onOpen?.();
} else {
onClose?.();
}
},
- [onOpen, onClose]
+ [onOpen, onClose, resetFilter]
);
const enablePointerEvents = React.useCallback(() => {
@@ -130,7 +139,7 @@ export const DropdownMenu = observer(function DropdownMenu({
);
}
- const content = toMenuItems(menuItems);
+ const content = toMenuItems(menuItems, query);
return (
@@ -144,9 +153,12 @@ export const DropdownMenu = observer(function DropdownMenu({
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
onCloseAutoFocus={preventDefault}
+ onEscapeKeyDown={handleEscapeKeyDown}
+ onKeyDownCapture={handleKeyDownCapture}
>
- {content}
- {append}
+
+ {content ?? (query ? : null)}
+ {query ? null : append}
diff --git a/app/components/Menu/MenuFilter.tsx b/app/components/Menu/MenuFilter.tsx
new file mode 100644
index 0000000000..6fae2db542
--- /dev/null
+++ b/app/components/Menu/MenuFilter.tsx
@@ -0,0 +1,330 @@
+import { VISUALLY_HIDDEN_STYLES } from "@radix-ui/react-visually-hidden";
+import * as React from "react";
+import { useTranslation } from "react-i18next";
+import styled from "styled-components";
+import { s } from "@shared/styles";
+import { breakpoint } from "@shared/styles/breakpoint";
+import isTextInput from "~/utils/isTextInput";
+
+interface MenuFilterState {
+ /** The current filter query, or undefined when the filter is hidden. */
+ query: string | undefined;
+ /** Sets the filter query. */
+ setQuery: (query: string) => void;
+ /** Capture-phase keydown handler to attach to the menu content. */
+ handleKeyDownCapture: (event: React.KeyboardEvent) => void;
+ /** Escape handler to attach to the menu content. */
+ handleEscapeKeyDown: (event: KeyboardEvent) => void;
+ /** Hides the filter and clears the query. */
+ reset: () => void;
+}
+
+/**
+ * Lets the user filter a menu by typing. When a key that types text is pressed
+ * on a menu item, focus moves to the filter input, which then receives the
+ * text.
+ *
+ * @returns the filter query and the handlers to attach to the menu content.
+ */
+export function useMenuFilter(): MenuFilterState {
+ const [query, setQuery] = React.useState();
+ const contentRef = React.useRef(null);
+ const highlightRef = React.useRef(null);
+
+ const reset = React.useCallback(() => {
+ contentRef.current = null;
+ highlightRef.current = null;
+ setQuery(undefined);
+ }, []);
+
+ const handleKeyDownCapture = React.useCallback(
+ (event: React.KeyboardEvent) => {
+ const { target, currentTarget } = event;
+ if (
+ !(target instanceof HTMLElement) ||
+ target.closest("[data-radix-menu-content]") !== currentTarget ||
+ (isTextInput(target) && !target.matches('[role^="menuitem"]')) ||
+ target.isContentEditable
+ ) {
+ return;
+ }
+
+ const input = currentTarget.querySelector(
+ `[${INPUT_ATTRIBUTE}]`
+ );
+
+ // AltGr is reported as Ctrl+Alt on Windows, but it types a character.
+ const isShortcut =
+ (event.ctrlKey || event.metaKey || event.altKey) &&
+ !event.getModifierState("AltGraph");
+ if (!input || isShortcut) {
+ return;
+ }
+
+ // Move up from the first item to the input while the filter is visible.
+ if (
+ event.key === "ArrowUp" &&
+ query !== undefined &&
+ target === currentTarget.querySelector(ITEM_SELECTOR)
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ highlightRef.current = highlightItem(currentTarget, target);
+ input.focus();
+ return;
+ }
+
+ const isText =
+ Array.from(event.key).length === 1 ||
+ (event.key === "Backspace" && !!query);
+ if (!isText) {
+ return;
+ }
+
+ // Space selects the focused item until there is a query to add it to.
+ if (event.key === " " && !query) {
+ return;
+ }
+
+ // The default action is kept, so the browser types into the input. Radix
+ // typeahead, item selection and global shortcuts must not handle the key.
+ event.stopPropagation();
+ contentRef.current = currentTarget;
+ if (target.matches(ITEM_SELECTOR)) {
+ highlightRef.current = target;
+ }
+ if (query === undefined) {
+ lockLayout(currentTarget);
+ }
+ input.focus();
+ },
+ [query]
+ );
+
+ const handleEscapeKeyDown = React.useCallback(
+ (event: KeyboardEvent) => {
+ if (query === undefined) {
+ return;
+ }
+ event.preventDefault();
+ setQuery(undefined);
+ },
+ [query]
+ );
+
+ // While the input has focus, highlight the item that had focus before, or
+ // the first match if it was filtered out. Otherwise move focus to the first
+ // item if the focused item was filtered out, or if the filter was hidden
+ // while it had focus. A passive effect runs after Radix removes unmounted
+ // items from its collection.
+ React.useEffect(() => {
+ const content = contentRef.current;
+ if (!content) {
+ return;
+ }
+
+ const active = document.activeElement;
+ if (query !== undefined && active?.hasAttribute(INPUT_ATTRIBUTE)) {
+ highlightRef.current = highlightItem(content, highlightRef.current);
+ return;
+ }
+ if (
+ active &&
+ content.contains(active) &&
+ active.getAttribute("role")?.startsWith("menuitem")
+ ) {
+ return;
+ }
+
+ const first = content.querySelector(ITEM_SELECTOR);
+ (first ?? content).focus();
+ }, [query]);
+
+ return { query, setQuery, handleKeyDownCapture, handleEscapeKeyDown, reset };
+}
+
+interface Props {
+ /** The current filter query, or undefined when the filter is hidden. */
+ query: string | undefined;
+ /** Called when the user changes the query. */
+ onChange: (query: string) => void;
+}
+
+/**
+ * Displays the filter input at the top of a menu. The input is always
+ * rendered, so that it can receive focus before the first character is typed,
+ * but it is only visible while there is a query.
+ */
+export function MenuFilter({ query, onChange }: Props) {
+ const { t } = useTranslation();
+ const isActive = query !== undefined;
+
+ const handleChange = React.useCallback(
+ (event: React.ChangeEvent) => {
+ onChange(event.target.value);
+ },
+ [onChange]
+ );
+
+ const handleKeyDown = React.useCallback(
+ (event: React.KeyboardEvent) => {
+ // Radix typeahead must not handle keys typed into the input, but Tab
+ // must reach the menu so that focus stays in it.
+ if (event.key !== "Tab") {
+ event.stopPropagation();
+ }
+ if (event.nativeEvent.isComposing) {
+ return;
+ }
+
+ const content = event.currentTarget.closest("[data-radix-menu-content]");
+ const items = content
+ ? Array.from(content.querySelectorAll(ITEM_SELECTOR))
+ : [];
+ const highlighted =
+ content?.querySelector(`[${HIGHLIGHT_ATTRIBUTE}]`) ??
+ items[0];
+
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ highlighted?.focus();
+ } else if (event.key === "ArrowUp") {
+ event.preventDefault();
+ items[items.length - 1]?.focus();
+ } else if (event.key === "Enter") {
+ event.preventDefault();
+ highlighted?.click();
+ }
+ },
+ []
+ );
+
+ return (
+
+
+
+ );
+}
+
+/**
+ * Displays a message when no menu items match the filter query.
+ */
+export function MenuFilterEmpty() {
+ const { t } = useTranslation();
+ return {t("No results")};
+}
+
+/**
+ * Records the current width and position of the menu. The filter row applies
+ * them, so that the menu does not move while the items are filtered.
+ */
+function lockLayout(content: HTMLElement) {
+ // The computed width is not changed by the scale of the open animation.
+ content.style.setProperty(
+ "--menu-filter-width",
+ getComputedStyle(content).width
+ );
+ content.setAttribute(LOCKED_ATTRIBUTE, "");
+
+ const wrapper = content.closest(
+ "[data-radix-popper-content-wrapper]"
+ );
+ if (wrapper?.style.transform) {
+ wrapper.style.setProperty(
+ "--menu-filter-transform",
+ wrapper.style.transform
+ );
+ wrapper.setAttribute(LOCKED_ATTRIBUTE, "");
+ }
+}
+
+/**
+ * Marks the item that Enter selects while the filter input has focus.
+ *
+ * @param content the menu content.
+ * @param preferred the item to mark if it is still in the menu.
+ * @returns the marked item, or null if the menu has no items.
+ */
+function highlightItem(content: HTMLElement, preferred: HTMLElement | null) {
+ const item =
+ preferred?.isConnected &&
+ content.contains(preferred) &&
+ preferred.matches(ITEM_SELECTOR)
+ ? preferred
+ : content.querySelector(ITEM_SELECTOR);
+
+ content
+ .querySelectorAll(`[${HIGHLIGHT_ATTRIBUTE}]`)
+ .forEach((element) => element.removeAttribute(HIGHLIGHT_ATTRIBUTE));
+ item?.setAttribute(HIGHLIGHT_ATTRIBUTE, "");
+ return item;
+}
+
+const ITEM_SELECTOR = '[role^="menuitem"]:not([data-disabled])';
+
+const HIGHLIGHT_ATTRIBUTE = "data-menu-filter-highlighted";
+
+const LOCKED_ATTRIBUTE = "data-menu-filter-locked";
+
+const INPUT_ATTRIBUTE = "data-menu-filter-input";
+
+const Wrapper = styled.label`
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ min-height: 40px;
+ margin: -6px -6px 6px;
+ padding: 8px 18px;
+ cursor: text;
+ background: ${s("menuBackground")};
+ border-bottom: 1px solid ${s("divider")};
+
+ // Keep the size and position that the menu had before filtering. This rule
+ // overrides the inline transform that Radix changes when the menu resizes.
+ [data-radix-menu-content][${LOCKED_ATTRIBUTE}]:has(&) {
+ width: var(--menu-filter-width);
+ }
+
+ [data-radix-popper-content-wrapper][${LOCKED_ATTRIBUTE}]:has(&) {
+ transform: var(--menu-filter-transform) !important;
+ }
+`;
+
+const Input = styled.input`
+ flex: 1;
+ min-width: 0;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ outline: none;
+ background: none;
+ font: inherit;
+ font-size: 16px;
+ color: ${s("text")};
+
+ &::placeholder {
+ color: ${s("placeholder")};
+ }
+
+ ${breakpoint("tablet")`
+ font-size: 14px;
+ `}
+`;
+
+const Empty = styled.div`
+ padding: 4px 12px;
+ font-size: 14px;
+ color: ${s("textTertiary")};
+`;
diff --git a/app/components/Menu/transformer.test.tsx b/app/components/Menu/transformer.test.tsx
new file mode 100644
index 0000000000..379aca1681
--- /dev/null
+++ b/app/components/Menu/transformer.test.tsx
@@ -0,0 +1,50 @@
+import type { ReactElement } from "react";
+import type { MenuItem } from "~/types";
+import { toMenuItems } from "./transformer";
+
+const noop = () => undefined;
+
+const items: MenuItem[] = [
+ { type: "button", title: "Team", onClick: noop },
+ { type: "button", title: "Due date", onClick: noop },
+ { type: "separator" },
+ {
+ type: "submenu",
+ title: "Move to",
+ items: [
+ { type: "button", title: "Engineering", onClick: noop },
+ { type: "button", title: "Design", onClick: noop },
+ ],
+ },
+ { type: "button", title: "Hidden date", visible: false, onClick: noop },
+];
+
+function render(query?: string) {
+ return (toMenuItems(items, query) ?? []).filter(
+ (element): element is ReactElement => !!element
+ );
+}
+
+describe("toMenuItems", () => {
+ it("returns all visible items without a query", () => {
+ expect(render().map((element) => element.key)).toEqual([
+ "button-0",
+ "button-1",
+ "separator-2",
+ "submenu-3",
+ ]);
+ });
+
+ it("returns only matching items and keeps their keys", () => {
+ expect(render("DATE").map((element) => element.key)).toEqual(["button-1"]);
+ });
+
+ it("keeps a submenu when one of its items matches", () => {
+ const [submenu] = render("design");
+ expect(submenu.key).toEqual("submenu-3");
+ });
+
+ it("returns null when nothing matches", () => {
+ expect(toMenuItems(items, "zzz")).toBeNull();
+ });
+});
diff --git a/app/components/Menu/transformer.tsx b/app/components/Menu/transformer.tsx
index 2ac0c4bf97..2dadb495ae 100644
--- a/app/components/Menu/transformer.tsx
+++ b/app/components/Menu/transformer.tsx
@@ -14,11 +14,27 @@ import type { MenuItem } from "~/types";
import { MouseSafeArea } from "~/components/MouseSafeArea";
import { createRef } from "react";
-export function toMenuItems(items: MenuItem[]) {
+/**
+ * Converts menu items to menu elements.
+ *
+ * @param items the menu items to convert.
+ * @param query an optional filter query, only matching items are returned.
+ * @returns the menu elements, or null if there are none.
+ */
+export function toMenuItems(items: MenuItem[], query?: string) {
const filteredItems = filterMenuItems(items);
const parentRef = createRef();
+ const normalizedQuery = query?.toLocaleLowerCase();
- if (!filteredItems.length) {
+ // Keys use the index before the query is applied, so that the focused item
+ // keeps its element while the query changes.
+ const entries = filteredItems
+ .map((item, index) => ({ item, index }))
+ .filter(
+ ({ item }) => !normalizedQuery || matchesQuery(item, normalizedQuery)
+ );
+
+ if (!entries.length) {
return null;
}
@@ -31,13 +47,19 @@ export function toMenuItems(items: MenuItem[]) {
!!item.icon
);
- return filteredItems.map((item, index) => {
+ return entries.map(({ item, index }) => {
const icon = showIcon ? (
{"icon" in item ? item.icon : null}
) : undefined;
+ // Children are filtered too, unless the parent title itself matches.
+ const childQuery =
+ normalizedQuery && !titleMatches(item, normalizedQuery)
+ ? normalizedQuery
+ : undefined;
+
switch (item.type) {
case "button":
return (
@@ -85,7 +107,7 @@ export function toMenuItems(items: MenuItem[]) {
);
case "submenu": {
- const submenuItems = toMenuItems(item.items);
+ const submenuItems = toMenuItems(item.items, childQuery);
if (!submenuItems?.length) {
return null;
@@ -116,7 +138,7 @@ export function toMenuItems(items: MenuItem[]) {
}
case "group": {
- const groupItems = toMenuItems(item.items);
+ const groupItems = toMenuItems(item.items, childQuery);
if (!groupItems?.length) {
return null;
@@ -287,6 +309,35 @@ export function toMobileMenuItems(
});
}
+function titleMatches(item: MenuItem, query: string): boolean {
+ return (
+ "title" in item &&
+ typeof item.title === "string" &&
+ item.title.toLocaleLowerCase().includes(query)
+ );
+}
+
+function matchesQuery(item: MenuItem, query: string): boolean {
+ if (item.visible === false) {
+ return false;
+ }
+
+ switch (item.type) {
+ case "button":
+ case "route":
+ case "link":
+ return titleMatches(item, query);
+ case "submenu":
+ case "group":
+ return (
+ titleMatches(item, query) ||
+ item.items.some((child) => matchesQuery(child, query))
+ );
+ default:
+ return false;
+ }
+}
+
function filterMenuItems(items: MenuItem[]): MenuItem[] {
return items
.filter((item) => item.visible !== false)
diff --git a/app/components/Sidebar/components/Disclosure.tsx b/app/components/Sidebar/components/Disclosure.tsx
index 0a2dad9004..60c457da46 100644
--- a/app/components/Sidebar/components/Disclosure.tsx
+++ b/app/components/Sidebar/components/Disclosure.tsx
@@ -2,7 +2,7 @@ import { CollapsedIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
-import { extraArea, s } from "@shared/styles";
+import { extraArea, hover, s } from "@shared/styles";
import NudeButton from "~/components/NudeButton";
type Props = React.ComponentProps & {
@@ -34,7 +34,7 @@ const Button = styled(NudeButton)`
margin: 2px;
${extraArea(4)}
- &:hover {
+ &:${hover} {
color: ${s("text")};
background: ${s("sidebarControlHoverBackground")};
}
diff --git a/app/components/Sidebar/components/DocumentRow.tsx b/app/components/Sidebar/components/DocumentRow.tsx
index eda31ebb72..e446f3d803 100644
--- a/app/components/Sidebar/components/DocumentRow.tsx
+++ b/app/components/Sidebar/components/DocumentRow.tsx
@@ -15,7 +15,7 @@ import useBoolean from "~/hooks/useBoolean";
import { ActionContextProvider } from "~/hooks/useActionContext";
import DropToImport from "./DropToImport";
import Relative from "./Relative";
-import SidebarLink from "./SidebarLink";
+import SidebarLink, { childDepthFor } from "./SidebarLink";
import { StaticLink } from "./StaticLink";
import type { SidebarContextType } from "./SidebarContext";
import { useSidebarContext } from "./SidebarContext";
@@ -94,8 +94,6 @@ export type DocumentRowProps = {
canCreateChild?: boolean;
/** Submit handler for the inline new-child title input. */
onCreateChild?: (title: string) => Promise;
- /** Depth of the inline new-child SidebarLink. Defaults to `depth + 1`. */
- newChildDepth?: number;
/** Context menu action for the row. */
contextAction?: ActionWithChildren | ActionFactory;
@@ -145,7 +143,6 @@ function DocumentRow({
menuOpen,
canCreateChild,
onCreateChild,
- newChildDepth,
contextAction,
isActiveOverride,
children,
@@ -306,7 +303,7 @@ function DocumentRow({
{isAddingNewChild && onCreateChild && (
true}
- depth={newChildDepth ?? depth + 1}
+ depth={childDepthFor(depth)}
ellipsis={false}
label={
{
+ if (!document) {
+ return;
+ }
+ const newDocument = await documents.create(
+ {
+ collectionId: document.collectionId ?? undefined,
+ parentDocumentId: document.id,
+ fullWidth:
+ document.fullWidth ??
+ user.getPreference(UserPreference.FullWidthDocuments),
+ title: input,
+ data: ProsemirrorDataHelper.getEmpty(),
+ },
+ { publish: true }
+ );
+ if (newDocument.collectionId) {
+ collections
+ .get(newDocument.collectionId)
+ ?.addDocument(newDocument, document.id);
+ }
+ membership.addDocument(newDocument, document.id);
+ history.push({
+ pathname: documentEditPath(newDocument),
+ state: { sidebarContext },
+ });
+ },
+ [
+ documents,
+ collections,
+ document,
+ membership,
+ sidebarContext,
+ user,
+ history,
+ ]
+ );
+
const parentRef = React.useRef(null);
const reparentableNode = React.useMemo(
() => document?.asNavigationNode,
@@ -236,6 +284,8 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) {
}
menu={menu}
menuOpen={menuOpen}
+ canCreateChild={can.createChildDocument}
+ onCreateChild={handleNewDoc}
isActiveOverride={isActive}
>
@@ -243,7 +293,7 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) {
(null);
+
+ const handleReplace = () => {
+ imageRef.current?.open();
+ };
const handleAvatarChange = async (avatarUrl: string | null) => {
try {
@@ -205,15 +211,21 @@ export const UserChangeAvatarDialog = observer(function UserChangeAvatarDialog({
onSuccess={handleAvatarChange}
onError={handleAvatarError}
model={user}
- showRemoveOption={false}
+ showActions={false}
+ ref={imageRef}
/>
-
- {user.avatarUrl && (
-
diff --git a/app/components/primitives/components/Menu.tsx b/app/components/primitives/components/Menu.tsx
index eb41ac9314..82cc2b1a52 100644
--- a/app/components/primitives/components/Menu.tsx
+++ b/app/components/primitives/components/Menu.tsx
@@ -68,7 +68,9 @@ const BaseMenuItemCSS = css`
`
&[data-highlighted],
&[data-state="open"],
- &:focus-visible {
+ &:focus-visible,
+ [data-radix-menu-content]:has([data-menu-filter-input]:focus)
+ &[data-menu-filter-highlighted] {
color: ${props.theme.accentText};
background: ${props.$dangerous ? props.theme.danger : props.theme.accent};
outline-color: ${
diff --git a/app/editor/components/ToolbarMenu.tsx b/app/editor/components/ToolbarMenu.tsx
index 48942118b1..fa67f235d0 100644
--- a/app/editor/components/ToolbarMenu.tsx
+++ b/app/editor/components/ToolbarMenu.tsx
@@ -16,6 +16,11 @@ import ToolbarButton from "./ToolbarButton";
import ToolbarSeparator from "./ToolbarSeparator";
import Tooltip from "./Tooltip";
import { toMenuItems } from "~/components/Menu/transformer";
+import {
+ MenuFilter,
+ MenuFilterEmpty,
+ useMenuFilter,
+} from "~/components/Menu/MenuFilter";
import { MenuContent } from "~/components/primitives/Menu";
import { MenuProvider } from "~/components/primitives/Menu/MenuContext";
import { Menu, MenuTrigger } from "~/components/primitives/Menu";
@@ -44,10 +49,23 @@ function ToolbarDropdown(props: ToolbarDropdownProps) {
const { item, shortcut, tooltip } = props;
const { state } = view;
const [isOpen, setIsOpen] = useState(false);
+ const {
+ query,
+ setQuery,
+ handleKeyDownCapture,
+ handleEscapeKeyDown,
+ reset: resetFilter,
+ } = useMenuFilter();
- const handleOpenChange = useCallback((open: boolean) => {
- setIsOpen(open);
- }, []);
+ const handleOpenChange = useCallback(
+ (open: boolean) => {
+ setIsOpen(open);
+ if (open) {
+ resetFilter();
+ }
+ },
+ [resetFilter]
+ );
const items: TMenuItem[] = useMemo(() => {
if (!isOpen) {
@@ -86,8 +104,14 @@ function ToolbarDropdown(props: ToolbarDropdownProps) {
align="end"
aria-label={item.tooltip || t("More options")}
onCloseAutoFocus={handleCloseAutoFocus}
+ onEscapeKeyDown={handleEscapeKeyDown}
+ onKeyDownCapture={handleKeyDownCapture}
>
- {toMenuItems(items)}
+
+
+ {toMenuItems(items, query) ??
+ (query ? : null)}
+
diff --git a/app/editor/extensions/DragHandle.ts b/app/editor/extensions/DragHandle.ts
index 703530f153..62ba35274a 100644
--- a/app/editor/extensions/DragHandle.ts
+++ b/app/editor/extensions/DragHandle.ts
@@ -37,7 +37,7 @@ const hoverPluginKey = new PluginKey(HOVER_META_KEY);
/**
* Renders a floating drag handle to the left of block-level nodes when the
- * user hovers within the editor, and lets the user drag the block to reorder
+ * user hovers near the side of the editor, and lets the user drag the block to reorder
* it. The handle is a real, always-draggable DOM element rather than a CSS
* pseudo on the block, which keeps drag-and-drop working uniformly across
* node types regardless of whether the schema declares `draggable: true`.
diff --git a/app/editor/plugins/DragTarget.ts b/app/editor/plugins/DragTarget.ts
index 9ba2e6d499..95dd87febd 100644
--- a/app/editor/plugins/DragTarget.ts
+++ b/app/editor/plugins/DragTarget.ts
@@ -18,12 +18,13 @@ export interface ResolvedDragTarget {
const LIST_TYPES = ["bullet_list", "ordered_list", "checkbox_list"];
-// Distance outside the content column in which the cursor still finds a block.
-const GUTTER_HIT_WIDTH = 60;
-
// Inset from the content edges, so that posAtCoords lands inside the block.
const CONTENT_INSET = 1;
+// Fraction of the content width, from the handle side, in which hover shows
+// the handle.
+const HOVER_ZONE_RATIO = 0.25;
+
/**
* A block in the editor that the drag handle can attach to. Holds the
* position of the block in the document and the DOM element that the handle
@@ -46,8 +47,9 @@ export class DragTarget {
}
/**
- * Finds the block under the cursor, also when the cursor is in the gutter
- * to the side of the content.
+ * Finds the block at the cursor's height when the cursor is on the side
+ * where the handle renders, either outside the content or in the first 25%
+ * of the content width.
*
* @param view - the editor view.
* @param event - the mouse event.
@@ -61,17 +63,20 @@ export class DragTarget {
if (event.clientY < rect.top || event.clientY > rect.bottom) {
return null;
}
+
+ // Ignore the cursor over other regions, such as the sidebar or a modal.
+ const region = view.dom.closest("[role='main']");
+ if (
+ region &&
+ !(event.target instanceof Node && region.contains(event.target))
+ ) {
+ return null;
+ }
const style = window.getComputedStyle(view.dom);
const paddingLeft = parseFloat(style.paddingLeft) || 0;
const paddingRight = parseFloat(style.paddingRight) || 0;
const contentLeft = rect.left + paddingLeft + CONTENT_INSET;
const contentRight = rect.right - paddingRight - CONTENT_INSET;
- if (
- event.clientX < contentLeft - GUTTER_HIT_WIDTH ||
- event.clientX > contentRight + GUTTER_HIT_WIDTH
- ) {
- return null;
- }
const projectedX = Math.max(
contentLeft,
Math.min(contentRight, event.clientX)
@@ -80,27 +85,20 @@ export class DragTarget {
// Mermaid diagrams hide their source code block and render an SVG widget
// next to it — target the underlying code block but anchor the handle to
// the visible diagram element.
- const mermaid = this.mermaidFromEvent(view, event, projectedX);
- if (mermaid) {
- return mermaid;
+ const target =
+ this.mermaidFromEvent(view, event, projectedX) ??
+ this.blockFromCoords(view, projectedX, event.clientY);
+ if (!target) {
+ return null;
}
- const coords = view.posAtCoords({
- left: projectedX,
- top: event.clientY,
- });
- if (!coords) {
- return null;
- }
- const resolved = this.resolvePos(view.state, coords.pos);
- if (!resolved) {
- return null;
- }
- const dom = view.nodeDOM(resolved.pos);
- if (!(dom instanceof HTMLElement)) {
- return null;
- }
- return new DragTarget(resolved.pos, dom, resolved.kind);
+ // Only show the handle when the cursor is on the side it renders on.
+ const zoneWidth = (contentRight - contentLeft) * HOVER_ZONE_RATIO;
+ const isRTL = window.getComputedStyle(target.element).direction === "rtl";
+ const inZone = isRTL
+ ? event.clientX >= contentRight - zoneWidth
+ : event.clientX <= contentLeft + zoneWidth;
+ return inZone ? target : null;
}
/**
@@ -258,6 +256,26 @@ export class DragTarget {
return found;
}
+ private static blockFromCoords(
+ view: EditorView,
+ left: number,
+ top: number
+ ): DragTarget | null {
+ const coords = view.posAtCoords({ left, top });
+ if (!coords) {
+ return null;
+ }
+ const resolved = this.resolvePos(view.state, coords.pos);
+ if (!resolved) {
+ return null;
+ }
+ const dom = view.nodeDOM(resolved.pos);
+ if (!(dom instanceof HTMLElement)) {
+ return null;
+ }
+ return new DragTarget(resolved.pos, dom, resolved.kind);
+ }
+
private static mermaidFromEvent(
view: EditorView,
event: MouseEvent,
diff --git a/app/models/Document.ts b/app/models/Document.ts
index 2b8c21d3ba..cd51e89b27 100644
--- a/app/models/Document.ts
+++ b/app/models/Document.ts
@@ -42,7 +42,6 @@ import type { Searchable } from "./interfaces/Searchable";
type SaveOptions = JSONObject & {
publish?: boolean;
- done?: boolean;
autosave?: boolean;
};
diff --git a/app/models/Group.ts b/app/models/Group.ts
index c04637daf7..08151c5be3 100644
--- a/app/models/Group.ts
+++ b/app/models/Group.ts
@@ -1,6 +1,7 @@
import { computed, observable } from "mobx";
import type GroupMembership from "./GroupMembership";
import Model from "./base/Model";
+import NavigableModel from "./base/NavigableModel";
import Field from "./decorators/Field";
import { GroupPermission } from "@shared/types";
import type { Searchable } from "./interfaces/Searchable";
@@ -110,6 +111,7 @@ class Group extends Model implements Searchable {
/**
* Returns the direct memberships that this group has to documents. Documents that the current
* user already has access to through a collection, archived, and trashed documents are not included.
+ * Documents nested under another shared document in the list are also not included.
*
* @returns A list of group memberships
*/
@@ -118,7 +120,7 @@ class Group extends Model implements Searchable {
const { groupMemberships, groupUsers, documents, policies, auth } =
this.store.rootStore;
- return groupMemberships.orderedData
+ const memberships = groupMemberships.orderedData
.filter((groupMembership) =>
groupUsers.orderedData.some(
(groupUser) =>
@@ -136,6 +138,8 @@ class Group extends Model implements Searchable {
: undefined;
return !policy?.abilities?.readDocument && !!document?.isActive;
});
+
+ return NavigableModel.filterRoots(memberships, documents);
}
}
diff --git a/app/models/User.test.ts b/app/models/User.test.ts
index c9278a7f58..9800ecafc8 100644
--- a/app/models/User.test.ts
+++ b/app/models/User.test.ts
@@ -194,4 +194,76 @@ describe("User model", () => {
expect(user.initials).toBe("JG");
});
});
+
+ describe("documentMemberships", () => {
+ const user = new User({ id: "300", name: "Member" }, users);
+
+ beforeEach(() => {
+ stores.documents.clear();
+ stores.userMemberships.clear();
+ });
+
+ const addDocument = (id: string, parentDocumentId?: string) =>
+ stores.documents.add({
+ id,
+ title: id,
+ parentDocumentId,
+ collectionId: "collection",
+ });
+
+ const addMembership = (id: string, documentId: string) =>
+ stores.userMemberships.add({
+ id,
+ userId: user.id,
+ documentId,
+ sourceId: null,
+ index: id,
+ });
+
+ it("should only include the highest shared document of a tree", () => {
+ addDocument("parent");
+ addDocument("child", "parent");
+ addDocument("grandchild", "child");
+ addMembership("m1", "grandchild");
+ addMembership("m2", "child");
+ addMembership("m3", "parent");
+
+ expect(user.documentMemberships.map((m) => m.documentId)).toEqual([
+ "parent",
+ ]);
+ });
+
+ it("should include a moved document that is still in a cached tree", () => {
+ addDocument("parent");
+ addDocument("child");
+ addMembership("m1", "child");
+ const parent = addMembership("m2", "parent");
+ parent.node = {
+ id: "parent",
+ title: "parent",
+ url: "/doc/parent",
+ children: [
+ { id: "child", title: "child", url: "/doc/child", children: [] },
+ ],
+ };
+
+ expect(user.documentMemberships.map((m) => m.documentId)).toEqual([
+ "child",
+ "parent",
+ ]);
+ });
+
+ it("should include a document whose parent is not shared", () => {
+ addDocument("parent");
+ addDocument("child", "parent");
+ addDocument("other");
+ addMembership("m1", "child");
+ addMembership("m2", "other");
+
+ expect(user.documentMemberships.map((m) => m.documentId)).toEqual([
+ "child",
+ "other",
+ ]);
+ });
+ });
});
diff --git a/app/models/User.ts b/app/models/User.ts
index acd9e00130..fbff30f53a 100644
--- a/app/models/User.ts
+++ b/app/models/User.ts
@@ -17,6 +17,7 @@ import { client } from "~/utils/ApiClient";
import type Document from "./Document";
import type Group from "./Group";
import type UserMembership from "./UserMembership";
+import NavigableModel from "./base/NavigableModel";
import ParanoidModel from "./base/ParanoidModel";
import Field from "./decorators/Field";
import Relation from "./decorators/Relation";
@@ -211,13 +212,14 @@ class User extends ParanoidModel implements Searchable {
/**
* Returns the direct memberships that this user has to documents. Documents that the
* user already has access to through a collection, archived, and trashed documents are not included.
+ * Documents nested under another shared document in the list are also not included.
*
* @returns A list of user memberships
*/
@computed
get documentMemberships(): UserMembership[] {
const { userMemberships, documents, policies } = this.store.rootStore;
- return userMemberships.orderedData
+ const memberships = userMemberships.orderedData
.filter(
(m) => m.userId === this.id && m.sourceId === null && m.documentId
)
@@ -228,6 +230,8 @@ class User extends ParanoidModel implements Searchable {
: undefined;
return !policy?.abilities?.readDocument && !!document?.isActive;
});
+
+ return NavigableModel.filterRoots(memberships, documents);
}
@computed
diff --git a/app/models/UserMembership.ts b/app/models/UserMembership.ts
index eab66c31d9..d43a2bbf32 100644
--- a/app/models/UserMembership.ts
+++ b/app/models/UserMembership.ts
@@ -29,7 +29,7 @@ class UserMembership extends NavigableModel {
document?: Document;
/** The source ID points to the root membership from which this inherits */
- sourceId?: string;
+ sourceId?: string | null;
/** The source points to the root membership from which this inherits */
@Relation(() => UserMembership, { onDelete: "cascade" })
diff --git a/app/models/base/NavigableModel.ts b/app/models/base/NavigableModel.ts
index a39b3bc1e0..06d4525408 100644
--- a/app/models/base/NavigableModel.ts
+++ b/app/models/base/NavigableModel.ts
@@ -3,8 +3,62 @@ import type { JSONObject, NavigationNode } from "@shared/types";
import { client } from "~/utils/ApiClient";
import Model from "./Model";
import type Document from "../Document";
+import type DocumentsStore from "~/stores/DocumentsStore";
export default abstract class NavigableModel extends Model {
+ /**
+ * Filters memberships to those whose document is not nested under the
+ * document of another membership in the list, so that each shared tree is
+ * shown once from its highest shared document.
+ *
+ * @param memberships the memberships to filter.
+ * @param documents the documents store used to find parent documents.
+ * @returns the memberships that are roots of a shared tree.
+ */
+ static filterRoots(
+ memberships: T[],
+ documents: DocumentsStore
+ ): T[] {
+ if (memberships.length < 2) {
+ return memberships;
+ }
+
+ const rootIds = new Set(memberships.map((m) => m.documentId));
+
+ return memberships.filter((membership) => {
+ const { documentId } = membership;
+ if (!documentId) {
+ return true;
+ }
+
+ const visited = new Set([documentId]);
+ let document = documents.get(documentId);
+ while (document?.parentDocumentId) {
+ const { parentDocumentId } = document;
+ if (rootIds.has(parentDocumentId)) {
+ return false;
+ }
+ if (visited.has(parentDocumentId)) {
+ return true;
+ }
+ visited.add(parentDocumentId);
+ document = documents.get(parentDocumentId);
+ }
+
+ // The parent chain is complete, so the loaded trees are not needed.
+ if (document) {
+ return true;
+ }
+
+ // Parent documents may not be loaded, so also check the loaded trees.
+ return !memberships.some(
+ (other) =>
+ other.documentId !== documentId &&
+ other.childrenByDocumentId.has(documentId)
+ );
+ });
+ }
+
private isFetching = false;
/** The document ID associated with this model. */
diff --git a/app/scenes/Document/hooks/useDocumentSave.ts b/app/scenes/Document/hooks/useDocumentSave.ts
index 5181d4047c..ba30a17bf6 100644
--- a/app/scenes/Document/hooks/useDocumentSave.ts
+++ b/app/scenes/Document/hooks/useDocumentSave.ts
@@ -165,7 +165,10 @@ export function useDocumentSave({
setIsPublishing(!!options.publish);
try {
- const savedDocument = await document.save(undefined, options);
+ const savedDocument = await document.save(undefined, {
+ publish: options.publish,
+ autosave: options.autosave,
+ });
isEditorDirtyRef.current = false;
setIsEditorDirty(false);
diff --git a/app/scenes/Settings/AI.tsx b/app/scenes/Settings/AI.tsx
index fa3261de67..6f6f61ef11 100644
--- a/app/scenes/Settings/AI.tsx
+++ b/app/scenes/Settings/AI.tsx
@@ -11,6 +11,7 @@ import Switch from "~/components/Switch";
import Text from "~/components/Text";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import SettingRow from "./components/SettingRow";
+import { SettingsSection } from "./components/SettingsSection";
import Input from "~/components/Input";
import Tooltip from "~/components/Tooltip";
import CopyToClipboard from "~/components/CopyToClipboard";
@@ -56,102 +57,102 @@ function AI() {
Control how AI features are used in the workspace.
- {t("MCP server")}
-
-
- {t(
- "Let members connect AI assistants and other apps to this workspace. Connected apps can read and edit content with the same permissions as the member who connects them."
- )}
-
- {team.getPreference(TeamPreference.MCP) && (
- <>
-
-
- ),
- }}
- />
-
-
-
-
-
-
-
-
-
-
- >
- )}
- >
- }
- >
-
-
-
- {team.getPreference(TeamPreference.MCP) && (
+
-
+
{t(
- "Optional instructions that are sent to connected AI apps, for example how your workspace is organized or where to find important information."
+ "Let members connect AI assistants and other apps to this workspace. Connected apps can read and edit content with the same permissions as the member who connects them."
)}
-
+ {t(
+ "Optional instructions that are sent to connected AI apps, for example how your workspace is organized or where to find important information."
+ )}
+
+
+ >
+ }
+ />
)}
- border={false}
- >
-
-
+
+
+
+
+
+
+
);
}
diff --git a/app/scenes/Settings/Authentication.tsx b/app/scenes/Settings/Authentication.tsx
index cef6030c9d..71e701064c 100644
--- a/app/scenes/Settings/Authentication.tsx
+++ b/app/scenes/Settings/Authentication.tsx
@@ -21,6 +21,7 @@ import usePolicy from "~/hooks/usePolicy";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import SettingRow from "./components/SettingRow";
+import { SettingsSection } from "./components/SettingsSection";
import { setPostLoginPath } from "~/hooks/useLastVisitedPath";
import { getRedirectUrl, toRelative } from "~/utils/urls";
import { settingsPath } from "~/utils/routeHelpers";
@@ -193,188 +194,188 @@ function Authentication() {
- {t("Sign in")}
+
+ {authenticationProviders.orderedData.map((provider) => {
+ // Group sync can still be disabled after losing the entitlement.
+ const showGroupSync =
+ provider.isActive &&
+ provider.groupSyncSupported &&
+ (!!can.externalGroupSync || !!provider.settings?.groupSyncEnabled);
- {authenticationProviders.orderedData.map((provider) => {
- // Group sync can still be disabled after losing the entitlement.
- const showGroupSync =
- provider.isActive &&
- provider.groupSyncSupported &&
- (!!can.externalGroupSync || !!provider.settings?.groupSyncEnabled);
-
- return (
-
-
- {provider.displayName}
-
- }
- name={provider.name}
- description={
- provider.isConnected
- ? t("Allow members to sign in with {{ authProvider }}", {
- authProvider: provider.displayName,
- })
- : t(
- "Connect {{ authProvider }} to allow members to sign in",
- {
+ return (
+
+
+ {provider.displayName}
+
+ }
+ name={provider.name}
+ description={
+ provider.isConnected
+ ? t("Allow members to sign in with {{ authProvider }}", {
authProvider: provider.displayName,
- }
- )
- }
- border={!showGroupSync}
- >
-
- {provider.isConnected ? (
-
+ })
+ : t(
+ "Connect {{ authProvider }} to allow members to sign in",
+ {
+ authProvider: provider.displayName,
+ }
+ )
+ }
+ border={!showGroupSync}
+ >
+
+ {provider.isConnected ? (
+
+
+ ) : (
+
+ )
+ }
+ onClick={() =>
+ !provider.isEnabled
+ ? handleToggleProvider(provider, true)
+ : handleRemoveProvider(provider)
+ }
+ neutral
+ >
+ {provider.isEnabled ? t("Connected") : t("Disabled")}
+
+
+ {provider.providerId}
+
+
+ ) : (
- ) : (
-
- )
- }
- onClick={() =>
- !provider.isEnabled
- ? handleToggleProvider(provider, true)
- : handleRemoveProvider(provider)
- }
+ onClick={() => handleConnectProvider(provider.name)}
neutral
>
- {provider.isEnabled ? t("Connected") : t("Disabled")}
+ {t("Connect")}
-
- {provider.providerId}
-
-
- ) : (
- handleConnectProvider(provider.name)}
- neutral
- >
- {t("Connect")}
-
- )}
-
-
- {showGroupSync && (
-
- {provider.groupSyncRequiresSetup &&
- !provider.settings?.groupSyncEnabled ? (
- handleToggleGroupSync(provider, true)}
- neutral
- >
- {t("Set up group sync")}
-
- ) : (
-
- handleToggleGroupSync(provider, checked)
- }
- />
- )}
-
- )}
- {showGroupSync &&
- provider.groupSyncUsesClaim &&
- provider.settings?.groupSyncEnabled && (
-
+
+ {showGroupSync && (
+
- ) => {
- const value = ev.target.value.trim();
- if (value !== (provider.settings?.groupClaim ?? "")) {
- void handleGroupClaimChange(provider, value);
+ {provider.groupSyncRequiresSetup &&
+ !provider.settings?.groupSyncEnabled ? (
+ handleToggleGroupSync(provider, true)}
+ neutral
+ >
+ {t("Set up group sync")}
+
+ ) : (
+
+ handleToggleGroupSync(provider, checked)
}
- }}
- />
+ />
+ )}
)}
-
- );
- })}
-
- {t("Email")}
-
- }
- name="guestSignin"
- description={
- env.EMAIL_ENABLED
- ? t("Allow members to sign in using their email address")
- : t("The server must have SMTP configured to enable this setting")
- }
- border={false}
- >
-
-
+ {showGroupSync &&
+ provider.groupSyncUsesClaim &&
+ provider.settings?.groupSyncEnabled && (
+
+ ) => {
+ const value = ev.target.value.trim();
+ if (value !== (provider.settings?.groupClaim ?? "")) {
+ void handleGroupClaimChange(provider, value);
+ }
+ }}
+ />
+
+ )}
+
+ );
+ })}
+
+ {t("Email")}
+
+ }
+ name="guestSignin"
+ description={
+ env.EMAIL_ENABLED
+ ? t("Allow members to sign in using their email address")
+ : t("The server must have SMTP configured to enable this setting")
+ }
+ >
+
+
-
- {t("Passkeys")}
-
- }
- name="passkeysEnabled"
- description={t("Allow members to sign in with a WebAuthn passkey")}
- >
- {
- try {
- await team.save({ passkeysEnabled: checked });
- toast.success(t("Settings saved"));
- } catch (err) {
- toast.error(errToString(err));
- }
- }}
- />
-
+
+ {t("Passkeys")}
+
+ }
+ name="passkeysEnabled"
+ description={t("Allow members to sign in with a WebAuthn passkey")}
+ >
+ {
+ try {
+ await team.save({ passkeysEnabled: checked });
+ toast.success(t("Settings saved"));
+ } catch (err) {
+ toast.error(errToString(err));
+ }
+ }}
+ />
+
+
- {t("Restrictions")}
-
+
+
+
);
}
diff --git a/app/scenes/Settings/Details.tsx b/app/scenes/Settings/Details.tsx
index bfb3d72f05..544722edf0 100644
--- a/app/scenes/Settings/Details.tsx
+++ b/app/scenes/Settings/Details.tsx
@@ -1,18 +1,19 @@
import { isHexColor } from "class-validator";
-import { pickBy } from "es-toolkit/compat";
+import { debounce, pickBy } from "es-toolkit/compat";
import { observer } from "mobx-react";
import { TeamIcon } from "outline-icons";
-import { useRef, useState } from "react";
+import { useState } from "react";
import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import { toast } from "sonner";
import { ThemeProvider } from "styled-components";
import { errToString } from "@shared/utils/error";
import { buildDarkTheme, buildLightTheme } from "@shared/styles/theme";
-import type { CustomTheme } from "@shared/types";
+import type { CustomTheme, TeamPreferences } from "@shared/types";
import { TOCPosition, TeamPreference, UserPreference } from "@shared/types";
import { getBaseDomain } from "@shared/utils/domains";
import { TeamValidation } from "@shared/validations";
+import { AvatarVariant } from "~/components/Avatar/Avatar";
import Button from "~/components/Button";
import ButtonLink from "~/components/ButtonLink";
import DefaultCollectionInputSelect from "~/components/DefaultCollectionInputSelect";
@@ -27,13 +28,18 @@ import useCurrentTeam from "~/hooks/useCurrentTeam";
import useCurrentUser from "~/hooks/useCurrentUser";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
+import type Team from "~/models/Team";
import isCloudHosted from "~/utils/isCloudHosted";
import TeamDelete from "../TeamDelete";
-import { ActionRow } from "./components/ActionRow";
import ImageInput from "./components/ImageInput";
import SettingRow from "./components/SettingRow";
+import { SettingsSection } from "./components/SettingsSection";
import { ThemeColorInputs } from "./components/ThemeColorInputs";
+type TeamUpdate = Partial<
+ Pick
+> & { preferences?: TeamPreferences };
+
function Details() {
const { dialogs, ui } = useStores();
const { t } = useTranslation();
@@ -41,7 +47,6 @@ function Details() {
const user = useCurrentUser();
const can = usePolicy(team);
- const form = useRef(null);
const [accent, setAccent] = useState(
team.preferences?.customTheme?.accent
);
@@ -51,12 +56,6 @@ function Details() {
const [name, setName] = useState(team.name);
const [description, setDescription] = useState(team.description || "");
const [subdomain, setSubdomain] = useState(team.subdomain);
- const [publicBranding, setPublicBranding] = useState(
- team.preferences?.publicBranding
- );
- const [defaultCollectionId, setDefaultCollectionId] = useState(
- team.defaultCollectionId
- );
const customTheme: Partial = React.useMemo(
() =>
@@ -70,10 +69,6 @@ function Details() {
[accent, accentText]
);
- const [tocPosition, setTocPosition] = useState(
- team.getPreference(TeamPreference.TocPosition) as TOCPosition
- );
-
const tocPositionOptions: Option[] = React.useMemo(
() =>
[
@@ -91,47 +86,103 @@ function Details() {
[t]
);
- const handleTocPositionChange = React.useCallback((position: string) => {
- setTocPosition(position as TOCPosition);
- }, []);
-
- const handleSubmit = React.useCallback(
- async (event?: React.SyntheticEvent) => {
- if (event) {
- event.preventDefault();
- }
-
- try {
- await team.save({
- name,
- description,
- subdomain,
- defaultCollectionId,
- preferences: {
- ...team.preferences,
- publicBranding,
- customTheme,
- tocPosition,
- },
- });
+ const showSuccessMessage = React.useMemo(
+ () =>
+ debounce(() => {
toast.success(t("Settings saved"));
+ }, 250),
+ [t]
+ );
+
+ const saveData = React.useCallback(
+ async (data: TeamUpdate) => {
+ try {
+ await team.save(data);
+ showSuccessMessage();
+ return true;
} catch (err) {
toast.error(errToString(err));
+ return false;
}
},
- [
- tocPosition,
- team,
- name,
- description,
- subdomain,
- defaultCollectionId,
- publicBranding,
- customTheme,
- t,
- ]
+ [team, showSuccessMessage]
);
+ const savePreference = React.useCallback(
+ (key: T, value: TeamPreferences[T]) =>
+ saveData({ preferences: { [key]: value } }),
+ [saveData]
+ );
+
+ const saveTheme = React.useMemo(
+ () =>
+ debounce((theme: Partial) => {
+ void savePreference(TeamPreference.CustomTheme, theme);
+ }, 500),
+ [savePreference]
+ );
+
+ // Save a pending theme change when the user leaves the page.
+ React.useEffect(() => () => saveTheme.flush(), [saveTheme]);
+
+ const handleThemeChange = React.useCallback(
+ (
+ nextAccent: string | null | undefined,
+ nextText: string | null | undefined
+ ) => {
+ // Wait until every entered color is complete or empty before saving.
+ const isReady = (value: string | null | undefined) =>
+ !value || value === "#" || isHexColor(value);
+ if (!isReady(nextAccent) || !isReady(nextText)) {
+ return;
+ }
+ saveTheme(
+ pickBy({ accent: nextAccent, accentText: nextText }, isHexColor)
+ );
+ },
+ [saveTheme]
+ );
+
+ const handleAccentChange = React.useCallback(
+ (value: string) => {
+ setAccent(value);
+ handleThemeChange(value, accentText);
+ },
+ [accentText, handleThemeChange]
+ );
+
+ const handleAccentTextChange = React.useCallback(
+ (value: string) => {
+ setAccentText(value);
+ handleThemeChange(accent, value);
+ },
+ [accent, handleThemeChange]
+ );
+
+ const handleResetTheme = React.useCallback(() => {
+ setAccent(null);
+ setAccentText(null);
+ saveTheme.cancel();
+ void savePreference(TeamPreference.CustomTheme, {});
+ }, [saveTheme, savePreference]);
+
+ const handleSubmit = React.useCallback((ev: React.FormEvent) => {
+ ev.preventDefault();
+ }, []);
+
+ const handleKeyDown = React.useCallback((ev: React.KeyboardEvent) => {
+ // Text fields save on blur, so Enter saves the focused field.
+ if (
+ ev.key === "Enter" &&
+ !ev.nativeEvent.isComposing &&
+ ev.target instanceof HTMLInputElement &&
+ ev.currentTarget.contains(ev.target)
+ ) {
+ ev.preventDefault();
+ ev.target.blur();
+ }
+ }, []);
+
const handleNameChange = React.useCallback(
(ev: React.ChangeEvent) => {
setName(ev.target.value);
@@ -139,6 +190,31 @@ function Details() {
[]
);
+ const handleNameBlur = React.useCallback(async () => {
+ if (name === team.name) {
+ return;
+ }
+ if (!name.trim() || !(await saveData({ name }))) {
+ setName(team.name);
+ }
+ }, [name, team, saveData]);
+
+ const handleDescriptionChange = React.useCallback(
+ (ev: React.ChangeEvent) => {
+ setDescription(ev.target.value);
+ },
+ []
+ );
+
+ const handleDescriptionBlur = React.useCallback(async () => {
+ if (description === (team.description || "")) {
+ return;
+ }
+ if (!(await saveData({ description }))) {
+ setDescription(team.description || "");
+ }
+ }, [description, team, saveData]);
+
const handleSubdomainChange = React.useCallback(
(ev: React.ChangeEvent) => {
setSubdomain(ev.target.value.toLowerCase());
@@ -146,6 +222,33 @@ function Details() {
[]
);
+ const handleSubdomainBlur = React.useCallback(async () => {
+ if (subdomain === team.subdomain) {
+ return;
+ }
+ if (!(await saveData({ subdomain }))) {
+ setSubdomain(team.subdomain);
+ }
+ }, [subdomain, team, saveData]);
+
+ const handlePublicBrandingChange = React.useCallback(
+ (checked: boolean) =>
+ savePreference(TeamPreference.PublicBranding, checked),
+ [savePreference]
+ );
+
+ const handleTocPositionChange = React.useCallback(
+ (position: string) =>
+ savePreference(TeamPreference.TocPosition, position as TOCPosition),
+ [savePreference]
+ );
+
+ const handleSelectCollection = React.useCallback(
+ (value: string) =>
+ saveData({ defaultCollectionId: value === "home" ? null : value }),
+ [saveData]
+ );
+
const handleAvatarChange = async (avatarUrl: string | null) => {
await team.save({ avatarUrl });
toast.success(t("Logo updated"));
@@ -165,28 +268,25 @@ function Details() {
});
};
- const onSelectCollection = React.useCallback((value: string) => {
- const selectedValue = value === "home" ? null : value;
- setDefaultCollectionId(selectedValue);
- }, []);
-
const handleSeamlessEditChange = React.useCallback(
async (checked: boolean) => {
- team.setPreference(TeamPreference.SeamlessEdit, !checked);
- await team.save();
+ if (!(await savePreference(TeamPreference.SeamlessEdit, !checked))) {
+ return;
+ }
// Enabling separate editing also applies it to the current user.
if (checked) {
- user.setPreference(UserPreference.SeamlessEdit, false);
- await user.save();
+ try {
+ user.setPreference(UserPreference.SeamlessEdit, false);
+ await user.save();
+ } catch (err) {
+ toast.error(errToString(err));
+ }
}
- toast.success(t("Settings saved"));
},
- [team, user, t]
+ [savePreference, user]
);
- const isValid = form.current?.checkValidity();
-
const newTheme = React.useMemo(
() =>
ui.resolvedTheme === "light"
@@ -206,206 +306,192 @@ function Details() {
-
+
+ {can.delete && (
+
+
+
+
+ {t("Delete workspace")}…
+
+
+
+
+ )}
);
diff --git a/app/scenes/Settings/Embeds.tsx b/app/scenes/Settings/Embeds.tsx
index f12209ed56..5b51ef5ce9 100644
--- a/app/scenes/Settings/Embeds.tsx
+++ b/app/scenes/Settings/Embeds.tsx
@@ -12,6 +12,7 @@ import Text from "~/components/Text";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import { IntegrationScene } from "./components/IntegrationScene";
import SettingRow from "./components/SettingRow";
+import { SettingsSection } from "./components/SettingsSection";
import { HStack } from "~/components/primitives/HStack";
/** List of embed providers available for configuration. */
@@ -99,15 +100,16 @@ function Embeds() {
{team.documentEmbeds && (
- <>
- {t("Providers")}
-
+
Enabled providers will appear in the editor slash menu and embed
automatically when a compatible link is pasted. Existing embeds in
documents will continue to display regardless of these settings.
-
+ }
+ >
);
})}
- >
+
)}
);
diff --git a/app/scenes/Settings/Preferences.tsx b/app/scenes/Settings/Preferences.tsx
index 1530a2f8b2..c79fab6405 100644
--- a/app/scenes/Settings/Preferences.tsx
+++ b/app/scenes/Settings/Preferences.tsx
@@ -24,6 +24,7 @@ import useStores from "~/hooks/useStores";
import UserDelete from "../UserDelete";
import { AutoLaunchSetting } from "./components/AutoLaunchSetting";
import SettingRow from "./components/SettingRow";
+import { SettingsSection } from "./components/SettingsSection";
function Preferences() {
const { t } = useTranslation();
@@ -181,173 +182,172 @@ function Preferences() {
Manage settings that affect your personal experience.
- {t("Appearance")}
-
-
- Choose the interface language. Community translations are accepted
- through our{" "}
-
- translation portal
-
- .
-
- >
- }
- >
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {t("Behavior")}
-
-
+
+ Choose the interface language. Community translations are
+ accepted through our{" "}
+
+ translation portal
+
+ .
+
+ >
}
- onChange={handleSeamlessEditChange}
- />
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
-
+ description={t(
+ "Choose how unread notifications are indicated on the app icon."
+ )}
+ >
+
+
+
{can.delete && (
- <>
- {t("Danger")}
+
- >
+
)}
);
diff --git a/app/scenes/Settings/Profile.tsx b/app/scenes/Settings/Profile.tsx
index 4ee6b30051..13d0303754 100644
--- a/app/scenes/Settings/Profile.tsx
+++ b/app/scenes/Settings/Profile.tsx
@@ -4,7 +4,6 @@ import * as React from "react";
import { Trans, useTranslation } from "react-i18next";
import { toast } from "sonner";
import { errToString } from "@shared/utils/error";
-import Button from "~/components/Button";
import Heading from "~/components/Heading";
import Input from "~/components/Input";
import Scene from "~/components/Scene";
@@ -20,17 +19,40 @@ import SettingRow from "./components/SettingRow";
const Profile = () => {
const user = useCurrentUser();
const { dialogs } = useStores();
- const form = React.useRef(null);
const [name, setName] = React.useState(user.name);
const { t } = useTranslation();
- const handleSubmit = async (ev: React.SyntheticEvent) => {
+ const handleSubmit = (ev: React.FormEvent) => {
ev.preventDefault();
+ };
+
+ const handleKeyDown = (ev: React.KeyboardEvent) => {
+ // The name saves on blur, so Enter saves it.
+ if (
+ ev.key === "Enter" &&
+ !ev.nativeEvent.isComposing &&
+ ev.target instanceof HTMLInputElement &&
+ ev.currentTarget.contains(ev.target)
+ ) {
+ ev.preventDefault();
+ ev.target.blur();
+ }
+ };
+
+ const handleNameBlur = async () => {
+ if (name === user.name) {
+ return;
+ }
+ if (!name.trim()) {
+ setName(user.name);
+ return;
+ }
try {
await user.save({ name });
toast.success(t("Profile saved"));
} catch (err) {
+ setName(user.name);
toast.error(errToString(err));
}
};
@@ -57,9 +79,6 @@ const Profile = () => {
toast.error(error || t("Unable to upload new profile picture"));
};
- const isValid = form.current?.checkValidity();
- const { isSaving } = user;
-
return (
}>
{t("Profile")}
@@ -67,7 +86,7 @@ const Profile = () => {
Manage how you appear to other members of the workspace.
-