Merge remote-tracking branch 'origin/main' into tommoor/external-sidebar-links-add

# Conflicts:
#	app/components/Sidebar/components/CollectionRow.tsx
#	app/components/Sidebar/components/DocumentRow.tsx
This commit is contained in:
Tom Moor committed 2026-11-15 16:39:26 -05:00
commit bd73c0983c
224 files changed
+11580 -3255

No files matched your search

@@ -0,0 +1,156 @@
// Drive the search filter bar: pinned chips, the "Filter" add menu, a pending
// chip that opens its options, a toggle filter, and removing a filter.
// Args: query= (a word in a document title, required), collection= (required).
export default async ({ page, click, step, args, log, psql, literal }) => {
if (!args.query || !args.collection) {
throw new Error("query= and collection= are required");
}
await page.goto("/search");
await page.waitForLoadState("networkidle");
await step("empty");
// Every filter is available before a query is typed.
for (const name of [/^Collection$/, /^Edited by$/, /^Status/]) {
await page.getByRole("button", { name }).waitFor();
}
await click(page.getByRole("button", { name: "More filters" }));
for (const name of ["Updated", "Created by", "Created", "Template", "Title only"]) {
await page.getByRole("menuitem", { name, exact: true }).waitFor();
}
await step("empty-add-menu");
await page.keyboard.press("Escape");
// A filter alone, with no query, lists results.
await click(page.getByRole("button", { name: "More filters" }));
await click(page.getByRole("menuitem", { name: "Updated", exact: true }));
await click(page.getByRole("menuitem", { name: "Past week" }));
await page.waitForURL(/updatedAt\.gte=-P1W/);
await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor();
await step("filter-without-query");
await click(page.getByRole("button", { name: "Remove filter" }));
await page.waitForURL((url) => !url.search.includes("updatedAt"));
// A toggle filter alone, with no query, lists results.
await click(page.getByRole("button", { name: "More filters" }));
await click(page.getByRole("menuitem", { name: "Title only" }));
await page.waitForURL(/titleOnly=true/);
await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor();
await step("title-only-without-query");
await click(page.getByRole("button", { name: "Remove filter" }));
await page.waitForURL((url) => !url.search.includes("titleOnly"));
// A document scope alone, with no query, lists results.
const [documentId] = await psql(
`select id from documents where title like ${literal(`%${args.query}%`)}`
);
await page.goto(`/search?documentId=${documentId}`);
await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor();
await step("document-scope-without-query");
await page.goto("/search");
const box = page.getByRole("searchbox");
await box.fill(args.query);
await box.press("Enter");
await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor();
await page.getByText("1 result", { exact: true }).waitFor();
await step("results");
// Pinned chip: pick a collection.
await click(page.getByRole("button", { name: "Collection", exact: true }));
await click(page.getByRole("menuitem", { name: args.collection }));
await page.waitForURL(/collectionId\.eq=/);
await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor();
await step("collection-chip");
// Extra filter: add "Created by", its options open on their own.
await click(page.getByRole("button", { name: "More filters" }));
await step("add-menu-open");
await click(page.getByRole("menuitem", { name: "Created by" }));
const menu = page.getByRole("menu");
await menu.waitFor({ timeout: 5000 });
await step("created-by-options-open");
await click(menu.getByRole("menuitem").first());
await page.waitForURL(/createdById\.eq=/);
await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor();
await step("created-by-chip");
// Toggle filter: "Title only" adds a chip with no options.
await click(page.getByRole("button", { name: "More filters" }));
await click(page.getByRole("menuitem", { name: "Title only" }));
await page.waitForURL(/titleOnly=true/);
await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor();
await step("title-only-chip");
// Add a filter, then close its options without a value: the chip goes away.
await click(page.getByRole("button", { name: "More filters" }));
await click(page.getByRole("menuitem", { name: "Template" }));
await page.getByRole("menu").waitFor({ timeout: 5000 });
await page.keyboard.press("Escape");
await page.getByRole("menu").waitFor({ state: "detached", timeout: 5000 });
const templateChips = await page
.getByRole("button", { name: /^Template/ })
.count();
if (templateChips !== 0) {
throw new Error("pending Template chip stayed after closing with no value");
}
await step("pending-chip-removed");
// Remove filters with their × buttons.
const removeButtons = page.getByRole("button", { name: "Remove filter" });
const before = await removeButtons.count();
await click(removeButtons.last());
await page.waitForURL((url) => !url.search.includes("titleOnly"));
const after = await removeButtons.count();
if (after !== before - 1) {
throw new Error(`expected ${before - 1} remove buttons, saw ${after}`);
}
await step("title-only-removed");
await page.reload();
await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor();
await step("after-reload");
// Legacy URLs still apply their filters.
const searchBodies = [];
let searchTitleCalls = 0;
page.on("request", (req) => {
if (req.url().endsWith("/api/documents.search_titles")) {
searchTitleCalls += 1;
searchBodies.push(req.postDataJSON());
}
});
await page.goto(`/search?q=${args.query}&dateFilter=week&titleFilter=true`);
await page.getByRole("button", { name: /^Updated\s*Past week/ }).waitFor();
await page.getByText("Title only", { exact: true }).waitFor();
await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor();
const legacyFilters = JSON.stringify(searchBodies.at(-1)?.filters ?? []);
if (!legacyFilters.includes('"field":"updatedAt","operator":"gte","value":"-P1W"')) {
throw new Error(`legacy dateFilter not sent to the API: ${legacyFilters}`);
}
if (!searchTitleCalls) {
throw new Error("legacy titleFilter did not use title search");
}
await step("legacy-url");
await page.goBack();
await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor();
const finalUrl = page.url();
log("final url:", finalUrl);
// Narrow viewport: chips wrap and sort moves to the header.
await page.setViewportSize({ width: 390, height: 844 });
await page.waitForTimeout(300);
await step("mobile");
await page.setViewportSize({ width: 1280, height: 800 });
// Drafts and Trash reuse the shared option hooks.
await page.goto("/drafts");
await page.getByRole("button", { name: "Any collection" }).waitFor();
await click(page.getByRole("button", { name: "Any collection" }));
await page.getByRole("menuitem", { name: args.collection }).waitFor();
await step("drafts-collection-filter");
await page.keyboard.press("Escape");
await page.goto("/trash");
await page.getByRole("button", { name: "Any time" }).waitFor();
await step("trash-filters");
return { url: finalUrl };
};
+47
View File
@@ -19,3 +19,50 @@ jobs:
type=raw,value=nightly
type=raw,value=nightly-{{date 'YYYYMMDD'}}
type=sha,prefix=nightly-,format=short
cleanup:
runs-on: ubuntu-latest
needs:
- publish
environment: dockerhub-nightly
env:
REPOSITORY: outlinewiki/outline
RETENTION_DAYS: 30
steps:
- name: Delete old nightly tags
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
run: |
set -euo pipefail
token=$(jq -n --arg id "$DOCKERHUB_USERNAME" --arg secret "$DOCKERHUB_TOKEN" \
'{identifier: $id, secret: $secret}' \
| curl -fsS -X POST -H "Content-Type: application/json" -d @- \
https://hub.docker.com/v2/auth/token \
| jq -r '.access_token')
echo "::add-mask::$token"
# Collect all matching tags before deleting so pagination stays stable.
tags=()
url="https://hub.docker.com/v2/repositories/${REPOSITORY}/tags?page_size=100&name=nightly-"
while [ -n "$url" ] && [ "$url" != "null" ]; do
page=$(curl -fsS -H "Authorization: Bearer $token" "$url")
while IFS= read -r tag; do
if [ -n "$tag" ]; then
tags+=("$tag")
fi
done < <(jq -r --argjson days "$RETENTION_DAYS" '
.results[]
| select(.name | startswith("nightly-"))
| select((.last_updated | sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601) < (now - $days * 86400))
| .name' <<< "$page")
url=$(jq -r '.next' <<< "$page")
done
echo "Deleting ${#tags[@]} tags older than ${RETENTION_DAYS} days"
for tag in "${tags[@]}"; do
echo "Deleting ${REPOSITORY}:${tag}"
curl -fsS -X DELETE -H "Authorization: Bearer $token" \
"https://hub.docker.com/v2/repositories/${REPOSITORY}/tags/${tag}/"
done
+1 -1
View File
@@ -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"
+1 -1
View File
@@ -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
+2 -2
View File
@@ -3,7 +3,7 @@ Business Source License 1.1
Parameters
Licensor: General Outline, Inc.
Licensed Work: Outline 1.12.0
Licensed Work: Outline 1.13.0
The Licensed Work is (c) 2026 General Outline, Inc.
Additional Use Grant: You may make use of the Licensed Work, provided that
you may not use the Licensed Work for a Document
@@ -15,7 +15,7 @@ Additional Use Grant: You may make use of the Licensed Work, provided that
Licensed Work by creating teams and documents
controlled by such third parties.
Change Date: 2030-10-23
Change Date: 2030-11-15
Change License: Apache License, Version 2.0
+2 -4
View File
@@ -1815,11 +1815,10 @@ export const toggleDocumentStats = createAction({
return;
}
user.setPreference(
await user.savePreference(
UserPreference.ShowDocumentStats,
!user.getPreference(UserPreference.ShowDocumentStats)
);
await user.save();
},
});
@@ -1865,8 +1864,7 @@ const changeHeadingPrefixFactory = (style: HeadingPrefixStyle) =>
if (!document) {
return;
}
document.setPreference(DocumentPreference.HeadingPrefix, style);
await document.save();
await document.savePreference(DocumentPreference.HeadingPrefix, style);
},
});
+92 -2
View File
@@ -1,15 +1,23 @@
import copy from "copy-to-clipboard";
import { addDays, endOfDay } from "date-fns";
import Share from "~/models/Share";
import { createAction, createInternalLinkAction } from "..";
import {
ActionSeparator,
createAction,
createActionWithChildren,
createInternalLinkAction,
} from "..";
import {
everyActiveModel,
performBatchOnActiveModels,
} from "~/actions/definitions/common";
import { ArrowIcon, CopyIcon, TrashIcon } from "outline-icons";
import { ArrowIcon, CalendarIcon, CopyIcon, TrashIcon } from "outline-icons";
import { ShareSection } from "../sections";
import type { ActionContext } from "~/types";
import env from "~/env";
import { toast } from "sonner";
import { errToString } from "@shared/utils/error";
import { ShareExpiryDialog } from "~/components/Sharing/components/ShareExpiryDialog";
export const copyShareUrl = createAction({
name: ({ t }) => t("Copy link"),
@@ -51,6 +59,70 @@ export const goToShareSource = createInternalLinkAction({
},
});
export const customShareExpiry = createAction({
name: ({ t }) => `${t("Custom")}…`,
analyticsName: "Set custom share expiry",
section: ShareSection,
perform: (context) => {
const share = singleActiveShare(context);
if (!share) {
return;
}
const { dialogs } = context.stores;
dialogs.openModal({
title: context.t("Set expiry"),
width: "600px",
content: (
<ShareExpiryDialog share={share} onSubmit={dialogs.closeAllModals} />
),
});
},
});
export const removeShareExpiry = createAction({
name: ({ t }) => t("Remove expiry"),
analyticsName: "Remove share expiry",
section: ShareSection,
visible: (context) => !!singleActiveShare(context)?.expiresAt,
perform: (context) =>
saveShareExpiry(context, null, context.t("Expiry removed")),
});
export const setShareExpiry = createActionWithChildren({
name: ({ t }) => t("Set expiry"),
analyticsName: "Set share expiry",
section: ShareSection,
icon: <CalendarIcon />,
visible: (context) => {
const { auth, policies } = context.stores;
const share = singleActiveShare(context);
return (
!!share &&
!!policies.abilities(auth.team?.id || "").share &&
!!policies.abilities(share.id).update
);
},
children: [
...[1, 7, 30].map((days) =>
createAction({
name: ({ t }) => t("{{ count }} days", { count: days }),
analyticsName: "Set share expiry preset",
section: ShareSection,
perform: (context) =>
saveShareExpiry(
context,
endOfDay(addDays(new Date(), days)),
context.t("Expiry updated")
),
})
),
customShareExpiry,
ActionSeparator,
removeShareExpiry,
],
});
export const revokeShare = createAction({
name: ({ t }) => t("Revoke link"),
analyticsName: "Revoke share",
@@ -86,6 +158,24 @@ export const revokeShare = createAction({
},
});
const saveShareExpiry = async (
context: ActionContext,
date: Date | null,
message: string
) => {
const share = singleActiveShare(context);
if (!share) {
return;
}
try {
await share.save({ expiresAt: date ? date.toISOString() : null });
toast.success(message);
} catch (err) {
toast.error(errToString(err));
}
};
const singleActiveShare = ({ getActiveModels }: ActionContext) => {
const shares = getActiveModels(Share);
return shares.length === 1 ? shares[0] : undefined;
+14 -8
View File
@@ -70,14 +70,16 @@ const ExpiryDatePicker = ({
side="right"
shrink
>
<Calendar
required
mode="single"
selected={selectedDate}
onSelect={handleSelect}
locale={locale}
disabled={{ before: new Date() }}
/>
<CalendarPadding>
<Calendar
required
mode="single"
selected={selectedDate}
onSelect={handleSelect}
locale={locale}
disabled={{ before: new Date() }}
/>
</CalendarPadding>
</PopoverContent>
</Popover>
{selectedDate && onClear && (
@@ -96,6 +98,10 @@ const ExpiryDatePicker = ({
);
};
const CalendarPadding = styled.div`
padding: 12px;
`;
const Wrapper = styled.div`
position: relative;
display: inline-flex;
+32 -6
View File
@@ -25,7 +25,7 @@ import { Menu, MenuContent, MenuTrigger, MenuButton } from "./primitives/Menu";
import * as MenuComponents from "./primitives/components/Menu";
import { MenuIconWrapper } from "./primitives/components/Menu";
interface TFilterOption extends PaginatedItem {
export interface TFilterOption extends PaginatedItem {
key: string;
label: string;
icon?: React.ReactNode;
@@ -42,6 +42,12 @@ type Props = {
fetchQuery?: (options: FetchPageParams) => Promise<PaginatedItem[]>;
fetchQueryOptions?: Record<string, string>;
disclosure?: boolean;
/** Custom element that opens the options, defaults to a button showing the selection. */
trigger?: React.ReactElement;
/** Whether the options are open when the component mounts. */
defaultOpen?: boolean;
/** Callback when the options open or close. */
onOpenChange?: (open: boolean) => void;
};
const FilterOptions = ({
@@ -54,13 +60,28 @@ const FilterOptions = ({
fetchQuery,
fetchQueryOptions,
disclosure = true,
trigger: customTrigger,
defaultOpen = false,
onOpenChange,
...rest
}: Props) => {
const { t } = useTranslation();
const isMobile = useMobile();
const searchInputRef = React.useRef<HTMLInputElement>(null);
const listRef = React.useRef<HTMLDivElement | null>(null);
const [open, setOpen] = React.useState(false);
const [open, setOpenState] = React.useState(defaultOpen);
// A menu that mounts open shows at once; later opens animate as usual.
const [skipAnimation, setSkipAnimation] = React.useState(defaultOpen);
const setOpen = React.useCallback(
(value: boolean) => {
setOpenState(value);
if (!value) {
setSkipAnimation(false);
}
onOpenChange?.(value);
},
[onOpenChange]
);
const selectedItems = options.filter((option) =>
selectedKeys.includes(option.key)
);
@@ -111,7 +132,7 @@ const FilterOptions = ({
/>
);
},
[onSelect, showIcons, selectedKeys, isMobile]
[onSelect, setOpen, showIcons, selectedKeys, isMobile]
);
const handleFilter = React.useCallback(
@@ -193,7 +214,7 @@ const FilterOptions = ({
break;
}
},
[filteredOptions, onSelect]
[filteredOptions, onSelect, setOpen]
);
const handleEscapeFromList = React.useCallback((ev: React.KeyboardEvent) => {
@@ -219,7 +240,7 @@ const FilterOptions = ({
const showFilterInput = showFilter || options.length > 10;
const defaultLabel = rest.defaultLabel || t("Filter options");
const trigger = (
const trigger = customTrigger ?? (
<StyledButton
className={className}
icon={selectedItems[0]?.key && selectedItems[0]?.icon}
@@ -271,7 +292,12 @@ const FilterOptions = ({
<MenuProvider variant="dropdown">
<Menu open={open} onOpenChange={setOpen}>
<MenuTrigger>{trigger}</MenuTrigger>
<MenuContent aria-label={defaultLabel} align="start">
<MenuContent
aria-label={defaultLabel}
align="start"
maxHeight="75vh"
skipAnimation={skipAnimation}
>
{list}
{showFilterInput && (
<SearchInput
+22
View File
@@ -0,0 +1,22 @@
type Props = {
/** The size of the icon, 24px is default to match standard icons */
size?: number;
/** The color of the icon, defaults to the current text color */
color?: string;
};
/**
* Three stacked lines of decreasing width, used for filter controls.
*
* @param props the icon props.
* @returns the icon.
*/
export function FilterIcon({ size = 24, color = "currentColor" }: Props) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
<rect x="5" y="7" width="14" height="2" rx="1" />
<rect x="7.5" y="11" width="9" height="2" rx="1" />
<rect x="10" y="15" width="4" height="2" rx="1" />
</svg>
);
}
+15 -3
View File
@@ -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 (
<MenuProvider variant="context">
@@ -97,8 +106,11 @@ export const ContextMenu = observer(
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
onCloseAutoFocus={preventDefault}
onEscapeKeyDown={handleEscapeKeyDown}
onKeyDownCapture={handleKeyDownCapture}
>
{content}
<MenuFilter query={query} onChange={setQuery} />
{content ?? (query ? <MenuFilterEmpty /> : null)}
</MenuContent>
</Menu>
</MenuProvider>
+16 -4
View File
@@ -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 (
<MenuProvider variant="dropdown">
@@ -144,9 +153,12 @@ export const DropdownMenu = observer(function DropdownMenu({
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
onCloseAutoFocus={preventDefault}
onEscapeKeyDown={handleEscapeKeyDown}
onKeyDownCapture={handleKeyDownCapture}
>
{content}
{append}
<MenuFilter query={query} onChange={setQuery} />
{content ?? (query ? <MenuFilterEmpty /> : null)}
{query ? null : append}
</MenuContent>
</Menu>
</MenuProvider>
+330
View File
@@ -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<HTMLElement>) => 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<string>();
const contentRef = React.useRef<HTMLElement | null>(null);
const highlightRef = React.useRef<HTMLElement | null>(null);
const reset = React.useCallback(() => {
contentRef.current = null;
highlightRef.current = null;
setQuery(undefined);
}, []);
const handleKeyDownCapture = React.useCallback(
(event: React.KeyboardEvent<HTMLElement>) => {
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<HTMLInputElement>(
`[${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<HTMLElement>(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<HTMLInputElement>) => {
onChange(event.target.value);
},
[onChange]
);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
// 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<HTMLElement>(ITEM_SELECTOR))
: [];
const highlighted =
content?.querySelector<HTMLElement>(`[${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 (
<Wrapper style={isActive ? undefined : VISUALLY_HIDDEN_STYLES}>
<Input
value={query ?? ""}
onChange={handleChange}
onKeyDown={handleKeyDown}
placeholder={`${t("Filter")}…`}
aria-label={t("Filter")}
tabIndex={-1}
autoComplete="off"
spellCheck={false}
{...{ [INPUT_ATTRIBUTE]: "" }}
/>
</Wrapper>
);
}
/**
* Displays a message when no menu items match the filter query.
*/
export function MenuFilterEmpty() {
const { t } = useTranslation();
return <Empty>{t("No results")}</Empty>;
}
/**
* 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<HTMLElement>(
"[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<HTMLElement>(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")};
`;
+50
View File
@@ -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();
});
});
+56 -5
View File
@@ -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<HTMLDivElement>();
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 ? (
<Components.MenuIconWrapper aria-hidden>
{"icon" in item ? item.icon : null}
</Components.MenuIconWrapper>
) : 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)
@@ -0,0 +1,84 @@
import { addWeeks, endOfDay } from "date-fns";
import { observer } from "mobx-react";
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { Calendar } from "@shared/components/Calendar";
import { dateLocale } from "@shared/utils/date";
import type Share from "~/models/Share";
import Button from "~/components/Button";
import Flex from "~/components/Flex";
import useUserLocale from "~/hooks/useUserLocale";
import { showErrorToast } from "./toasts";
interface Props {
/** The share to change the expiry of. */
share: Share;
/** Called after the expiry is saved. */
onSubmit: () => void;
}
/**
* Dialog content to choose the date after which a public link stops working.
*/
export const ShareExpiryDialog = observer(function ShareExpiryDialog({
share,
onSubmit,
}: Props) {
const { t } = useTranslation();
const userLocale = useUserLocale();
const [date, setDate] = useState<Date | undefined>(() => {
if (!share.expiresAt) {
return undefined;
}
// A past date cannot be selected, so suggest a week from today instead.
return share.isExpired
? addWeeks(new Date(), 1)
: new Date(share.expiresAt);
});
const [isSaving, setIsSaving] = useState(false);
const handleSubmit = useCallback(
async (ev: React.FormEvent) => {
ev.preventDefault();
if (!date) {
return;
}
setIsSaving(true);
try {
await share.save({ expiresAt: endOfDay(date).toISOString() });
toast.success(t("Expiry updated"));
onSubmit();
} catch (err) {
showErrorToast(err);
} finally {
setIsSaving(false);
}
},
[date, share, onSubmit, t]
);
return (
<form onSubmit={handleSubmit}>
<Flex gap={12} column>
<Calendar
required
mode="single"
numberOfMonths={2}
selected={date}
onSelect={setDate}
defaultMonth={date}
locale={dateLocale(userLocale)}
disabled={{ before: new Date() }}
/>
<Flex justify="flex-end">
<Button type="submit" disabled={!date || isSaving}>
{isSaving ? `${t("Saving")}…` : t("Save")}
</Button>
</Flex>
</Flex>
</form>
);
});
@@ -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<typeof Button> & {
@@ -34,7 +34,7 @@ const Button = styled(NudeButton)`
margin: 2px;
${extraArea(4)}
&:hover {
&:${hover} {
color: ${s("text")};
background: ${s("sidebarControlHoverBackground")};
}
@@ -165,8 +165,7 @@ function DraggableSection({ section, children }: Props) {
target
);
if (newOrder) {
user.setPreference(UserPreference.SidebarSectionOrder, newOrder);
void user.save();
void user.savePreference(UserPreference.SidebarSectionOrder, newOrder);
}
},
[findVisibleSibling, section, user]
@@ -1,4 +1,5 @@
import * as React from "react";
import { flushSync } from "react-dom";
import { useTranslation } from "react-i18next";
import {
DocumentValidation,
@@ -53,7 +54,9 @@ export function NewChildInput({
} else {
await onCreateChild(value);
}
onClose();
// Remove the input in the same paint as the new tree item.
flushSync(onClose);
},
[t, onCreateChild, onCreateChildLink, onClose]
);
@@ -1,14 +1,15 @@
import styled, { css } from "styled-components";
import EventBoundary from "@shared/components/EventBoundary";
import { s } from "@shared/styles";
import { hover, s } from "@shared/styles";
import NudeButton from "~/components/NudeButton";
/**
* Selector list matching a sidebar row that is hovered, pressed, or has one
* of its menus open. Radix marks the open trigger with `data-state="open"`:
* the row itself for a context menu, a descendant button for a dropdown.
* the row itself for a context menu, a descendant button for a dropdown. On
* touch devices `:hover` sticks after a tap, so only `:active` is matched.
*/
export const hoveredOrMenuOpen = `&:hover, &:active, &[data-state="open"], &:has([data-state="open"])`;
export const hoveredOrMenuOpen = `&:${hover}, &:active, &[data-state="open"], &:has([data-state="open"])`;
/**
* Trailing action buttons for a sidebar row. Hidden until the row reveals
@@ -200,8 +200,7 @@ export function useDropToReorderSidebarSection(
drop: (item) => {
const order = getNewOrder(item.id);
if (order) {
user.setPreference(UserPreference.SidebarSectionOrder, order);
void user.save();
void user.savePreference(UserPreference.SidebarSectionOrder, order);
}
},
canDrop: (item) => !!getNewOrder(item.id),
+18 -6
View File
@@ -13,6 +13,7 @@ import Input from "~/components/Input";
import useCurrentUser from "~/hooks/useCurrentUser";
import useStores from "~/hooks/useStores";
import ImageInput from "~/scenes/Settings/components/ImageInput";
import type { ImageUploadHandle } from "~/scenes/Settings/components/ImageUpload";
import { performBatch } from "~/actions/definitions/common";
import { client } from "~/utils/ApiClient";
import Text from "./Text";
@@ -183,6 +184,11 @@ export const UserChangeAvatarDialog = observer(function UserChangeAvatarDialog({
onSubmit,
}: Props) {
const { t } = useTranslation();
const imageRef = React.useRef<ImageUploadHandle>(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}
/>
</Flex>
<Flex justify="flex-end" gap={8}>
{user.avatarUrl && (
<Button onClick={() => handleAvatarChange(null)} neutral>
{t("Remove")}
<Flex justify="space-between" gap={8}>
<Flex gap={8}>
<Button onClick={handleReplace} neutral>
{user.avatarUrl ? t("Replace") : t("Upload")}…
</Button>
)}
{user.avatarUrl && (
<Button onClick={() => handleAvatarChange(null)} neutral>
{t("Delete")}
</Button>
)}
</Flex>
<Button onClick={onSubmit}>{t("Done")}</Button>
</Flex>
</Flex>
+11 -2
View File
@@ -78,11 +78,15 @@ type ContentProps = React.ComponentPropsWithoutRef<
> &
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content> & {
ref?: React.Ref<React.ComponentRef<typeof DropdownMenuPrimitive.Content>>;
/** The largest height of the menu, defaults to 85vh. */
maxHeight?: string;
/** Show the menu at once, without the opening animation. */
skipAnimation?: boolean;
};
function MenuContent(props: ContentProps) {
const { variant } = useMenuContext();
const { ref, children, ...rest } = props;
const { ref, children, maxHeight, skipAnimation, ...rest } = props;
const Portal =
variant === "dropdown"
@@ -111,7 +115,12 @@ function MenuContent(props: ContentProps) {
return (
<Portal>
<Content ref={ref} {...offsetProp} {...rest} collisionPadding={6} asChild>
<Components.MenuContent {...contentProps} hiddenScrollbars>
<Components.MenuContent
{...contentProps}
maxHeight={maxHeight}
$skipAnimation={skipAnimation}
hiddenScrollbars
>
{children}
</Components.MenuContent>
</Content>
+16 -5
View File
@@ -68,7 +68,9 @@ const BaseMenuItemCSS = css<BaseMenuItemProps>`
`
&[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: ${
@@ -192,6 +194,10 @@ export const MenuShortcut = styled.span`
type MenuContentProps = {
maxHeightVar: string;
transformOriginVar: string;
/** The largest height of the menu, defaults to 85vh. */
maxHeight?: string;
/** Show the menu at once, without the opening animation. */
$skipAnimation?: boolean;
};
export const MenuContent = styled(Scrollable).attrs<MenuContentProps>(
@@ -205,7 +211,8 @@ export const MenuContent = styled(Scrollable).attrs<MenuContentProps>(
min-width: 180px;
max-width: 320px;
min-height: 44px;
max-height: ${({ maxHeightVar }) => `min(85vh, var(${maxHeightVar}))`};
max-height: ${({ maxHeight = "85vh", maxHeightVar }) =>
`min(${maxHeight}, var(${maxHeightVar}))`};
font-weight: normal;
background: ${s("menuBackground")};
@@ -225,9 +232,13 @@ export const MenuContent = styled(Scrollable).attrs<MenuContentProps>(
transform-origin: ${({ transformOriginVar }) => `var(${transformOriginVar})`};
&[data-state="open"] {
animation: ${fadeAndScaleIn} 150ms ease-out;
}
${({ $skipAnimation }) =>
!$skipAnimation &&
css`
&[data-state="open"] {
animation: ${fadeAndScaleIn} 150ms ease-out;
}
`}
@media print {
display: none;
+22 -7
View File
@@ -19,9 +19,9 @@ 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 { client } from "~/utils/ApiClient";
import Input from "./Input";
import SuggestionsMenuItem from "./SuggestionsMenuItem";
import ToolbarButton from "./ToolbarButton";
@@ -29,6 +29,9 @@ 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;
@@ -67,18 +70,30 @@ const LinkEditor: React.FC<Props> = ({
? 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(async () => {
const res = await client.post("/suggestions.mention", { query });
res.data.documents.map(documents.add);
}, [documents, query])
React.useCallback(
() =>
documents.searchTitles({
query: requestQuery,
limit: 25,
filters: [
{ field: "archivedAt", operator: "isNull" },
{ field: "publishedAt", operator: "isNotNull" },
],
}),
[documents, requestQuery]
)
);
useEffect(() => {
if (trimmedQuery) {
if (requestQuery) {
void request();
}
}, [trimmedQuery, 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.
+19 -4
View File
@@ -1,7 +1,7 @@
import { observer } from "mobx-react";
import { v4 as uuidv4 } from "uuid";
import { runInAction } from "mobx";
import { useState, useCallback, useEffect } from "react";
import { useState, useCallback, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { MentionType } from "@shared/types";
@@ -25,6 +25,7 @@ import {
groupMentionItem,
userMentionItem,
} from "~/editor/menus/mention";
import useDebouncedValue from "~/hooks/useDebouncedValue";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import useUserLocale from "~/hooks/useUserLocale";
@@ -36,6 +37,9 @@ import type { Props as SuggestionsMenuProps } from "./SuggestionsMenu";
import SuggestionsMenu from "./SuggestionsMenu";
import SuggestionsMenuItem from "./SuggestionsMenuItem";
/** The time in milliseconds the search must stay the same before it is sent. */
const RequestDelay = 100;
type Props = Omit<
SuggestionsMenuProps<MentionMenuItem>,
"renderMenuItem" | "items" | "embeds"
@@ -122,13 +126,24 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) {
];
}
// Results from the store show at once, the server is only asked for more
// when the user stops typing.
const requestSearch = useDebouncedValue(search, RequestDelay);
const latestRequestId = useRef(0);
const { loading, request } = useRequest(
useCallback(async () => {
const requestId = ++latestRequestId.current;
const res = await client.post("/suggestions.mention", {
query: search,
limit: maxResultsInSection,
query: requestSearch,
limit: requestSearch ? 25 : 5,
});
// A newer request was sent while this one was in progress.
if (requestId !== latestRequestId.current) {
return;
}
runInAction(() => {
res.data.documents.map(documents.add);
res.data.users.map(users.add);
@@ -143,7 +158,7 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) {
...Object.entries<number>(res.data.familiarity ?? {}),
])
);
}, [search, documents, users, collections, groups, maxResultsInSection])
}, [requestSearch, documents, users, collections, groups])
);
// Suggestions that the current user is familiar with, for example a member of
+28 -4
View File
@@ -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<boolean>(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}
>
<EventBoundary>{toMenuItems(items)}</EventBoundary>
<MenuFilter query={query} onChange={setQuery} />
<EventBoundary>
{toMenuItems(items, query) ??
(query ? <MenuFilterEmpty /> : null)}
</EventBoundary>
</MenuContent>
</Menu>
</MenuProvider>
+1 -1
View File
@@ -37,7 +37,7 @@ const hoverPluginKey = new PluginKey<number | null>(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`.
+48 -30
View File
@@ -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,
+20
View File
@@ -0,0 +1,20 @@
import { useEffect, useState } from "react";
/**
* Returns a value that only changes after the given value has stayed the same
* for the wait time. The first value is returned at once.
*
* @param value the value to debounce.
* @param wait the time in milliseconds the value must stay the same.
* @returns the last value that stayed the same for the wait time.
*/
export default function useDebouncedValue<T>(value: T, wait: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timeout = setTimeout(() => setDebounced(value), wait);
return () => clearTimeout(timeout);
}, [value, wait]);
return debounced;
}
+32
View File
@@ -0,0 +1,32 @@
import { getCookie, removeCookie } from "tiny-cookie";
import { setPostLoginPath } from "./useLastVisitedPath";
const key = "postLoginRedirectPath";
describe("setPostLoginPath", () => {
beforeEach(() => {
sessionStorage.clear();
removeCookie(key);
});
it("stores the path in session storage and the shared cookie", () => {
setPostLoginPath("/doc/a");
expect(sessionStorage.getItem(key)).toBe("/doc/a");
expect(getCookie(key)).toBe("/doc/a");
});
it("does not change the shared cookie when tabOnly is set", () => {
setPostLoginPath("/doc/a");
setPostLoginPath("/doc/b", { tabOnly: true });
expect(sessionStorage.getItem(key)).toBe("/doc/b");
expect(getCookie(key)).toBe("/doc/a");
});
it("ignores paths that are not allowed as a login redirect", () => {
setPostLoginPath("/home", { tabOnly: true });
expect(sessionStorage.getItem(key)).toBeNull();
});
});
+9 -2
View File
@@ -56,12 +56,19 @@ export function useTrackLastVisitedPath(currentPath: string): void {
* Sets the path that the user visited before being asked to login.
*
* @param path The path to set as the post login path.
* @param options.tabOnly Whether to store the path for the current tab only, rather than
* also sharing it with other tabs through a cookie.
*/
export function setPostLoginPath(path: string) {
export function setPostLoginPath(
path: string,
options: { tabOnly?: boolean } = {}
) {
const key = "postLoginRedirectPath";
if (isAllowedLoginRedirect(path)) {
setCookie(key, path, { expires: 1 });
if (!options.tabOnly) {
setCookie(key, path, { expires: 1 });
}
try {
sessionStorage.setItem(key, path);
+8 -1
View File
@@ -4,6 +4,7 @@ import {
copyShareUrl,
goToShareSource,
revokeShare,
setShareExpiry,
} from "~/actions/definitions/shares";
import { useMenuAction } from "~/hooks/useMenuAction";
@@ -15,7 +16,13 @@ import { useMenuAction } from "~/hooks/useMenuAction";
*/
export function useShareMenuActions() {
const actions = useMemo(
() => [copyShareUrl, goToShareSource, ActionSeparator, revokeShare],
() => [
copyShareUrl,
goToShareSource,
setShareExpiry,
ActionSeparator,
revokeShare,
],
[]
);
+2 -1
View File
@@ -33,7 +33,8 @@ import { ActionContextProvider } from "./hooks/useActionContext";
// Load plugins as soon as possible
void PluginManager.loadPlugins();
initI18n(env.DEFAULT_LANGUAGE);
// Start with the language of the stored user to prevent a second fetch.
initI18n(stores.auth.user?.language ?? env.DEFAULT_LANGUAGE);
// Register ahead of rendering so the capture-phase listeners run before any
// React-mounted listener, such as kbar's Enter handler.
+1 -3
View File
@@ -115,9 +115,7 @@ function DocumentMenu({
const handleFullWidthToggle = React.useCallback(
(checked: boolean) => {
user.setPreference(UserPreference.FullWidthDocuments, checked);
void user.save();
document.fullWidth = checked;
void user.savePreference(UserPreference.FullWidthDocuments, checked);
void document.save({ fullWidth: checked });
},
[user, document]
+4 -9
View File
@@ -21,6 +21,7 @@ import {
} from "@shared/utils/collections";
import type CollectionsStore from "~/stores/CollectionsStore";
import type Document from "~/models/Document";
import { CoalescedFetch } from "~/models/base/CoalescedFetch";
import ParanoidModel from "~/models/base/ParanoidModel";
import { client } from "~/utils/ApiClient";
import type User from "./User";
@@ -285,15 +286,11 @@ export default class Collection extends ParanoidModel {
}
fetchDocuments = async (options?: { force: boolean }) => {
if (this.isFetching) {
return;
}
if (this.documents && options?.force !== true) {
return;
}
try {
this.isFetching = true;
await this.documentsFetch.run(async () => {
const res = await client.post("/collections.documents", {
id: this.id,
});
@@ -302,9 +299,7 @@ export default class Collection extends ParanoidModel {
runInAction(() => {
this.documents = res.data;
});
} finally {
this.isFetching = false;
}
}, options?.force);
};
/**
@@ -513,5 +508,5 @@ export default class Collection extends ParanoidModel {
}
}
private isFetching = false;
private documentsFetch = new CoalescedFetch();
}
+16 -11
View File
@@ -41,7 +41,6 @@ import type { Searchable } from "./interfaces/Searchable";
type SaveOptions = JSONObject & {
publish?: boolean;
done?: boolean;
autosave?: boolean;
};
@@ -508,20 +507,20 @@ export default class Document extends ArchivableModel implements Searchable {
}
/**
* Set the value for a specific display preference key.
* Set the value for a specific display preference key and save it to the
* server. The value is applied at once and reverted if the request fails.
*
* @param key The DocumentPreference key to set
* @param value The value to set
* @param key The DocumentPreference key to set.
* @param value The value to set.
* @returns a promise that resolves when the preference is saved.
*/
@action
setPreference<K extends DocumentPreference>(
savePreference<K extends DocumentPreference>(
key: K,
value: NonNullable<DocumentPreferences[K]>
) {
this.preferences = {
...this.preferences,
[key]: value,
};
return this.save({
preferences: { ...this.preferences, [key]: value },
});
}
/**
@@ -628,12 +627,14 @@ export default class Document extends ArchivableModel implements Searchable {
@action
save = async (
fields?: Properties<typeof this>,
fields?: Properties<Document>,
options?: SaveOptions
): Promise<Document> => {
const params = fields ?? this.toAPI();
this.isSaving = true;
const settle = this.applyOptimistic(fields ?? {});
try {
const model = await this.store.save(
{ ...params, ...fields, id: this.id },
@@ -644,8 +645,12 @@ export default class Document extends ArchivableModel implements Searchable {
set(this, Object.assign({}, params, model));
this.persistedAttributes = this.toAPI();
settle(true);
return model;
} catch (err) {
settle(false);
throw err;
} finally {
this.isSaving = false;
}
+3 -6
View File
@@ -160,8 +160,7 @@ class Notification extends Model {
*/
@action
toggleRead() {
this.viewedAt = this.viewedAt ? null : new Date();
return this.save();
return this.save({ viewedAt: this.viewedAt ? null : new Date() });
}
/**
@@ -175,8 +174,7 @@ class Notification extends Model {
return;
}
this.viewedAt = new Date();
return this.save();
return this.save({ viewedAt: new Date() });
}
/**
@@ -190,8 +188,7 @@ class Notification extends Model {
return;
}
this.archivedAt = new Date();
return this.save();
return this.save({ archivedAt: new Date() });
}
/**
+7 -6
View File
@@ -156,16 +156,17 @@ class Team extends Model {
}
/**
* Set the value for a specific preference key.
* Set the value for a specific preference key and save it to the server.
* The value is applied at once and reverted if the request fails.
*
* @param key The TeamPreference key to set.
* @param value The value to set.
* @returns a promise that resolves when the preference is saved.
*/
setPreference<T extends TeamPreference>(key: T, value: TeamPreferences[T]) {
this.preferences = {
...this.preferences,
[key]: value,
};
savePreference<T extends TeamPreference>(key: T, value: TeamPreferences[T]) {
return this.save({
preferences: { ...this.preferences, [key]: value },
});
}
}
+55
View File
@@ -1,5 +1,10 @@
import { vi } from "vitest";
import { UserPreference } from "@shared/types";
import User from "./User";
import stores from "~/stores";
import { client } from "~/utils/ApiClient";
const post = vi.mocked(client.post);
describe("User model", () => {
const users = stores.users;
@@ -266,4 +271,54 @@ describe("User model", () => {
]);
});
});
describe("savePreference", () => {
beforeEach(() => {
post.mockReset();
});
it("should send only preferences and keep other values", async () => {
const user = users.add({
id: "pref-success",
name: "Alice",
preferences: { [UserPreference.RememberLastPath]: true },
});
post.mockResolvedValueOnce({ data: { id: "pref-success" } });
const promise = user.savePreference(
UserPreference.UseCursorPointer,
false
);
expect(user.getPreference(UserPreference.UseCursorPointer)).toBe(false);
await promise;
expect(post).toHaveBeenCalledWith("/users.update", {
id: "pref-success",
preferences: {
[UserPreference.RememberLastPath]: true,
[UserPreference.UseCursorPointer]: false,
},
});
expect(user.getPreference(UserPreference.UseCursorPointer)).toBe(false);
expect(user.getPreference(UserPreference.RememberLastPath)).toBe(true);
});
it("should revert the preference on failure", async () => {
const user = users.add({
id: "pref-failure",
name: "Alice",
preferences: { [UserPreference.UseCursorPointer]: true },
});
post.mockRejectedValueOnce(new Error("server error"));
const promise = user.savePreference(
UserPreference.UseCursorPointer,
false
);
expect(user.getPreference(UserPreference.UseCursorPointer)).toBe(false);
await expect(promise).rejects.toThrow("server error");
expect(user.getPreference(UserPreference.UseCursorPointer)).toBe(true);
});
});
});
+9 -9
View File
@@ -302,20 +302,20 @@ class User extends ParanoidModel implements Searchable {
}
/**
* Set the value for a specific preference key.
* Set the value for a specific preference key and save it to the server.
* The value is applied at once and reverted if the request fails.
*
* @param key The UserPreference key to retrieve
* @param value The value to set
* @param key The UserPreference key to set.
* @param value The value to set.
* @returns a promise that resolves when the preference is saved.
*/
@action
setPreference<K extends UserPreference>(
savePreference<K extends UserPreference>(
key: K,
value: NonNullable<UserPreferences[K]>
) {
this.preferences = {
...this.preferences,
[key]: value,
};
return this.save({
preferences: { ...this.preferences, [key]: value },
});
}
getMembership(document: Document) {
+110
View File
@@ -0,0 +1,110 @@
import { CoalescedFetch, KeyedCoalescedFetch } from "./CoalescedFetch";
function deferred() {
let resolve = () => {};
let reject = (_err: Error) => {};
const promise = new Promise<void>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
describe("CoalescedFetch", () => {
it("should share an in-flight request with unforced calls", async () => {
const queue = new CoalescedFetch();
const request = deferred();
const fetch = vi.fn(() => request.promise);
const first = queue.run(fetch);
const second = queue.run(fetch);
request.resolve();
await Promise.all([first, second]);
expect(fetch).toHaveBeenCalledTimes(1);
});
it("should run one more request after an in-flight request when forced", async () => {
const queue = new CoalescedFetch();
const requests = [deferred(), deferred()];
let calls = 0;
const fetch = vi.fn(() => requests[calls++].promise);
const first = queue.run(fetch);
const forced = queue.run(fetch, true);
const forcedAgain = queue.run(fetch, true);
expect(fetch).toHaveBeenCalledTimes(1);
requests[0].resolve();
await first;
await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
let settled = false;
void forced.then(() => {
settled = true;
});
await Promise.resolve();
expect(settled).toBe(false);
requests[1].resolve();
await Promise.all([forced, forcedAgain]);
expect(fetch).toHaveBeenCalledTimes(2);
});
it("should run the forced request when the in-flight request fails", async () => {
const queue = new CoalescedFetch();
const failed = deferred();
const fetch = vi
.fn<() => Promise<void>>()
.mockReturnValueOnce(failed.promise)
.mockResolvedValueOnce(undefined);
const first = queue.run(fetch);
const forced = queue.run(fetch, true);
failed.reject(new Error("Network error"));
await expect(first).rejects.toThrow("Network error");
await expect(forced).resolves.toBeUndefined();
expect(fetch).toHaveBeenCalledTimes(2);
});
it("should start a new request after the previous one completes", async () => {
const queue = new CoalescedFetch();
const fetch = vi.fn(() => Promise.resolve());
await queue.run(fetch);
await queue.run(fetch);
expect(fetch).toHaveBeenCalledTimes(2);
});
});
describe("KeyedCoalescedFetch", () => {
it("should share requests for the same key only", async () => {
const fetches = new KeyedCoalescedFetch<string>();
const fetch = vi.fn((value: string) => Promise.resolve(value));
const results = await Promise.all([
fetches.run("a", () => fetch("a1")),
fetches.run("a", () => fetch("a2")),
fetches.run("b", () => fetch("b1")),
]);
expect(results).toEqual(["a1", "a1", "b1"]);
expect(fetch).toHaveBeenCalledTimes(2);
});
it("should return the result of the follow-up request to a forced call", async () => {
const fetches = new KeyedCoalescedFetch<number>();
let calls = 0;
const fetch = () => Promise.resolve(++calls);
const results = await Promise.all([
fetches.run("a", fetch),
fetches.run("a", fetch, true),
]);
expect(results).toEqual([1, 2]);
expect(await fetches.run("a", fetch)).toBe(3);
});
});
+76
View File
@@ -0,0 +1,76 @@
/**
* Runs an async fetch so that concurrent calls share one request. A forced
* call made while a request is in flight runs one more request after it, so
* the result is never older than the forced call.
*/
export class CoalescedFetch<T = void> {
/** Whether no request is in flight or queued. */
get isIdle(): boolean {
return !this.current && !this.next;
}
/**
* Runs the fetch, or joins the request that is in flight.
*
* @param fetch the function that performs the request.
* @param force whether the result must start after this call.
* @returns a promise that resolves with the result of the request.
*/
run(fetch: () => Promise<T>, force = false): Promise<T> {
if (!this.current) {
this.current = fetch().finally(() => {
this.current = undefined;
});
return this.current;
}
if (!force) {
return this.current;
}
this.next ??= this.current
.catch(() => undefined)
.then(() => {
this.next = undefined;
return this.run(fetch, true);
});
return this.next;
}
private current?: Promise<T>;
private next?: Promise<T>;
}
/**
* Runs a separate {@link CoalescedFetch} for each key, and discards it when
* its requests are complete.
*/
export class KeyedCoalescedFetch<T> {
/**
* Runs the fetch for the key, or joins the request for the key that is in
* flight.
*
* @param key the key that identifies the resource.
* @param fetch the function that performs the request.
* @param force whether the result must start after this call.
* @returns a promise that resolves with the result of the request.
*/
run(key: string, fetch: () => Promise<T>, force = false): Promise<T> {
let entry = this.entries.get(key);
if (!entry) {
entry = new CoalescedFetch<T>();
this.entries.set(key, entry);
}
const promise = entry.run(fetch, force);
const cleanup = () => {
if (entry.isIdle && this.entries.get(key) === entry) {
this.entries.delete(key);
}
};
void promise.then(cleanup, cleanup);
return promise;
}
private entries = new Map<string, CoalescedFetch<T>>();
}
+284
View File
@@ -1,5 +1,289 @@
import { autorun, isAction, isObservableProp } from "mobx";
import { vi } from "vitest";
import { CollectionPermission } from "@shared/types";
import Collection from "~/models/Collection";
import stores from "~/stores";
import { client } from "~/utils/ApiClient";
const post = vi.mocked(client.post);
const defer = () => {
let resolve!: (value: unknown) => void;
let reject!: (error: unknown) => void;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
};
describe("Model#save", () => {
beforeEach(() => {
post.mockReset();
});
it("should apply params before the server responds and keep them on success", async () => {
const collection = stores.collections.add({
id: "success",
name: "Before",
});
const request = defer();
post.mockReturnValueOnce(request.promise);
const promise = collection.save({ name: "After" });
expect(collection.name).toBe("After");
expect(collection.isSaving).toBe(true);
expect(collection.isDirty()).toBe(true);
request.resolve({ data: { id: "success", name: "After" }, policies: [] });
await promise;
expect(collection.name).toBe("After");
expect(collection.isSaving).toBe(false);
expect(collection.isDirty()).toBe(false);
});
it("should revert params on failure", async () => {
const collection = stores.collections.add({
id: "failure",
name: "Before",
});
post.mockRejectedValueOnce(new Error("server error"));
const promise = collection.save({ name: "After" });
expect(collection.name).toBe("After");
await expect(promise).rejects.toThrow("server error");
expect(collection.name).toBe("Before");
expect(collection.isSaving).toBe(false);
expect(collection.isDirty()).toBe(false);
});
it("should not apply params that are not fields", async () => {
const collection = stores.collections.add({
id: "non-field",
name: "Before",
});
const request = defer();
post.mockReturnValueOnce(request.promise);
const promise = collection.save({ name: "After", publish: true });
expect("publish" in collection).toBe(false);
request.reject(new Error("server error"));
await expect(promise).rejects.toThrow("server error");
});
it("should keep unsaved changes when saving without params fails", async () => {
const collection = stores.collections.add({ id: "direct", name: "Before" });
collection.name = "Edited";
const request = defer();
post.mockReturnValueOnce(request.promise);
const promise = collection.save();
collection.name = "Edited again";
request.reject(new Error("server error"));
await expect(promise).rejects.toThrow("server error");
expect(collection.name).toBe("Edited again");
expect(collection.isDirty()).toBe(true);
});
it("should keep changes made to a document while a failed save was in flight", async () => {
const document = stores.documents.add({ id: "document", title: "Before" });
document.title = "Edited";
const request = defer();
post.mockReturnValueOnce(request.promise);
const promise = document.save();
document.title = "Edited again";
request.reject(new Error("server error"));
await expect(promise).rejects.toThrow("server error");
expect(document.title).toBe("Edited again");
});
it("should revert document fields on failure", async () => {
const document = stores.documents.add({
id: "document-fields",
title: "Before",
});
post.mockRejectedValueOnce(new Error("server error"));
const promise = document.save({ title: "After" });
expect(document.title).toBe("After");
await expect(promise).rejects.toThrow("server error");
expect(document.title).toBe("Before");
});
it("should keep a newer successful save when an older one fails", async () => {
const collection = stores.collections.add({ id: "stale", name: "Before" });
const first = defer();
const second = defer();
post.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
const firstSave = collection.save({ name: "One" });
const secondSave = collection.save({ name: "Two" });
second.resolve({ data: { id: "stale", name: "Two" }, policies: [] });
await secondSave;
first.reject(new Error("server error"));
await expect(firstSave).rejects.toThrow("server error");
expect(collection.name).toBe("Two");
expect(collection.isDirty()).toBe(false);
});
it("should revert to the confirmed value when overlapping saves all fail", async () => {
const collection = stores.collections.add({
id: "overlap",
name: "Before",
});
const first = defer();
const second = defer();
post.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
const firstSave = collection.save({ name: "One" });
const secondSave = collection.save({ name: "Two" });
first.reject(new Error("server error"));
await expect(firstSave).rejects.toThrow("server error");
expect(collection.name).toBe("Two");
second.reject(new Error("server error"));
await expect(secondSave).rejects.toThrow("server error");
expect(collection.name).toBe("Before");
expect(collection.isDirty()).toBe(false);
});
it("should keep an update received while a failed save was in flight", async () => {
const collection = stores.collections.add({ id: "remote", name: "Before" });
const request = defer();
post.mockReturnValueOnce(request.promise);
const promise = collection.save({ name: "Mine" });
stores.collections.add({ id: "remote", name: "Theirs" });
request.reject(new Error("server error"));
await expect(promise).rejects.toThrow("server error");
expect(collection.name).toBe("Theirs");
expect(collection.isDirty()).toBe(false);
});
it("should stay clean when an unrelated update arrives before a failure", async () => {
const collection = stores.collections.add({
id: "unrelated",
name: "Before",
icon: "one",
});
const request = defer();
post.mockReturnValueOnce(request.promise);
const promise = collection.save({ name: "Mine" });
stores.collections.add({ id: "unrelated", icon: "two" });
request.reject(new Error("server error"));
await expect(promise).rejects.toThrow("server error");
expect(collection.name).toBe("Before");
expect(collection.icon).toBe("two");
expect(collection.isDirty()).toBe(false);
});
it("should run change hooks when the server confirms, not before", async () => {
const collection = stores.collections.add({
id: "hooks",
name: "Hooks",
permission: undefined,
});
stores.documents.add({
id: "hooks-doc",
title: "t",
collectionId: "hooks",
});
stores.policies.add({ id: "hooks-doc", abilities: {} });
const request = defer();
post.mockReturnValueOnce(request.promise);
const promise = collection.save({ permission: CollectionPermission.Read });
expect(stores.policies.get("hooks-doc")).toBeDefined();
request.resolve({
data: { id: "hooks", name: "Hooks", permission: "read" },
policies: [],
});
await promise;
expect(stores.policies.get("hooks-doc")).toBeUndefined();
});
it("should not run change hooks for an unrelated update during a save", async () => {
const collection = stores.collections.add({
id: "hooks-unrelated",
name: "Hooks",
icon: "one",
permission: undefined,
});
stores.documents.add({
id: "hooks-unrelated-doc",
title: "t",
collectionId: "hooks-unrelated",
});
stores.policies.add({ id: "hooks-unrelated-doc", abilities: {} });
const request = defer();
post.mockReturnValueOnce(request.promise);
const promise = collection.save({ permission: CollectionPermission.Read });
stores.collections.add({ id: "hooks-unrelated", icon: "two" });
expect(stores.policies.get("hooks-unrelated-doc")).toBeDefined();
request.reject(new Error("server error"));
await expect(promise).rejects.toThrow("server error");
expect(collection.permission).toBeUndefined();
expect(stores.policies.get("hooks-unrelated-doc")).toBeDefined();
});
it("should not run change hooks when the save fails", async () => {
const collection = stores.collections.add({
id: "hooks-failure",
name: "Hooks",
permission: undefined,
});
stores.documents.add({
id: "hooks-failure-doc",
title: "t",
collectionId: "hooks-failure",
});
stores.policies.add({ id: "hooks-failure-doc", abilities: {} });
post.mockRejectedValueOnce(new Error("server error"));
await expect(
collection.save({ permission: CollectionPermission.Read })
).rejects.toThrow("server error");
expect(collection.permission).toBeUndefined();
expect(stores.policies.get("hooks-failure-doc")).toBeDefined();
});
it("should leave a new model new and out of the store on failure", async () => {
const collection = new Collection({ name: "Draft" }, stores.collections);
expect(collection.isNew).toBe(true);
post.mockRejectedValueOnce(new Error("server error"));
const promise = collection.save({ name: "Named" });
expect(collection.name).toBe("Named");
await expect(promise).rejects.toThrow("server error");
expect(collection.name).toBe("Draft");
expect(collection.isNew).toBe(true);
expect(
Array.from(stores.collections.data.values()).includes(collection)
).toBe(false);
});
});
describe("Model observability", () => {
it("annotates fields declared on the base class and on subclasses", () => {
+122 -39
View File
@@ -1,5 +1,5 @@
import { isEqual, pick } from "es-toolkit/compat";
import { action, makeObservable, observable, toJS } from "mobx";
import { action, makeObservable, observable, runInAction, toJS } from "mobx";
import type { JSONObject } from "@shared/types";
import type Store from "~/stores/base/Store";
import type { PartialExcept } from "~/types";
@@ -47,6 +47,16 @@ function getAnnotatedKeysForModel(target: Model): (string | symbol)[] {
return [];
}
interface PendingField {
/** The last value known to be accepted by the server. */
confirmed: unknown;
/** The number of requests in flight that wrote to the field. */
count: number;
}
/** Fields on each model that have an optimistic write in flight. */
const pendingFields = new WeakMap<Model, Map<string, PendingField>>();
export default abstract class Model {
static modelName: string;
@@ -128,50 +138,46 @@ export default abstract class Model {
this: Model,
options: { withoutPolicies?: boolean } = {}
): Promise<unknown> {
// this is to ensure that multiple loads don’t happen in parallel
if (this.loadingRelations) {
return this.loadingRelations;
}
return this.store.relationFetches.run(this.id, () => {
const promises = [];
const promises = [];
const relations = getRelationsForModelClass(
this.constructor as typeof Model
);
const relations = getRelationsForModelClass(
this.constructor as typeof Model
);
if (relations) {
for (const properties of relations.values()) {
const store = this.store.rootStore.getStoreForModelName(
properties.relationClassResolver().modelName
);
if ("canFetchById" in store && store.canFetchById) {
const id = this[properties.idKey];
if (id) {
promises.push(store.fetch(id as string));
if (relations) {
for (const properties of relations.values()) {
const store = this.store.rootStore.getStoreForModelName(
properties.relationClassResolver().modelName
);
if ("canFetchById" in store && store.canFetchById) {
const id = this[properties.idKey];
if (id) {
promises.push(store.fetch(id as string));
}
}
}
}
}
const policy = this.store.rootStore.policies.get(this.id);
if (!policy && !options.withoutPolicies && this.store.canFetchById) {
promises.push(this.store.fetch(this.id, { force: true }));
}
const policy = this.store.rootStore.policies.get(this.id);
if (!policy && !options.withoutPolicies && this.store.canFetchById) {
promises.push(this.store.fetch(this.id, { force: true }));
}
try {
this.loadingRelations = Promise.all(promises);
return await this.loadingRelations;
} finally {
this.loadingRelations = undefined;
}
return Promise.all(promises);
});
}
/**
* Persists the model to the server API
* Persists the model to the server API.
*
* Fields passed as params are applied optimistically, and reverted if the
* request fails.
*
* @param params Specific fields to save, if not provided the model will be serialized
* @param options Options to pass to the store
* @returns A promise that resolves with the updated model
* @throws The original error if the request fails.
*/
save = async (
params?: Record<string, unknown>,
@@ -179,22 +185,25 @@ export default abstract class Model {
): Promise<Model> => {
const isNew = this.isNew;
this.isSaving = true;
let settle: ((success: boolean) => void) | undefined;
try {
// ensure that the id is passed if the document has one
if (!params) {
params = this.toAPI();
}
if (isNew) {
LifecycleManager.executeHooks(this.constructor, "beforeCreate", this);
} else {
LifecycleManager.executeHooks(this.constructor, "beforeUpdate", this);
}
if (params) {
settle = this.applyOptimistic(params);
} else {
params = this.toAPI();
}
const model = await this.store.save(
{
...params,
// ensure that the id is passed if the document has one
id: this.id,
},
{
@@ -205,6 +214,7 @@ export default abstract class Model {
// if saving is successful set the new values on the model itself
this.updateData(Object.assign({}, params, model));
settle?.(true);
if (isNew) {
LifecycleManager.executeHooks(this.constructor, "afterCreate", this);
@@ -213,17 +223,89 @@ export default abstract class Model {
}
return model;
} catch (err) {
settle?.(false);
throw err;
} finally {
this.isSaving = false;
}
};
/**
* Sets declared fields on the model ahead of a request to the server, so
* that observers update without waiting for the response.
*
* @param params the values being saved.
* @returns a function to call once when the request settles. On failure each
* field still holding its optimistic value is reverted to the last value
* confirmed by the server.
*/
protected applyOptimistic(
params: Record<string, unknown>
): (success: boolean) => void {
const fields = getFieldsForModel(this);
const keys = Object.keys(params).filter((key) => fields.includes(key));
const pending = pendingFields.get(this) ?? new Map<string, PendingField>();
pendingFields.set(this, pending);
runInAction(() => {
for (const key of keys) {
const entry = pending.get(key);
if (entry) {
entry.count++;
} else {
pending.set(key, { confirmed: Reflect.get(this, key), count: 1 });
}
Reflect.set(this, key, params[key]);
}
});
let settled = false;
return action((success: boolean) => {
if (settled) {
return;
}
settled = true;
for (const key of keys) {
const entry = pending.get(key);
if (!entry) {
continue;
}
// A value changed since the optimistic write is newer, so it is kept.
if (!success && isEqual(toJS(Reflect.get(this, key)), params[key])) {
Reflect.set(this, key, entry.confirmed);
if (
isEqual(Reflect.get(this.persistedAttributes, key), params[key])
) {
Reflect.set(this.persistedAttributes, key, toJS(entry.confirmed));
}
}
if (--entry.count === 0) {
pending.delete(key);
}
}
});
}
updateData = action((data: Record<string, unknown>) => {
if (this.initialized) {
LifecycleManager.executeHooks(this.constructor, "beforeChange", this);
}
// Change hooks compare incoming fields against confirmed values, not
// optimistic ones.
const pending = pendingFields.get(this);
const previousAttributes = this.toAPI();
pending?.forEach((entry, key) => {
if (key in data) {
Reflect.set(previousAttributes, key, entry.confirmed);
}
});
let addedKeys = false;
for (const key in data) {
@@ -232,6 +314,10 @@ export default abstract class Model {
if (key === "initialized") {
continue;
}
const entry = pending?.get(key);
if (entry) {
entry.confirmed = data[key];
}
if (isEqual(toJS(Reflect.get(this, key)), data[key])) {
continue;
}
@@ -348,9 +434,6 @@ export default abstract class Model {
protected persistedAttributes: Partial<Model> = {};
/** A promise that resolves when all relations have been loaded. */
private loadingRelations: Promise<unknown[]> | undefined;
/** A boolean representing if the constructor has been called. */
private initialized = false;
}
+4 -10
View File
@@ -1,6 +1,7 @@
import { action, computed, observable, runInAction } from "mobx";
import type { JSONObject, NavigationNode } from "@shared/types";
import { client } from "~/utils/ApiClient";
import { CoalescedFetch } from "./CoalescedFetch";
import Model from "./Model";
import type Document from "../Document";
import type DocumentsStore from "~/stores/DocumentsStore";
@@ -59,7 +60,7 @@ export default abstract class NavigableModel extends Model {
});
}
private isFetching = false;
private documentsFetch = new CoalescedFetch();
/** The document ID associated with this model. */
documentId?: string;
@@ -74,24 +75,17 @@ export default abstract class NavigableModel extends Model {
params: JSONObject;
force?: boolean;
}) {
if (this.isFetching) {
return;
}
if (this.documents && options.force !== true) {
return;
}
try {
this.isFetching = true;
await this.documentsFetch.run(async () => {
const res = await client.post(options.path, options.params);
runInAction(() => {
this.node = res.data;
});
} finally {
this.isFetching = false;
}
}, options.force);
}
/**
@@ -31,11 +31,10 @@ const CommentSortMenu = ({ viewingResolved, onChange }: Props) => {
(val: CommentSortType | "resolved") => {
if (val !== "resolved") {
if (val !== preferredSortType) {
user.setPreference(
void user.savePreference(
UserPreference.SortCommentsByOrderInDocument,
val === CommentSortType.OrderInDocument
);
void user.save();
}
}
@@ -1,5 +1,4 @@
import { differenceInMilliseconds } from "date-fns";
import { runInAction } from "mobx";
import { observer } from "mobx-react";
import { DoneIcon } from "outline-icons";
import { darken } from "polished";
@@ -184,8 +183,7 @@ function CommentThreadItem({
try {
handleSetReadOnly();
runInAction(() => (comment.data = data));
await comment.save();
await comment.save({ data });
} catch (_err) {
setEditing();
toast.error(t("Error updating comment"));
+4 -1
View File
@@ -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);
+290 -210
View File
@@ -8,13 +8,10 @@ import styled from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import { Pagination } from "@shared/constants";
import type { Filter } from "@shared/helpers/FilterHelper";
import { DURATION_BY_DATE_FILTER } from "@shared/helpers/FilterHelper";
import type {
SortFilter as TSortFilter,
DirectionFilter as TDirectionFilter,
DateFilter as TDateFilter,
} from "@shared/types";
import { StatusFilter as TStatusFilter } from "@shared/types";
import ArrowKeyNavigation from "~/components/ArrowKeyNavigation";
import DocumentListItem from "~/components/DocumentListItem";
import DocumentSelectionToolbar from "~/components/DocumentSelectionToolbar";
@@ -24,31 +21,39 @@ import LoadingIndicator from "~/components/LoadingIndicator";
import { ModelSelectionProvider } from "~/components/ModelSelectionContext";
import RegisterKeyDown from "~/components/RegisterKeyDown";
import Scene from "~/components/Scene";
import Switch from "~/components/Switch";
import Text from "~/components/Text";
import { Waypoint } from "~/components/Waypoint";
import usePaginatedRequest from "~/hooks/usePaginatedRequest";
import useQuery from "~/hooks/useQuery";
import useStores from "~/hooks/useStores";
import useUserLocale from "~/hooks/useUserLocale";
import { PAGINATION_SYMBOL } from "~/stores/base/Store";
import type { PaginationParams, SearchResult } from "~/types";
import { preventDefault } from "~/utils/events";
import { searchPath } from "~/utils/routeHelpers";
import { decodeURIComponentSafe, isTruthyQueryValue } from "~/utils/urls";
import CollectionFilter from "./components/CollectionFilter";
import DateFilter from "./components/DateFilter";
import { decodeURIComponentSafe } from "~/utils/urls";
import { AddFilterButton } from "./components/AddFilterButton";
import { DocumentFilter } from "./components/DocumentFilter";
import DocumentTypeFilter from "./components/DocumentTypeFilter";
import RecentSearches from "./components/RecentSearches";
import SearchInput from "./components/SearchInput";
import { SortInput } from "./components/SortInput";
import UserFilter from "./components/UserFilter";
import { HStack } from "~/components/primitives/HStack";
import useMobile from "~/hooks/useMobile";
import { SearchFilterChip } from "./components/SearchFilterChip";
import { DateRangeDialog } from "./components/DateRangeDialog";
import type { DateRange, SearchFilter } from "./searchFilters";
import {
TOGGLE_ON,
formatDateRange,
getDateRange,
getDateRangeParamChanges,
getFilterParamChanges,
readFilter,
useSearchFilters,
} from "./searchFilters";
function Search() {
const { t } = useTranslation();
const { documents, searches, policies } = useStores();
const isMobile = useMobile();
const { documents, searches, policies, dialogs } = useStores();
const userLocale = useUserLocale();
// routing
const params = useQuery();
@@ -66,99 +71,79 @@ function Search() {
routeMatch.params.query ?? params.get("q") ?? params.get("query") ?? ""
).trim();
const query = decodedQuery !== "" ? decodedQuery : undefined;
const collectionId = params.get("collectionId") ?? "";
const userId = params.get("userId") ?? "";
const documentId = params.get("documentId") ?? undefined;
const dateFilter = (params.get("dateFilter") as TDateFilter) ?? "";
// Keyed on the serialized value so the array keeps a stable identity between
// renders and can be used directly as a dependency.
const statusFilterKey = params.getAll("statusFilter").join(",");
const statusFilter = React.useMemo(
() =>
statusFilterKey
? (statusFilterKey.split(",") as TStatusFilter[])
: [TStatusFilter.Published, TStatusFilter.Draft],
[statusFilterKey]
);
const titleFilter = isTruthyQueryValue(params.get("titleFilter"));
const documentId =
params.get("documentId") ?? params.get("documentId.eq") ?? undefined;
const sort = (params.get("sort") as TSortFilter) ?? "";
const direction = (params.get("direction") as TDirectionFilter) ?? "";
const isSearchable = !!(query || collectionId || userId);
const document = documentId ? documents.get(documentId) : undefined;
const filterVisibility = {
document: !!document,
collection: !document,
user: !document || !!(document && query),
documentType: isSearchable,
date: isSearchable,
title: !!query && !document,
sort: isSearchable,
};
const searchFilters = useSearchFilters();
// A filter added from the "More" menu shows while its options are open.
const [pendingFilterId, setPendingFilterId] = React.useState<string>();
// A filter stays shown while its custom date range dialog is open.
const [rangeFilterId, setRangeFilterId] = React.useState<string>();
const filters = React.useMemo<Filter[] | undefined>(() => {
const children: Filter[] = [];
if (collectionId) {
children.push({
field: "collectionId",
operator: "eq",
value: collectionId,
});
}
if (userId) {
children.push({ field: "userId", operator: "eq", value: userId });
}
if (documentId) {
children.push({
field: "documentId",
operator: "eq",
value: documentId,
});
}
if (dateFilter) {
const duration = DURATION_BY_DATE_FILTER[dateFilter];
if (duration) {
children.push({ field: "updatedAt", operator: "gte", value: duration });
const { isSearchable, visibleFilters, filterStates, filters, titleFilter } =
React.useMemo(() => {
const visible = searchFilters.filter(
(filter) => filter.isAvailable?.({ document }) ?? true
);
const states = new Map(
visible.map((filter) => [filter.id, readFilter(filter, params)])
);
const setStates = [...states.values()];
const expressions = setStates
.map((state) => state.apiFilter)
.filter((filter): filter is Filter => !!filter);
if (documentId) {
expressions.push({
field: "documentId",
operator: "eq",
value: documentId,
});
}
}
if (statusFilter.length > 0) {
const statusShape = (status: TStatusFilter): Filter => {
if (status === TStatusFilter.Archived) {
return { field: "archivedAt", operator: "isNotNull" };
}
if (status === TStatusFilter.Published) {
return {
operator: "AND",
filters: [
{ field: "archivedAt", operator: "isNull" },
{ field: "publishedAt", operator: "isNotNull" },
],
};
}
return {
operator: "AND",
filters: [
{ field: "archivedAt", operator: "isNull" },
{ field: "publishedAt", operator: "isNull" },
],
};
return {
// Show results when there is a query or at least one filter is set.
isSearchable:
!!query || !!documentId || setStates.some((state) => state.isSet),
visibleFilters: visible,
filterStates: states,
filters: expressions.length > 0 ? expressions : undefined,
// An empty query matches every title, so list all results without one.
titleFilter: !!query && !!states.get("titleOnly")?.isSet,
};
const statusGroup =
statusFilter.length === 1
? statusShape(statusFilter[0])
: ({
operator: "OR",
filters: statusFilter.map(statusShape),
} as Filter);
children.push(statusGroup);
}
if (children.length === 0) {
return undefined;
}
return children;
}, [collectionId, userId, documentId, dateFilter, statusFilter]);
}, [searchFilters, params, query, document, documentId]);
const rangeLabels = React.useMemo(
() =>
new Map(
[...filterStates].map(([id, state]) => [
id,
state.range ? formatDateRange(state.range, t, userLocale) : undefined,
])
),
[filterStates, t, userLocale]
);
const isCollectionScoped = !!filterStates.get("collectionId")?.isSet;
const { shownFilters, addableFilters } = React.useMemo(() => {
const shown = visibleFilters.filter(
(filter) =>
filter.pinned ||
filterStates.get(filter.id)?.isSet ||
pendingFilterId === filter.id ||
rangeFilterId === filter.id
);
return {
shownFilters: shown,
addableFilters: visibleFilters.filter(
(filter) => !shown.includes(filter)
),
};
}, [visibleFilters, filterStates, pendingFilterId, rangeFilterId]);
const requestParams = React.useMemo(
() => ({
@@ -171,6 +156,17 @@ function Search() {
[query, titleFilter, sort, direction, filters]
);
const [resultCount, setResultCount] = React.useState<{
params: typeof requestParams;
total: number;
}>();
// Responses from earlier searches must not replace the current count.
const currentRequestParams = React.useRef(requestParams);
React.useEffect(() => {
currentRequestParams.current = requestParams;
}, [requestParams]);
const requestFn = React.useMemo(() => {
// Add to the searches store so this search can immediately appear in the recent searches list
// without a flash of loading.
@@ -188,15 +184,26 @@ function Search() {
offset: params?.offset,
limit: params?.limit,
};
return titleFilter
? await documents.searchTitles({
...requestParams,
...paginationParams,
})
: await documents.search({
...requestParams,
...paginationParams,
});
if (titleFilter) {
return await documents.searchTitles({
...requestParams,
...paginationParams,
});
}
const results = await documents.search({
...requestParams,
...paginationParams,
});
const total = results[PAGINATION_SYMBOL]?.total;
if (
!params?.offset &&
total !== undefined &&
currentRequestParams.current === requestParams
) {
setResultCount({ params: requestParams, total });
}
return results;
};
}
@@ -207,6 +214,10 @@ function Search() {
limit: Pagination.defaultLimit,
});
// Keep the previous count on screen, disabled, until the new one arrives.
const isResultCountStale = resultCount?.params !== requestParams;
const total = titleFilter || error ? undefined : resultCount?.total;
// Only updatable documents are selectable, matching the per-item checkboxes.
const itemIds = React.useMemo(
() =>
@@ -233,33 +244,96 @@ function Search() {
});
};
// All filters go through the query string so that searches are bookmarkable, which neccesitates
// some complexity as the query string is the source of truth for the filters.
const handleFilterChange = (search: {
collectionId?: string | undefined;
documentId?: string | undefined;
userId?: string | undefined;
dateFilter?: TDateFilter;
statusFilter?: TStatusFilter[];
titleFilter?: boolean | undefined;
sort?: string | undefined;
direction?: string | undefined;
}) => {
if (search.sort === "relevance") {
search.sort = undefined;
search.direction = undefined;
}
// All filters go through the query string so that searches are bookmarkable,
// which means the query string is the source of truth for the filters.
const replaceParams = React.useCallback(
(
getChanges: (
current: URLSearchParams
) => Record<string, string | string[] | undefined>
) => {
const { search } = history.location;
history.replace({
pathname: history.location.pathname,
search: queryString.stringify(
{
...queryString.parse(search),
...getChanges(new URLSearchParams(search)),
},
{ skipEmptyString: true, arrayFormat: "comma" }
),
});
},
[history]
);
history.replace({
pathname: history.location.pathname,
search: queryString.stringify(
{ ...queryString.parse(history.location.search), ...search },
{
skipEmptyString: true,
}
const handleChangeFilter = React.useCallback(
(filter: SearchFilter, values: string[] | undefined) =>
replaceParams((current) =>
getFilterParamChanges(filter, values, current)
),
});
};
[replaceParams]
);
const handleCustomRange = React.useCallback(
(filter: SearchFilter) => {
const handleSubmit = (range: Required<DateRange>) => {
replaceParams((current) =>
getDateRangeParamChanges(filter, range, current)
);
setRangeFilterId(undefined);
dialogs.closeAllModals();
};
setRangeFilterId(filter.id);
dialogs.openModal({
title: filter.label,
width: "600px",
onClose: () => setRangeFilterId(undefined),
content: (
<DateRangeDialog
defaultRange={getDateRange(
filter,
new URLSearchParams(history.location.search)
)}
onSubmit={handleSubmit}
/>
),
});
},
[dialogs, history, replaceParams]
);
const handleAddFilter = React.useCallback(
(id: string) => {
const filter = searchFilters.find((item) => item.id === id);
if (filter?.type === "toggle") {
handleChangeFilter(filter, [TOGGLE_ON]);
return;
}
setPendingFilterId(id);
},
[searchFilters, handleChangeFilter]
);
const handleFilterOpenChange = React.useCallback(
(filter: SearchFilter, open: boolean) => {
if (!open) {
setPendingFilterId((id) => (id === filter.id ? undefined : id));
}
},
[]
);
const handleSort = React.useCallback(
(sort: string, direction: string) =>
replaceParams(() =>
sort === "relevance"
? { sort: undefined, direction: undefined }
: { sort, direction }
),
[replaceParams]
);
const handleKeyDown = (ev: React.KeyboardEvent<HTMLInputElement>) => {
if (ev.nativeEvent.isComposing) {
@@ -309,21 +383,28 @@ function Search() {
};
const handleEscape = () => searchInputRef.current?.focus();
const showEmpty = !loading && query && data?.length === 0;
const showEmpty = !loading && isSearchable && data?.length === 0;
const sortInput = filterVisibility.sort ? (
<SortInput
sort={sort}
direction={direction}
onSelect={(sort, direction) => handleFilterChange({ sort, direction })}
const renderFilterChip = (filter: SearchFilter) => (
<SearchFilterChip
key={filter.id}
filter={filter}
values={filterStates.get(filter.id)?.values ?? EMPTY_VALUES}
isSet={!!filterStates.get(filter.id)?.isSet}
defaultOpen={pendingFilterId === filter.id}
onChange={handleChangeFilter}
onOpenChange={handleFilterOpenChange}
rangeLabel={rangeLabels.get(filter.id)}
onCustomRange={handleCustomRange}
/>
);
const sortInput = isSearchable ? (
<SortInput sort={sort} direction={direction} onSelect={handleSort} />
) : null;
return (
<Scene
textTitle={query ? `${query} – ${t("Search")}` : t("Search")}
actions={isMobile ? sortInput : null}
>
<Scene textTitle={query ? `${query} – ${t("Search")}` : t("Search")}>
<RegisterKeyDown trigger="Escape" handler={handleGoBack} />
{loading && <LoadingIndicator />}
<ResultsWrapper column auto>
@@ -335,66 +416,50 @@ function Search() {
placeholder={`${
documentId
? t("Search in document")
: collectionId
: isCollectionScoped
? t("Search in collection")
: t("Search")
}…`}
onKeyDown={handleKeyDown}
defaultValue={query ?? ""}
/>
<Filters>
<Flex align="center" gap={4} wrap>
{filterVisibility.document && (
<DocumentFilter
document={document!}
onClick={() => {
handleFilterChange({ documentId: undefined });
}}
/>
<FilterChips align="center" gap={6} wrap>
{document && (
<DocumentFilter
document={document}
onRemove={() =>
replaceParams(() => ({
documentId: undefined,
"documentId.eq": undefined,
}))
}
/>
)}
{shownFilters.map(renderFilterChip)}
{addableFilters.length > 0 && (
<AddFilterButton
filters={addableFilters}
onSelect={handleAddFilter}
/>
)}
</FilterChips>
{sortInput && (
<ResultsMeta
as="div"
type="secondary"
size="small"
aria-busy={isResultCountStale}
$disabled={isResultCountStale && total !== undefined}
>
{total !== undefined && (
<>
<span>{t("{{ count }} result", { count: total })}</span>
<span aria-hidden>·</span>
</>
)}
{filterVisibility.collection && (
<CollectionFilter
collectionId={collectionId}
onSelect={(collectionId) =>
handleFilterChange({ collectionId })
}
/>
)}
{filterVisibility.user && (
<UserFilter
userId={userId}
onSelect={(userId) => handleFilterChange({ userId })}
/>
)}
{filterVisibility.documentType && (
<DocumentTypeFilter
statusFilter={statusFilter}
onSelect={({ statusFilter }) =>
handleFilterChange({ statusFilter })
}
/>
)}
{filterVisibility.date && (
<DateFilter
dateFilter={dateFilter}
onSelect={(dateFilter) => handleFilterChange({ dateFilter })}
/>
)}
{filterVisibility.title && (
<SearchTitlesFilter
width={26}
height={14}
label={t("Search titles only")}
onChange={(checked: boolean) => {
handleFilterChange({ titleFilter: checked });
}}
checked={titleFilter}
inForm={false}
/>
)}
</Flex>
{isMobile ? null : sortInput}
</Filters>
{sortInput}
</ResultsMeta>
)}
</form>
{isSearchable ? (
<>
@@ -451,7 +516,7 @@ function Search() {
</ResultList>
</ModelSelectionProvider>
</>
) : documentId ? null : (
) : (
<RecentSearches ref={recentSearchesRef} onEscape={handleEscape} />
)}
</ResultsWrapper>
@@ -482,24 +547,39 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
flex: 1;
`;
const Filters = styled(HStack)`
flex-wrap: wrap;
justify-content: space-between;
const FilterChips = styled(Flex)`
row-gap: 8px;
margin-bottom: 12px;
transition: opacity 100ms ease-in-out;
padding: 8px 0;
padding-top: 4px;
${breakpoint("tablet")`
padding: 0;
${breakpoint("mobile", "tablet")`
flex-wrap: nowrap;
overflow-x: auto;
scrollbar-width: none;
margin-inline: -16px;
padding: 4px 16px 0;
& > * {
flex-shrink: 0;
}
`};
`;
const SearchTitlesFilter = styled(Switch)`
white-space: nowrap;
margin-left: 8px;
font-size: 14px;
font-weight: 400;
height: 28px;
const ResultsMeta = styled(Text)<{ $disabled: boolean }>`
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 8px;
transition: opacity 100ms ease-out;
${(props) =>
props.$disabled &&
`
opacity: 0.8;
pointer-events: none;
`}
`;
const EMPTY_VALUES: string[] = [];
export default observer(Search);
@@ -0,0 +1,59 @@
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import FilterOptions from "~/components/FilterOptions";
import { FilterIcon } from "~/components/Icons/FilterIcon";
import type { SearchFilter } from "../searchFilters";
import { Chip, ChipButton, ChipContent } from "./FilterChip";
interface Props {
/** The filters that can be added. */
filters: SearchFilter[];
/** Callback when a filter is picked. */
onSelect: (id: string) => void;
}
/**
* A button that opens a list of the filters that are not shown yet.
*
* @param props the button props.
* @returns the add filter button.
*/
export function AddFilterButton({ filters, onSelect }: Props) {
const { t } = useTranslation();
const handleSelect = useCallback(
(key: string | null | undefined) => {
if (key) {
onSelect(key);
}
},
[onSelect]
);
const options = useMemo(
() =>
filters.map((filter) => ({
key: filter.id,
label: filter.label,
icon: filter.icon,
})),
[filters]
);
return (
<Chip>
<FilterOptions
options={options}
selectedKeys={NO_SELECTION}
onSelect={handleSelect}
defaultLabel={t("More filters")}
trigger={
<ChipButton aria-label={t("More filters")}>
<ChipContent icon={<FilterIcon />} label={t("More")} disclosure />
</ChipButton>
}
/>
</Chip>
);
}
const NO_SELECTION: string[] = [];
@@ -3,8 +3,7 @@ import { CollectionIcon as SVGCollectionIcon } from "outline-icons";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import FilterOptions from "~/components/FilterOptions";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import useStores from "~/hooks/useStores";
import { useCollectionOptions } from "../filterOptions";
type Props = {
/** The currently selected collection ID */
@@ -15,23 +14,19 @@ type Props = {
function CollectionFilter(props: Props) {
const { t } = useTranslation();
const { collections } = useStores();
const { onSelect, collectionId } = props;
const options = useMemo(() => {
const collectionOptions = collections.orderedData.map((collection) => ({
key: collection.id,
label: collection.displayName,
icon: <CollectionIcon collection={collection} size={24} />,
}));
return [
const source = useCollectionOptions();
const options = useMemo(
() => [
{
key: "",
label: t("Any collection"),
icon: <SVGCollectionIcon size={24} />,
},
...collectionOptions,
];
}, [collections.orderedData, t]);
...source.options,
],
[source.options, t]
);
return (
<FilterOptions
+4 -23
View File
@@ -2,6 +2,7 @@ import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import type { DateFilter as TDateFilter } from "@shared/types";
import FilterOptions from "~/components/FilterOptions";
import { useDateOptions } from "../filterOptions";
type Props = {
/** The selected date filter */
@@ -12,30 +13,10 @@ type Props = {
const DateFilter = ({ dateFilter, onSelect }: Props) => {
const { t } = useTranslation();
const source = useDateOptions();
const options = useMemo(
() => [
{
key: "",
label: t("All time"),
},
{
key: "day",
label: t("Past day"),
},
{
key: "week",
label: t("Past week"),
},
{
key: "month",
label: t("Past month"),
},
{
key: "year",
label: t("Past year"),
},
],
[t]
() => [{ key: "", label: t("All time") }, ...source.options],
[source.options, t]
);
return (
@@ -0,0 +1,99 @@
import { subMonths } from "date-fns";
import { useCallback, useState } from "react";
import type { DateRange as DayPickerRange } from "react-day-picker";
import { useTranslation } from "react-i18next";
import { Calendar } from "@shared/components/Calendar";
import {
dateLocale,
dateRangeToReadable,
parseISODate,
toISODate,
} from "@shared/utils/date";
import Button from "~/components/Button";
import Flex from "~/components/Flex";
import Text from "~/components/Text";
import useUserLocale from "~/hooks/useUserLocale";
import type { DateRange } from "../searchFilters";
interface Props {
/** The range to show as selected when the dialog opens. */
defaultRange?: DateRange;
/** Called with the chosen range as ISO dates. */
onSubmit: (range: Required<DateRange>) => void;
}
/**
* Dialog content to choose the first and last day of a date filter.
*/
export function DateRangeDialog({ defaultRange, onSubmit }: Props) {
const { t } = useTranslation();
const userLocale = useUserLocale();
const [today] = useState(() => new Date());
const [range, setRange] = useState<DayPickerRange | undefined>(() => {
const from = defaultRange?.from ? parseISODate(defaultRange.from) : null;
const to = defaultRange?.to ? parseISODate(defaultRange.to) : null;
if (!from && !to) {
return undefined;
}
return { from: from ?? to ?? undefined, to: to ?? undefined };
});
// Show the last day of the range in the right month, so that future months
// (which cannot be picked) are not shown.
const [defaultMonth] = useState(() => subMonths(range?.to ?? today, 1));
// When a whole range is selected, the next click starts a new range.
const handleSelect = useCallback(
(next: DayPickerRange | undefined, selectedDay: Date) => {
setRange((current) =>
current?.from && current.to ? { from: selectedDay } : next
);
},
[]
);
const handleSubmit = useCallback(
(ev: React.FormEvent) => {
ev.preventDefault();
if (!range?.from) {
return;
}
onSubmit({
from: toISODate(range.from),
to: toISODate(range.to ?? range.from),
});
},
[range, onSubmit]
);
return (
<form onSubmit={handleSubmit}>
<Flex gap={12} column>
<Calendar
mode="range"
numberOfMonths={2}
showOutsideDays={false}
selected={range}
onSelect={handleSelect}
defaultMonth={defaultMonth}
locale={dateLocale(userLocale)}
disabled={{ after: today }}
/>
<Flex justify="space-between" align="center" gap={12}>
<Text type="secondary" size="small">
{range?.from
? dateRangeToReadable(
range.from,
range.to ?? range.from,
userLocale
)
: t("Choose the first and last day")}
</Text>
<Button type="submit" disabled={!range?.from}>
{t("Apply")}
</Button>
</Flex>
</Flex>
</form>
);
}
+16 -12
View File
@@ -1,27 +1,31 @@
import { CloseIcon } from "outline-icons";
import * as React from "react";
import { DocumentIcon } from "outline-icons";
import { useTranslation } from "react-i18next";
import type Document from "~/models/Document";
import { StyledButton } from "~/components/FilterOptions";
import Tooltip from "~/components/Tooltip";
import { Chip, ChipContent, ChipRemoveButton, ChipStatic } from "./FilterChip";
type Props = {
/** The currently selected document */
document: Document;
/** Callback to remove the document filter */
onClick: React.MouseEventHandler;
onRemove: () => void;
};
export function DocumentFilter(props: Props) {
const { t } = useTranslation();
return (
<div>
<Tooltip content={t("Remove document filter")}>
<StyledButton onClick={props.onClick} icon={<CloseIcon />} neutral>
{props.document.displayTitle}
</StyledButton>
</Tooltip>
</div>
<Chip>
<ChipStatic>
<ChipContent
icon={<DocumentIcon />}
label={t("Document")}
value={props.document.displayTitle}
/>
</ChipStatic>
<ChipRemoveButton
label={t("Remove document filter")}
onClick={props.onRemove}
/>
</Chip>
);
}
@@ -1,54 +0,0 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { StatusFilter as TStatusFilter } from "@shared/types";
import FilterOptions from "~/components/FilterOptions";
type Props = {
/** The selected status filters */
statusFilter: TStatusFilter[];
/** Callback when a status filter is selected */
onSelect: (option: { statusFilter: TStatusFilter[] }) => void;
};
const DocumentTypeFilter = ({ statusFilter, onSelect }: Props) => {
const { t } = useTranslation();
const options = useMemo(
() => [
{
key: TStatusFilter.Published,
label: t("Published"),
},
{
key: TStatusFilter.Archived,
label: t("Archived"),
},
{
key: TStatusFilter.Draft,
label: t("Drafts"),
},
],
[t]
);
const handleSelect = (key: TStatusFilter) => {
let modifiedStatusFilter;
if (statusFilter.includes(key)) {
modifiedStatusFilter = statusFilter.filter((status) => status !== key);
} else {
modifiedStatusFilter = [...statusFilter, key];
}
onSelect({ statusFilter: modifiedStatusFilter });
};
return (
<FilterOptions
options={options}
selectedKeys={statusFilter}
onSelect={handleSelect}
defaultLabel={t("Any status")}
/>
);
};
export default DocumentTypeFilter;
+189
View File
@@ -0,0 +1,189 @@
import { CloseIcon, DisclosureIcon } from "outline-icons";
import styled from "styled-components";
import { hover, s } from "@shared/styles";
import { breakpoint } from "@shared/styles/breakpoint";
import NudeButton from "~/components/NudeButton";
import Text from "~/components/Text";
import Tooltip from "~/components/Tooltip";
interface ChipContentProps {
/** Icon shown before the label. */
icon?: React.ReactNode;
/** Name of the filter. */
label: string;
/** The selected value, omitted when there is no value. */
value?: string;
/** Whether to show a disclosure arrow after the content. */
disclosure?: boolean;
}
/**
* The icon, filter name and selected value shown inside a filter chip.
*
* @param props the content props.
* @returns the chip content.
*/
export function ChipContent({
icon,
label,
value,
disclosure,
}: ChipContentProps) {
return (
<>
{icon && <ChipIcon aria-hidden>{icon}</ChipIcon>}
<ChipLabel type={value ? "secondary" : undefined}>{label}</ChipLabel>
{value && (
<ChipValue weight="bold" ellipsis>
{value}
</ChipValue>
)}
{disclosure && <Disclosure size={20} aria-hidden />}
</>
);
}
interface ChipRemoveButtonProps {
/** Accessible label and tooltip for the button. */
label: string;
/** Callback when the button is clicked. */
onClick: () => void;
}
/**
* A button at the end of a filter chip that removes the filter.
*
* @param props the button props.
* @returns the remove button.
*/
export function ChipRemoveButton({ label, onClick }: ChipRemoveButtonProps) {
return (
<Tooltip content={label}>
<RemoveButton aria-label={label} onClick={onClick}>
<CloseIcon size={18} />
</RemoveButton>
</Tooltip>
);
}
/** Outlined container for a filter chip. */
export const Chip = styled.div`
display: inline-flex;
align-items: stretch;
max-width: 100%;
height: 28px;
border: 1px solid ${s("buttonNeutralBorder")};
border-radius: 8px;
overflow: hidden;
user-select: none;
font-size: 13px;
font-weight: 450;
color: ${s("text")};
&:has(:focus-visible) {
border-color: ${s("inputBorderFocused")};
}
${breakpoint("mobile", "tablet")`
height: 36px;
font-size: 15px;
`};
`;
/** The button inside a chip that opens the options of the filter. */
export const ChipButton = styled.button`
display: inline-flex;
align-items: center;
gap: 4px;
min-width: 0;
height: 100%;
padding: 0 4px 0 7px;
margin: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
cursor: var(--pointer);
transition: background 100ms ease-out;
&:${hover},
&[aria-expanded="true"] {
background: ${s("buttonNeutralHoverBackground")};
}
&:focus-visible {
outline: none;
}
`;
/** A part of a chip that only shows content, for filters without options. */
export const ChipStatic = styled.span`
display: inline-flex;
align-items: center;
gap: 4px;
min-width: 0;
padding: 0 4px 0 6px;
`;
const ChipIcon = styled.span`
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 18px;
height: 18px;
margin-inline-start: -2px;
color: ${s("textTertiary")};
svg {
width: 18px;
height: 18px;
}
`;
const ChipLabel = styled(Text)`
flex-shrink: 0;
white-space: nowrap;
`;
const ChipValue = styled(Text)`
max-width: 240px;
`;
const RemoveButton = styled(NudeButton)`
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 24px;
height: auto;
padding-inline-end: 2px;
border-radius: 0;
border-inline-start: 1px solid transparent;
color: ${s("textTertiary")};
transition:
background 100ms ease-out,
border-color 100ms ease-out,
color 100ms ease-out;
&:${hover},
&:focus-visible {
color: ${s("text")};
background: ${s("buttonNeutralHoverBackground")};
border-color: ${s("buttonNeutralBorder")};
}
&:focus-visible {
outline: none;
}
${breakpoint("mobile", "tablet")`
width: 32px;
`};
`;
const Disclosure = styled(DisclosureIcon)`
flex-shrink: 0;
margin-inline-start: -3px;
color: ${s("textTertiary")};
`;
@@ -0,0 +1,154 @@
import { observer } from "mobx-react";
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import FilterOptions from "~/components/FilterOptions";
import type { SearchFilter, SelectSearchFilter } from "../searchFilters";
import { CUSTOM_RANGE } from "../searchFilters";
import {
Chip,
ChipButton,
ChipContent,
ChipRemoveButton,
ChipStatic,
} from "./FilterChip";
interface Props {
/** The filter to show. */
filter: SearchFilter;
/** The selected values, including defaults. */
values: string[];
/** Whether the URL sets the filter, as opposed to using its defaults. */
isSet: boolean;
/** Whether the options are open when the chip mounts. */
defaultOpen?: boolean;
/** Callback when the selected values change, undefined removes the filter. */
onChange: (filter: SearchFilter, values: string[] | undefined) => void;
/** Callback when the options open or close. */
onOpenChange?: (filter: SearchFilter, open: boolean) => void;
/** Label of a custom date range, shown in place of an option label. */
rangeLabel?: string;
/** Callback when the user asks to choose a custom date range. */
onCustomRange?: (filter: SearchFilter) => void;
}
/**
* A chip that shows the value of one search filter and lets the user change
* or remove it.
*
* @param props the chip props.
* @returns the filter chip.
*/
export function SearchFilterChip(props: Props) {
const { t } = useTranslation();
const { filter, onChange } = props;
if (filter.type === "select") {
return <SelectFilterChip {...props} filter={filter} />;
}
return (
<Chip>
<ChipStatic>
<ChipContent icon={filter.icon} label={filter.label} />
</ChipStatic>
<ChipRemoveButton
label={t("Remove filter")}
onClick={() => onChange(filter, undefined)}
/>
</Chip>
);
}
const SelectFilterChip = observer(function SelectFilterChip_({
filter,
values,
isSet,
defaultOpen,
onChange,
onOpenChange,
rangeLabel,
onCustomRange,
}: Props & { filter: SelectSearchFilter }) {
const { t } = useTranslation();
const source = filter.useOptions();
const { multiple } = filter;
const allowsRange = filter.selection === "date" && !!onCustomRange;
const options = useMemo(
() =>
allowsRange
? [...source.options, { key: CUSTOM_RANGE, label: `${t("Custom")}…` }]
: source.options,
[allowsRange, source.options, t]
);
const selected = useMemo(
() => source.options.filter((option) => values.includes(option.key)),
[source.options, values]
);
const handleSelect = useCallback(
(key: string | null | undefined) => {
if (!key) {
return;
}
if (key === CUSTOM_RANGE) {
onCustomRange?.(filter);
return;
}
if (!multiple) {
onChange(filter, [key]);
return;
}
const next = values.includes(key)
? values.filter((value) => value !== key)
: [...values, key];
onChange(filter, next.length ? next : undefined);
},
[filter, multiple, values, onChange, onCustomRange]
);
const handleOpenChange = useCallback(
(open: boolean) => onOpenChange?.(filter, open),
[filter, onOpenChange]
);
// Default values are implied, so only show values that the user picked.
const shown = isSet ? selected : [];
const icon =
shown.length === 1 && shown[0].icon ? shown[0].icon : filter.icon;
return (
<Chip>
<FilterOptions
options={options}
selectedKeys={rangeLabel ? [CUSTOM_RANGE] : values}
onSelect={handleSelect}
fetchQuery={source.fetchQuery}
fetchQueryOptions={source.fetchQueryOptions}
showFilter={source.showFilter}
defaultLabel={filter.label}
defaultOpen={defaultOpen}
onOpenChange={handleOpenChange}
trigger={
<ChipButton>
<ChipContent
icon={icon}
label={filter.label}
value={
rangeLabel ?? shown.map((option) => option.label).join(", ")
}
disclosure={!isSet}
/>
</ChipButton>
}
/>
{isSet && (
<ChipRemoveButton
label={t("Remove filter")}
onClick={() => onChange(filter, undefined)}
/>
)}
</Chip>
);
});
+34 -53
View File
@@ -1,8 +1,8 @@
import { SearchIcon } from "outline-icons";
import * as React from "react";
import styled, { useTheme } from "styled-components";
import styled from "styled-components";
import { s } from "@shared/styles";
import Flex from "~/components/Flex";
import Input, { NativeInput, Outline } from "~/components/Input";
interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
name: string;
@@ -11,77 +11,58 @@ interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
}
function SearchInput({ defaultValue, ref, ...rest }: Props) {
const theme = useTheme();
const focusInput = React.useCallback(() => {
ref.current?.focus();
}, [ref]);
React.useEffect(() => {
// ensure that focus is placed at end of input
const len = (defaultValue || "").length;
ref.current?.setSelectionRange(len, len);
const timeoutId = setTimeout(() => {
focusInput();
ref.current?.focus();
}, 100); // arbitrary number
return () => {
clearTimeout(timeoutId);
};
}, [ref, defaultValue, focusInput]);
}, [ref, defaultValue]);
return (
<Wrapper align="center">
<StyledIcon size={46} color={theme.placeholder} onClick={focusInput} />
<StyledInput
{...rest}
defaultValue={defaultValue}
ref={ref}
spellCheck="false"
type="search"
autoFocus
/>
</Wrapper>
<StyledInput
{...rest}
type="search"
icon={<StyledSearchIcon />}
defaultValue={defaultValue}
ref={ref}
spellCheck="false"
margin="0 0 12px"
autoFocus
/>
);
}
const Wrapper = styled(Flex)`
position: relative;
margin-bottom: 8px;
`;
const StyledInput = styled(Input)`
${Outline} {
border-color: transparent;
border-radius: 10px;
background: ${s("backgroundSecondary")};
transition:
background 100ms ease-out,
border-color 100ms ease-out;
}
const StyledInput = styled.input`
width: 100%;
padding-block: 10px 10px;
padding-inline: 60px 10px;
font-size: 30px;
font-weight: 400;
outline: none;
border: 0;
background: ${s("inputBackground")};
border-radius: 4px;
color: ${s("text")};
&:focus-within ${Outline} {
border-color: ${s("inputBorderFocused")};
background: ${s("background")};
}
&::-webkit-search-cancel-button {
-webkit-appearance: none;
}
&::-webkit-input-placeholder {
color: ${s("placeholder")};
}
&:-moz-placeholder {
color: ${s("placeholder")};
}
&::-moz-placeholder {
color: ${s("placeholder")};
}
&:-ms-input-placeholder {
color: ${s("placeholder")};
${NativeInput} {
height: 46px;
padding-inline-start: 12px;
font-size: 17px;
}
`;
const StyledIcon = styled(SearchIcon)`
position: absolute;
inset-inline-start: 8px;
opacity: 0.7;
const StyledSearchIcon = styled(SearchIcon)`
margin-inline-start: 4px;
color: ${s("textTertiary")};
`;
export default SearchInput;
+57 -10
View File
@@ -1,7 +1,13 @@
import type { DirectionFilter, SortFilter as TSortFilter } from "@shared/types";
import { SortAscendingIcon, SortDescendingIcon } from "outline-icons";
import {
DisclosureIcon,
SortAscendingIcon,
SortDescendingIcon,
} from "outline-icons";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { hover, s } from "@shared/styles";
import FilterOptions from "~/components/FilterOptions";
type Props = {
@@ -64,15 +70,56 @@ export const SortInput = ({ sort, direction, onSelect }: Props) => {
onSelect(sortField, sortDirection);
};
const selectedLabel =
options.find((option) => option.key === selectedKey)?.label ??
t("Relevance");
return (
<FilterOptions
showFilter={false}
showIcons={false}
disclosure={false}
options={options}
selectedKeys={[selectedKey]}
onSelect={handleSelect}
defaultLabel={t("Relevance")}
/>
<Wrapper>
{t("Sorted by")}
<FilterOptions
showFilter={false}
showIcons={false}
options={options}
selectedKeys={[selectedKey]}
onSelect={handleSelect}
defaultLabel={t("Sort")}
trigger={
<Trigger>
{selectedLabel}
<Disclosure size={20} aria-hidden />
</Trigger>
}
/>
</Wrapper>
);
};
const Wrapper = styled.div`
display: flex;
align-items: center;
gap: 4px;
`;
const Trigger = styled.button`
display: inline-flex;
align-items: center;
margin: 0;
padding: 0 0 0 2px;
border: 0;
border-radius: 4px;
background: none;
font: inherit;
font-weight: 500;
color: ${s("text")};
cursor: var(--pointer);
&:${hover},
&[aria-expanded="true"] {
text-decoration: underline;
}
`;
const Disclosure = styled(DisclosureIcon)`
color: ${s("textTertiary")};
`;
+10 -26
View File
@@ -2,12 +2,8 @@ import { observer } from "mobx-react";
import { UserIcon } from "outline-icons";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { Avatar, AvatarSize } from "~/components/Avatar";
import FilterOptions from "~/components/FilterOptions";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import { useUserOptions } from "../filterOptions";
type Props = {
/** The currently selected user ID */
@@ -18,31 +14,23 @@ type Props = {
onSelect: (key: string | undefined) => void;
};
const fetchQueryOptions = { sort: "name", direction: "ASC" };
function UserFilter(props: Props) {
const { onSelect, userId } = props;
const { t } = useTranslation();
const { users } = useStores();
const team = useCurrentTeam();
const can = usePolicy(team);
const source = useUserOptions();
const anyLabel = props.anyLabel ?? t("Any author");
const options = useMemo(() => {
const userOptions = users.all.map((user) => ({
key: user.id,
label: user.name,
icon: <StyledAvatar model={user} size={AvatarSize.Small} />,
}));
return [
const options = useMemo(
() => [
{
key: "",
label: anyLabel,
icon: <UserIcon size={20} />,
},
...userOptions,
];
}, [users.all, anyLabel]);
...source.options,
],
[source.options, anyLabel]
);
return (
<FilterOptions
@@ -50,15 +38,11 @@ function UserFilter(props: Props) {
selectedKeys={[userId]}
onSelect={onSelect}
defaultLabel={anyLabel}
fetchQuery={can.listUsers ? users.fetchPage : undefined}
fetchQueryOptions={fetchQueryOptions}
fetchQuery={source.fetchQuery}
fetchQueryOptions={source.fetchQueryOptions}
showFilter
/>
);
}
const StyledAvatar = styled(Avatar)`
margin: 2px;
`;
export default observer(UserFilter);
+177
View File
@@ -0,0 +1,177 @@
import { NewDocumentIcon } from "outline-icons";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import Icon from "@shared/components/Icon";
import { durationForDateFilter } from "@shared/helpers/FilterHelper";
import { StatusFilter } from "@shared/types";
import { Avatar, AvatarSize } from "~/components/Avatar";
import type { TFilterOption } from "~/components/FilterOptions";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import type { PaginatedItem } from "~/components/PaginatedList";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useCurrentUser from "~/hooks/useCurrentUser";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import type { FetchPageParams } from "~/stores/base/Store";
/** The options a filter picks from, and how to load more of them. */
export interface FilterOptionSource {
/** The options to pick from. */
options: TFilterOption[];
/** Loads more options from the server as the user types. */
fetchQuery?: (options: FetchPageParams) => Promise<PaginatedItem[]>;
/** Extra parameters to send with fetchQuery. */
fetchQueryOptions?: Record<string, string>;
/** Whether to show the filter input even for a short list. */
showFilter?: boolean;
}
const userFetchQueryOptions = { sort: "name", direction: "ASC" };
/**
* Options for each collection the user can see.
*
* @returns the collection options.
*/
export function useCollectionOptions(): FilterOptionSource {
const { collections } = useStores();
return useMemo(
() => ({
options: collections.orderedData.map((collection) => ({
key: collection.id,
label: collection.displayName,
icon: <CollectionIcon collection={collection} size={24} />,
})),
showFilter: true,
}),
[collections.orderedData]
);
}
/**
* Options for each user in the workspace, loaded from the server as needed.
* The current user is the first option.
*
* @returns the user options.
*/
export function useUserOptions(): FilterOptionSource {
const { users } = useStores();
const team = useCurrentTeam();
const currentUserId = useCurrentUser({ rejectOnEmpty: false })?.id;
const can = usePolicy(team);
const fetchQuery = can.listUsers ? users.fetchPage : undefined;
return useMemo(
() => ({
options: [
...users.all.filter((user) => user.id === currentUserId),
...users.all.filter((user) => user.id !== currentUserId),
].map((user) => ({
key: user.id,
label: user.name,
icon: <StyledAvatar model={user} size={AvatarSize.Small} />,
})),
fetchQuery,
fetchQueryOptions: userFetchQueryOptions,
showFilter: true,
}),
[users.all, currentUserId, fetchQuery]
);
}
/**
* Options for each template, loaded from the server as needed.
*
* @returns the template options.
*/
export function useTemplateOptions(): FilterOptionSource {
const { templates } = useStores();
return useMemo(
() => ({
options: templates.all.map((template) => ({
key: template.id,
label: template.displayTitle,
icon: template.icon ? (
<Icon
value={template.icon}
initial={template.initial}
color={template.color ?? undefined}
/>
) : (
<NewDocumentIcon />
),
})),
fetchQuery: templates.fetchPage,
showFilter: true,
}),
[templates.all, templates.fetchPage]
);
}
/**
* Options for a relative date range, from the past day to the past year.
*
* @returns the date options.
*/
export function useDateOptions(): FilterOptionSource {
const { t } = useTranslation();
return useMemo(
() => ({
options: [
{ key: "day", label: t("Past day") },
{ key: "week", label: t("Past week") },
{ key: "month", label: t("Past month") },
{ key: "year", label: t("Past year") },
],
}),
[t]
);
}
/**
* Options for a relative date range, keyed by the ISO 8601 duration that the
* API accepts as a lower bound.
*
* @returns the relative date options.
*/
export function useRelativeDateOptions(): FilterOptionSource {
const source = useDateOptions();
return useMemo(
() => ({
options: source.options.map((option) => ({
...option,
key: durationForDateFilter(option.key) ?? option.key,
})),
}),
[source.options]
);
}
/**
* Options for the status of a document.
*
* @returns the status options.
*/
export function useStatusOptions(): FilterOptionSource {
const { t } = useTranslation();
return useMemo(
() => ({
options: [
{ key: StatusFilter.Published, label: t("Published") },
{ key: StatusFilter.Archived, label: t("Archived") },
{ key: StatusFilter.Draft, label: t("Drafts") },
],
}),
[t]
);
}
const StyledAvatar = styled(Avatar)`
margin: 2px;
`;
+387
View File
@@ -0,0 +1,387 @@
import { endOfDay, startOfDay } from "date-fns";
import i18next from "i18next";
import { StatusFilter } from "@shared/types";
import type { SearchFilter, SelectSearchFilter } from "./searchFilters";
import {
createSearchFilters,
formatDateRange,
getApiFilter,
getDateRange,
getDateRangeParamChanges,
getFilterConditions,
getFilterParamChanges,
getFilterValues,
isFilterSet,
parseKey,
} from "./searchFilters";
const filters = createSearchFilters(i18next.t);
const collectionA = "9f1b8c2e-3a4d-4e5f-8a6b-7c8d9e0f1a2b";
const collectionB = "1a2b3c4d-5e6f-4a8b-9c0d-1e2f3a4b5c6d";
function getFilter(id: string): SearchFilter {
const filter = filters.find((item) => item.id === id);
if (!filter) {
throw new Error(`Missing filter ${id}`);
}
return filter;
}
function getSelectFilter(id: string): SelectSearchFilter {
const filter = getFilter(id);
if (filter.type !== "select") {
throw new Error(`Filter ${id} is not a select filter`);
}
return filter;
}
function params(search: string) {
return new URLSearchParams(search);
}
describe("searchFilters", () => {
it("has a unique id for each filter", () => {
const ids = filters.map((filter) => filter.id);
expect(new Set(ids).size).toBe(ids.length);
});
it("offers every filter without a query", () => {
const available = filters.filter(
(filter) => filter.isAvailable?.({}) ?? true
);
expect(available).toEqual(filters);
});
describe("parseKey", () => {
it("reads a bare key as eq", () => {
expect(parseKey("collectionId")).toEqual({
field: "collectionId",
operator: "eq",
});
});
it("splits the field and operator", () => {
expect(parseKey("updatedAt.gte")).toEqual({
field: "updatedAt",
operator: "gte",
});
});
it("rejects an unknown operator", () => {
expect(parseKey("updatedAt.after")).toBeUndefined();
});
});
describe("getFilterConditions", () => {
it("reads bare, eq and in keys", () => {
const collection = getSelectFilter("collectionId");
expect(
getFilterConditions(collection, params(`collectionId=${collectionA}`))
).toEqual({ eq: [collectionA] });
expect(
getFilterConditions(
collection,
params(`collectionId.in=${collectionA},${collectionB}`)
)
).toEqual({ in: [collectionA, collectionB] });
});
it("drops operators the filter does not allow", () => {
expect(
getFilterConditions(
getSelectFilter("userId"),
params(`userId.neq=${collectionA}`)
)
).toEqual({});
});
it("drops values that are not valid", () => {
expect(
getFilterConditions(
getSelectFilter("collectionId"),
params("collectionId=not-a-uuid")
)
).toEqual({});
expect(
getFilterConditions(
getSelectFilter("updatedAt"),
params("updatedAt.gte=yesterday")
)
).toEqual({});
});
it("reads date ranges with durations and dates", () => {
expect(
getFilterConditions(
getSelectFilter("createdAt"),
params("createdAt.gte=2026-03-01&createdAt.lte=2026-04-15")
)
).toEqual({ gte: ["2026-03-01"], lte: ["2026-04-15"] });
});
it("reads legacy parameters", () => {
expect(
getFilterConditions(
getSelectFilter("updatedAt"),
params("dateFilter=week")
)
).toEqual({ gte: ["-P1W"] });
expect(
getFilterConditions(
getSelectFilter("status"),
params("statusFilter=archived&statusFilter=draft")
)
).toEqual({ in: [StatusFilter.Archived, StatusFilter.Draft] });
expect(
getFilterConditions(
getSelectFilter("status"),
params("statusFilter=archived,draft")
)
).toEqual({ in: [StatusFilter.Archived, StatusFilter.Draft] });
});
it("prefers the current format over a legacy parameter", () => {
expect(
getFilterConditions(
getSelectFilter("updatedAt"),
params("updatedAt.gte=-P1D&dateFilter=week")
)
).toEqual({ gte: ["-P1D"] });
});
});
describe("getFilterValues", () => {
it("falls back to default values", () => {
const status = getFilter("status");
expect(isFilterSet(status, params(""))).toBe(false);
expect(getFilterValues(status, params(""))).toEqual([
StatusFilter.Published,
StatusFilter.Draft,
]);
});
it("reads toggle filters, including the legacy parameter", () => {
const title = getFilter("titleOnly");
expect(isFilterSet(title, params("titleOnly=true"))).toBe(true);
expect(isFilterSet(title, params("titleFilter=true"))).toBe(true);
expect(isFilterSet(title, params("titleOnly=false"))).toBe(false);
});
});
describe("getApiFilter", () => {
it("matches one or many values", () => {
const createdBy = getFilter("createdById");
expect(getApiFilter(createdBy, params(""))).toBeUndefined();
expect(
getApiFilter(createdBy, params(`createdById.eq=${collectionA}`))
).toEqual({ field: "createdById", operator: "eq", value: collectionA });
expect(
getApiFilter(
createdBy,
params(`createdById.in=${collectionA},${collectionB}`)
)
).toEqual({
field: "createdById",
operator: "in",
value: [collectionA, collectionB],
});
});
it("supports exclusion", () => {
expect(
getApiFilter(
getFilter("collectionId"),
params(`collectionId.neq=${collectionA}`)
)
).toEqual({ field: "collectionId", operator: "neq", value: collectionA });
});
it("sends a date range as whole local days, combined with AND", () => {
expect(
getApiFilter(
getFilter("publishedAt"),
params("publishedAt.gte=2026-03-01&publishedAt.lte=2026-04-15")
)
).toEqual({
operator: "AND",
filters: [
{
field: "publishedAt",
operator: "lte",
value: endOfDay(new Date(2026, 3, 15)).toISOString(),
},
{
field: "publishedAt",
operator: "gte",
value: startOfDay(new Date(2026, 2, 1)).toISOString(),
},
],
});
});
it("sends durations and full timestamps without change", () => {
expect(
getApiFilter(getFilter("updatedAt"), params("updatedAt.gte=-P1W"))
).toEqual({ field: "updatedAt", operator: "gte", value: "-P1W" });
expect(
getApiFilter(
getFilter("updatedAt"),
params("updatedAt.lt=2026-03-01T10:00:00Z")
)
).toEqual({
field: "updatedAt",
operator: "lt",
value: "2026-03-01T10:00:00Z",
});
});
it("combines default statuses with OR", () => {
expect(getApiFilter(getFilter("status"), params(""))).toEqual({
operator: "OR",
filters: [
{
operator: "AND",
filters: [
{ field: "archivedAt", operator: "isNull" },
{ field: "publishedAt", operator: "isNotNull" },
],
},
{
operator: "AND",
filters: [
{ field: "archivedAt", operator: "isNull" },
{ field: "publishedAt", operator: "isNull" },
],
},
],
});
expect(
getApiFilter(getFilter("status"), params("status.eq=archived"))
).toEqual({ field: "archivedAt", operator: "isNotNull" });
});
it("adds no condition for toggle filters", () => {
expect(
getApiFilter(getFilter("titleOnly"), params("titleOnly=true"))
).toBeUndefined();
});
});
describe("getFilterParamChanges", () => {
it("writes one value as eq and many as in", () => {
const collection = getFilter("collectionId");
expect(
getFilterParamChanges(collection, [collectionA], params(""))
).toEqual({ "collectionId.eq": collectionA });
expect(
getFilterParamChanges(
collection,
[collectionA, collectionB],
params(`collectionId.eq=${collectionA}`)
)
).toEqual({
"collectionId.eq": undefined,
"collectionId.in": [collectionA, collectionB],
});
});
it("writes dates as a lower bound and clears the legacy parameter", () => {
expect(
getFilterParamChanges(
getFilter("updatedAt"),
["-P1M"],
params("dateFilter=week")
)
).toEqual({ dateFilter: undefined, "updatedAt.gte": "-P1M" });
});
it("clears every key of a removed filter", () => {
expect(
getFilterParamChanges(
getFilter("createdAt"),
undefined,
params("createdAt.gte=2026-03-01&createdAt.lte=2026-04-15&q=x")
)
).toEqual({ "createdAt.gte": undefined, "createdAt.lte": undefined });
});
it("round trips through the URL", () => {
const status = getFilter("status");
const changes = getFilterParamChanges(
status,
[StatusFilter.Archived, StatusFilter.Draft],
params("")
);
const next = new URLSearchParams();
for (const [key, value] of Object.entries(changes)) {
if (value !== undefined) {
next.set(key, Array.isArray(value) ? value.join(",") : value);
}
}
expect(getFilterValues(status, next)).toEqual([
StatusFilter.Archived,
StatusFilter.Draft,
]);
});
it("writes toggles and clears the legacy parameter", () => {
expect(
getFilterParamChanges(
getFilter("titleOnly"),
["true"],
params("titleFilter=true")
)
).toEqual({ titleFilter: undefined, titleOnly: "true" });
});
});
describe("date ranges", () => {
it("reads a custom range and ignores presets", () => {
const updated = getFilter("updatedAt");
expect(
getDateRange(
updated,
params("updatedAt.gte=2026-03-01&updatedAt.lte=2026-04-15")
)
).toEqual({ from: "2026-03-01", to: "2026-04-15" });
expect(
getDateRange(updated, params("updatedAt.gte=-P1W"))
).toBeUndefined();
expect(
getDateRange(getFilter("collectionId"), params(""))
).toBeUndefined();
});
it("replaces a preset with a range", () => {
expect(
getDateRangeParamChanges(
getFilter("updatedAt"),
{ from: "2026-03-01", to: "2026-04-15" },
params("updatedAt.gte=-P1W&dateFilter=week")
)
).toEqual({
dateFilter: undefined,
"updatedAt.gte": "2026-03-01",
"updatedAt.lte": "2026-04-15",
});
});
it("labels ranges with one bound", () => {
expect(formatDateRange({ from: "2026-03-01" }, i18next.t)).toMatch(
/^From /
);
expect(formatDateRange({ to: "2026-03-01" }, i18next.t)).toMatch(
/^Until /
);
expect(formatDateRange({ from: "bad" }, i18next.t)).toBeUndefined();
});
});
});
+635
View File
@@ -0,0 +1,635 @@
import {
CalendarIcon,
CollectionIcon,
DoneIcon,
EditIcon,
NewDocumentIcon,
CaseSensitiveIcon,
UserIcon,
} from "outline-icons";
import { endOfDay, startOfDay } from "date-fns";
import { uniq } from "es-toolkit/compat";
import { useMemo } from "react";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import type { Filter } from "@shared/helpers/FilterHelper";
import {
ComparisonOperator,
durationForDateFilter,
RANGE_OPERATORS,
scalarMatchesKind,
statusToFilter,
} from "@shared/helpers/FilterHelper";
import { StatusFilter } from "@shared/types";
import {
dateRangeToReadable,
isISODate,
parseISODate,
} from "@shared/utils/date";
import type { locales } from "@shared/utils/date";
import type Document from "~/models/Document";
import { isTruthyQueryValue } from "~/utils/urls";
import type { FilterOptionSource } from "./filterOptions";
import {
useCollectionOptions,
useRelativeDateOptions,
useStatusOptions,
useTemplateOptions,
useUserOptions,
} from "./filterOptions";
/** The state of the search page that controls which filters can show. */
interface SearchFilterContext {
/** The document that the search is limited to, if there is one. */
document?: Document;
}
/** The values of a filter for each operator, as read from the URL. */
export type FilterConditions = Partial<Record<ComparisonOperator, string[]>>;
/** A URL parameter from before the `<field>.<operator>` format. */
interface LegacyParam {
/** The name of the URL parameter. */
param: string;
/** The operator that the parameter stands for. */
operator: ComparisonOperator;
/** Converts a legacy value to the current format, undefined drops it. */
map?: (value: string) => string | undefined;
}
interface BaseSearchFilter {
/**
* Unique identifier and the field name in the URL, which is
* `<id>.<operator>=<value>`. A bare `<id>=<value>` is read as `eq`.
*/
id: string;
/** Name of the filter, shown on the chip and in the add menu. */
label: string;
/** Icon shown in the add menu and on the chip when there is no value icon. */
icon: React.ReactNode;
/** Pinned filters always show, others are added from the "More" menu. */
pinned?: boolean;
/** Whether the filter can be used in the given context, defaults to always. */
isAvailable?: (context: SearchFilterContext) => boolean;
}
/** A filter where the user picks one or more values from a list. */
export interface SelectSearchFilter extends BaseSearchFilter {
type: "select";
/** Operators that the URL may use for this filter, others are dropped. */
operators: readonly ComparisonOperator[];
/** Whether a URL value is valid for the operator, others are dropped. */
isValidValue: (value: string, operator: ComparisonOperator) => boolean;
/**
* How a selection is written to the URL: "match" writes one value as `eq`
* and many as `in`, "date" writes a preset as a `gte` lower bound and a
* custom range as `gte` and `lte` dates.
*/
selection: "match" | "date";
/** Whether more than one value can be selected. */
multiple?: boolean;
/** Values that apply when the URL does not include the filter. */
defaultValues?: string[];
/** Hook that returns the options to pick from. */
useOptions: () => FilterOptionSource;
/** A URL parameter from before the current format, still read. */
legacy?: LegacyParam;
/** Builds the API expression, defaults to one condition per operator. */
toFilter?: (conditions: FilterConditions) => Filter | undefined;
}
/** A filter that is either on or off, and is not an API condition. */
export interface ToggleSearchFilter extends BaseSearchFilter {
type: "toggle";
/** A URL parameter from before the current format, still read. */
legacyParam?: string;
}
/** A filter that can be applied on the search page. */
export type SearchFilter = SelectSearchFilter | ToggleSearchFilter;
/** A custom date range, as ISO dates (yyyy-MM-dd) in local time. */
export interface DateRange {
/** The first day of the range. */
from?: string;
/** The last day of the range. */
to?: string;
}
/** The URL value that turns a toggle filter on. */
export const TOGGLE_ON = "true";
/** The option key that opens the custom date range picker. */
export const CUSTOM_RANGE = "custom";
/**
* Hook that returns every filter that can be applied on the search page.
*
* @returns the search filters.
*/
export function useSearchFilters(): SearchFilter[] {
const { t } = useTranslation();
return useMemo(() => createSearchFilters(t), [t]);
}
/**
* Create every filter that can be applied on the search page, in display
* order. To add a filter, add a definition to this list.
*
* @param t the translation function.
* @returns the search filters.
*/
export function createSearchFilters(t: TFunction): SearchFilter[] {
return [
{
type: "select",
id: "collectionId",
label: t("Collection"),
icon: <CollectionIcon />,
pinned: true,
isAvailable: ({ document }) => !document,
...matchSelection,
useOptions: useCollectionOptions,
},
{
type: "select",
id: "userId",
label: t("Edited by"),
icon: <UserIcon />,
pinned: true,
...matchSelection,
// The API only supports membership checks for these fields.
operators: ["eq", "in"],
useOptions: useUserOptions,
},
{
type: "select",
id: "status",
label: t("Status"),
icon: <DoneIcon />,
pinned: true,
operators: ["eq", "in"],
isValidValue: isStatus,
selection: "match",
multiple: true,
defaultValues: [StatusFilter.Published, StatusFilter.Draft],
useOptions: useStatusOptions,
legacy: { param: "statusFilter", operator: "in" },
toFilter: (conditions) =>
statusesToFilter([...(conditions.eq ?? []), ...(conditions.in ?? [])]),
},
{
type: "select",
id: "updatedAt",
label: t("Updated"),
icon: <CalendarIcon />,
...dateSelection,
legacy: {
param: "dateFilter",
operator: "gte",
map: durationForDateFilter,
},
},
{
type: "select",
id: "createdById",
label: t("Created by"),
icon: <EditIcon />,
...matchSelection,
// The API only supports membership checks for these fields.
operators: ["eq", "in"],
useOptions: useUserOptions,
},
{
type: "select",
id: "createdAt",
label: t("Created"),
icon: <CalendarIcon />,
...dateSelection,
},
{
type: "select",
id: "publishedAt",
label: t("Published"),
icon: <CalendarIcon />,
...dateSelection,
},
{
type: "select",
id: "templateId",
label: t("Template"),
icon: <NewDocumentIcon />,
...matchSelection,
useOptions: useTemplateOptions,
},
{
type: "toggle",
id: "titleOnly",
label: t("Title only"),
icon: <CaseSensitiveIcon />,
legacyParam: "titleFilter",
},
];
}
/**
* Read the conditions of a filter that the URL sets, from both the
* `<field>.<operator>` format and any legacy parameter. Keys with an unknown
* operator, an operator the filter does not allow, or a value that is not
* valid are dropped.
*
* @param filter the filter to read.
* @param params the URL query parameters.
* @returns the conditions, empty when the URL does not set the filter.
*/
export function getFilterConditions(
filter: SelectSearchFilter,
params: URLSearchParams
): FilterConditions {
const conditions: FilterConditions = {};
const add = (operator: ComparisonOperator, raw: string) => {
if (!filter.operators.includes(operator)) {
return;
}
const values = splitValues(operator, raw).filter((value) =>
filter.isValidValue(value, operator)
);
if (values.length > 0 || isNullOperator(operator)) {
conditions[operator] = [...(conditions[operator] ?? []), ...values];
}
};
for (const [key, raw] of params.entries()) {
const parsed = parseKey(key);
if (parsed?.field === filter.id) {
add(parsed.operator, raw);
}
}
const { legacy } = filter;
if (legacy && Object.keys(conditions).length === 0) {
for (const raw of params.getAll(legacy.param)) {
for (const value of raw.split(",").filter(Boolean)) {
const mapped = legacy.map ? legacy.map(value) : value;
if (mapped) {
add(legacy.operator, mapped);
}
}
}
}
return conditions;
}
/** The state of one filter, read from the URL in one pass. */
export interface FilterState {
/** Whether the URL sets the filter, as opposed to it using its defaults. */
isSet: boolean;
/** The selected option keys, including defaults. */
values: string[];
/** The API expression, undefined when the filter adds no condition. */
apiFilter?: Filter;
/** A custom date range, for date filters only. */
range?: DateRange;
}
/**
* Read the full state of a filter from the URL, parsing it once.
*
* @param filter the filter to read.
* @param params the URL query parameters.
* @returns the state of the filter.
*/
export function readFilter(
filter: SearchFilter,
params: URLSearchParams
): FilterState {
if (filter.type === "toggle") {
const isSet =
isTruthyQueryValue(params.get(filter.id)) ||
(!!filter.legacyParam &&
isTruthyQueryValue(params.get(filter.legacyParam)));
return { isSet, values: isSet ? [TOGGLE_ON] : [] };
}
const set = getFilterConditions(filter, params);
const isSet = Object.keys(set).length > 0;
const isDate = filter.selection === "date";
const selected = isDate
? (set.gte ?? [])
: uniq([...(set.eq ?? []), ...(set.in ?? [])]);
const conditions =
isSet || !filter.defaultValues ? set : { in: filter.defaultValues };
const apiFilter = filter.toFilter
? filter.toFilter(conditions)
: conditionsToFilter(
filter.id,
isDate ? toLocalDayBounds(conditions) : conditions
);
const from = set.gte?.find(isISODate);
const to = set.lte?.find(isISODate);
return {
isSet,
values: selected.length > 0 ? selected : (filter.defaultValues ?? []),
apiFilter,
range: isDate && (from || to) ? { from, to } : undefined,
};
}
/**
* Whether the URL sets a value for the filter, as opposed to the filter using
* its default values.
*
* @param filter the filter to check.
* @param params the URL query parameters.
* @returns true if the URL sets the filter.
*/
export function isFilterSet(
filter: SearchFilter,
params: URLSearchParams
): boolean {
return readFilter(filter, params).isSet;
}
/**
* Read the selected values of a filter from the URL, falling back to its
* defaults. These are the option keys that the chip shows as selected.
*
* @param filter the filter to read.
* @param params the URL query parameters.
* @returns the selected values.
*/
export function getFilterValues(
filter: SearchFilter,
params: URLSearchParams
): string[] {
return readFilter(filter, params).values;
}
/**
* Convert the state of a filter in the URL to an API filter expression.
*
* @param filter the filter to convert.
* @param params the URL query parameters.
* @returns the expression, or undefined when the filter adds no condition.
*/
export function getApiFilter(
filter: SearchFilter,
params: URLSearchParams
): Filter | undefined {
return readFilter(filter, params).apiFilter;
}
/**
* Read a custom date range of a date filter from the URL.
*
* @param filter the filter to read.
* @param params the URL query parameters.
* @returns the range as ISO dates, or undefined when the filter has none.
*/
export function getDateRange(
filter: SearchFilter,
params: URLSearchParams
): DateRange | undefined {
return readFilter(filter, params).range;
}
/**
* Build the URL parameter changes that replace the state of a filter. Every
* key the filter uses now is cleared, including legacy parameters.
*
* @param filter the filter to change.
* @param values the new selected values, or undefined to remove the filter.
* @param params the current URL query parameters.
* @returns a map of parameter name to new value, undefined removes the key
* and an array is a comma separated list.
*/
export function getFilterParamChanges(
filter: SearchFilter,
values: string[] | undefined,
params: URLSearchParams
): Record<string, string | string[] | undefined> {
if (filter.type === "toggle") {
const changes = clearFilterParams(filter, params);
changes[filter.id] = values?.length ? TOGGLE_ON : undefined;
return changes;
}
if (!values?.length) {
return clearFilterParams(filter, params);
}
if (filter.selection === "date") {
return getConditionParamChanges(filter, { gte: [values[0]] }, params);
}
return getConditionParamChanges(
filter,
values.length === 1 ? { eq: values } : { in: values },
params
);
}
/**
* Format a custom date range as a short label, for example "Mar 1 – 15, 2026".
* A range with one bound is labelled "From …" or "Until …".
*
* @param range the range as ISO dates.
* @param t the translation function.
* @param language the user's language preference.
* @returns the label, or undefined when the range has no valid date.
*/
export function formatDateRange(
range: DateRange,
t: TFunction,
language?: keyof typeof locales | null
): string | undefined {
const from = range.from ? parseISODate(range.from) : null;
const to = range.to ? parseISODate(range.to) : null;
if (from && to) {
return dateRangeToReadable(from, to, language);
}
if (from) {
return t("From {{ date }}", {
date: dateRangeToReadable(from, null, language),
});
}
if (to) {
return t("Until {{ date }}", {
date: dateRangeToReadable(null, to, language),
});
}
return undefined;
}
/**
* Build the URL parameter changes that set a custom date range on a date
* filter, replacing any value it has now.
*
* @param filter the date filter to change.
* @param range the range as ISO dates.
* @param params the current URL query parameters.
* @returns a map of parameter name to new value, undefined removes the key.
*/
export function getDateRangeParamChanges(
filter: SearchFilter,
range: Required<DateRange>,
params: URLSearchParams
): Record<string, string | string[] | undefined> {
return getConditionParamChanges(
filter,
{ gte: [range.from], lte: [range.to] },
params
);
}
/**
* Split a URL key in the `<field>.<operator>` format. A key without an
* operator is read as `eq`.
*
* @param key the URL parameter name.
* @returns the field and operator, or undefined if the operator is unknown.
*/
export function parseKey(
key: string
): { field: string; operator: ComparisonOperator } | undefined {
const dot = key.lastIndexOf(".");
if (dot === -1) {
return { field: key, operator: "eq" };
}
const operator = ComparisonOperator.safeParse(key.slice(dot + 1));
return operator.success
? { field: key.slice(0, dot), operator: operator.data }
: undefined;
}
const matchSelection = {
operators: ["eq", "neq", "in", "notIn"],
isValidValue: (value: string, operator: ComparisonOperator) =>
scalarMatchesKind("uuid", value, operator),
selection: "match",
} as const;
const dateSelection = {
operators: [...RANGE_OPERATORS],
isValidValue: (value: string, operator: ComparisonOperator) =>
scalarMatchesKind("date", value, operator),
selection: "date",
useOptions: useRelativeDateOptions,
} as const;
function clearFilterParams(
filter: SearchFilter,
params: URLSearchParams
): Record<string, string | string[] | undefined> {
const changes: Record<string, string | string[] | undefined> = {};
for (const key of params.keys()) {
if (parseKey(key)?.field === filter.id) {
changes[key] = undefined;
}
}
const legacyParam =
filter.type === "toggle" ? filter.legacyParam : filter.legacy?.param;
if (legacyParam) {
changes[legacyParam] = undefined;
}
return changes;
}
function getConditionParamChanges(
filter: SearchFilter,
conditions: FilterConditions,
params: URLSearchParams
): Record<string, string | string[] | undefined> {
const changes = clearFilterParams(filter, params);
for (const operator of ComparisonOperator.options) {
const values = conditions[operator];
if (values?.length) {
changes[`${filter.id}.${operator}`] = isListOperator(operator)
? values
: values[0];
}
}
return changes;
}
/**
* Convert date-only bounds to the start or end of that day in local time, so
* that a range includes the whole of its first and last day.
*/
function toLocalDayBounds(conditions: FilterConditions): FilterConditions {
const result: FilterConditions = { ...conditions };
for (const operator of RANGE_OPERATORS) {
result[operator] = conditions[operator]?.map((value) => {
const date = isISODate(value) ? parseISODate(value) : null;
if (!date) {
return value;
}
const bound =
operator === "gt" || operator === "gte"
? startOfDay(date)
: endOfDay(date);
return bound.toISOString();
});
}
return result;
}
function isNullOperator(operator: ComparisonOperator) {
return operator === "isNull" || operator === "isNotNull";
}
function isListOperator(operator: ComparisonOperator) {
return operator === "in" || operator === "notIn";
}
function splitValues(operator: ComparisonOperator, raw: string): string[] {
if (isNullOperator(operator)) {
return [];
}
return isListOperator(operator) ? raw.split(",").filter(Boolean) : [raw];
}
function conditionsToFilter(
field: string,
conditions: FilterConditions
): Filter | undefined {
const leaves = ComparisonOperator.options.flatMap((operator): Filter[] => {
const values = conditions[operator];
if (!values) {
return [];
}
if (isNullOperator(operator)) {
return [{ field, operator }];
}
if (isListOperator(operator)) {
return [{ field, operator, value: values }];
}
if (values.length > 1 && (operator === "eq" || operator === "neq")) {
return [
{
field,
operator: operator === "eq" ? "in" : "notIn",
value: values,
},
];
}
return values.map((value) => ({ field, operator, value }));
});
if (leaves.length === 0) {
return undefined;
}
return leaves.length === 1 ? leaves[0] : { operator: "AND", filters: leaves };
}
function statusesToFilter(values: string[]): Filter | undefined {
const shapes = uniq(values).filter(isStatus).map(statusToFilter);
if (shapes.length === 0) {
return undefined;
}
return shapes.length === 1 ? shapes[0] : { operator: "OR", filters: shapes };
}
function isStatus(value: string): value is StatusFilter {
return Object.values<string>(StatusFilter).includes(value);
}
+89 -89
View File
@@ -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";
@@ -24,8 +25,7 @@ function AI() {
const handleMCPChange = React.useCallback(
async (checked: boolean) => {
team.setPreference(TeamPreference.MCP, checked);
await team.save();
await team.savePreference(TeamPreference.MCP, checked);
toast.success(t("Settings saved"));
},
[team, t]
@@ -56,102 +56,102 @@ function AI() {
<Trans>Control how AI features are used in the workspace.</Trans>
</Text>
<Heading as="h2">{t("MCP server")}</Heading>
<SettingRow
name={TeamPreference.MCP}
label={t("Enabled")}
description={
<>
<Text type="secondary" as="p">
{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."
)}
</Text>
{team.getPreference(TeamPreference.MCP) && (
<>
<Text
type="secondary"
as="p"
style={{ marginTop: 8, marginBottom: 4 }}
>
<Trans
defaults="Use this URL in your MCP client. See <a>the setup guide</a> for more details."
components={{
a: (
<Text
as="a"
weight="bold"
href="https://docs.getoutline.com/s/guide/doc/mcp-6j9jtENNKL"
target="_blank"
rel="noopener noreferrer"
/>
),
}}
/>
</Text>
<Input readOnly value={mcpEndpoint}>
<Tooltip content={t("Copy URL")}>
<CopyToClipboard text={mcpEndpoint} onCopy={handleCopied}>
<NudeButton type="button" style={{ marginRight: 3 }}>
<CopyIcon color={theme.placeholder} size={18} />
</NudeButton>
</CopyToClipboard>
</Tooltip>
</Input>
</>
)}
</>
}
>
<Switch
id={TeamPreference.MCP}
name={TeamPreference.MCP}
aria-label={t("MCP server")}
checked={team.getPreference(TeamPreference.MCP)}
onChange={handleMCPChange}
/>
</SettingRow>
{team.getPreference(TeamPreference.MCP) && (
<SettingsSection title={t("MCP server")}>
<SettingRow
name="guidanceMCP"
label={t("Custom instructions")}
border={false}
name={TeamPreference.MCP}
label={t("Enabled")}
description={
<>
<div style={{ marginBottom: 8 }}>
<Text type="secondary" as="p">
{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."
)}
</div>
<Input
id="guidanceMCP"
type="textarea"
autoSize
minHeight="6lh"
maxHeight="20lh"
value={team.guidanceMCP ?? ""}
maxLength={TeamValidation.maxGuidanceMCPLength}
warningLimit={TeamValidation.warnGuidanceMCPLength}
onChange={handleGuidanceMCPChange}
onBlur={handleGuidanceMCPBlur}
/>
</Text>
{team.getPreference(TeamPreference.MCP) && (
<>
<Text
type="secondary"
as="p"
style={{ marginTop: 8, marginBottom: 4 }}
>
<Trans
defaults="Use this URL in your MCP client. See <a>the setup guide</a> for more details."
components={{
a: (
<Text
as="a"
weight="bold"
href="https://docs.getoutline.com/s/guide/doc/mcp-6j9jtENNKL"
target="_blank"
rel="noopener noreferrer"
/>
),
}}
/>
</Text>
<Input readOnly value={mcpEndpoint}>
<Tooltip content={t("Copy URL")}>
<CopyToClipboard text={mcpEndpoint} onCopy={handleCopied}>
<NudeButton type="button" style={{ marginRight: 3 }}>
<CopyIcon color={theme.placeholder} size={18} />
</NudeButton>
</CopyToClipboard>
</Tooltip>
</Input>
</>
)}
</>
}
/>
)}
>
<Switch
id={TeamPreference.MCP}
name={TeamPreference.MCP}
aria-label={t("MCP server")}
checked={team.getPreference(TeamPreference.MCP)}
onChange={handleMCPChange}
/>
</SettingRow>
<Heading as="h2">{t("AI answers")}</Heading>
<SettingRow
name="answers"
label={t("Enabled")}
description={t(
"Show AI-generated answers to questions in search, based on content in your workspace. Requires a paid license."
{team.getPreference(TeamPreference.MCP) && (
<SettingRow
name="guidanceMCP"
label={t("Custom instructions")}
description={
<>
<div style={{ marginBottom: 8 }}>
{t(
"Optional instructions that are sent to connected AI apps, for example how your workspace is organized or where to find important information."
)}
</div>
<Input
id="guidanceMCP"
type="textarea"
autoSize
minHeight="6lh"
maxHeight="20lh"
value={team.guidanceMCP ?? ""}
maxLength={TeamValidation.maxGuidanceMCPLength}
warningLimit={TeamValidation.warnGuidanceMCPLength}
onChange={handleGuidanceMCPChange}
onBlur={handleGuidanceMCPBlur}
/>
</>
}
/>
)}
border={false}
>
<Switch disabled />
</SettingRow>
</SettingsSection>
<SettingsSection title={t("AI answers")}>
<SettingRow
name="answers"
label={t("Enabled")}
description={t(
"Show AI-generated answers to questions in search, based on content in your workspace. Requires a paid license."
)}
>
<Switch disabled />
</SettingRow>
</SettingsSection>
</Scene>
);
}
+170 -169
View File
@@ -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() {
</Trans>
</Text>
<Heading as="h2">{t("Sign in")}</Heading>
<SettingsSection title={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 (
<React.Fragment key={provider.name}>
<SettingRow
label={
<Flex gap={8} align="center">
<PluginIcon id={provider.name} /> {provider.displayName}
</Flex>
}
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 (
<React.Fragment key={provider.name}>
<SettingRow
label={
<Flex gap={8} align="center">
<PluginIcon id={provider.name} /> {provider.displayName}
</Flex>
}
name={provider.name}
description={
provider.isConnected
? t("Allow members to sign in with {{ authProvider }}", {
authProvider: provider.displayName,
}
)
}
border={!showGroupSync}
>
<Flex align="center" gap={12}>
{provider.isConnected ? (
<VStack align="start">
})
: t(
"Connect {{ authProvider }} to allow members to sign in",
{
authProvider: provider.displayName,
}
)
}
border={!showGroupSync}
>
<Flex align="center" gap={12}>
{provider.isConnected ? (
<VStack align="start">
<Button
icon={
provider.isEnabled ? (
<ConnectedIcon />
) : (
<ConnectedIcon color={theme.textSecondary} />
)
}
onClick={() =>
!provider.isEnabled
? handleToggleProvider(provider, true)
: handleRemoveProvider(provider)
}
neutral
>
{provider.isEnabled ? t("Connected") : t("Disabled")}
</Button>
<Text type="tertiary" size="small">
{provider.providerId}
</Text>
</VStack>
) : (
<Button
icon={
provider.isEnabled ? (
<ConnectedIcon />
) : (
<ConnectedIcon color={theme.textSecondary} />
)
}
onClick={() =>
!provider.isEnabled
? handleToggleProvider(provider, true)
: handleRemoveProvider(provider)
}
onClick={() => handleConnectProvider(provider.name)}
neutral
>
{provider.isEnabled ? t("Connected") : t("Disabled")}
{t("Connect")}
</Button>
<Text type="tertiary" size="small">
{provider.providerId}
</Text>
</VStack>
) : (
<Button
onClick={() => handleConnectProvider(provider.name)}
neutral
>
{t("Connect")}
</Button>
)}
</Flex>
</SettingRow>
{showGroupSync && (
<SettingRow
label={t("Group sync")}
name={`groupSync-${provider.name}`}
description={
provider.groupSyncRequiresSetup &&
!provider.settings?.groupSyncEnabled
? t(
"An administrator of {{ authProvider }} must approve group access for this workspace",
{ authProvider: provider.displayName }
)
: t(
"Sync group memberships from {{ authProvider }} on each sign-in",
{ authProvider: provider.displayName }
)
}
border={
!(
provider.settings?.groupSyncEnabled &&
provider.groupSyncUsesClaim
)
}
>
{provider.groupSyncRequiresSetup &&
!provider.settings?.groupSyncEnabled ? (
<Button
onClick={() => handleToggleGroupSync(provider, true)}
neutral
>
{t("Set up group sync")}
</Button>
) : (
<Switch
id={`groupSync-${provider.name}`}
checked={provider.settings?.groupSyncEnabled ?? false}
onChange={(checked) =>
handleToggleGroupSync(provider, checked)
}
/>
)}
</SettingRow>
)}
{showGroupSync &&
provider.groupSyncUsesClaim &&
provider.settings?.groupSyncEnabled && (
<SettingRow
label={t("Group claim")}
name={`groupClaim-${provider.name}`}
description={t(
"The claim in the provider response that contains group names (e.g. groups, roles)"
)}
border={false}
</Flex>
</SettingRow>
{showGroupSync && (
<SettingRow
label={t("Group sync")}
name={`groupSync-${provider.name}`}
description={
provider.groupSyncRequiresSetup &&
!provider.settings?.groupSyncEnabled
? t(
"An administrator of {{ authProvider }} must approve group access for this workspace",
{ authProvider: provider.displayName }
)
: t(
"Sync group memberships from {{ authProvider }} on each sign-in",
{ authProvider: provider.displayName }
)
}
border={
!(
provider.settings?.groupSyncEnabled &&
provider.groupSyncUsesClaim
)
}
>
<Input
id={`groupClaim-${provider.name}`}
defaultValue={provider.settings?.groupClaim ?? "groups"}
placeholder="groups"
onBlur={(ev: React.FocusEvent<HTMLInputElement>) => {
const value = ev.target.value.trim();
if (value !== (provider.settings?.groupClaim ?? "")) {
void handleGroupClaimChange(provider, value);
{provider.groupSyncRequiresSetup &&
!provider.settings?.groupSyncEnabled ? (
<Button
onClick={() => handleToggleGroupSync(provider, true)}
neutral
>
{t("Set up group sync")}
</Button>
) : (
<Switch
id={`groupSync-${provider.name}`}
checked={provider.settings?.groupSyncEnabled ?? false}
onChange={(checked) =>
handleToggleGroupSync(provider, checked)
}
}}
/>
/>
)}
</SettingRow>
)}
</React.Fragment>
);
})}
<SettingRow
label={
<Flex gap={8} align="center">
<EmailIcon /> {t("Email")}
</Flex>
}
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}
>
<Switch
id="guestSignin"
checked={team.guestSignin}
onChange={handleGuestSigninChange}
disabled={!env.EMAIL_ENABLED}
/>
</SettingRow>
{showGroupSync &&
provider.groupSyncUsesClaim &&
provider.settings?.groupSyncEnabled && (
<SettingRow
label={t("Group claim")}
name={`groupClaim-${provider.name}`}
description={t(
"The claim in the provider response that contains group names (e.g. groups, roles)"
)}
border={false}
>
<Input
id={`groupClaim-${provider.name}`}
defaultValue={provider.settings?.groupClaim ?? "groups"}
placeholder="groups"
onBlur={(ev: React.FocusEvent<HTMLInputElement>) => {
const value = ev.target.value.trim();
if (value !== (provider.settings?.groupClaim ?? "")) {
void handleGroupClaimChange(provider, value);
}
}}
/>
</SettingRow>
)}
</React.Fragment>
);
})}
<SettingRow
label={
<Flex gap={8} align="center">
<EmailIcon /> {t("Email")}
</Flex>
}
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")
}
>
<Switch
id="guestSignin"
checked={team.guestSignin}
onChange={handleGuestSigninChange}
disabled={!env.EMAIL_ENABLED}
/>
</SettingRow>
<SettingRow
label={
<Flex gap={8} align="center">
<PadlockIcon /> {t("Passkeys")}
</Flex>
}
name="passkeysEnabled"
description={t("Allow members to sign in with a WebAuthn passkey")}
>
<Switch
id="passkeysEnabled"
checked={team.passkeysEnabled}
onChange={async (checked) => {
try {
await team.save({ passkeysEnabled: checked });
toast.success(t("Settings saved"));
} catch (err) {
toast.error(errToString(err));
}
}}
/>
</SettingRow>
<SettingRow
label={
<Flex gap={8} align="center">
<PadlockIcon /> {t("Passkeys")}
</Flex>
}
name="passkeysEnabled"
description={t("Allow members to sign in with a WebAuthn passkey")}
>
<Switch
id="passkeysEnabled"
checked={team.passkeysEnabled}
onChange={async (checked) => {
try {
await team.save({ passkeysEnabled: checked });
toast.success(t("Settings saved"));
} catch (err) {
toast.error(errToString(err));
}
}}
/>
</SettingRow>
</SettingsSection>
<Heading as="h2">{t("Restrictions")}</Heading>
<DomainManagement onSuccess={showSuccessMessage} />
<SettingsSection title={t("Restrictions")}>
<DomainManagement onSuccess={showSuccessMessage} />
</SettingsSection>
</Scene>
);
}
+336 -251
View File
@@ -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<Team, "name" | "description" | "subdomain" | "defaultCollectionId">
> & { 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<HTMLFormElement>(null);
const [accent, setAccent] = useState<null | undefined | string>(
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<string | null>(
team.defaultCollectionId
);
const customTheme: Partial<CustomTheme> = 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(
<T extends TeamPreference>(key: T, value: TeamPreferences[T]) =>
saveData({ preferences: { [key]: value } }),
[saveData]
);
const saveTheme = React.useMemo(
() =>
debounce((theme: Partial<CustomTheme>) => {
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<HTMLInputElement>) => {
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<HTMLInputElement>) => {
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<HTMLInputElement>) => {
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,24 @@ 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 {
await user.savePreference(UserPreference.SeamlessEdit, false);
} 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 +305,192 @@ function Details() {
</Trans>
</Text>
<form onSubmit={handleSubmit} ref={form}>
<Heading as="h2">{t("Appearance")}</Heading>
<SettingRow
label={t("Logo")}
name="avatarUrl"
description={t(
"The logo is displayed at the top left of the application."
)}
>
<ImageInput
alt={t("Workspace logo")}
onSuccess={handleAvatarChange}
onError={handleAvatarError}
model={team}
borderRadius={0}
/>
</SettingRow>
<SettingRow
label={t("Name")}
name="name"
description={t(
"The workspace name, usually the same as your company name."
)}
>
<Input
id="name"
autoComplete="organization"
value={name}
onChange={handleNameChange}
maxLength={TeamValidation.maxNameLength}
showCharacterCount
required
/>
</SettingRow>
<SettingRow
label={t("Description")}
name="description"
description={t("A short description of your workspace.")}
>
<Input
id="description"
value={description}
onChange={(ev: React.ChangeEvent<HTMLInputElement>) => {
setDescription(ev.target.value);
}}
maxLength={TeamValidation.maxDescriptionLength}
showCharacterCount
/>
</SettingRow>
<SettingRow
label={t("Theme")}
name="accent"
description={
<>
{t("Customize the interface look and feel.")}{" "}
{accent && (
<>
<ButtonLink
onClick={() => {
setAccent(null);
setAccentText(null);
}}
>
<form onSubmit={handleSubmit} onKeyDown={handleKeyDown}>
<SettingsSection title={t("Appearance")}>
<SettingRow
label={t("Logo")}
name="avatarUrl"
description={t(
"The logo is displayed at the top left of the application."
)}
>
<ImageInput
alt={t("Workspace logo")}
onSuccess={handleAvatarChange}
onError={handleAvatarError}
model={team}
borderRadius={0}
variant={AvatarVariant.Square}
/>
</SettingRow>
<SettingRow
label={t("Name")}
name="name"
description={t(
"The workspace name, usually the same as your company name."
)}
>
<Input
id="name"
autoComplete="organization"
value={name}
onChange={handleNameChange}
onBlur={handleNameBlur}
maxLength={TeamValidation.maxNameLength}
showCharacterCount
required
/>
</SettingRow>
<SettingRow
label={t("Description")}
name="description"
description={t("A short description of your workspace.")}
>
<Input
id="description"
value={description}
onChange={handleDescriptionChange}
onBlur={handleDescriptionBlur}
maxLength={TeamValidation.maxDescriptionLength}
showCharacterCount
/>
</SettingRow>
<SettingRow
label={t("Theme")}
name="accent"
description={
<>
{t("Customize the interface look and feel.")}{" "}
{accent && (
<ButtonLink onClick={handleResetTheme}>
{t("Reset theme")}
</ButtonLink>
</>
)}
</>
}
>
<ThemeColorInputs
accent={accent}
accentText={accentText}
onAccentChange={handleAccentChange}
onAccentTextChange={handleAccentTextChange}
/>
</SettingRow>
{(team.avatarUrl || team.description) && (
<SettingRow
name={TeamPreference.PublicBranding}
label={t("Public branding")}
description={t(
"Show your workspace logo, description, and branding on publicly shared pages."
)}
</>
}
>
<ThemeColorInputs
accent={accent}
accentText={accentText}
onAccentChange={setAccent}
onAccentTextChange={setAccentText}
/>
</SettingRow>
{(team.avatarUrl || team.description) && (
>
<Switch
id={TeamPreference.PublicBranding}
name={TeamPreference.PublicBranding}
checked={!!team.getPreference(TeamPreference.PublicBranding)}
onChange={handlePublicBrandingChange}
/>
</SettingRow>
)}
<SettingRow
name={TeamPreference.PublicBranding}
label={t("Public branding")}
label={t("Table of contents position")}
name="tocPosition"
description={t(
"Show your workspace logo, description, and branding on publicly shared pages."
"The side to display the table of contents in relation to the main content."
)}
>
<InputSelect
options={tocPositionOptions}
value={
team.getPreference(TeamPreference.TocPosition) || undefined
}
onChange={handleTocPositionChange}
label={t("Table of contents position")}
labelHidden
/>
</SettingRow>
</SettingsSection>
<SettingsSection title={t("Behavior")}>
<SettingRow
visible={isCloudHosted}
label={t("Subdomain")}
name="subdomain"
description={
subdomain ? (
<>
<Trans>Your workspace will be accessible at</Trans>{" "}
<strong>
{subdomain}.{getBaseDomain()}
</strong>
</>
) : (
t(
"Choose a subdomain to enable a login page just for your team."
)
)
}
>
<Input
id="subdomain"
value={subdomain || ""}
onChange={handleSubdomainChange}
onBlur={handleSubdomainBlur}
autoComplete="off"
minLength={TeamValidation.minSubdomainLength}
maxLength={
isCloudHosted
? TeamValidation.maxSubdomainLength
: TeamValidation.maxSubdomainSelfHostedLength
}
/>
</SettingRow>
<SettingRow
label={t("Start view")}
name="defaultCollectionId"
description={t(
"This is the screen that workspace members will first see when they sign in."
)}
>
<DefaultCollectionInputSelect
onSelectCollection={handleSelectCollection}
defaultCollectionId={team.defaultCollectionId}
/>
</SettingRow>
<SettingRow
name={TeamPreference.SeamlessEdit}
label={t("Separate editing")}
description={t(
"When enabled, documents have a separate editing mode by default instead of being always editable. This setting can be overridden by user preferences."
)}
>
<Switch
id={TeamPreference.PublicBranding}
name={TeamPreference.PublicBranding}
checked={publicBranding}
onChange={(checked: boolean) => setPublicBranding(checked)}
id={TeamPreference.SeamlessEdit}
name={TeamPreference.SeamlessEdit}
checked={!team.getPreference(TeamPreference.SeamlessEdit)}
onChange={handleSeamlessEditChange}
/>
</SettingRow>
)}
<SettingRow
border={false}
label={t("Table of contents position")}
name="tocPosition"
description={t(
"The side to display the table of contents in relation to the main content."
)}
>
<InputSelect
options={tocPositionOptions}
value={tocPosition}
onChange={handleTocPositionChange}
label={t("Table of contents position")}
labelHidden
/>
</SettingRow>
<Heading as="h2">{t("Behavior")}</Heading>
<SettingRow
visible={isCloudHosted}
label={t("Subdomain")}
name="subdomain"
description={
subdomain ? (
<>
<Trans>Your workspace will be accessible at</Trans>{" "}
<strong>
{subdomain}.{getBaseDomain()}
</strong>
</>
) : (
t(
"Choose a subdomain to enable a login page just for your team."
)
)
}
>
<Input
id="subdomain"
value={subdomain || ""}
onChange={handleSubdomainChange}
autoComplete="off"
minLength={TeamValidation.minSubdomainLength}
maxLength={
isCloudHosted
? TeamValidation.maxSubdomainLength
: TeamValidation.maxSubdomainSelfHostedLength
}
/>
</SettingRow>
<SettingRow
label={t("Start view")}
name="defaultCollectionId"
description={t(
"This is the screen that workspace members will first see when they sign in."
)}
>
<DefaultCollectionInputSelect
onSelectCollection={onSelectCollection}
defaultCollectionId={defaultCollectionId}
/>
</SettingRow>
<SettingRow
border={false}
name={TeamPreference.SeamlessEdit}
label={t("Separate editing")}
description={t(
"When enabled, documents have a separate editing mode by default instead of being always editable. This setting can be overridden by user preferences."
)}
>
<Switch
id={TeamPreference.SeamlessEdit}
name={TeamPreference.SeamlessEdit}
checked={!team.getPreference(TeamPreference.SeamlessEdit)}
onChange={handleSeamlessEditChange}
/>
</SettingRow>
<ActionRow>
<Button type="submit" disabled={team.isSaving || !isValid}>
{team.isSaving ? `${t("Saving")}…` : t("Save")}
</Button>
</ActionRow>
{can.delete && (
<>
<p>&nbsp;</p>
<Heading as="h2">{t("Danger")}</Heading>
<SettingRow
name="delete"
border={false}
label={t("Delete workspace")}
description={t(
"You can delete this entire workspace including collections, documents, and users."
)}
>
<span>
<Button onClick={showDeleteWorkspace} neutral>
{t("Delete workspace")}…
</Button>
</span>
</SettingRow>
</>
)}
</SettingsSection>
</form>
{can.delete && (
<SettingsSection title={t("Danger")} danger>
<SettingRow
name="delete"
label={t("Delete workspace")}
description={t(
"You can delete this entire workspace including collections, documents, and users."
)}
>
<span>
<Button onClick={showDeleteWorkspace} neutral>
{t("Delete workspace")}…
</Button>
</span>
</SettingRow>
</SettingsSection>
)}
</Scene>
</ThemeProvider>
);
+15 -9
View File
@@ -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. */
@@ -57,9 +58,11 @@ function Embeds() {
? disabledEmbeds.filter((t) => t !== id)
: [...disabledEmbeds, id];
team.setPreference(TeamPreference.DisabledEmbeds, updated);
await saveData({
preferences: { ...team.preferences },
preferences: {
...team.preferences,
[TeamPreference.DisabledEmbeds]: updated,
},
});
},
[team, saveData]
@@ -69,9 +72,11 @@ function Embeds() {
async (enabled: boolean) => {
const updated = enabled ? [] : providers.map((e) => e.id);
team.setPreference(TeamPreference.DisabledEmbeds, updated);
await saveData({
preferences: { ...team.preferences },
preferences: {
...team.preferences,
[TeamPreference.DisabledEmbeds]: updated,
},
});
},
[team, saveData]
@@ -99,15 +104,16 @@ function Embeds() {
</SettingRow>
{team.documentEmbeds && (
<>
<Heading as="h2">{t("Providers")}</Heading>
<Text as="p" type="secondary">
<SettingsSection
title={t("Providers")}
description={
<Trans>
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.
</Trans>
</Text>
}
>
<SettingRow
name="allEmbeds"
label={t("All providers")}
@@ -148,7 +154,7 @@ function Embeds() {
</SettingRow>
);
})}
</>
</SettingsSection>
)}
</IntegrationScene>
);
+169 -177
View File
@@ -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();
@@ -57,8 +58,7 @@ function Preferences() {
const handleUseCursorPointerChange = React.useCallback(
async (checked: boolean) => {
user.setPreference(UserPreference.UseCursorPointer, checked);
await user.save();
await user.savePreference(UserPreference.UseCursorPointer, checked);
toast.success(t("Preferences saved"));
},
[user, t]
@@ -66,8 +66,7 @@ function Preferences() {
const handleCodeBlockLineNumbersChange = React.useCallback(
async (checked: boolean) => {
user.setPreference(UserPreference.CodeBlockLineNumers, checked);
await user.save();
await user.savePreference(UserPreference.CodeBlockLineNumers, checked);
toast.success(t("Preferences saved"));
},
[user, t]
@@ -75,8 +74,7 @@ function Preferences() {
const handleCommentsInGutterChange = React.useCallback(
async (checked: boolean) => {
user.setPreference(UserPreference.CommentsInGutter, checked);
await user.save();
await user.savePreference(UserPreference.CommentsInGutter, checked);
toast.success(t("Preferences saved"));
},
[user, t]
@@ -84,8 +82,7 @@ function Preferences() {
const handleShowDocumentStatsChange = React.useCallback(
async (checked: boolean) => {
user.setPreference(UserPreference.ShowDocumentStats, checked);
await user.save();
await user.savePreference(UserPreference.ShowDocumentStats, checked);
toast.success(t("Preferences saved"));
},
[user, t]
@@ -93,8 +90,7 @@ function Preferences() {
const handleSeamlessEditChange = React.useCallback(
async (checked: boolean) => {
user.setPreference(UserPreference.SeamlessEdit, !checked);
await user.save();
await user.savePreference(UserPreference.SeamlessEdit, !checked);
toast.success(t("Preferences saved"));
},
[user, t]
@@ -102,8 +98,7 @@ function Preferences() {
const handleRememberLastPathChange = React.useCallback(
async (checked: boolean) => {
user.setPreference(UserPreference.RememberLastPath, checked);
await user.save();
await user.savePreference(UserPreference.RememberLastPath, checked);
toast.success(t("Preferences saved"));
},
[user, t]
@@ -111,8 +106,7 @@ function Preferences() {
const handleEnableSmartTextChange = React.useCallback(
async (checked: boolean) => {
user.setPreference(UserPreference.EnableSmartText, checked);
await user.save();
await user.savePreference(UserPreference.EnableSmartText, checked);
toast.success(t("Preferences saved"));
},
[user, t]
@@ -141,11 +135,10 @@ function Preferences() {
const handleNotificationBadgeChange = React.useCallback(
async (value: string) => {
user.setPreference(
await user.savePreference(
UserPreference.NotificationBadge,
value as NotificationBadgeType
);
await user.save();
toast.success(t("Preferences saved"));
},
[user, t]
@@ -181,173 +174,172 @@ function Preferences() {
<Trans>Manage settings that affect your personal experience.</Trans>
</Text>
<Heading as="h2">{t("Appearance")}</Heading>
<SettingRow
label={t("Language")}
name="language"
description={
<>
<Trans>
Choose the interface language. Community translations are accepted
through our{" "}
<a
href="https://translate.getoutline.com"
target="_blank"
rel="noreferrer"
>
translation portal
</a>
.
</Trans>
</>
}
>
<InputSelect
options={languageOptions}
value={user.language}
onChange={handleLanguageChange}
<SettingsSection title={t("Appearance")}>
<SettingRow
label={t("Language")}
labelHidden
/>
</SettingRow>
<SettingRow
name="theme"
label={t("Theme")}
description={t("Choose your preferred interface color scheme.")}
>
<InputSelect
options={themeOptions}
value={ui.theme}
onChange={handleThemeChange}
label={t("Theme")}
labelHidden
/>
</SettingRow>
<SettingRow
name={UserPreference.UseCursorPointer}
label={t("Use pointer cursor")}
description={t(
"Show a hand cursor when hovering over interactive elements."
)}
>
<Switch
id={UserPreference.UseCursorPointer}
name={UserPreference.UseCursorPointer}
checked={user.getPreference(UserPreference.UseCursorPointer)}
onChange={handleUseCursorPointerChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.CodeBlockLineNumers}
label={t("Show line numbers")}
description={t("Show line numbers on code blocks in documents.")}
>
<Switch
id={UserPreference.CodeBlockLineNumers}
name={UserPreference.CodeBlockLineNumers}
checked={user.getPreference(UserPreference.CodeBlockLineNumers)}
onChange={handleCodeBlockLineNumbersChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.CommentsInGutter}
label={t("Show comment marker")}
description={t(
"Display a marker beside lines in the editor that contain comments."
)}
>
<Switch
id={UserPreference.CommentsInGutter}
name={UserPreference.CommentsInGutter}
checked={user.getPreference(UserPreference.CommentsInGutter)}
onChange={handleCommentsInGutterChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.ShowDocumentStats}
label={t("Show editing stats")}
description={t(
"Display live word, character, and paragraph counts while editing."
)}
border={false}
>
<Switch
id={UserPreference.ShowDocumentStats}
name={UserPreference.ShowDocumentStats}
checked={user.getPreference(UserPreference.ShowDocumentStats)}
onChange={handleShowDocumentStatsChange}
/>
</SettingRow>
<Heading as="h2">{t("Behavior")}</Heading>
<SettingRow
name={UserPreference.SeamlessEdit}
label={t("Separate editing")}
description={t(
`When enabled, documents have a separate editing mode. When disabled, documents are always editable when you have permission.`
)}
>
<Switch
id={UserPreference.SeamlessEdit}
name={UserPreference.SeamlessEdit}
checked={
!user.getPreference(
UserPreference.SeamlessEdit,
team.getPreference(TeamPreference.SeamlessEdit)
)
name="language"
description={
<>
<Trans>
Choose the interface language. Community translations are
accepted through our{" "}
<a
href="https://translate.getoutline.com"
target="_blank"
rel="noreferrer"
>
translation portal
</a>
.
</Trans>
</>
}
onChange={handleSeamlessEditChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.RememberLastPath}
label={t("Remember previous location")}
description={t(
"Automatically return to the document you were last viewing when the app is reopened."
)}
>
<Switch
id={UserPreference.RememberLastPath}
>
<InputSelect
options={languageOptions}
value={user.language}
onChange={handleLanguageChange}
label={t("Language")}
labelHidden
/>
</SettingRow>
<SettingRow
name="theme"
label={t("Theme")}
description={t("Choose your preferred interface color scheme.")}
>
<InputSelect
options={themeOptions}
value={ui.theme}
onChange={handleThemeChange}
label={t("Theme")}
labelHidden
/>
</SettingRow>
<SettingRow
name={UserPreference.UseCursorPointer}
label={t("Use pointer cursor")}
description={t(
"Show a hand cursor when hovering over interactive elements."
)}
>
<Switch
id={UserPreference.UseCursorPointer}
name={UserPreference.UseCursorPointer}
checked={user.getPreference(UserPreference.UseCursorPointer)}
onChange={handleUseCursorPointerChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.CodeBlockLineNumers}
label={t("Show line numbers")}
description={t("Show line numbers on code blocks in documents.")}
>
<Switch
id={UserPreference.CodeBlockLineNumers}
name={UserPreference.CodeBlockLineNumers}
checked={user.getPreference(UserPreference.CodeBlockLineNumers)}
onChange={handleCodeBlockLineNumbersChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.CommentsInGutter}
label={t("Show comment marker")}
description={t(
"Display a marker beside lines in the editor that contain comments."
)}
>
<Switch
id={UserPreference.CommentsInGutter}
name={UserPreference.CommentsInGutter}
checked={user.getPreference(UserPreference.CommentsInGutter)}
onChange={handleCommentsInGutterChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.ShowDocumentStats}
label={t("Show editing stats")}
description={t(
"Display live word, character, and paragraph counts while editing."
)}
>
<Switch
id={UserPreference.ShowDocumentStats}
name={UserPreference.ShowDocumentStats}
checked={user.getPreference(UserPreference.ShowDocumentStats)}
onChange={handleShowDocumentStatsChange}
/>
</SettingRow>
</SettingsSection>
<SettingsSection title={t("Behavior")}>
<SettingRow
name={UserPreference.SeamlessEdit}
label={t("Separate editing")}
description={t(
`When enabled, documents have a separate editing mode. When disabled, documents are always editable when you have permission.`
)}
>
<Switch
id={UserPreference.SeamlessEdit}
name={UserPreference.SeamlessEdit}
checked={
!user.getPreference(
UserPreference.SeamlessEdit,
team.getPreference(TeamPreference.SeamlessEdit)
)
}
onChange={handleSeamlessEditChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.RememberLastPath}
checked={!!user.getPreference(UserPreference.RememberLastPath)}
onChange={handleRememberLastPathChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.EnableSmartText}
label={t("Smart text replacements")}
description={t(
"Auto-format text by replacing shortcuts with symbols, dashes, smart quotes, and other typographical elements."
)}
>
<Switch
id={UserPreference.EnableSmartText}
label={t("Remember previous location")}
description={t(
"Automatically return to the document you were last viewing when the app is reopened."
)}
>
<Switch
id={UserPreference.RememberLastPath}
name={UserPreference.RememberLastPath}
checked={!!user.getPreference(UserPreference.RememberLastPath)}
onChange={handleRememberLastPathChange}
/>
</SettingRow>
<SettingRow
name={UserPreference.EnableSmartText}
checked={!!user.getPreference(UserPreference.EnableSmartText)}
onChange={handleEnableSmartTextChange}
/>
</SettingRow>
<AutoLaunchSetting />
<SettingRow
border={false}
name={UserPreference.NotificationBadge}
label={t("Notification badge")}
description={t(
"Choose how unread notifications are indicated on the app icon."
)}
>
<InputSelect
options={notificationBadgeOptions}
value={user.getPreference(UserPreference.NotificationBadge)}
onChange={handleNotificationBadgeChange}
label={t("Smart text replacements")}
description={t(
"Auto-format text by replacing shortcuts with symbols, dashes, smart quotes, and other typographical elements."
)}
>
<Switch
id={UserPreference.EnableSmartText}
name={UserPreference.EnableSmartText}
checked={!!user.getPreference(UserPreference.EnableSmartText)}
onChange={handleEnableSmartTextChange}
/>
</SettingRow>
<AutoLaunchSetting />
<SettingRow
name={UserPreference.NotificationBadge}
label={t("Notification badge")}
labelHidden
/>
</SettingRow>
description={t(
"Choose how unread notifications are indicated on the app icon."
)}
>
<InputSelect
options={notificationBadgeOptions}
value={user.getPreference(UserPreference.NotificationBadge)}
onChange={handleNotificationBadgeChange}
label={t("Notification badge")}
labelHidden
/>
</SettingRow>
</SettingsSection>
{can.delete && (
<>
<Heading as="h2">{t("Danger")}</Heading>
<SettingsSection title={t("Danger")} danger>
<SettingRow
name="delete"
label={t("Delete account")}
@@ -361,7 +353,7 @@ function Preferences() {
</Button>
</span>
</SettingRow>
</>
</SettingsSection>
)}
</Scene>
);
+27 -11
View File
@@ -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<HTMLFormElement>(null);
const [name, setName] = React.useState<string>(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 (
<Scene title={t("Profile")} icon={<ProfileIcon />}>
<Heading>{t("Profile")}</Heading>
@@ -67,7 +86,7 @@ const Profile = () => {
<Trans>Manage how you appear to other members of the workspace.</Trans>
</Text>
<form onSubmit={handleSubmit} ref={form}>
<form onSubmit={handleSubmit} onKeyDown={handleKeyDown}>
<SettingRow
label={t("Photo")}
name="avatarUrl"
@@ -93,6 +112,7 @@ const Profile = () => {
autoComplete="name"
value={name}
onChange={handleNameChange}
onBlur={handleNameBlur}
maxLength={UserValidation.maxNameLength}
showCharacterCount
required
@@ -109,10 +129,6 @@ const Profile = () => {
/>
</SettingRow>
)}
<Button type="submit" disabled={isSaving || !isValid}>
{isSaving ? `${t("Saving")}…` : t("Save")}
</Button>
</form>
</Scene>
);
+167 -163
View File
@@ -21,6 +21,7 @@ import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import isCloudHosted from "~/utils/isCloudHosted";
import SettingRow from "./components/SettingRow";
import { SettingsSection } from "./components/SettingsSection";
function Security() {
const { dialogs } = useStores();
@@ -280,186 +281,189 @@ function Security() {
</Trans>
</Text>
<Heading as="h2">{t("Invites")}</Heading>
<SettingRow
label={t("Allow users to send invites")}
name={TeamPreference.MembersCanInvite}
description={t("Allow editors to invite other people to the workspace")}
>
<Switch
id={TeamPreference.MembersCanInvite}
checked={team.getPreference(TeamPreference.MembersCanInvite)}
onChange={handleMembersCanInviteChange}
/>
</SettingRow>
{isCloudHosted && (
<SettingsSection title={t("Invites")}>
<SettingRow
label={t("Require invites")}
name="inviteRequired"
label={t("Allow users to send invites")}
name={TeamPreference.MembersCanInvite}
description={t(
"Require members to be invited to the workspace before they can create an account using SSO."
"Allow editors to invite other people to the workspace"
)}
>
<Switch
id="inviteRequired"
checked={data.inviteRequired}
onChange={handleInviteRequiredChange}
id={TeamPreference.MembersCanInvite}
checked={team.getPreference(TeamPreference.MembersCanInvite)}
onChange={handleMembersCanInviteChange}
/>
</SettingRow>
)}
{!data.inviteRequired && (
<SettingRow
label={t("Default role")}
name="defaultUserRole"
description={t(
"The default user role for new accounts. Changing this setting does not affect existing user accounts."
)}
border={false}
>
<InputSelect
value={data.defaultUserRole}
options={userRoleOptions}
onChange={handleDefaultRoleChange}
label={t("Default role")}
labelHidden
short
/>
</SettingRow>
)}
<Heading as="h2">{t("Behavior")}</Heading>
<SettingRow
label={t("Public document sharing")}
name="sharing"
description={t(
"When enabled, documents can be shared publicly on the internet by any member of the workspace"
)}
>
<Switch
id="sharing"
checked={data.sharing}
onChange={handleSharingChange}
/>
</SettingRow>
{can.setDefaultShareExpiry && (
<SettingRow
label={t("Default link expiration")}
name={TeamPreference.DefaultShareExpiryDays}
description={t(
"New public links will expire after this period. Existing links are not affected."
)}
>
<InputSelect
value={String(
team.getPreference(TeamPreference.DefaultShareExpiryDays)
{isCloudHosted && (
<SettingRow
label={t("Require invites")}
name="inviteRequired"
description={t(
"Require members to be invited to the workspace before they can create an account using SSO."
)}
options={defaultShareExpiryOptions}
onChange={handleDefaultShareExpiryChange}
>
<Switch
id="inviteRequired"
checked={data.inviteRequired}
onChange={handleInviteRequiredChange}
/>
</SettingRow>
)}
{!data.inviteRequired && (
<SettingRow
label={t("Default role")}
name="defaultUserRole"
description={t(
"The default user role for new accounts. Changing this setting does not affect existing user accounts."
)}
>
<InputSelect
value={data.defaultUserRole}
options={userRoleOptions}
onChange={handleDefaultRoleChange}
label={t("Default role")}
labelHidden
short
/>
</SettingRow>
)}
</SettingsSection>
<SettingsSection title={t("Behavior")}>
<SettingRow
label={t("Public document sharing")}
name="sharing"
description={t(
"When enabled, documents can be shared publicly on the internet by any member of the workspace"
)}
>
<Switch
id="sharing"
checked={data.sharing}
onChange={handleSharingChange}
/>
</SettingRow>
{can.setDefaultShareExpiry && (
<SettingRow
label={t("Default link expiration")}
name={TeamPreference.DefaultShareExpiryDays}
description={t(
"New public links will expire after this period. Existing links are not affected."
)}
>
<InputSelect
value={String(
team.getPreference(TeamPreference.DefaultShareExpiryDays)
)}
options={defaultShareExpiryOptions}
onChange={handleDefaultShareExpiryChange}
label={t("Default link expiration")}
labelHidden
short
/>
</SettingRow>
)}
<SettingRow
label={t("Viewer document exports")}
name={TeamPreference.ViewersCanExport}
description={t(
"When enabled, viewers can see download options for documents"
)}
>
<Switch
id={TeamPreference.ViewersCanExport}
checked={team.getPreference(TeamPreference.ViewersCanExport)}
onChange={handleViewersCanExportChange}
/>
</SettingRow>
<SettingRow
label={t("Users can delete account")}
name={TeamPreference.MembersCanDeleteAccount}
description={t(
"When enabled, users can delete their own account from the workspace"
)}
>
<Switch
id={TeamPreference.MembersCanDeleteAccount}
checked={team.getPreference(TeamPreference.MembersCanDeleteAccount)}
onChange={handleMembersCanDeleteAccountChange}
/>
</SettingRow>
<SettingRow
label={t("Email address visibility")}
name={TeamPreference.EmailDisplay}
description={t(
"Controls who can see user email addresses in the workspace"
)}
>
<InputSelect
value={team.getPreference(TeamPreference.EmailDisplay) as string}
options={emailDisplayOptions}
onChange={handleEmailDisplayChange}
label={t("Email address visibility")}
labelHidden
short
/>
</SettingRow>
)}
<SettingRow
label={t("Viewer document exports")}
name={TeamPreference.ViewersCanExport}
description={t(
"When enabled, viewers can see download options for documents"
)}
>
<Switch
id={TeamPreference.ViewersCanExport}
checked={team.getPreference(TeamPreference.ViewersCanExport)}
onChange={handleViewersCanExportChange}
/>
</SettingRow>
<SettingRow
label={t("Users can delete account")}
name={TeamPreference.MembersCanDeleteAccount}
description={t(
"When enabled, users can delete their own account from the workspace"
)}
>
<Switch
id={TeamPreference.MembersCanDeleteAccount}
checked={team.getPreference(TeamPreference.MembersCanDeleteAccount)}
onChange={handleMembersCanDeleteAccountChange}
/>
</SettingRow>
<SettingRow
label={t("Email address visibility")}
name={TeamPreference.EmailDisplay}
description={t(
"Controls who can see user email addresses in the workspace"
)}
>
<InputSelect
value={team.getPreference(TeamPreference.EmailDisplay) as string}
options={emailDisplayOptions}
onChange={handleEmailDisplayChange}
label={t("Email address visibility")}
labelHidden
short
/>
</SettingRow>
<SettingRow
label={t("Commenting")}
name={TeamPreference.Commenting}
description={t("Controls who can add comments to documents")}
>
<InputSelect
value={
team.getPreference(TeamPreference.Commenting) ||
CommentingAccess.Members
}
options={commentingOptions}
onChange={handleCommentingChange}
label={t("Commenting")}
labelHidden
short
/>
</SettingRow>
<SettingRow
label={t("Personal documents")}
name={TeamPreference.PersonalDocs}
description={t(
"Allow editors to create personal documents that are only visible to themselves and the people they share them with"
)}
>
<Switch
id={TeamPreference.PersonalDocs}
checked={team.getPreference(TeamPreference.PersonalDocs)}
onChange={handlePersonalDocsChange}
/>
</SettingRow>
<SettingRow
label={t("Collection creation")}
name="memberCollectionCreate"
description={t(
"Allow editors to create new collections within the workspace"
)}
>
<Switch
id="memberCollectionCreate"
checked={data.memberCollectionCreate}
onChange={handleMemberCollectionCreateChange}
/>
</SettingRow>
{isCloudHosted && (
<SettingRow
label={t("Workspace creation")}
name="memberTeamCreate"
description={t("Allow editors to create new workspaces")}
label={t("Commenting")}
name={TeamPreference.Commenting}
description={t("Controls who can add comments to documents")}
>
<Switch
id="memberTeamCreate"
checked={data.memberTeamCreate}
onChange={handleMemberTeamCreateChange}
<InputSelect
value={
team.getPreference(TeamPreference.Commenting) ||
CommentingAccess.Members
}
options={commentingOptions}
onChange={handleCommentingChange}
label={t("Commenting")}
labelHidden
short
/>
</SettingRow>
)}
<SettingRow
label={t("Personal documents")}
name={TeamPreference.PersonalDocs}
description={t(
"Allow editors to create personal documents that are only visible to themselves and the people they share them with"
)}
>
<Switch
id={TeamPreference.PersonalDocs}
checked={team.getPreference(TeamPreference.PersonalDocs)}
onChange={handlePersonalDocsChange}
/>
</SettingRow>
<SettingRow
label={t("Collection creation")}
name="memberCollectionCreate"
description={t(
"Allow editors to create new collections within the workspace"
)}
>
<Switch
id="memberCollectionCreate"
checked={data.memberCollectionCreate}
onChange={handleMemberCollectionCreateChange}
/>
</SettingRow>
{isCloudHosted && (
<SettingRow
label={t("Workspace creation")}
name="memberTeamCreate"
description={t("Allow editors to create new workspaces")}
>
<Switch
id="memberTeamCreate"
checked={data.memberTeamCreate}
onChange={handleMemberTeamCreateChange}
/>
</SettingRow>
)}
</SettingsSection>
</Scene>
);
}
+76 -19
View File
@@ -1,13 +1,19 @@
import { EditIcon } from "outline-icons";
import { observer } from "mobx-react";
import { EditIcon, ExportIcon, TrashIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { s } from "@shared/styles";
import type { IAvatar } from "~/components/Avatar";
import { Avatar, AvatarSize } from "~/components/Avatar";
import { AvatarVariant } from "~/components/Avatar/Avatar";
import Button from "~/components/Button";
import Flex from "~/components/Flex";
import type { Props as ImageUploadProps } from "./ImageUpload";
import NudeButton from "~/components/NudeButton";
import Tooltip from "~/components/Tooltip";
import type {
ImageUploadHandle,
Props as ImageUploadProps,
} from "./ImageUpload";
import ImageUpload from "./ImageUpload";
type Props = ImageUploadProps & {
@@ -15,26 +21,48 @@ type Props = ImageUploadProps & {
model: IAvatar;
/** Alt text for the avatar image. */
alt: string;
/** The shape of the avatar preview. Defaults to round. */
variant?: AvatarVariant;
/**
* Whether to render the inline "Remove" button when the model has an
* existing avatar. Defaults to true.
* Whether to render the change and remove buttons below the image. Hide
* them when the parent provides its own controls. Defaults to true.
*/
showRemoveOption?: boolean;
showActions?: boolean;
/** Handle to open the file picker from the parent. */
ref?: React.Ref<ImageUploadHandle>;
};
export default function ImageInput({
function ImageInput({
model,
onSuccess,
alt,
showRemoveOption = true,
variant = AvatarVariant.Round,
showActions = true,
ref,
...rest
}: Props) {
const { t } = useTranslation();
const uploadRef = React.useRef<ImageUploadHandle>(null);
React.useImperativeHandle(
ref,
() => ({ open: () => uploadRef.current?.open() }),
[]
);
const handleChange = React.useCallback(() => {
uploadRef.current?.open();
}, []);
const handleRemove = React.useCallback(() => {
void onSuccess(null);
}, [onSuccess]);
return (
<Flex gap={8} justify="space-between">
<ImageBox>
<Wrapper column align="center" gap={4}>
<ImageBox $variant={variant}>
<ImageUpload
ref={uploadRef}
onSuccess={onSuccess}
submitText={t("Crop image")}
{...rest}
@@ -42,33 +70,62 @@ export default function ImageInput({
<Avatar
model={model}
size={AvatarSize.Upload}
variant={AvatarVariant.Round}
variant={variant}
alt={alt}
/>
<Flex auto align="center" justify="center" className="upload">
<EditIcon />
<ExportIcon />
</Flex>
</ImageUpload>
</ImageBox>
{model.avatarUrl && showRemoveOption && (
<Button onClick={() => onSuccess(null)} neutral>
{t("Remove")}
</Button>
{showActions && (
<Actions gap={4} justify="center">
<Tooltip content={t("Change image")}>
<NudeButton aria-label={t("Change image")} onClick={handleChange}>
<EditIcon />
</NudeButton>
</Tooltip>
{model.avatarUrl && (
<Tooltip content={t("Remove image")}>
<NudeButton aria-label={t("Remove image")} onClick={handleRemove}>
<TrashIcon />
</NudeButton>
</Tooltip>
)}
</Actions>
)}
</Flex>
</Wrapper>
);
}
export default observer(ImageInput);
const Wrapper = styled(Flex)`
width: fit-content;
`;
const Actions = styled(Flex)`
color: ${s("textSecondary")};
button:hover,
button:focus-visible {
color: ${s("text")};
}
`;
const avatarStyles = `
width: ${AvatarSize.Upload}px;
height: ${AvatarSize.Upload}px;
`;
const ImageBox = styled(Flex)`
const ImageBox = styled(Flex)<{ $variant: AvatarVariant }>`
${avatarStyles};
position: relative;
font-size: 14px;
border-radius: 50%;
border-radius: ${(props) =>
props.$variant === AvatarVariant.Round
? "50%"
: `${AvatarSize.Upload / 8}px`};
box-shadow: 0 0 0 1px ${s("backgroundSecondary")};
background: ${s("background")};
overflow: hidden;
+12 -3
View File
@@ -26,13 +26,20 @@ export type Props = {
children?: React.ReactNode;
};
const ImageUpload: React.FC<Props> = ({
/** Imperative handle exposed by ImageUpload. */
export interface ImageUploadHandle {
/** Opens the file picker. */
open: () => void;
}
const ImageUpload = ({
onSuccess,
onError,
submitText,
borderRadius,
children,
}) => {
ref,
}: Props & { ref?: React.Ref<ImageUploadHandle> }) => {
const { dialogs } = useStores();
const { t } = useTranslation();
@@ -110,11 +117,13 @@ const ImageUpload: React.FC<Props> = ({
[t, dialogs, handleUpload, handleClose, onError, borderRadius, submitText]
);
const { getRootProps, getInputProps } = useDropzone({
const { getRootProps, getInputProps, open } = useDropzone({
accept: avatarAccept,
onDropAccepted,
});
React.useImperativeHandle(ref, () => ({ open }), [open]);
if (isCropping) {
return null; // onDropAccepted would have opened a modal for cropping the image.
}
+16 -5
View File
@@ -28,6 +28,18 @@ const Row = styled(Flex)<{ $border?: boolean; $compact?: boolean }>`
border-bottom: 0;
}
/* Center switches, unless the text column also holds a field. */
&:has(> :last-child > [role="switch"]):not(
:has(> :first-child :is(input, textarea))
) {
align-items: center;
}
/* A switch column is only as wide as the switch. */
&:has(> :last-child > [role="switch"]) > :last-child {
flex: 0 0 auto;
}
${breakpoint("mobile", "tablet")`
&:has([role="switch"]) {
gap: 16px;
@@ -73,11 +85,10 @@ const Column = styled.div`
align-self: flex-end;
}
${breakpoint("tablet")`
> * {
align-self: initial;
}
`}
/* Text fields and selects fill the column. */
> :has(input:not([type="file"]), textarea, [role="combobox"]) {
align-self: stretch;
}
}
${breakpoint("tablet")`
@@ -0,0 +1,74 @@
import { transparentize } from "polished";
import * as React from "react";
import styled, { css } from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import Text from "~/components/Text";
interface Props {
/** The section heading. */
title: React.ReactNode;
/** Optional text shown below the heading. */
description?: React.ReactNode;
/** Whether the section holds destructive actions. */
danger?: boolean;
/** The rows in the section, usually SettingRow components. */
children: React.ReactNode;
}
/**
* A titled group of setting rows on a settings screen.
*
* @param props the section props.
* @returns the section element.
*/
export function SettingsSection({
title,
description,
danger,
children,
}: Props) {
const titleId = React.useId();
return (
<Section aria-labelledby={titleId}>
<Title id={titleId}>{title}</Title>
{description && (
<Description as="p" type="secondary">
{description}
</Description>
)}
<Rows $danger={danger}>{children}</Rows>
</Section>
);
}
const Section = styled.section`
margin-top: 32px;
${breakpoint("tablet")`
margin-top: 48px;
`}
`;
const Title = styled.h2`
font-size: 20px;
font-weight: 600;
margin: 0;
`;
const Description = styled(Text)`
margin: 4px 0 8px;
`;
const Rows = styled.div<{ $danger?: boolean }>`
${(props) =>
props.$danger &&
css`
/* Inset by the shadow width so the shadow aligns with the content. */
margin: 24px 8px 8px;
padding: 0 16px;
border: 1px solid ${transparentize(0.6, props.theme.danger)};
border-radius: 8px;
box-shadow: 0 0 0 8px ${transparentize(0.9, props.theme.danger)};
`}
`;
+29 -1
View File
@@ -1,8 +1,10 @@
import { format as formatDate } from "date-fns";
import { compact } from "es-toolkit/compat";
import { observer } from "mobx-react";
import * as React from "react";
import { useMemo, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { dateLocale } from "@shared/utils/date";
import type Share from "~/models/Share";
import Badge from "~/components/Badge";
import { HEADER_HEIGHT } from "~/components/Header";
@@ -11,6 +13,7 @@ import {
SortableTable,
} from "~/components/SortableTable";
import { type Column as TableColumn } from "~/components/Table";
import Text from "~/components/Text";
import { UserLabel } from "~/components/UserLabel";
import { ContextMenu } from "~/components/Menu/ContextMenu";
import { ActionContextProvider } from "~/hooks/useActionContext";
@@ -19,6 +22,7 @@ import Time from "~/components/Time";
import ShareMenu from "~/menus/ShareMenu";
import { useFormatNumber } from "~/hooks/useFormatNumber";
import useStores from "~/hooks/useStores";
import useUserLocale from "~/hooks/useUserLocale";
import ShareSelectionToolbar from "./ShareSelectionToolbar";
const ROW_HEIGHT = 50;
@@ -50,6 +54,7 @@ export function SharesTable({ data, canManage, ...rest }: Props) {
const { t } = useTranslation();
const formatNumber = useFormatNumber();
const { policies } = useStores();
const userLocale = useUserLocale();
const hasDomain = data.some((share) => share.domain);
const isRowSelectable = useCallback(
@@ -115,6 +120,29 @@ export function SharesTable({ data, canManage, ...rest }: Props) {
) : null,
width: "2fr",
},
{
type: "data",
id: "expiresAt",
header: t("Expires"),
accessor: (share) => share.expiresAt,
component: (share) =>
!share.expiresAt ? (
<Text type="tertiary">{t("No expiry")}</Text>
) : share.isExpired ? (
<Text type="danger">
{t("Expired")} <Time dateTime={share.expiresAt} addSuffix />
</Text>
) : (
<Text type="tertiary">
<Time dateTime={share.expiresAt}>
{formatDate(Date.parse(share.expiresAt), "MMM dd, yyyy", {
locale: dateLocale(userLocale),
})}
</Time>
</Text>
),
width: "2fr",
},
hasDomain
? {
type: "data",
@@ -143,7 +171,7 @@ export function SharesTable({ data, canManage, ...rest }: Props) {
}
: undefined,
]),
[t, hasDomain, canManage, formatNumber]
[t, userLocale, hasDomain, canManage, formatNumber]
);
return (
+7 -4
View File
@@ -130,7 +130,7 @@ export default class AuthStore extends Store<Team> {
if (this.authenticated) {
if (isNil(newData.user)) {
void this.logout({
savePath: false,
savePath: "tab",
clearCache: false,
revokeToken: false,
});
@@ -338,7 +338,8 @@ export default class AuthStore extends Store<Team> {
*
* @param clearCache Whether to clear the IndexedDB databases used for document caching.
* @param revokeToken Whether the auth token should attempt to be revoked, this should be
* @param savePath Whether the current path should be saved and returned to after login.
* @param savePath Whether the current path should be saved and returned to after login,
* "tab" saves it for the current tab only.
* @param userInitiated Whether the logout was initiated by the user.
* disabled with requests from ApiClient to prevent infinite loops.
*/
@@ -351,13 +352,15 @@ export default class AuthStore extends Store<Team> {
}: {
clearCache?: boolean;
revokeToken?: boolean;
savePath?: boolean;
savePath?: boolean | "tab";
userInitiated?: boolean;
}) => {
// if this logout was forced from an authenticated route then
// save the current path so we can go back there once signed in
if (savePath) {
setPostLoginPath(window.location.pathname + window.location.search);
setPostLoginPath(window.location.pathname + window.location.search, {
tabOnly: savePath === "tab",
});
}
if (revokeToken) {
+7 -3
View File
@@ -21,7 +21,8 @@ import { subtractDate } from "@shared/utils/date";
import { bytesToHumanReadable } from "@shared/utils/files";
import naturalSort from "@shared/utils/naturalSort";
import type RootStore from "~/stores/RootStore";
import Store from "~/stores/base/Store";
import type { PaginatedResponse } from "~/stores/base/Store";
import Store, { PAGINATION_SYMBOL } from "~/stores/base/Store";
import Document from "~/models/Document";
import env from "~/env";
import type {
@@ -510,7 +511,9 @@ export default class DocumentsStore extends Store<Document> {
};
@action
search = async (options: SearchParams): Promise<SearchResult[]> => {
search = async (
options: SearchParams
): Promise<PaginatedResponse<SearchResult>> => {
const compactedOptions = omitBy(options, (o) => !o);
const res = await client.post("/documents.search", {
...compactedOptions,
@@ -525,7 +528,7 @@ export default class DocumentsStore extends Store<Document> {
// store a reference to the document model in the search cache instead
// of the original result from the API.
const results: SearchResult[] = compact(
const results: PaginatedResponse<SearchResult> = compact(
res.data.map((result: SearchResult) => {
const document = this.data.get(result.document.id);
if (!document) {
@@ -539,6 +542,7 @@ export default class DocumentsStore extends Store<Document> {
};
})
);
results[PAGINATION_SYMBOL] = res.pagination;
return results;
};
+1 -13
View File
@@ -47,19 +47,7 @@ export default class RevisionsStore extends Store<Revision> {
*/
fetchLatest = async (documentId: string): Promise<Revision> => {
const id = RevisionHelper.latestId(documentId);
const inflight = this.requests.get(id);
if (inflight) {
return inflight;
}
const promise = this.requestLatest(documentId);
this.requests.set(id, promise);
try {
return await promise;
} finally {
this.requests.delete(id);
}
return this.fetches.run(id, () => this.requestLatest(documentId));
};
private async requestLatest(documentId: string): Promise<Revision> {
+29 -27
View File
@@ -22,6 +22,7 @@ import { type JSONObject } from "@shared/types";
import type RootStore from "~/stores/RootStore";
import type Policy from "~/models/Policy";
import type ArchivableModel from "~/models/base/ArchivableModel";
import { KeyedCoalescedFetch } from "~/models/base/CoalescedFetch";
import type Model from "~/models/base/Model";
import { LifecycleManager } from "~/models/decorators/Lifecycle";
import { getInverseRelationsForModelClass } from "~/models/decorators/Relation";
@@ -89,8 +90,8 @@ export default abstract class Store<T extends Model> {
@observable
isLoaded = false;
// oxlint-disable-next-line no-explicit-any
requests: Map<string, Promise<any>> = new Map();
/** Calls to `Model.loadRelations` that are in flight, keyed by model id. */
relationFetches = new KeyedCoalescedFetch<unknown>();
model: ModelClass<T>;
@@ -488,25 +489,24 @@ export default abstract class Store<T extends Model> {
return item;
}
if (this.requests.has(id)) {
return this.requests.get(id);
}
return this.fetches.run(
id,
async () => {
runInAction(() => {
this.isFetching = true;
});
this.isFetching = true;
try {
const res = await client.post(`/${this.apiEndpoint}.info`, {
id,
});
const promise = new Promise<T>((resolve, reject) => {
client
.post(`/${this.apiEndpoint}.info`, {
id,
})
.then((res) =>
runInAction(() => {
return runInAction(() => {
invariant(res?.data, "Data should be available");
this.addPolicies(res.policies);
resolve(this.add(accessor(res)));
})
)
.catch((err) => {
return this.add(accessor(res));
});
} catch (err) {
if (
err instanceof AuthorizationError ||
err instanceof NotFoundError
@@ -514,16 +514,15 @@ export default abstract class Store<T extends Model> {
this.remove(id);
}
reject(err);
})
.finally(() => {
this.requests.delete(id);
this.isFetching = false;
});
});
this.requests.set(id, promise);
return promise;
throw err;
} finally {
runInAction(() => {
this.isFetching = false;
});
}
},
Boolean(options.force)
);
}
// Not annotated: subclasses replace this field, and MobX makes an annotated
@@ -686,6 +685,9 @@ export default abstract class Store<T extends Model> {
}
}
/** Requests by `fetch` that are in flight, keyed by model id. */
protected fetches = new KeyedCoalescedFetch<T>();
/** Results of `fetchAll` calls keyed by their params, see `fetchAllIfNeeded`. */
private fetchAllResults = new Map<string, PaginatedResponse<T>>();
}
+25
View File
@@ -1,5 +1,6 @@
import i18n from "i18next";
import de_DE from "../../shared/i18n/locales/de_DE/translation.json";
import en_GB from "../../shared/i18n/locales/en_GB/translation.json";
import en_US from "../../shared/i18n/locales/en_US/translation.json";
import pt_PT from "../../shared/i18n/locales/pt_PT/translation.json";
@@ -87,3 +88,27 @@ describe("i18n env is pt-PT", () => {
expect(i18n.t("Saving")).toBe("Speichert");
});
});
describe("translations without entries that match their key", () => {
beforeAll(async () => {
i18n.addResources(
"en-GB",
"translation",
Object.fromEntries(
Object.entries(en_GB).filter(([key, value]) => key !== value)
)
);
await i18n.changeLanguage("en-GB");
});
it("should show the key", () => expect(i18n.t("Saving")).toBe("Saving"));
it("should keep plurals", () => {
expect(i18n.t("{{ count }} document starred", { count: 1 })).toBe(
"1 document marked with a star"
);
expect(i18n.t("{{ count }} document starred", { count: 2 })).toBe(
"2 documents marked with a star"
);
});
});
+4 -1
View File
@@ -42,7 +42,10 @@ export function initI18n(defaultLanguage = "en_US") {
useSuspense: false,
},
lng,
fallbackLng: lng,
// Keys are the English strings, and the server omits entries that match
// their key, so a missing entry must show the key.
fallbackLng: false,
supportedLngs: languages.map(unicodeCLDRtoBCP47),
keySeparator: false,
returnNull: false,
+33 -1
View File
@@ -1,4 +1,6 @@
import { detectLanguage } from "./language";
import i18n from "i18next";
import Desktop from "./Desktop";
import { changeLanguage, detectLanguage } from "./language";
describe("detectLanguage", () => {
const mockLanguage = (language: string) =>
@@ -32,3 +34,33 @@ describe("detectLanguage", () => {
expect(detectLanguage()).toBe("zh_TW");
});
});
describe("changeLanguage", () => {
const setSpellCheckerLanguages = vi.fn();
const bridge = Desktop.bridge;
beforeEach(() => {
setSpellCheckerLanguages.mockClear();
i18n.addResourceBundle("de-DE", "translation", {});
Desktop.bridge = {
setSpellCheckerLanguages,
} as unknown as typeof Desktop.bridge;
});
afterEach(() => {
Desktop.bridge = bridge;
});
it("should set the spellchecker when the language is unchanged", async () => {
await i18n.changeLanguage("de-DE");
await changeLanguage("de_DE", i18n);
expect(setSpellCheckerLanguages).toHaveBeenCalledWith(["en-US", "de-DE"]);
});
it("should keep the current language for an unsupported language", async () => {
await i18n.changeLanguage("de-DE");
await changeLanguage("ar_EG", i18n);
expect(i18n.languages).toEqual(["de-DE"]);
expect(setSpellCheckerLanguages).not.toHaveBeenCalled();
});
});
+15 -5
View File
@@ -1,4 +1,5 @@
import type { i18n } from "i18next";
import { languages } from "@shared/i18n";
import type { locales } from "@shared/utils/date";
import { unicodeCLDRtoBCP47 } from "@shared/utils/date";
import { isRTLLanguage } from "@shared/utils/rtl";
@@ -27,7 +28,7 @@ export function detectLanguage() {
/**
* Changes the language of the app, and updates the spellchecker language
* if running in the desktop shell.
* if running in the desktop shell. An unsupported language is ignored.
*
* @param locale The locale to change to, in CLDR format (en_US)
* @param instance The i18n instance to use
@@ -36,16 +37,25 @@ export async function changeLanguage(
locale: string | null | undefined,
instance: i18n
) {
const language = languages.find((value) => value === locale);
// An unsupported language keeps the current language.
if (!language) {
return;
}
// Languages are stored in en_US format in the database, however the
// frontend translation framework (i18next) expects en-US
const localeBCP = locale ? unicodeCLDRtoBCP47(locale) : undefined;
const localeBCP = unicodeCLDRtoBCP47(language);
if (localeBCP && instance.languages?.[0] !== localeBCP) {
if (instance.languages?.[0] !== localeBCP) {
await instance.changeLanguage(localeBCP);
await Desktop.bridge?.setSpellCheckerLanguages(["en-US", localeBCP]);
}
// i18n can start in this locale, so set the spellchecker in all cases.
await Desktop.bridge?.setSpellCheckerLanguages(["en-US", localeBCP]);
if (typeof document !== "undefined") {
document.documentElement.dir = isRTLLanguage(locale) ? "rtl" : "ltr";
document.documentElement.dir = isRTLLanguage(language) ? "rtl" : "ltr";
}
}
+4 -2
View File
@@ -2,12 +2,14 @@ services:
redis:
image: redis
ports:
- "127.0.0.1:6379:6379"
# Set REDIS_PORT in .env to run alongside another checkout.
- "127.0.0.1:${REDIS_PORT:-6379}:6379"
user: "redis:redis"
postgres:
image: postgres
ports:
- "127.0.0.1:5432:5432"
# Set POSTGRES_PORT in .env to run alongside another checkout.
- "127.0.0.1:${POSTGRES_PORT:-5432}:5432"
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
+21 -22
View File
@@ -42,7 +42,7 @@
"url": "https://github.com/sponsors/outline"
},
"engines": {
"node": ">=22.23.4 <23 || >=24.22.1 <25 || >=26.12.1 <27"
"node": ">=22.23.5 <23 || >=24.22.3 <25 || >=26.13.1 <27"
},
"repository": {
"type": "git",
@@ -52,12 +52,12 @@
"> 0.25%, not dead"
],
"dependencies": {
"@aws-sdk/client-s3": "^3.1159.0",
"@aws-sdk/cloudfront-signer": "^3.1157.0",
"@aws-sdk/lib-storage": "^3.1159.0",
"@aws-sdk/s3-presigned-post": "^3.1159.0",
"@aws-sdk/s3-request-presigner": "^3.1159.0",
"@aws-sdk/signature-v4-crt": "^3.1159.0",
"@aws-sdk/client-s3": "^3.1162.0",
"@aws-sdk/cloudfront-signer": "^3.1161.0",
"@aws-sdk/lib-storage": "^3.1162.0",
"@aws-sdk/s3-presigned-post": "^3.1162.0",
"@aws-sdk/s3-request-presigner": "^3.1162.0",
"@aws-sdk/signature-v4-crt": "^3.1162.0",
"@benrbray/prosemirror-math": "^0.2.2",
"@bull-board/api": "^6.21.3",
"@bull-board/koa": "^6.21.3",
@@ -70,13 +70,12 @@
"@emoji-mart/data": "^1.2.1",
"@emotion/is-prop-valid": "^1.4.0",
"@fast-csv/parse": "^5.0.8",
"@firecrawl/pdf-inspector": "^1.11.2",
"@firecrawl/pdf-inspector": "^1.25.2",
"@fortawesome/fontawesome-svg-core": "^7.3.1",
"@fortawesome/free-brands-svg-icons": "^7.3.1",
"@fortawesome/free-solid-svg-icons": "^7.3.1",
"@fortawesome/react-fontawesome": "^3.5.0",
"@getoutline/react-roving-tabindex": "^3.2.4",
"@gitbeaker/rest": "^43.8.0",
"@hocuspocus/extension-redis": "1.1.3",
"@hocuspocus/extension-throttle": "1.1.3",
"@hocuspocus/provider": "1.1.3",
@@ -113,7 +112,7 @@
"@simplewebauthn/server": "^13.3.3",
"@socket.io/redis-adapter": "^8.3.0",
"@tanstack/react-table": "^8.21.3",
"@tanstack/react-virtual": "^3.14.23",
"@tanstack/react-virtual": "^3.14.26",
"@types/mailparser": "^3.9.0",
"@vitejs/plugin-react": "^6.1.2",
"async-sema": "^3.1.1",
@@ -151,8 +150,8 @@
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6",
"i18next": "^22.5.1",
"i18next-fs-backend": "^2.6.9",
"i18next-http-backend": "^4.0.9",
"i18next-fs-backend": "^2.6.10",
"i18next-http-backend": "^4.0.10",
"invariant": "^2.2.4",
"ioredis": "^5.11.1",
"ipaddr.js": "^2.5.0",
@@ -183,7 +182,7 @@
"mobx-utils": "^6.1.1",
"natural-sort": "^1.0.0",
"node-fetch": "2.7.0",
"nodemailer": "^10.0.9",
"nodemailer": "^10.3.1",
"octokit": "^5.0.5",
"outline-icons": "^4.6.0",
"pako": "^3.0.2",
@@ -217,20 +216,20 @@
"proxy-from-env": "^1.1.0",
"query-string": "^9.5.0",
"rate-limiter-flexible": "^11.2.3",
"react": "^19.3.0",
"react": "^19.3.1",
"react-avatar-editor": "^15.1.0",
"react-colorful": "^5.8.0",
"react-colorful": "^5.8.1",
"react-day-picker": "^8.10.2",
"react-dom": "^19.3.0",
"react-dom": "^19.3.1",
"react-dropzone": "^20.1.4",
"react-hook-form": "^7.85.0",
"react-i18next": "^12.3.1",
"react-is": "^19.3.0",
"react-is": "^19.3.1",
"react-merge-refs": "^3.0.2",
"react-remove-scroll": "^2.7.2",
"react-router-dom": "^5.3.4",
"react-use-measure": "^2.1.7",
"react-window": "^2.3.4",
"react-window": "^2.5.3",
"react-zoom-pan-pinch": "^3.7.0",
"reflect-metadata": "^0.2.2",
"refractor": "^5.0.0",
@@ -272,7 +271,7 @@
"@faker-js/faker": "^10.6.0",
"@relative-ci/agent": "^4.3.1",
"@swc/cli": "^0.8.2",
"@swc/core": "^1.16.20",
"@swc/core": "^1.16.22",
"@types/cookie": "0.6.0",
"@types/diff": "^5.0.9",
"@types/escape-html": "^1.0.4",
@@ -321,7 +320,7 @@
"browserslist-to-esbuild": "^1.2.0",
"concurrently": "^8.2.2",
"discord-api-types": "^0.38.48",
"fake-indexeddb": "^6.2.6",
"fake-indexeddb": "^6.2.8",
"husky": "^9.1.7",
"i18next-parser": "^9.4.0",
"ioredis-mock": "^8.13.1",
@@ -329,7 +328,7 @@
"msw": "^2.15.0",
"oxfmt": "0.73.0",
"oxlint": "1.90.0",
"oxlint-tsgolint": "7.0.2005",
"oxlint-tsgolint": "7.0.2006",
"react-refresh": "^0.19.0",
"rimraf": "^6.1.3",
"rollup-plugin-webpack-stats": "^3.1.3",
@@ -354,6 +353,6 @@
"deepmerge-ts@npm:^7.1.5": "^8.0.1",
"i18next-parser/i18next": "^23.16.8"
},
"version": "1.12.0",
"version": "1.13.0",
"packageManager": "yarn@4.18.0"
}
+8 -54
View File
@@ -23,10 +23,7 @@ import {
import config from "../../plugin.json";
import env from "../env";
import { createContext } from "@server/context";
import fetch from "@server/utils/fetch";
import UploadUserAvatarTask from "@server/queues/tasks/UploadUserAvatarTask";
import AttachmentHelper from "@server/models/helpers/AttachmentHelper";
import { AttachmentPreset } from "@shared/types";
import { UserFlag } from "@server/models/User";
import { getEmailVerified } from "./getEmailVerified";
import { MicrosoftGraphError } from "../errors";
@@ -34,45 +31,6 @@ import { MicrosoftGraphError } from "../errors";
const router = new Router();
const scopes: string[] = [];
/**
* Loads the user's profile photo from the Microsoft Graph API and encodes it as
* a data URL. Entra ID does not emit a `picture` claim in the ID token, so the
* photo is only available via Graph. Requires no additional permissions beyond
* the delegated `User.Read` already used to load the profile.
*
* @param accessToken The delegated access token for the Microsoft Graph API.
* @returns A base64 encoded data URL for the photo, or undefined if not set.
*/
async function requestPhoto(accessToken: string): Promise<string | undefined> {
try {
const response = await fetch(
"https://graph.microsoft.com/v1.0/me/photo/$value",
{
method: "GET",
allowPrivateIPAddress: true,
// Cap how long we'll wait and how many bytes we'll buffer so a slow or
// oversized response can never stall the login callback.
timeout: 10000,
size: AttachmentHelper.presetToMaxUploadSize(AttachmentPreset.Avatar),
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
// A missing photo returns 404, which we can safely ignore.
if (!response.ok) {
return undefined;
}
const contentType = response.headers.get("content-type") ?? "image/jpeg";
const buffer = await response.buffer();
return `data:${contentType};base64,${buffer.toString("base64")}`;
} catch (_err) {
return undefined;
}
}
if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) {
const strategy = new AzureStrategy(
{
@@ -194,22 +152,18 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) {
scopes,
},
});
// Entra ID does not include the photo in the token, so it must be
// fetched separately from Graph. To avoid the extra round-trip on every
// sign-in we only do so when the user has no avatar yet and hasn't set
// one manually — this also backfills accounts created before avatar
// syncing was supported, and stops once an avatar is stored.
// Entra ID does not include the photo in the token, so it is loaded
// from Graph in the background when the user has no avatar yet.
if (
result.authentication &&
!result.user.avatarUrl &&
!result.user.getFlag(UserFlag.AvatarUpdated)
) {
const avatarUrl = await requestPhoto(accessToken);
if (avatarUrl) {
await new UploadUserAvatarTask().schedule({
userId: result.user.id,
avatarUrl,
});
}
await new UploadUserAvatarTask().schedule({
userId: result.user.id,
avatarUrl: "https://graph.microsoft.com/v1.0/me/photo/$value",
userAuthenticationId: result.authentication.id,
});
}
return done(null, result.user, { ...result, client });
+3 -3
View File
@@ -131,7 +131,7 @@ export class GitHubIssueProvider extends BaseIssueProvider {
required: true,
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: Integration },
});
const authentication = integration.authentication;
@@ -172,7 +172,7 @@ export class GitHubIssueProvider extends BaseIssueProvider {
"settings.github.installation.id": installationId,
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
if (!integration) {
@@ -241,7 +241,7 @@ export class GitHubIssueProvider extends BaseIssueProvider {
"settings.github.installation.id": installationId,
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
if (!integration) {
+5 -5
View File
@@ -142,7 +142,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
const integration = (await Integration.findOne({
where,
replacements: { jsonCondition },
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
})) as Integration<IntegrationType.Embed>;
@@ -213,7 +213,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
const integrations = (await Integration.findAll({
where: whereCondition,
replacements,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
})) as Integration<IntegrationType.Embed>[];
@@ -257,7 +257,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
replacements: {
projectJson: JSON.stringify([{ id: String(payload.project_id) }]),
},
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
});
@@ -303,7 +303,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
...(teamId ? { teamId } : {}),
"settings.gitlab.installation.account.id": payload.user_id,
},
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
})) as Integration<IntegrationType.Embed>;
@@ -354,7 +354,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
replacements: {
projectJson: JSON.stringify([{ id: String(payload.project_id) }]),
},
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
});
+1 -1
View File
@@ -269,7 +269,7 @@ router.get(
account: {
id: userInfo.id,
name: userInfo.username,
avatarUrl: userInfo.avatar_url,
avatarUrl: userInfo.avatar_url ?? "",
},
},
},
+238
View File
@@ -0,0 +1,238 @@
import { randomUUID } from "node:crypto";
import { addHours, subHours } from "date-fns";
import { http, HttpResponse } from "msw";
import { IntegrationService, IntegrationType } from "@shared/types";
import { Integration, IntegrationAuthentication } from "@server/models";
import { buildUser } from "@server/test/factories";
import { server } from "@server/test/msw";
import { GitLab } from "./gitlab";
const author = { id: 7, username: "octo", avatar_url: "https://a.test/a.png" };
const buildBaseUrl = () => `https://${randomUUID()}.example.com`;
async function buildGitLabIntegration({
teamId,
userId,
url,
expiresAt = addHours(new Date(), 1),
}: {
teamId: string;
userId: string;
url: string;
expiresAt?: Date;
}) {
const authentication = await IntegrationAuthentication.create({
service: IntegrationService.GitLab,
userId,
teamId,
clientId: "client-id",
clientSecret: "client-secret",
token: "token",
refreshToken: "refresh",
expiresAt,
});
const integration = await Integration.create({
service: IntegrationService.GitLab,
type: IntegrationType.Embed,
userId,
teamId,
authenticationId: authentication.id,
settings: { gitlab: { url } },
});
return { integration, authentication };
}
describe("GitLab", () => {
describe("getIssue", () => {
it("should request the issue with an encoded project path", async () => {
const customUrl = buildBaseUrl();
let requestUrl: URL | undefined;
let authorization: string | null = null;
server.use(
http.get(
`${customUrl}/api/v4/projects/:project/issues`,
({ request }) => {
requestUrl = new URL(request.url);
authorization = request.headers.get("authorization");
return HttpResponse.json([
{
iid: 12,
title: "Fix it",
description: "Details",
web_url: `${customUrl}/group/repo/-/issues/12`,
state: "opened",
author,
labels: [{ name: "bug", color: "#ff0000" }],
created_at: "2026-01-01T00:00:00Z",
},
]);
}
)
);
const issue = await GitLab.getIssue({
accessToken: "token",
customUrl,
path: "group/repo",
id: 12,
});
expect(issue.title).toEqual("Fix it");
expect(requestUrl?.pathname).toEqual(
"/api/v4/projects/group%2Frepo/issues"
);
expect(requestUrl?.searchParams.get("iids[]")).toEqual("12");
expect(authorization).toEqual("Bearer token");
});
});
describe("getProjects", () => {
it("should follow pagination", async () => {
const user = await buildUser();
const pages: (string | null)[] = [];
server.use(
http.get("https://gitlab.com/api/v4/projects", ({ request }) => {
const page = new URL(request.url).searchParams.get("page");
pages.push(page);
return HttpResponse.json(
[
{
id: Number(page),
name: `project-${page}`,
namespace: { id: 1, full_path: "group" },
},
],
{ headers: { "x-next-page": page === "1" ? "2" : "" } }
);
})
);
const projects = await GitLab.getProjects({
accessToken: "token",
teamId: user.teamId,
});
expect(pages).toEqual(["1", "2"]);
expect(projects.map((project) => project.name)).toEqual([
"project-1",
"project-2",
]);
});
});
describe("unfurl", () => {
it("should refresh an expired token and use the new token", async () => {
const user = await buildUser();
const customUrl = buildBaseUrl();
const { authentication } = await buildGitLabIntegration({
teamId: user.teamId,
userId: user.id,
url: customUrl,
expiresAt: subHours(new Date(), 1),
});
let tokenRequest: Record<string, string> | undefined;
let authorization: string | null = null;
server.use(
http.post(`${customUrl}/oauth/token`, async ({ request }) => {
tokenRequest = (await request.json()) as Record<string, string>;
return HttpResponse.json({
access_token: "new-token",
token_type: "Bearer",
expires_in: 7200,
refresh_token: "new-refresh",
scope: "read_api read_user",
created_at: 0,
});
}),
http.get(
`${customUrl}/api/v4/projects/:project/merge_requests/5`,
({ request }) => {
authorization = request.headers.get("authorization");
return HttpResponse.json({
iid: 5,
title: "Change",
web_url: `${customUrl}/group/repo/-/merge_requests/5`,
state: "opened",
author,
created_at: "2026-01-01T00:00:00Z",
});
}
)
);
const result = await GitLab.unfurl(
`${customUrl}/group/repo/-/merge_requests/5`,
user
);
expect(result).toMatchObject({ title: "Change" });
expect(tokenRequest).toMatchObject({
grant_type: "refresh_token",
refresh_token: "refresh",
client_id: "client-id",
client_secret: "client-secret",
});
expect(authorization).toEqual("Bearer new-token");
await authentication.reload();
expect(authentication.token).toEqual("new-token");
expect(authentication.refreshToken).toEqual("new-refresh");
});
it("should unfurl a project without progress when statistics fail", async () => {
const user = await buildUser();
const customUrl = buildBaseUrl();
await buildGitLabIntegration({
teamId: user.teamId,
userId: user.id,
url: customUrl,
});
server.use(
http.get(`${customUrl}/api/v4/projects/:project`, () =>
HttpResponse.json({
id: 1,
name: "repo",
web_url: `${customUrl}/group/repo`,
visibility: "public",
created_at: "2026-01-01T00:00:00Z",
})
),
http.get(
`${customUrl}/api/v4/projects/:project/issues_statistics`,
() => HttpResponse.json({}, { status: 500 })
)
);
const result = await GitLab.unfurl(`${customUrl}/group/repo`, user);
expect(result).toMatchObject({ name: "repo", progress: undefined });
});
it("should not return the response body of a failed request", async () => {
const user = await buildUser();
const customUrl = buildBaseUrl();
await buildGitLabIntegration({
teamId: user.teamId,
userId: user.id,
url: customUrl,
});
server.use(
http.get(`${customUrl}/api/v4/projects/:project/merge_requests/5`, () =>
HttpResponse.json({ message: "secret" }, { status: 500 })
)
);
const result = await GitLab.unfurl(
`${customUrl}/group/repo/-/merge_requests/5`,
user
);
expect(result).toEqual({
error:
"Error while requesting /projects/group%2Frepo/merge_requests/5 from GitLab; status: 500",
});
});
});
});
+291 -177
View File
@@ -1,12 +1,3 @@
import { Gitlab } from "@gitbeaker/rest";
import type {
EpicSchema,
IssueSchemaWithExpandedLabels,
MergeRequestSchema,
ProjectSchema,
SimpleLabelSchema,
StatisticsSchema,
} from "@gitbeaker/rest";
import z from "zod";
import {
type IntegrationType,
@@ -14,6 +5,7 @@ import {
UnfurlResourceType,
} from "@shared/types";
import { toError, errToString } from "@shared/utils/error";
import { Second } from "@shared/utils/time";
import Logger from "@server/logging/Logger";
import type { User } from "@server/models";
import { Integration, IntegrationAuthentication } from "@server/models";
@@ -22,8 +14,7 @@ import type {
UnfurlProject,
UnfurlSignature,
} from "@server/types";
import fetch from "@server/utils/fetch";
import { validateUrlNotPrivate } from "@server/utils/url";
import fetch, { type Headers } from "@server/utils/fetch";
import { GitLabUtils } from "../shared/GitLabUtils";
import env from "./env";
@@ -36,10 +27,97 @@ const AccessTokenResponseSchema = z.object({
created_at: z.number(),
});
export class GitLab {
private static clientSecret = env.GITLAB_CLIENT_SECRET;
private static clientId = env.GITLAB_CLIENT_ID;
const UserSchema = z.object({
id: z.number(),
username: z.string(),
avatar_url: z.string().nullish(),
});
const LabelSchema = z.object({
name: z.string(),
color: z.string(),
});
const IssueSchema = z.object({
iid: z.number(),
title: z.string(),
description: z.string().nullish(),
web_url: z.string(),
state: z.string(),
author: UserSchema.nullish(),
labels: z.array(LabelSchema),
created_at: z.string(),
});
// Epics are returned without label color details.
const EpicSchema = IssueSchema.extend({
labels: z.array(z.string()),
});
const MergeRequestSchema = z.object({
iid: z.number(),
title: z.string(),
description: z.string().nullish(),
web_url: z.string(),
state: z.string(),
author: UserSchema,
draft: z.boolean().nullish(),
merged_at: z.string().nullish(),
created_at: z.string(),
});
const NamespaceSchema = z.object({
id: z.number(),
full_path: z.string(),
});
const SimpleProjectSchema = z.object({
id: z.number(),
name: z.string(),
namespace: NamespaceSchema,
});
const ProjectSchema = z.object({
id: z.number(),
name: z.string(),
description: z.string().nullish(),
web_url: z.string(),
avatar_url: z.string().nullish(),
visibility: z.string().nullish(),
owner: z
.object({ name: z.string(), avatar_url: z.string().nullish() })
.nullish(),
topics: z.array(z.string()).nullish(),
created_at: z.string(),
});
const IssueStatisticsSchema = z.object({
statistics: z.object({
counts: z.object({
opened: z.number(),
closed: z.number(),
}),
}),
});
type Issue = z.infer<typeof IssueSchema>;
type Epic = z.infer<typeof EpicSchema>;
type MergeRequest = z.infer<typeof MergeRequestSchema>;
type SimpleProject = z.infer<typeof SimpleProjectSchema>;
type Project = z.infer<typeof ProjectSchema>;
type IssueStatistics = z.infer<typeof IssueStatisticsSchema>;
interface RequestParams {
accessToken: string;
customUrl?: string;
}
interface ResourceParams extends RequestParams {
path: string;
id: number;
}
export class GitLab {
/**
* Fetches the custom GitLab URL for a team from the first matching
* integration, falling back to the default.
@@ -58,93 +136,90 @@ export class GitLab {
return url || GitLabUtils.defaultGitlabUrl;
}
/**
* Creates a Gitbeaker client instance.
*
* @param accessToken - The access token for authentication.
* @param customUrl - Optional custom GitLab URL from integration settings.
* @returns A configured Gitbeaker client.
*/
public static async createClient(accessToken: string, customUrl?: string) {
const host = customUrl || GitLabUtils.defaultGitlabUrl;
// Validate the URL to prevent SSRF as GitLab instance does not use our
// fetch wrapper which has built-in SSRF protection.
await validateUrlNotPrivate(host);
return new Gitlab({
host,
oauthToken: accessToken,
});
}
/**
* Fetches an issue from a GitLab project.
*
* @param accessToken - The access token for authentication.
* @param projectPath - The project path (owner/repo).
* @param issueIid - The issue IID (internal ID within the project).
* @param customUrl - Optional custom GitLab URL from integration settings.
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The project path (owner/repo).
* @param params.id - The issue IID (internal ID within the project).
* @returns The issue data.
* @throws If the issue does not exist.
*/
public static async getIssue(
accessToken: string,
projectPath: string,
issueIid: number,
customUrl?: string
) {
const client = await this.createClient(accessToken, customUrl);
const issues = await client.Issues.all({
projectId: projectPath,
iids: [issueIid],
withLabelsDetails: true,
public static async getIssue({ path, id, ...params }: ResourceParams) {
const { data } = await this.request({
...params,
path: `/projects/${encodeURIComponent(path)}/issues?iids[]=${id}&with_labels_details=true`,
schema: z.array(IssueSchema),
});
if (!issues || issues.length === 0) {
throw new Error(`Issue ${issueIid} not found in project ${projectPath}`);
if (data.length === 0) {
throw new Error(`Issue ${id} not found in project ${path}`);
}
return issues[0];
return data[0];
}
/**
* Fetches an epic from a GitLab group.
*
* @param accessToken - The access token for authentication.
* @param groupPath - The full path of the group.
* @param epicIid - The epic IID (internal ID within the group).
* @param customUrl - Optional custom GitLab URL from integration settings.
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The full path of the group.
* @param params.id - The epic IID (internal ID within the group).
* @returns The epic data.
*/
public static async getEpic(
accessToken: string,
groupPath: string,
epicIid: number,
customUrl?: string
) {
const client = await this.createClient(accessToken, customUrl);
return client.Epics.show(groupPath, epicIid);
public static async getEpic({ path, id, ...params }: ResourceParams) {
const { data } = await this.request({
...params,
path: `/groups/${encodeURIComponent(path)}/epics/${id}`,
schema: EpicSchema,
});
return data;
}
/**
* Fetches a merge request from a GitLab project.
*
* @param accessToken - The access token for authentication.
* @param projectPath - The project path (owner/repo).
* @param mrIid - The merge request IID (internal ID within the project).
* @param customUrl - Optional custom GitLab URL from integration settings.
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The project path (owner/repo).
* @param params.id - The merge request IID (internal ID within the project).
* @returns The merge request data.
*/
public static async getMergeRequest(
accessToken: string,
projectPath: string,
mrIid: number,
customUrl?: string
) {
const client = await this.createClient(accessToken, customUrl);
const mr = await client.MergeRequests.show(projectPath, mrIid);
return mr;
public static async getMergeRequest({ path, id, ...params }: ResourceParams) {
const { data } = await this.request({
...params,
path: `/projects/${encodeURIComponent(path)}/merge_requests/${id}`,
schema: MergeRequestSchema,
});
return data;
}
/**
* Fetches a GitLab project and its issue statistics.
*
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The project path (owner/repo).
* @returns The project data and its issue statistics, if available.
*/
public static async getProject({
path,
...params
}: RequestParams & { path: string }) {
const projectPath = `/projects/${encodeURIComponent(path)}`;
const [project, issueStats] = await Promise.all([
this.request({ ...params, path: projectPath, schema: ProjectSchema }),
// Statistics can be slow for projects with many issues, so they are optional.
this.request({
...params,
path: `${projectPath}/issues_statistics`,
schema: IssueStatisticsSchema,
}).catch(() => undefined),
]);
return { project: project.data, issueStats: issueStats?.data };
}
/**
@@ -154,26 +229,21 @@ export class GitLab {
* @param params.customUrl - Optional custom GitLab URL. Falls back to default.
* @returns User information including the resolved URL.
*/
public static async getCurrentUser({
accessToken,
customUrl,
}: {
accessToken: string;
customUrl?: string;
}) {
const url = customUrl || GitLabUtils.defaultGitlabUrl;
const client = await this.createClient(accessToken, url);
const userData = await client.Users.showCurrentUser({
showExpanded: false,
public static async getCurrentUser(params: RequestParams) {
const url = params.customUrl || GitLabUtils.defaultGitlabUrl;
const { data } = await this.request({
...params,
path: "/user",
schema: UserSchema,
});
return { ...userData, url };
return { ...data, url };
}
/**
* Fetches projects accessible to the user.
* Fetches projects that the user can maintain.
*
* @param accessToken - Access token for authentication.
* @param params.accessToken - Access token for authentication.
* @param params.teamId - The team ID used to find the GitLab URL.
* @returns Array of projects.
*/
public static async getProjects({
@@ -184,13 +254,22 @@ export class GitLab {
teamId: string;
}) {
const customUrl = await this.getGitLabUrl(teamId);
const client = await this.createClient(accessToken, customUrl);
const projects: SimpleProject[] = [];
let page: string | null = "1";
for (let i = 0; i < this.maxPages && page; i++) {
const res: { data: SimpleProject[]; headers: Headers } =
await this.request({
accessToken,
customUrl,
// At least Maintainer access to reduce the sheer volume of projects.
path: `/projects?simple=true&min_access_level=40&per_page=100&page=${page}`,
schema: z.array(SimpleProjectSchema),
});
projects.push(...res.data);
page = res.headers.get("x-next-page");
}
const projects = await client.Projects.all({
simple: true,
perPage: 100,
minAccessLevel: 40, // At least Maintainer access to reduce the sheer volume of projects
});
return projects;
}
@@ -250,7 +329,7 @@ export class GitLab {
try {
const customUrl = matchedIntegration.settings?.gitlab?.url;
const { authentication } = matchedIntegration;
const token = await authentication.refreshTokenIfNeeded(
const accessToken = await authentication.refreshTokenIfNeeded(
async (refreshToken: string) =>
GitLab.refreshToken({
refreshToken,
@@ -265,41 +344,41 @@ export class GitLab {
resource.type === UnfurlResourceType.Issue &&
resource.scope === "group"
) {
const epic = await this.getEpic(
token,
resource.owner,
resource.id,
customUrl
);
const epic = await this.getEpic({
accessToken,
customUrl,
path: resource.owner,
id: resource.id,
});
return this.transformIssue(epic);
}
const projectPath = `${resource.owner}/${resource.repo}`;
const path = `${resource.owner}/${resource.repo}`;
if (resource.type === UnfurlResourceType.Issue) {
const issue = await this.getIssue(
token,
projectPath,
resource.id,
customUrl
);
const issue = await this.getIssue({
accessToken,
customUrl,
path,
id: resource.id,
});
return this.transformIssue(issue);
} else if (resource.type === UnfurlResourceType.PR) {
const mr = await this.getMergeRequest(
token,
projectPath,
resource.id,
customUrl
);
const mr = await this.getMergeRequest({
accessToken,
customUrl,
path,
id: resource.id,
});
return this.transformMR(mr);
} else if (resource.type === UnfurlResourceType.Project) {
const client = await this.createClient(token, customUrl);
const [project, issueStats] = await Promise.all([
client.Projects.show(projectPath),
client.IssuesStatistics.all({ projectId: projectPath }),
]);
const { project, issueStats } = await this.getProject({
accessToken,
customUrl,
path,
});
return this.transformProject(project, issueStats);
}
@@ -321,7 +400,7 @@ export class GitLab {
* @param params.clientSecret - Optional custom client secret (falls back to env var).
* @returns The parsed access token response.
*/
public static oauthAccess = async ({
public static async oauthAccess({
code,
customUrl,
clientId,
@@ -331,30 +410,61 @@ export class GitLab {
customUrl?: string;
clientId?: string;
clientSecret?: string;
}) => {
const url = customUrl || GitLabUtils.defaultGitlabUrl;
const res = await fetch(GitLabUtils.getOauthUrl(url) + "/token", {
method: "POST",
}) {
return this.requestToken(customUrl, {
code: code ?? "",
client_id: clientId || this.clientId || "",
client_secret: clientSecret || this.clientSecret || "",
grant_type: "authorization_code",
redirect_uri: GitLabUtils.callbackUrl(),
});
}
/** The time to wait for a response from a GitLab instance. */
private static timeout = 10 * Second.ms;
/** The maximum number of pages to fetch from a paginated endpoint. */
private static maxPages = 10;
private static clientSecret = env.GITLAB_CLIENT_SECRET;
private static clientId = env.GITLAB_CLIENT_ID;
/**
* Makes an authenticated GET request to the GitLab API.
*
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The API path, starting with a slash.
* @param params.schema - The schema to parse the response body with.
* @returns The parsed body and the response headers.
* @throws If the response status is not successful.
*/
private static async request<T extends z.ZodType>({
accessToken,
customUrl,
path,
schema,
}: RequestParams & { path: string; schema: T }) {
const baseUrl = customUrl || GitLabUtils.defaultGitlabUrl;
const res = await fetch(`${baseUrl}/api/v4${path}`, {
timeout: this.timeout,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
code,
client_id: clientId || this.clientId,
client_secret: clientSecret || this.clientSecret,
grant_type: "authorization_code",
redirect_uri: GitLabUtils.callbackUrl(),
}),
});
if (res.status !== 200) {
if (!res.ok) {
throw new Error(
`Error while validating oauth code from GitLab; status: ${res.status}`
`Error while requesting ${path} from GitLab; status: ${res.status}`
);
}
return AccessTokenResponseSchema.parse(await res.json());
};
// Read the body at once, a body left unread while awaiting other requests
// can be closed early.
return { data: schema.parse(await res.json()), headers: res.headers };
}
private static async refreshToken({
refreshToken,
@@ -367,39 +477,40 @@ export class GitLab {
clientId?: string;
clientSecret?: string;
}) {
const queryParams = new URLSearchParams({
client_id: clientId || this.clientId!,
client_secret: clientSecret || this.clientSecret!,
grant_type: "refresh_token",
return this.requestToken(customUrl, {
refresh_token: refreshToken,
client_id: clientId || this.clientId || "",
client_secret: clientSecret || this.clientSecret || "",
grant_type: "refresh_token",
redirect_uri: GitLabUtils.callbackUrl(),
});
}
private static async requestToken(
customUrl: string | undefined,
body: Record<string, string>
) {
const res = await fetch(`${GitLabUtils.getOauthUrl(customUrl)}/token`, {
method: "POST",
timeout: this.timeout,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(body),
});
const res = await fetch(
`${GitLabUtils.getOauthUrl(customUrl)}/token?${queryParams.toString()}`,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
}
);
const resJson = await res.json();
if (res.status !== 200) {
Logger.error("failed to refresh access token from GitLab", resJson);
throw new Error(
`Error while refreshing access token from GitLab; status: ${res.status}`
`Error while requesting access token from GitLab; status: ${res.status}`
);
}
return AccessTokenResponseSchema.parse(resJson);
return AccessTokenResponseSchema.parse(await res.json());
}
private static transformIssue(
issue: IssueSchemaWithExpandedLabels | EpicSchema
) {
const labels: (string | SimpleLabelSchema)[] = issue.labels;
private static transformIssue(issue: Issue | Epic) {
const labels: (string | z.infer<typeof LabelSchema>)[] = issue.labels;
return {
type: UnfurlResourceType.Issue,
@@ -411,7 +522,6 @@ export class GitLab {
name: issue.author?.username ?? "",
avatarUrl: issue.author?.avatar_url ?? "",
},
// Epics are returned without label color details.
labels: labels.map((label) =>
typeof label === "string"
? { name: label, color: GitLabUtils.defaultLabelColor }
@@ -425,8 +535,10 @@ export class GitLab {
} satisfies UnfurlIssueOrPR;
}
private static transformMR(mr: MergeRequestSchema) {
private static transformMR(mr: MergeRequest) {
const mrState = mr.merged_at ? "merged" : mr.state;
const draft = !!mr.draft;
return {
type: UnfurlResourceType.PR,
url: mr.web_url,
@@ -435,28 +547,30 @@ export class GitLab {
description: GitLabUtils.sanitizeGitLabMarkdown(mr.description) ?? "",
author: {
name: mr.author.username,
avatarUrl: mr.author.avatar_url,
avatarUrl: mr.author.avatar_url ?? "",
},
state: {
name: mrState,
color: GitLabUtils.getColorForStatus(mrState, !!mr.draft),
draft: mr.draft,
color: GitLabUtils.getColorForStatus(mrState, draft),
draft,
},
createdAt: mr.created_at,
} satisfies UnfurlIssueOrPR;
}
private static transformProject(
project: ProjectSchema,
issueStats: StatisticsSchema
project: Project,
issueStats?: IssueStatistics
) {
const visibility = project.visibility ?? "private";
const owner = project.owner as
| { name: string; avatar_url?: string }
| undefined;
const { opened, closed } = issueStats.statistics.counts;
const total = opened + closed;
const progress = total > 0 ? closed / total : 0;
const { owner } = project;
const counts = issueStats?.statistics.counts;
let progress: number | undefined;
if (counts) {
const total = counts.opened + counts.closed;
progress = total > 0 ? counts.closed / total : 0;
}
return {
type: UnfurlResourceType.Project,
@@ -477,7 +591,7 @@ export class GitLab {
name: visibility.charAt(0).toUpperCase() + visibility.slice(1),
color: GitLabUtils.getColorForVisibility(visibility),
},
labels: (project.topics ?? []).map((topic: string) => ({
labels: (project.topics ?? []).map((topic) => ({
name: topic,
color: GitLabUtils.defaultLabelColor,
})),
+1 -1
View File
@@ -13,7 +13,7 @@ PluginManager.add({
type: Hook.ImportSchema,
value: IntegrationImportBodySchema.extend({
service: z.literal(IntegrationService.Notion),
input: z.array(NotionImportInputItemSchema),
input: z.array(NotionImportInputItemSchema).min(1),
}),
});
@@ -259,6 +259,38 @@ describe("#passkeys.verifyRegistration", () => {
expect(body.message).toEqual("Invalid authentication type");
});
it("should consume the challenge on a failed attempt", async () => {
const team = await buildTeam({ passkeysEnabled: true });
const user = await buildUser({ teamId: team.id });
const options = await server.post(
"/auth/passkeys.generateRegistrationOptions",
user
);
const { data } = await options.json();
const failed = await server.post(
"/auth/passkeys.verifyRegistration",
user,
{
body: buildNoneAttestationResponse(
isoBase64URL.fromBuffer(randomBytes(32)),
data.rp.id
),
}
);
expect(failed.status).toEqual(400);
const res = await server.post("/auth/passkeys.verifyRegistration", user, {
body: buildNoneAttestationResponse(data.challenge, data.rp.id),
});
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toEqual(
"No registration challenge found or challenge expired"
);
});
it("should record the registration in the audit log", async () => {
const planSpy = vi
.spyOn(Team.prototype, "plan", "get")
@@ -290,3 +322,40 @@ describe("#passkeys.verifyRegistration", () => {
planSpy.mockRestore();
});
});
describe("#passkeys.verifyAuthentication", () => {
it("should consume the challenge on a failed attempt", async () => {
const options = await server.post(
"/auth/passkeys.generateAuthenticationOptions",
{ body: {} }
);
const { data } = await options.json();
const body = {
challengeId: data.challengeId,
id: "unknown",
rawId: "unknown",
response: {
authenticatorData: "",
clientDataJSON: "",
signature: "",
},
type: "public-key",
};
const failed = await server.post("/auth/passkeys.verifyAuthentication", {
body,
});
const failedBody = await failed.json();
expect(failed.status).toEqual(400);
expect(failedBody.message).toContain("Passkey not found");
const res = await server.post("/auth/passkeys.verifyAuthentication", {
body,
});
const resBody = await res.json();
expect(res.status).toEqual(400);
expect(resBody.message).toEqual(
"No authentication challenge found or challenge expired"
);
});
});
+4 -9
View File
@@ -157,8 +157,8 @@ router.post(
const body = ctx.input.body;
authorize(user, "createUserPasskey", user.team);
// Retrieve challenge from Redis
const expectedChallenge = await Redis.defaultClient.get(
// Consume the challenge atomically so it can only be used once
const expectedChallenge = await Redis.defaultClient.getdel(
getRegistrationChallengeKey(user.id)
);
@@ -238,8 +238,6 @@ router.post(
});
}
// Delete challenge from Redis
await Redis.defaultClient.del(getRegistrationChallengeKey(user.id));
ctx.body = { data: { verified: true } };
} else {
throw ValidationError("Verification failed");
@@ -301,8 +299,8 @@ router.post(
const body = ctx.input.body;
const { challengeId, client = Client.Web } = body;
// Retrieve challenge from Redis
const expectedChallenge = await Redis.defaultClient.get(
// Consume the challenge atomically so it can only be used once
const expectedChallenge = await Redis.defaultClient.getdel(
getAuthenticationChallengeKey(challengeId)
);
@@ -371,9 +369,6 @@ router.post(
passkey.lastActiveAt = new Date();
await passkey.save({ silent: true });
// Delete challenge from Redis
await Redis.defaultClient.del(getAuthenticationChallengeKey(challengeId));
// Use the signIn utility which handles all sign-in logic
await signIn(ctx, "passkeys", {
user,
@@ -1,5 +1,4 @@
import { uniq } from "es-toolkit/compat";
import { runInAction } from "mobx";
import { observer } from "mobx-react";
import { Trans, useTranslation } from "react-i18next";
import { toast } from "sonner";
@@ -30,16 +29,12 @@ function SlackListItem({ integration, collection }: Props) {
const { t } = useTranslation();
const handleChange = (eventName: string) => async (checked: boolean) => {
runInAction(() => {
if (checked) {
integration.events = uniq([...integration.events, eventName]);
} else {
integration.events = integration.events.filter((n) => n !== eventName);
}
await integration.save({
events: checked
? uniq([...integration.events, eventName])
: integration.events.filter((n) => n !== eventName),
});
await integration.save();
toast.success(t("Settings saved"));
};
@@ -121,7 +121,7 @@ router.post(
const webhookSubscription = await WebhookSubscription.findByPk(id, {
rejectOnEmpty: true,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: WebhookSubscription },
transaction,
});
@@ -152,7 +152,7 @@ router.post(
const webhookSubscription = await WebhookSubscription.findByPk(id, {
rejectOnEmpty: true,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: WebhookSubscription },
transaction,
});
@@ -137,6 +137,67 @@ describe("DeliverWebhookTask", () => {
expect(delivery.responseBody).toEqual("SUCCESS");
});
it("should truncate stored response bodies", async () => {
const subscription = await buildWebhookSubscription({
url: "http://example.com",
events: ["*"],
});
const signedInUser = await buildUser({ teamId: subscription.teamId });
captureWebhook(
"http://example.com",
() => new HttpResponse("a".repeat(5000), { status: 200 })
);
await new DeliverWebhookTask().perform({
subscriptionId: subscription.id,
event: {
name: "users.signin",
userId: signedInUser.id,
teamId: subscription.teamId,
actorId: signedInUser.id,
ip,
},
});
const delivery = await WebhookDelivery.findOne({
where: { webhookSubscriptionId: subscription.id },
rejectOnEmpty: true,
});
expect(delivery.status).toBe("success");
expect(delivery.responseBody).toEqual("a".repeat(1024));
});
it("should not read response bodies over the size limit", async () => {
const subscription = await buildWebhookSubscription({
url: "http://example.com",
events: ["*"],
});
const signedInUser = await buildUser({ teamId: subscription.teamId });
captureWebhook(
"http://example.com",
() => new HttpResponse("a".repeat(128 * 1024), { status: 200 })
);
await new DeliverWebhookTask().perform({
subscriptionId: subscription.id,
event: {
name: "users.signin",
userId: signedInUser.id,
teamId: subscription.teamId,
actorId: signedInUser.id,
ip,
},
});
const delivery = await WebhookDelivery.findOne({
where: { webhookSubscriptionId: subscription.id },
rejectOnEmpty: true,
});
expect(delivery.status).toBe("success");
expect(delivery.statusCode).toBe(200);
expect(delivery.responseBody).toEqual("");
});
it("should hit the subscription url with signature header", async () => {
const subscription = await buildWebhookSubscription({
url: "http://example.com",
@@ -799,9 +799,12 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
});
}
/** Maximum number of bytes to read from webhook response bodies. */
/** Maximum number of bytes to store from webhook response bodies. */
private static readonly MAX_RESPONSE_BODY_SIZE = 1024;
/** Maximum number of bytes to read from webhook response bodies. */
private static readonly MAX_RESPONSE_READ_SIZE = 64 * 1024;
private async sendWebhook({
event,
subscription,
@@ -842,6 +845,7 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
body: JSON.stringify(requestBody),
redirect: "error",
timeout: 5000,
size: DeliverWebhookTask.MAX_RESPONSE_READ_SIZE,
});
status = response.ok ? "success" : "failed";
} catch (err) {
@@ -862,7 +866,6 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
if (response) {
try {
// TODO: Use stream to avoid buffering large responses in memory.
const text = await response.text();
responseBody = text.slice(0, DeliverWebhookTask.MAX_RESPONSE_BODY_SIZE);
} catch (err) {
+1 -1
View File
@@ -66,7 +66,7 @@ export default class PersistenceExtension implements Extension {
const document = await Document.unscoped().findOne({
attributes: ["id", "state", "content", "text"],
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
rejectOnEmpty: true,
where: {
id: documentId,
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff. Show more