Merge remote-tracking branch 'origin/main' into tommoor/chat-provider-interface

# Conflicts:
#	server/utils/PluginManager.ts
This commit is contained in:
Tom Moor committed 2026-10-18 10:31:47 -04:00
commit 034e9b219c
465 files changed
+6055 -11336

No files matched your search

+2 -1
View File
@@ -118,7 +118,8 @@ import { isMac, isWindows } from "@shared/utils/browser";
import isCloudHosted from "~/utils/isCloudHosted";
import DocumentMove from "~/components/DocumentExplorer/DocumentMove";
const Insights = lazyWithRetry(
/** Lazy insights dialog, exported so that triggers can preload it. */
export const Insights = lazyWithRetry(
() => import("~/scenes/Document/components/Insights")
);
const SharePopover = lazyWithRetry(
+1 -1
View File
@@ -56,7 +56,7 @@ const useIconColor = (collection?: Collection) => {
: randomElement(colorPalette)),
// Deliberately only keyed on the collection color so the randomly picked
// fallback stays stable while the form is open.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[collection?.color]
);
return iconColor;
+1 -1
View File
@@ -132,7 +132,7 @@ export function useSearchIndex(query: string): UseSearchIndex {
const results = useMemo<SearchIndexResult[]>(
() => (query ? index.search(query) : []),
// The index mutates in place, so `version` is what marks the memo stale.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[index, query, version]
);
@@ -163,7 +163,7 @@ function DocumentExplorer({
setTimeout(() => listRef.current?.scrollToItem(index, "center"), 50);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [defaultValue]);
const baseDepth = nodes.reduce(
(min, node) => (node.depth ? Math.min(min, node.depth) : min),
+24 -2
View File
@@ -13,6 +13,7 @@ import DocumentTasks from "~/components/DocumentTasks";
import Flex from "~/components/Flex";
import { MetaButton, Separator, metaStyles } from "~/components/HeaderMeta";
import Time from "~/components/Time";
import useClickIntent from "~/hooks/useClickIntent";
import useCurrentUser from "~/hooks/useCurrentUser";
import useStores from "~/hooks/useStores";
@@ -37,6 +38,8 @@ type Props = {
to?: LocationDescriptor;
/** Called when the meta content is clicked, renders it as a button. Takes precedence over `to`. */
onClick?: () => void;
/** Called when the user is likely to click the meta content, used to preload. */
onClickIntent?: () => void;
};
const DocumentMeta: React.FC<Props> = ({
@@ -50,9 +53,15 @@ const DocumentMeta: React.FC<Props> = ({
replace,
to,
onClick,
onClickIntent,
...rest
}: Props) => {
const { t } = useTranslation();
const {
ref: intentRef,
handleMouseEnter,
handleMouseLeave,
} = useClickIntent(onClickIntent, { predict: !!onClickIntent });
const { collections } = useStores();
const user = useCurrentUser();
const {
@@ -194,9 +203,22 @@ const DocumentMeta: React.FC<Props> = ({
return (
<Container align="center" $rtl={document.dir === "rtl"} {...rest} dir="ltr">
{onClick ? (
<MetaButton onClick={onClick}>{content}</MetaButton>
<MetaButton
ref={intentRef}
onClick={onClick}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{content}
</MetaButton>
) : to ? (
<Link to={to} replace={replace}>
<Link
ref={intentRef}
to={to}
replace={replace}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{content}
</Link>
) : (
+1 -65
View File
@@ -1,8 +1,6 @@
import { difference } from "es-toolkit/compat";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { mergeRefs } from "react-merge-refs";
import type { Optional } from "utility-types";
import EditorContainer from "@shared/editor/components/Styles";
@@ -31,30 +29,14 @@ export type Props = Optional<
};
function Editor({ ref, ...props }: Props & { ref?: React.Ref<SharedEditor> }) {
const {
id,
onChange,
onCreateCommentMark,
onDeleteCommentMark,
onFileUploadStart,
onFileUploadStop,
} = props;
const { id, onChange, onCreateCommentMark, onDeleteCommentMark } = props;
const { comments } = useStores();
const { shareId } = useShare();
const { t } = useTranslation();
const embeds = useEmbeds(!shareId);
const localRef = React.useRef<SharedEditor | null>(null);
const preferences = useCurrentUser({ rejectOnEmpty: false })?.preferences;
const previousCommentIds = React.useRef<string[] | undefined>(undefined);
// Upload progress tracking for delayed toast
const progressMap = React.useMemo(() => new Map<string, number>(), []);
const uploadState = React.useRef<{
toastId?: string | number;
timeoutId?: ReturnType<typeof setTimeout>;
progress: Map<string, number>;
}>({ progress: progressMap });
const handleUploadFile = React.useCallback(
async (
file: File | string,
@@ -80,49 +62,6 @@ function Editor({ ref, ...props }: Props & { ref?: React.Ref<SharedEditor> }) {
const { handleClickLink } = useEditorClickHandlers({ shareId });
// Show toast only after uploads have been running for 2 seconds
const handleFileUploadStart = React.useCallback(() => {
uploadState.current.timeoutId = setTimeout(() => {
uploadState.current.toastId = toast.loading(
t("Uploading… {{ progress }}%", { progress: 0 })
);
}, 2000);
onFileUploadStart?.();
}, [onFileUploadStart, t]);
const handleFileUploadProgress = React.useCallback(
(fileId: string, fractionComplete: number) => {
uploadState.current.progress.set(fileId, fractionComplete);
// Calculate average progress across all files
const progressValues = Array.from(uploadState.current.progress.values());
const avgProgress =
progressValues.reduce((a, b) => a + b, 0) / progressValues.length;
const percent = Math.round(avgProgress * 100);
// Update toast if visible
if (uploadState.current.toastId) {
toast.loading(t("Uploading… {{ progress }}%", { progress: percent }), {
id: uploadState.current.toastId,
});
}
},
[t]
);
const handleFileUploadStop = React.useCallback(() => {
if (uploadState.current.timeoutId) {
clearTimeout(uploadState.current.timeoutId);
uploadState.current.timeoutId = undefined;
}
if (uploadState.current.toastId) {
toast.dismiss(uploadState.current.toastId);
uploadState.current.toastId = undefined;
}
uploadState.current.progress.clear();
onFileUploadStop?.();
}, [onFileUploadStop]);
const focusAtEnd = React.useCallback(() => {
localRef?.current?.focusAtEnd();
}, [localRef]);
@@ -244,9 +183,6 @@ function Editor({ ref, ...props }: Props & { ref?: React.Ref<SharedEditor> }) {
{...props}
onClickLink={handleClickLink}
onChange={handleChange}
onFileUploadStart={handleFileUploadStart}
onFileUploadStop={handleFileUploadStop}
onFileUploadProgress={handleFileUploadProgress}
placeholder={props.placeholder || ""}
defaultValue={props.defaultValue || ""}
/>
+1 -7
View File
@@ -12,7 +12,6 @@ import useMeasure from "react-use-measure";
import { HEADER_HEIGHT } from "@shared/constants";
import { depths, s } from "@shared/styles";
import { metaDisplay } from "@shared/utils/keyboard";
import { supportsPassiveListener } from "@shared/utils/browser";
import Button from "~/components/Button";
import Fade from "~/components/Fade";
import Flex from "~/components/Flex";
@@ -72,12 +71,7 @@ function Header({ left, title, actions, hasSidebar, className, ref }: Props) {
[]
);
useEventListener(
"scroll",
handleScroll,
window,
supportsPassiveListener ? { passive: true } : { capture: false }
);
useEventListener("scroll", handleScroll, window, { passive: true });
const handleClickTitle = React.useCallback(() => {
window.scrollTo({
+1 -1
View File
@@ -234,7 +234,7 @@ const PaginatedList = <T extends PaginatedItem>({
}
// `fetchResults` changes identity as pagination advances, depending on it
// here would re-run the initial fetch for every page.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [fetch]);
// Handle updates to fetch or options
@@ -1,3 +0,0 @@
import SharePopover from "./SharePopover";
export default SharePopover;
@@ -32,7 +32,7 @@ export const GroupMembersPopover = observer(({ group, children }: Props) => {
// when group membership changes in the store.
const members = React.useMemo(
() => groupUsers.inGroup(group.id),
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[groupUsers.orderedData, group.id]
);
@@ -117,7 +117,7 @@ export const Suggestions = observer(function Suggestions({
];
// The store collections listed below are observable dependencies, they
// are what recompute the suggestions when the underlying data changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [
getSuggestionForEmail,
users,
+1 -1
View File
@@ -58,7 +58,7 @@ function SharedSidebar({ share }: Props) {
useEffect(() => {
ui.tocVisible = share.showTOC;
// Only seed the initial visibility, the user can toggle it afterwards.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (!rootNode?.children.length) {
@@ -17,6 +17,7 @@ import { ActionContextProvider } from "~/hooks/useActionContext";
import DropToImport from "./DropToImport";
import Relative from "./Relative";
import SidebarLink from "./SidebarLink";
import { StaticLink } from "./StaticLink";
import type { SidebarContextType } from "./SidebarContext";
import { useSidebarContext } from "./SidebarContext";
import { useSidebarNavigation } from "./SidebarNavigation";
@@ -223,8 +224,7 @@ function CollectionRow({
const sidebarLinkElement = (
<SidebarLink
// @ts-expect-error react-router type is wrong, string component is fine.
component={isEditing ? "div" : undefined}
component={isEditing ? StaticLink : undefined}
depth={depth}
to={to}
onClick={onClick}
@@ -16,6 +16,7 @@ import { ActionContextProvider } from "~/hooks/useActionContext";
import DropToImport from "./DropToImport";
import Relative from "./Relative";
import SidebarLink from "./SidebarLink";
import { StaticLink } from "./StaticLink";
import type { SidebarContextType } from "./SidebarContext";
import { useSidebarContext } from "./SidebarContext";
import type { ActionFactory, ActionWithChildren } from "~/types";
@@ -251,8 +252,7 @@ function DocumentRow({
const sidebarLinkElement = (
<SidebarLink
// @ts-expect-error react-router type is wrong, string component is fine.
component={isEditing ? "div" : undefined}
component={isEditing ? StaticLink : undefined}
depth={depth}
to={to}
expanded={hasChildren && !isDragging ? expanded : undefined}
@@ -198,7 +198,7 @@ export const DocumentTree = observer(function DocumentTree({
});
}
// Scroll when the active row appears, not when rows above it change.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [activeNodeId, isActiveRowRendered, isScrollContext]);
React.useEffect(() => {
@@ -94,7 +94,7 @@ function SharedWithMe() {
}
// `history` is read imperatively, the sidebar context should only be
// recalculated when the active document or memberships change.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [
ui.activeDocumentId,
locationSidebarContext,
@@ -55,7 +55,7 @@ type Props = Omit<NavLinkProps, "to"> & {
/** Callback fired when the link is clicked */
onClick?: React.MouseEventHandler<HTMLAnchorElement>;
/** Callback when we expect the user to click on the link. Used for prefetching data. */
onClickIntent?: React.MouseEventHandler<HTMLElement>;
onClickIntent?: () => void;
/** Callback fired when the disclosure icon is clicked */
onDisclosureClick?: React.MouseEventHandler<HTMLElement>;
/** Icon to display on the left side of the link */
@@ -0,0 +1,21 @@
import type * as React from "react";
interface Props extends React.HTMLAttributes<HTMLDivElement> {
/** Provided by react-router's Link and ignored. */
href?: string;
/** Provided by react-router's Link and ignored. */
navigate?: () => void;
/** Ref forwarded by react-router's Link. */
innerRef?: React.Ref<HTMLDivElement>;
}
/**
* A non-navigating replacement for a Link's anchor element, used while a
* sidebar row is being edited.
*
* @param props The props passed through by react-router's Link.
* @returns A div with the link's presentational props.
*/
export function StaticLink({ href, navigate, innerRef, ...rest }: Props) {
return <div ref={innerRef} {...rest} />;
}
+1 -1
View File
@@ -154,7 +154,7 @@ export const TemplateForm = observer(function TemplateForm_({
void saveRef.current();
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[]
);
+1 -29
View File
@@ -15,7 +15,7 @@ type Props = {
};
const Theme: React.FC<Props> = ({ children }: Props) => {
const { auth, ui } = useStores();
const { auth } = useStores();
const { i18n } = useTranslation();
const theme = useBuildTheme(
auth.team?.getPreference(TeamPreference.CustomTheme) ||
@@ -24,34 +24,6 @@ const Theme: React.FC<Props> = ({ children }: Props) => {
);
const direction = isRTLLanguage(i18n.language) ? "rtl" : "ltr";
React.useEffect(() => {
window.dispatchEvent(
new CustomEvent("theme-changed", {
detail: { isDark: ui.resolvedTheme === "dark" },
})
);
}, [ui.resolvedTheme]);
// Some editor elements such as Mermaid diagrams rely on theme-changed event
// to render the correct color.
// Listen on the print media query, which fires consistently for both the
// print dialog and print preview.
React.useEffect(() => {
const mediaQuery = window.matchMedia("print");
const handleChange = (event: MediaQueryListEvent) => {
window.dispatchEvent(
new CustomEvent("theme-changed", {
detail: {
isDark: event.matches ? false : ui.resolvedTheme === "dark",
},
})
);
};
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, [ui.resolvedTheme]);
return (
<DirectionProvider dir={direction}>
<StyleSheetProvider>
+1 -1
View File
@@ -961,7 +961,7 @@ function WebsocketProvider({ children }: React.PropsWithChildren<object>) {
}
document.removeEventListener(getVisibilityListener(), checkConnection);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
+6 -5
View File
@@ -56,7 +56,7 @@ function usePosition({
// Measure the menu width after DOM updates to ensure accurate positioning.
// Runs after every render by design, the width comparison prevents a loop.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
React.useLayoutEffect(() => {
if (menuRef.current) {
const width = menuRef.current.offsetWidth;
@@ -66,6 +66,11 @@ function usePosition({
}
});
// Measuring the selection forces a layout, so skip it while hidden.
if (!active || !menuRef.current) {
return defaultPosition;
}
// based on the start and end of the selection calculate the position at
// the center top
let fromPos;
@@ -124,10 +129,6 @@ function usePosition({
}
}
if (!active || !menuRef.current || !menuHeight) {
return defaultPosition;
}
// tables are an oddity, and need their own positioning logic
const colIndex = getColumnIndex(view.state);
const rowIndex = getRowIndex(view.state);
+5
View File
@@ -174,6 +174,11 @@ export function MediaDimension() {
width: finalWidth,
height: finalHeight,
});
} else if (nodeType === "video") {
commands["resizeVideo"]({
width: finalWidth,
height: finalHeight,
});
}
}, [
commands,
+12 -8
View File
@@ -34,10 +34,10 @@ export function MediaLinkEditor({
const [localUrl, setLocalUrl] = useState(url);
const wrapperRef = useRef<HTMLDivElement>(null);
// If we're attempting to edit an image, autofocus the input
// Not doing for embed type because it made the editor scroll to top
// unexpectedly–leaving that out for now
const isEditingImgUrl = node?.type.name === "image";
// Image and video nodes store their URL in `src` and autofocus the input.
// Embeds use `href` and do not autofocus, as it made the editor scroll to
// top unexpectedly–leaving that out for now
const isSrcNode = node?.type.name === "image" || node?.type.name === "video";
const moveSelectionToEnd = useCallback(() => {
const { state, dispatch } = view;
@@ -64,7 +64,7 @@ export function MediaLinkEditor({
const update = useCallback(() => {
const { state } = view;
const hrefType = node?.type.name === "image" ? "src" : "href";
const hrefType = isSrcNode ? "src" : "href";
const tr = state.tr.setNodeMarkup(state.selection.from, undefined, {
...node?.attrs,
[hrefType]: localUrl,
@@ -73,7 +73,7 @@ export function MediaLinkEditor({
view.dispatch(tr);
moveSelectionToEnd();
onLinkUpdate();
}, [localUrl, node, view, moveSelectionToEnd, onLinkUpdate]);
}, [localUrl, node, isSrcNode, view, moveSelectionToEnd, onLinkUpdate]);
useOnClickOutside(wrapperRef, onClickOutside);
@@ -108,7 +108,7 @@ export function MediaLinkEditor({
return (
<Wrapper ref={wrapperRef}>
<Input
autoFocus={isEditingImgUrl}
autoFocus={isSrcNode}
value={localUrl}
placeholder={`${t("Paste a link")}…`}
onChange={(e) => setLocalUrl(e.target.value)}
@@ -123,7 +123,11 @@ export function MediaLinkEditor({
{view.editable && (
<Tooltip
content={
node.type.name === "embed" ? t("Delete embed") : t("Delete image")
node.type.name === "embed"
? t("Delete embed")
: node.type.name === "video"
? t("Delete video")
: t("Delete image")
}
>
<ToolbarButton onClick={remove}>
+18 -7
View File
@@ -1,3 +1,4 @@
import { observer } from "mobx-react";
import type { EditorState, Selection } from "prosemirror-state";
import Suggestion from "~/editor/extensions/Suggestion";
import { NodeSelection, TextSelection } from "prosemirror-state";
@@ -26,6 +27,7 @@ import LinkEditor from "./LinkEditor";
import ToolbarMenu from "./ToolbarMenu";
import InlineMenu from "./InlineMenu";
import StickyBlockToolbar from "./StickyBlockToolbar";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
import { isModKey } from "@shared/utils/keyboard";
type Props = {
@@ -67,9 +69,12 @@ enum Toolbar {
Menu = "menu",
}
export function SelectionToolbar(props: Props) {
export const SelectionToolbar = observer(function SelectionToolbar(
props: Props
) {
const { readOnly = false, isEditorFocused } = props;
const { view, extensions, commands, selectionToolbarMenus } = useEditor();
const editor = useEditor();
const { view, extensions, commands, selectionToolbarMenus } = editor;
const menuRef = React.useRef<HTMLDivElement | null>(null);
const isMobile = useMobile();
const isActive = props.isActive || isMobile;
@@ -78,7 +83,10 @@ export function SelectionToolbar(props: Props) {
// visible for as long as the editor is being edited rather than only while
// there is a selection.
const isMobileEditing = isMobile && !readOnly && isEditorFocused;
const { state } = view;
// Only an active toolbar follows the editor state, so an inactive toolbar
// does not render on each transaction.
const state = isActive ? editor.editorState : view.state;
const [autoFocusLinkInput, setAutoFocusLinkInput] = React.useState(false);
const isDragging = useIsDragging(state);
const { selection } = state;
@@ -122,7 +130,7 @@ export function SelectionToolbar(props: Props) {
}
// `activeToolbar` is read to decide whether the link toolbar should stay
// open, re-running when it changes would fight the user's own selection.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [
readOnly,
isActive,
@@ -248,7 +256,7 @@ export function SelectionToolbar(props: Props) {
items = items.map((item) => {
if (item.children && Array.isArray(item.children)) {
item.children = item.children.map((child) => {
if (child.name === "editImageUrl") {
if (child.name === "editImageUrl" || child.name === "editVideoUrl") {
child.onClick = () => {
setActiveToolbar(Toolbar.Media);
};
@@ -267,7 +275,10 @@ export function SelectionToolbar(props: Props) {
});
const handleClickOutsideLinkEditor = (ev: MouseEvent | TouchEvent) => {
if (ev.target instanceof Element && ev.target.closest(".image-wrapper")) {
if (
ev.target instanceof Element &&
ev.target.closest(`.${EditorStyleHelper.imageWrapper}`)
) {
return;
}
setActiveToolbar(null);
@@ -337,4 +348,4 @@ export function SelectionToolbar(props: Props) {
) : null}
</FloatingToolbar>
);
}
});
+1 -1
View File
@@ -107,7 +107,7 @@ function StickyBlockToolbar({ items, rtl, ref }: Props) {
// Measure the block relative to the portal's offset parent. Runs after every
// render by design, the rect comparison prevents a loop.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
React.useLayoutEffect(() => {
const track = trackRef.current;
if (!element || !track) {
+2 -9
View File
@@ -42,7 +42,6 @@ export type Props<T extends MenuItem = MenuItem> = {
uploadFile?: (file: File) => Promise<string>;
onFileUploadStart?: () => void;
onFileUploadStop?: () => void;
onFileUploadProgress?: (id: string, fractionComplete: number) => void;
/** Callback when the menu is closed */
onClose: (insertNewLine?: boolean) => void;
/** Optional callback when a suggestion is selected */
@@ -281,7 +280,7 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) {
} else {
selectionRef.current = null;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [props.isActive, props.search]);
React.useEffect(() => {
@@ -525,12 +524,7 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) {
) => {
restoreSelection();
const {
uploadFile,
onFileUploadStart,
onFileUploadStop,
onFileUploadProgress,
} = props;
const { uploadFile, onFileUploadStart, onFileUploadStop } = props;
const files = getEventFiles(event);
const parent = findParentNode((node) => !!node)(view.state.selection);
const attrs = event.currentTarget.dataset.attrs
@@ -548,7 +542,6 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) {
uploadFile,
onFileUploadStart,
onFileUploadStop,
onFileUploadProgress,
onNotice: toastNotice,
isAttachment: inputRef.current?.accept === "*",
attrs,
+1 -1
View File
@@ -58,7 +58,7 @@ function ToolbarDropdown(props: ToolbarDropdownProps) {
: [];
// Menu items are resolved against the editor state at the moment the menu
// opens, recomputing on every transaction would rebuild the open menu.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen, commands]);
const handleCloseAutoFocus = useCallback((ev: Event) => {
-1
View File
@@ -123,7 +123,6 @@ export default class BlockMenuExtension extends Suggestion {
uploadFile={props.uploadFile}
onFileUploadStart={props.onFileUploadStart}
onFileUploadStop={props.onFileUploadStop}
onFileUploadProgress={props.onFileUploadProgress}
embeds={props.embeds}
/>
);
+9 -1
View File
@@ -22,6 +22,7 @@ import getReadOnlyMenuItems from "../menus/readOnly";
import getTableMenuItems from "../menus/table";
import getTableColMenuItems from "../menus/tableCol";
import getTableRowMenuItems from "../menus/tableRow";
import getVideoMenuItems from "../menus/video";
export default class SelectionToolbarExtension extends Extension {
get name() {
@@ -106,6 +107,11 @@ export default class SelectionToolbarExtension extends Extension {
matches: (ctx) => ctx.selectedNodeType === "attachment",
getItems: (ctx) => getAttachmentMenuItems(ctx),
},
{
priority: 50,
matches: (ctx) => ctx.selectedNodeType === "video",
getItems: (ctx) => getVideoMenuItems(ctx),
},
{
priority: 30,
matches: (ctx) => ctx.readOnly,
@@ -163,7 +169,9 @@ export default class SelectionToolbarExtension extends Extension {
if (
selection instanceof NodeSelection &&
["image", "attachment", "embed"].includes(selection.node.type.name)
["image", "attachment", "embed", "video"].includes(
selection.node.type.name
)
) {
return selection;
}
+43 -27
View File
@@ -162,8 +162,6 @@ export type Props = {
onFileUploadStart?: () => void;
/** Callback when a file upload ends */
onFileUploadStop?: () => void;
/** Callback when file upload progress changes */
onFileUploadProgress?: (id: string, fractionComplete: number) => void;
/** Callback when a link is created, should return url to created document */
onCreateLink?: (
params: Properties<Document>,
@@ -268,6 +266,18 @@ export class Editor extends React.PureComponent<
rulePlugins: PluginSimple[];
events = new EventEmitter();
mutationObserver?: MutationObserver;
private observableState = observable.box<EditorState | undefined>(undefined, {
deep: false,
});
/**
* The current editor state. Unlike `view.state` it is observable, so an
* observer component that reads it during render updates on every
* transaction, and a component that does not read it is not rendered.
*/
public get editorState(): EditorState {
return this.observableState.get() ?? this.view.state;
}
/**
* The markdown serializer for the editor schema, created on first use.
@@ -302,7 +312,9 @@ export class Editor extends React.PureComponent<
public componentDidMount() {
this.init();
this.handleEditorInit();
window.addEventListener("theme-changed", this.dispatchThemeChanged);
// The widgets are created by init, render again to mount them.
this.forceUpdate();
if (this.props.scrollTo) {
void this.scrollToAnchor(this.props.scrollTo);
@@ -324,6 +336,7 @@ export class Editor extends React.PureComponent<
if (this.props.value && prevProps.value !== this.props.value) {
const newState = this.createState(this.props.value);
this.view.updateState(newState);
this.syncObservableState();
// Positions held by the lightbox refer to the previous document.
if (this.state.activeLightboxImage) {
@@ -339,6 +352,8 @@ export class Editor extends React.PureComponent<
this.init();
const newState = this.createState(docJSON);
this.view.updateState(newState);
this.syncObservableState();
this.forceUpdate();
} else if (!prevProps.readOnly && this.props.readOnly) {
// pass readOnly changes through to underlying editor instance
this.view.update({
@@ -389,7 +404,6 @@ export class Editor extends React.PureComponent<
}
public componentWillUnmount(): void {
window.removeEventListener("theme-changed", this.dispatchThemeChanged);
this.view?.destroy();
this.mutationObserver?.disconnect();
this.handleEditorDestroy();
@@ -420,6 +434,7 @@ export class Editor extends React.PureComponent<
// Node views register their renderers as they are created, batch them so
// that React renders them once.
this.view = runInAction(() => this.createView());
this.syncObservableState();
this.commands = this.createCommands();
this.selectionToolbarMenus = this.extensions.selectionToolbarMenus;
}
@@ -609,7 +624,10 @@ export class Editor extends React.PureComponent<
this.state.applyTransaction(transaction);
// Batch node view renderer changes so that React renders them once.
runInAction(() => this.updateState(state));
runInAction(() => {
this.updateState(state);
self.observableState.set(state);
});
// If any of the transactions being dispatched resulted in the doc
// changing then call our own change handler to let the outside world
@@ -630,10 +648,6 @@ export class Editor extends React.PureComponent<
self.handleEditorInit();
self.calculateDir();
// Because Prosemirror and React are not linked we must tell React that
// a render is needed whenever the Prosemirror state changes.
self.forceUpdate();
},
});
@@ -709,6 +723,10 @@ export class Editor extends React.PureComponent<
).toJSON();
};
private syncObservableState() {
runInAction(() => this.observableState.set(this.view.state));
}
private calculateDir = () => {
const element = this.elementRef.current;
if (!element) {
@@ -865,7 +883,7 @@ export class Editor extends React.PureComponent<
public getLightboxImages = (): LightboxImage[] => {
const lightboxNodes = ProsemirrorHelper.getLightboxNodes(
this.view.state.doc
this.editorState.doc
);
return map(lightboxNodes, (node) =>
@@ -1043,10 +1061,6 @@ export class Editor extends React.PureComponent<
return textBetween(doc, 0, doc.content.size);
};
private dispatchThemeChanged = (event: CustomEvent) => {
this.view.dispatch(this.view.state.tr.setMeta("theme", event.detail));
};
private handleChange = (event?: { remote: boolean }) => {
if (!this.props.onChange) {
return;
@@ -1139,7 +1153,7 @@ export class Editor extends React.PureComponent<
public render() {
const { readOnly, canUpdate, grow, style, className, onKeyDown } =
this.props;
const { isRTL } = this.state;
const { isRTL, activeLightboxImage } = this.state;
return (
<PortalContext.Provider value={this.wrapperRef.current}>
@@ -1174,8 +1188,6 @@ export class Editor extends React.PureComponent<
key={String(index)}
rtl={isRTL}
readOnly={readOnly}
selection={this.view.state.selection}
storedMarks={this.view.state.storedMarks}
isEditorFocused={this.state.isEditorFocused}
/>
))}
@@ -1189,14 +1201,18 @@ export class Editor extends React.PureComponent<
)}
</Observer>
</Flex>
{!isNull(this.state.activeLightboxImage) && (
<Lightbox
readOnly={readOnly}
images={this.getLightboxImages()}
activeImage={this.state.activeLightboxImage}
onUpdate={this.updateActiveLightboxImage}
onClose={this.view.focus.bind(this.view)}
/>
{!isNull(activeLightboxImage) && (
<Observer>
{() => (
<Lightbox
readOnly={readOnly}
images={this.getLightboxImages()}
activeImage={activeLightboxImage}
onUpdate={this.updateActiveLightboxImage}
onClose={this.view.focus.bind(this.view)}
/>
)}
</Observer>
)}
</EditorContext.Provider>
</PortalContext.Provider>
@@ -1222,7 +1238,7 @@ const StyledEditorContainer = styled(Styles)<{
}
a#comment-${props.focusedCommentId}
~ span.component-image
div.image-wrapper {
div.${EditorStyleHelper.imageWrapper} {
outline: ${props.theme.commentedImageOutlineDark} solid 2px;
}
`}
@@ -1240,7 +1256,7 @@ const StyledEditorContainer = styled(Styles)<{
}
a#comment-${props.hoveredCommentId}
~ span.component-image
div.image-wrapper {
div.${EditorStyleHelper.imageWrapper} {
outline: ${props.theme.commentedImageOutlineDark} solid 2px;
}
`}
+56
View File
@@ -0,0 +1,56 @@
import { t } from "i18next";
import { TrashIcon, DownloadIcon, ReplaceIcon } from "outline-icons";
import { NodeSelection } from "prosemirror-state";
import type { MenuItem, SelectionContext } from "@shared/editor/types";
/**
* Returns menu items for the video selection toolbar.
*
* @param ctx - the current selection context.
* @returns an array of menu items.
*/
export default function videoMenuItems(ctx: SelectionContext): MenuItem[] {
if (ctx.readOnly) {
return [];
}
const { selection } = ctx.state;
const hasWidth =
selection instanceof NodeSelection && !!selection.node.attrs.width;
return [
{
name: "dimensions",
tooltip: `${t("Width")} × ${t("Height")}`,
visible: hasWidth,
skipIcon: true,
},
{
name: "separator",
},
{
name: "downloadVideo",
tooltip: t("Download video"),
icon: <DownloadIcon />,
},
{
tooltip: t("Replace video"),
icon: <ReplaceIcon />,
children: [
{
name: "replaceVideo",
label: t("Upload a video"),
},
{
name: "editVideoUrl",
label: t("Edit video URL"),
},
],
},
{
name: "deleteVideo",
tooltip: t("Delete video"),
icon: <TrashIcon />,
},
];
}
+44 -6
View File
@@ -1,16 +1,54 @@
import { ForesightManager } from "js.foresight";
import * as React from "react";
import { Second } from "@shared/utils/time";
import useUnmount from "./useUnmount";
interface Options {
/** Milliseconds the cursor must hover before intent fires, defaults to 100. */
delay?: number;
/**
* Also fire when the cursor moves towards the element, or keyboard focus is
* about to reach it. Use only for a small number of elements.
*/
predict?: boolean;
}
/**
* Hook to handle click intent logic with mouse enter/leave events.
* Sets a timer on mouse enter to call the intent callback after a delay,
* and clears the timer on mouse leave or component unmount.
* Hook to call a callback when the user is likely to click an element, used
* to preload data or code. Intent fires after the cursor hovers the element for
* a delay. With the predict option, it also fires when the cursor moves towards
* the element; attach the returned ref for this.
*
* @param onClickIntent callback to call when click intent is detected.
* @param options optional configuration.
* @returns mouse handlers and a ref to attach to the element.
*/
export default function useClickIntent(
onClickIntent?: React.MouseEventHandler<HTMLElement>,
delay = 100
onClickIntent?: () => void,
{ delay = 100, predict = false }: Options = {}
) {
const timer = React.useRef<number | undefined>(undefined);
const callbackRef = React.useRef(onClickIntent);
const [element, setElement] = React.useState<HTMLElement | null>(null);
React.useEffect(() => {
callbackRef.current = onClickIntent;
}, [onClickIntent]);
React.useEffect(() => {
if (!predict || !element) {
return;
}
const manager = ForesightManager.initialize({ setDataAttributes: false });
const { unregister } = manager.register({
element,
callback: () => callbackRef.current?.(),
reactivateAfter: 5 * Second.ms,
});
return unregister;
}, [predict, element]);
const handleMouseEnter = React.useCallback(() => {
if (timer.current) {
@@ -34,5 +72,5 @@ export default function useClickIntent(
}
});
return { handleMouseEnter, handleMouseLeave };
return { ref: setElement, handleMouseEnter, handleMouseLeave };
}
+1 -1
View File
@@ -12,7 +12,7 @@ export function useComputed<T>(
inputs: DependencyList = []
): T {
// The dependency list is supplied by the caller so it cannot be verified here.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
const value = useMemo(() => computed(callback), inputs);
return value.get();
}
+1 -1
View File
@@ -52,7 +52,7 @@ export default function useEmbeds(loadIfMissing = false) {
return e;
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[integrations.orderedData, team?.preferences]
);
}
-1
View File
@@ -16,7 +16,6 @@ export default function useInterval(callback: Callback, delay: number) {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current?.();
+1 -1
View File
@@ -26,6 +26,6 @@ export default function useKeyboardShortcutsQuery() {
});
// Only the query param should open the guide, re-running when the other
// dependencies change would reopen an already dismissed dialog.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [shortcutsQuery]);
}
+1 -1
View File
@@ -74,7 +74,7 @@ export default function useOnScreen(
return () => observer.disconnect();
},
// Re-create when option primitives change; options object identity ignored
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[root, rootMargin, threshold]
);
+2 -2
View File
@@ -83,7 +83,7 @@ export default function usePaginatedRequest<T = unknown>(
}
// `params` is intentionally omitted, callers pass an object literal which
// changes identity on every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [offset, fetchLimit, requestFn]);
const next = useCallback(() => {
@@ -105,7 +105,7 @@ export default function usePaginatedRequest<T = unknown>(
);
// `params` and `fetchLimit` are intentionally omitted, resetting pagination
// should only be driven by the request function changing.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [requestFn]);
return { data, next, loading, error, page, offset, end };
+1 -1
View File
@@ -52,7 +52,7 @@ export default function useRequest<T = unknown>(
}
// Only ever request on mount, later changes to the request function are
// surfaced through the returned `request` for the caller to invoke.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { data, loading, loaded, error, request };
+47 -46
View File
@@ -30,13 +30,13 @@ import useCurrentUser from "./useCurrentUser";
import usePolicy from "./usePolicy";
import useStores from "./useStores";
const AI = lazy(() => import("~/scenes/Settings/AI"));
const ApiKeys = lazy(() => import("~/scenes/Settings/ApiKeys"));
const Applications = lazy(() => import("~/scenes/Settings/Applications"));
const APIAndAccess = lazy(() => import("~/scenes/Settings/APIAndAccess"));
const Authentication = lazy(() => import("~/scenes/Settings/Authentication"));
const Details = lazy(() => import("~/scenes/Settings/Details"));
const Export = lazy(() => import("~/scenes/Settings/Export"));
const Features = lazy(() => import("~/scenes/Settings/Features"));
const Groups = lazy(() => import("~/scenes/Settings/Groups"));
const Import = lazy(() => import("~/scenes/Settings/Import"));
const Integrations = lazy(() => import("~/scenes/Settings/Integrations"));
@@ -114,11 +114,11 @@ const useSettingsConfig = () => {
preload: APIAndAccess.preload,
enabled: true,
group: t("Account"),
icon: PadlockIcon,
icon: CodeIcon,
},
// Workspace
{
name: t("Details"),
name: t("General"),
path: settingsPath("details"),
component: Details.Component,
preload: Details.preload,
@@ -126,33 +126,6 @@ const useSettingsConfig = () => {
group: t("Workspace"),
icon: TeamIcon,
},
{
name: t("Authentication"),
path: settingsPath("authentication"),
component: Authentication.Component,
preload: Authentication.preload,
enabled: can.update,
group: t("Workspace"),
icon: PadlockIcon,
},
{
name: t("Security"),
path: settingsPath("security"),
component: Security.Component,
preload: Security.preload,
enabled: can.update,
group: t("Workspace"),
icon: ShieldIcon,
},
{
name: t("AI"),
path: settingsPath("features"),
component: Features.Component,
preload: Features.preload,
enabled: can.update,
group: t("Workspace"),
icon: SparklesIcon,
},
{
name: t("Users"),
path: settingsPath("users"),
@@ -171,6 +144,24 @@ const useSettingsConfig = () => {
group: t("Workspace"),
icon: GroupIcon,
},
{
name: t("Authentication"),
path: settingsPath("authentication"),
component: Authentication.Component,
preload: Authentication.preload,
enabled: can.update,
group: t("Workspace"),
icon: PadlockIcon,
},
{
name: t("Security"),
path: settingsPath("security"),
component: Security.Component,
preload: Security.preload,
enabled: can.update,
group: t("Workspace"),
icon: ShieldIcon,
},
{
name: t("Templates"),
path: settingsPath("templates"),
@@ -190,25 +181,16 @@ const useSettingsConfig = () => {
icon: SmileyIcon,
},
{
name: t("API Keys"),
path: settingsPath("api-keys"),
component: ApiKeys.Component,
preload: ApiKeys.preload,
enabled: can.listApiKeys,
name: t("AI"),
path: settingsPath("ai"),
component: AI.Component,
preload: AI.preload,
enabled: can.update,
group: t("Workspace"),
icon: CodeIcon,
icon: SparklesIcon,
},
{
name: t("Applications"),
path: settingsPath("applications"),
component: Applications.Component,
preload: Applications.preload,
enabled: can.listOAuthClients,
group: t("Workspace"),
icon: InternetIcon,
},
{
name: t("Shared Links"),
name: t("Shared links"),
path: settingsPath("shares"),
component: Shares.Component,
preload: Shares.preload,
@@ -256,6 +238,25 @@ const useSettingsConfig = () => {
group: t("Integrations"),
icon: PlusIcon,
},
// Developer
{
name: t("API keys"),
path: settingsPath("api-keys"),
component: ApiKeys.Component,
preload: ApiKeys.preload,
enabled: can.listApiKeys,
group: t("Developer"),
icon: CodeIcon,
},
{
name: t("Applications"),
path: settingsPath("applications"),
component: Applications.Component,
preload: Applications.preload,
enabled: can.listOAuthClients,
group: t("Developer"),
icon: InternetIcon,
},
];
// Plugins
+1 -1
View File
@@ -48,6 +48,6 @@ export function useSyncSidebarContext(
);
// `history` is read imperatively, the sidebar context should only be
// recalculated when the active document or memberships change.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [ui.activeDocumentId, locationSidebarContext, belongsToSection, resolve]);
}
+1 -1
View File
@@ -107,7 +107,7 @@ export default function useWebMCPActions(
Analytics.track("webmcp", "register");
return () => controller.abort();
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [enabled, toolNames.join(","), pathname, ...additionalDeps]);
}
+1 -6
View File
@@ -2,7 +2,6 @@
// maintained.
import { throttle } from "es-toolkit/compat";
import { useCallback, useRef, useSyncExternalStore } from "react";
import { supportsPassiveListener } from "@shared/utils/browser";
type ScrollPosition = { x: number; y: number };
@@ -41,11 +40,7 @@ export default function useWindowScrollPosition(options: {
const subscribe = useCallback(
(onStoreChange: () => void) => {
const handleScroll = throttle(onStoreChange, throttleMs);
window.addEventListener(
"scroll",
handleScroll,
supportsPassiveListener ? { passive: true } : false
);
window.addEventListener("scroll", handleScroll, { passive: true });
return () => {
handleScroll.cancel();
window.removeEventListener("scroll", handleScroll);
+3 -1
View File
@@ -42,7 +42,9 @@ const relations = new Map<string, Map<string, RelationProperties>>(new Map());
* @param targetClass The model class to get inverse relations for.
* @returns A map of inverse relation properties keyed by the property name.
*/
export const getInverseRelationsForModelClass = (targetClass: typeof Model) => {
export const getInverseRelationsForModelClass = (
targetClass: Pick<typeof Model, "modelName">
) => {
const inverseRelations = new Map<string, InverseRelationProperties>();
relations.forEach((relation, modelName) => {
+1 -1
View File
@@ -66,7 +66,7 @@ function AuthenticatedRoutes() {
) {
Scenes.preloadEditor();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
+2 -1
View File
@@ -32,7 +32,8 @@ function SettingsRoutes() {
from={settingsPath("members")}
to={settingsPath("users")}
/>
{/* TODO: Refactor these exceptions into config? */}
{/* Features was renamed to AI, redirect for backwards compatibility */}
<Redirect exact from={settingsPath("features")} to={settingsPath("ai")} />
<Route
exact
path={settingsPath("groups", ":id", "members")}
@@ -11,6 +11,7 @@ import {
} from "~/components/primitives/Popover";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useMobile from "~/hooks/useMobile";
import useClickIntent from "~/hooks/useClickIntent";
import useShareDataLoader from "~/hooks/useShareDataLoader";
import useStores from "~/hooks/useStores";
import { preventDefault } from "~/utils/events";
@@ -48,6 +49,16 @@ function ShareButton({ collection }: Props) {
[preload, reset]
);
const handleIntent = useCallback(() => {
preload();
void SharePopover.preload();
}, [preload]);
const {
ref: intentRef,
handleMouseEnter,
handleMouseLeave,
} = useClickIntent(handleIntent, { predict: true });
const closePopover = useCallback(() => {
handleOpenChange(false);
}, [handleOpenChange]);
@@ -65,7 +76,13 @@ function ShareButton({ collection }: Props) {
return (
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger>
<Button icon={icon} neutral onMouseEnter={preload}>
<Button
ref={intentRef}
icon={icon}
neutral
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{t("Share")}
</Button>
</PopoverTrigger>
+1 -1
View File
@@ -118,7 +118,7 @@ const CollectionScene = observer(function CollectionScene_() {
void fetchData();
// Fetched once on mount, the slug in `id` also changes when the collection
// is renamed which must not trigger a refetch.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
+1 -6
View File
@@ -10,7 +10,6 @@ import { HeadingPrefixHelper } from "@shared/editor/extensions/HeadingPrefix";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
import { DocumentPreference, HeadingPrefixStyle } from "@shared/types";
import { depths, hideScrollbars, s } from "@shared/styles";
import { supportsPassiveListener } from "@shared/utils/browser";
import { useDocumentContext } from "~/components/DocumentContext";
import useWindowScrollPosition from "~/hooks/useWindowScrollPosition";
import { patchLocation } from "~/utils/history";
@@ -110,11 +109,7 @@ function Contents() {
}
};
window.addEventListener(
"scroll",
handleScroll,
supportsPassiveListener ? { passive: true } : false
);
window.addEventListener("scroll", handleScroll, { passive: true });
return () => window.removeEventListener("scroll", handleScroll);
}, [selectedSlug]);
@@ -101,7 +101,7 @@ function DataLoader({ match, children }: Props) {
const missingPolicy = !can || Object.keys(can).length === 0;
const isJustCreated = React.useMemo(
() => !!document?.isJustCreated,
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[document?.id]
);
@@ -8,7 +8,10 @@ import styled from "styled-components";
import type Document from "~/models/Document";
import type Revision from "~/models/Revision";
import type Template from "~/models/Template";
import { openDocumentInsights } from "~/actions/definitions/documents";
import {
Insights,
openDocumentInsights,
} from "~/actions/definitions/documents";
import DocumentMeta from "~/components/DocumentMeta";
import {
MetaButton,
@@ -17,11 +20,13 @@ import {
} from "~/components/HeaderMeta";
import Fade from "~/components/Fade";
import { useSplitView } from "~/components/SplitView/context";
import useClickIntent from "~/hooks/useClickIntent";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import { documentPath } from "~/utils/routeHelpers";
import { DocumentComments, DocumentHistory } from "../hooks/useDocumentSidebar";
type Props = {
/* The document to display meta data for */
@@ -50,6 +55,19 @@ function TitleDocumentMeta({ to, document, revision, rtl, ...rest }: Props) {
const commentingEnabled = team.commentingEnabled;
const commentsOpen = ui.getRightSidebar(pane) === "comments";
const {
ref: commentsRef,
handleMouseEnter: handleCommentsMouseEnter,
handleMouseLeave: handleCommentsMouseLeave,
} = useClickIntent(DocumentComments.preload, {
predict: true,
});
const {
ref: insightsRef,
handleMouseEnter: handleInsightsMouseEnter,
handleMouseLeave: handleInsightsMouseLeave,
} = useClickIntent(Insights.preload, { predict: true });
const handleClickMeta = useCallback(() => {
if (to) {
history.replace(to);
@@ -69,13 +87,20 @@ function TitleDocumentMeta({ to, document, revision, rtl, ...rest }: Props) {
document={document as Document}
revision={revision}
onClick={to ? handleClickMeta : undefined}
onClickIntent={to ? DocumentHistory.preload : undefined}
$rtl={rtl}
{...rest}
>
{commentingEnabled && can.comment && (
<>
<Separator />
<MetaButton onClick={handleClickComment} aria-expanded={commentsOpen}>
<MetaButton
ref={commentsRef}
onClick={handleClickComment}
onMouseEnter={handleCommentsMouseEnter}
onMouseLeave={handleCommentsMouseLeave}
aria-expanded={commentsOpen}
>
<CommentIcon size={18} />
{commentsCount
? t("{{ count }} comment", { count: commentsCount })
@@ -86,7 +111,12 @@ function TitleDocumentMeta({ to, document, revision, rtl, ...rest }: Props) {
{totalViewers && can.listViews && !(document as Document).isDraft ? (
<Wrapper>
<Separator />
<MetaButton action={openDocumentInsights}>
<MetaButton
ref={insightsRef}
action={openDocumentInsights}
onMouseEnter={handleInsightsMouseEnter}
onMouseLeave={handleInsightsMouseLeave}
>
{t("Viewed by")}{" "}
{onlyYou
? t("only you")
@@ -174,7 +174,7 @@ function History() {
.getByDocumentId(document.id)
.filter((revision: Revision) => revision.id !== latestRevisionId)
.slice(0, revisionsOffset);
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [document, revisions.orderedData, revisionsOffset]);
// The revisions list is lightweight and omits document content, so load the
@@ -208,7 +208,7 @@ function History() {
document
? events.getByDocumentId(document.id).slice(0, eventsOffset)
: [],
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[document, events.orderedData, eventsOffset]
);
@@ -18,7 +18,6 @@ import { EditorUpdateError } from "@shared/collaboration/CloseEvents";
import History from "@shared/editor/extensions/History";
import EDITOR_VERSION from "@shared/editor/version";
import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
import { supportsPassiveListener } from "@shared/utils/browser";
import type { Props as EditorProps } from "~/components/Editor";
import { useDocumentContext } from "~/components/DocumentContext";
import Editor from "~/components/Editor";
@@ -110,11 +109,7 @@ function MultiplayerEditor({ onSynced, ref, ...props }: Props) {
window.addEventListener("click", finishObserving);
window.addEventListener("wheel", finishObserving);
window.addEventListener(
"scroll",
syncScrollPosition,
supportsPassiveListener ? { passive: true } : false
);
window.addEventListener("scroll", syncScrollPosition, { passive: true });
provider.on("authenticationFailed", () => {
provider.shouldConnect = false;
@@ -248,7 +243,7 @@ function MultiplayerEditor({ onSynced, ref, ...props }: Props) {
};
// `token` is intentionally omitted, it is only read when establishing the
// connection and a refreshed token must not tear down the provider.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [
history,
t,
@@ -425,8 +425,8 @@ const SlideContent = styled.div`
font-size: 1.4em;
}
.image-wrapper,
.image-wrapper img,
.${EditorStyleHelper.imageWrapper},
.${EditorStyleHelper.imageWrapper} img,
.${EditorStyleHelper.mermaidDiagram} {
pointer-events: none !important;
}
@@ -33,7 +33,7 @@ function References({ document }: Props) {
const [activeTab, setActiveTab] = useState<TabType>("children");
const isJustCreated = useMemo(
() => document.isJustCreated,
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[document.id]
);
+19 -2
View File
@@ -10,13 +10,14 @@ import {
PopoverContent,
} from "~/components/primitives/Popover";
import useMobile from "~/hooks/useMobile";
import useClickIntent from "~/hooks/useClickIntent";
import useShareDataLoader from "~/hooks/useShareDataLoader";
import useStores from "~/hooks/useStores";
import { preventDefault } from "~/utils/events";
import lazyWithRetry from "@shared/utils/lazyWithRetry";
const SharePopover = lazyWithRetry(
() => import("~/components/Sharing/Document")
() => import("~/components/Sharing/Document/SharePopover")
);
type Props = {
@@ -46,6 +47,16 @@ function ShareButton({ document }: Props) {
[preload, reset]
);
const handleIntent = useCallback(() => {
preload();
void SharePopover.preload();
}, [preload]);
const {
ref: intentRef,
handleMouseEnter,
handleMouseLeave,
} = useClickIntent(handleIntent, { predict: true });
const closePopover = useCallback(() => {
handleOpenChange(false);
}, [handleOpenChange]);
@@ -59,7 +70,13 @@ function ShareButton({ document }: Props) {
return (
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger>
<Button icon={icon} neutral onMouseEnter={preload}>
<Button
ref={intentRef}
icon={icon}
neutral
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{t("Share")} {domain && <>&middot; {domain}</>}
</Button>
</PopoverTrigger>
+2 -2
View File
@@ -325,7 +325,7 @@ export function useDocumentSave({
// Initial dirty check on mount
useEffect(() => {
updateIsDirty();
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, []);
// When readOnly changes from true to false, recalculate dirty state
@@ -364,7 +364,7 @@ export function useDocumentSave({
});
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[]
);
@@ -18,10 +18,13 @@ import {
} from "~/utils/routeHelpers";
import SidebarLayout from "~/scenes/Document/components/SidebarLayout";
const DocumentComments = lazyWithRetry(
/** Lazy comments sidebar, exported so that triggers can preload it. */
export const DocumentComments = lazyWithRetry(
() => import("~/scenes/Document/components/Comments/Comments")
);
const DocumentHistory = lazyWithRetry(
/** Lazy history sidebar, exported so that triggers can preload it. */
export const DocumentHistory = lazyWithRetry(
() => import("~/scenes/Document/components/History/History")
);
+1 -1
View File
@@ -82,7 +82,7 @@ function DocumentNew() {
}
void createDocument();
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
@@ -17,7 +17,7 @@ import CopyToClipboard from "~/components/CopyToClipboard";
import NudeButton from "~/components/NudeButton";
import { useTheme } from "styled-components";
function Features() {
function AI() {
const { t } = useTranslation();
const team = useCurrentTeam();
const theme = useTheme();
@@ -53,18 +53,18 @@ function Features() {
<Scene title={t("AI")} icon={<SparklesIcon />}>
<Heading>{t("AI")}</Heading>
<Text as="p" type="secondary">
<Trans>Manage AI and integration features for your workspace.</Trans>
<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("MCP server")}
border={!team.getPreference(TeamPreference.MCP)}
label={t("Enabled")}
description={
<>
<Text type="secondary" as="p">
{t(
"Allow members to connect to this workspace with MCP to read and write data."
"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) && (
@@ -75,7 +75,7 @@ function Features() {
style={{ marginTop: 8, marginBottom: 4 }}
>
<Trans
defaults="Use the following endpoint to connect to the MCP server from your app. Find out more about setup in <a>the docs</a>."
defaults="Use this URL in your MCP client. See <a>the setup guide</a> for more details."
components={{
a: (
<Text
@@ -106,6 +106,7 @@ function Features() {
<Switch
id={TeamPreference.MCP}
name={TeamPreference.MCP}
aria-label={t("MCP server")}
checked={team.getPreference(TeamPreference.MCP)}
onChange={handleMCPChange}
/>
@@ -114,12 +115,13 @@ function Features() {
{team.getPreference(TeamPreference.MCP) && (
<SettingRow
name="guidanceMCP"
label={t("Additional guidance")}
label={t("Custom instructions")}
border={false}
description={
<>
<div style={{ marginBottom: 8 }}>
{t(
"You can use these optional instructions to tell MCP clients how to use your knowledge base."
"Optional instructions that are sent to connected AI apps, for example how your workspace is organized or where to find important information."
)}
</div>
<Input
@@ -139,11 +141,12 @@ function Features() {
/>
)}
<Heading as="h2">{t("AI answers")}</Heading>
<SettingRow
name="answers"
label={t("AI answers")}
label={t("Enabled")}
description={t(
"Use AI to get direct answers to questions in search. This feature requires a paid license."
"Show AI-generated answers to questions in search, based on content in your workspace. Requires a paid license."
)}
border={false}
>
@@ -153,4 +156,4 @@ function Features() {
);
}
export default observer(Features);
export default observer(AI);
+2 -2
View File
@@ -1,5 +1,5 @@
import { observer } from "mobx-react";
import { PadlockIcon } from "outline-icons";
import { CodeIcon } from "outline-icons";
import { useTranslation, Trans } from "react-i18next";
import type ApiKey from "~/models/ApiKey";
import type OAuthAuthentication from "~/models/oauth/OAuthAuthentication";
@@ -29,7 +29,7 @@ function APIAndAccess() {
return (
<Scene
title={t("API & Access")}
icon={<PadlockIcon />}
icon={<CodeIcon />}
actions={
<>
{can.createApiKey && (
+1 -1
View File
@@ -117,7 +117,7 @@ function ApiKeys() {
}
wide
>
<Heading>{t("API Keys")}</Heading>
<Heading>{t("API keys")}</Heading>
<Text as="p" type="secondary">
<Trans
defaults="API keys can be used to authenticate with the API and programmatically control your workspace’s data. For more details see the <em>developer documentation</em>."
+3 -3
View File
@@ -185,8 +185,8 @@ function Details() {
return (
<ThemeProvider theme={newTheme}>
<Scene title={t("Details")} icon={<TeamIcon />}>
<Heading>{t("Details")}</Heading>
<Scene title={t("General")} icon={<TeamIcon />}>
<Heading>{t("General")}</Heading>
<Text as="p" type="secondary">
<Trans>
These settings affect the way that your workspace appears to
@@ -195,7 +195,7 @@ function Details() {
</Text>
<form onSubmit={handleSubmit} ref={form}>
<Heading as="h2">{t("Display")}</Heading>
<Heading as="h2">{t("Appearance")}</Heading>
<SettingRow
label={t("Logo")}
name="avatarUrl"
+3 -3
View File
@@ -181,7 +181,7 @@ function Preferences() {
<Trans>Manage settings that affect your personal experience.</Trans>
</Text>
<Heading as="h2">{t("Display")}</Heading>
<Heading as="h2">{t("Appearance")}</Heading>
<SettingRow
label={t("Language")}
name="language"
@@ -212,14 +212,14 @@ function Preferences() {
</SettingRow>
<SettingRow
name="theme"
label={t("Appearance")}
label={t("Theme")}
description={t("Choose your preferred interface color scheme.")}
>
<InputSelect
options={themeOptions}
value={ui.theme}
onChange={handleThemeChange}
label={t("Appearance")}
label={t("Theme")}
labelHidden
/>
</SettingRow>
-23
View File
@@ -31,7 +31,6 @@ function Security() {
memberCollectionCreate: team.memberCollectionCreate,
memberTeamCreate: team.memberTeamCreate,
inviteRequired: team.inviteRequired,
passkeysEnabled: team.passkeysEnabled,
});
const userRoleOptions: Option[] = React.useMemo(
@@ -132,13 +131,6 @@ function Security() {
[saveData]
);
const handlePasskeysEnabledChange = React.useCallback(
async (checked: boolean) => {
await saveData({ passkeysEnabled: checked });
},
[saveData]
);
const handleMemberCollectionCreateChange = React.useCallback(
async (checked: boolean) => {
await saveData({ memberCollectionCreate: checked });
@@ -312,21 +304,6 @@ function Security() {
</SettingRow>
)}
<Heading as="h2">{t("Authentication")}</Heading>
<SettingRow
label={t("Passkeys")}
name="passkeysEnabled"
description={t(
"Allow users to sign in with passkeys for passwordless authentication"
)}
>
<Switch
id="passkeysEnabled"
checked={data.passkeysEnabled}
onChange={handlePasskeysEnabledChange}
/>
</SettingRow>
<Heading as="h2">{t("Behavior")}</Heading>
<SettingRow
label={t("Public document sharing")}
+2 -2
View File
@@ -93,8 +93,8 @@ function Shares() {
}, [query, updateParams]);
return (
<Scene title={t("Shared Links")} icon={<GlobeIcon />} wide>
<Heading>{t("Shared Links")}</Heading>
<Scene title={t("Shared links")} icon={<GlobeIcon />} wide>
<Heading>{t("Shared links")}</Heading>
{can.update && !canShareDocuments && (
<>
+1 -1
View File
@@ -32,7 +32,7 @@ function TemplateNewScene() {
}
void createTemplate();
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
+10 -6
View File
@@ -32,11 +32,18 @@ import { AuthorizationError, NotFoundError } from "~/utils/errors";
import ParanoidModel from "~/models/base/ParanoidModel";
import StorePersistence from "./StorePersistence";
// A concrete model constructor along with the static members of Model.
type ModelClass<T extends Model> = (new (
fields: PartialExcept<T, "id">,
store: Store<T>
) => T) &
Pick<typeof Model, keyof typeof Model>;
type ListPredicate<T> =
| ((value: T, index: number, collection: ArrayLike<T>) => boolean)
| PropertyKey
| [PropertyKey, unknown]
| Partial<T>;
| { [P in keyof T]?: T[P] extends object ? object : T[P] };
export enum RPCAction {
Info = "info",
@@ -85,7 +92,7 @@ export default abstract class Store<T extends Model> {
// oxlint-disable-next-line no-explicit-any
requests: Map<string, Promise<any>> = new Map();
model: typeof Model;
model: ModelClass<T>;
modelName: string;
@@ -115,7 +122,7 @@ export default abstract class Store<T extends Model> {
RPCAction.Delete,
];
constructor(rootStore: RootStore, model: typeof Model) {
constructor(rootStore: RootStore, model: ModelClass<T>) {
this.rootStore = rootStore;
this.model = model;
this.modelName = model.modelName;
@@ -250,7 +257,6 @@ export default abstract class Store<T extends Model> {
return existingModel;
}
// @ts-expect-error TS thinks that we're instantiating an abstract class here
const newModel: T = new ModelClass(item, this);
this.data.set(newModel.id, newModel);
this.persistence?.persist(newModel.id);
@@ -598,7 +604,6 @@ export default abstract class Store<T extends Model> {
* @param predicate A function that returns true if the item matches, or an object with the properties to match.
*/
find = (predicate: ListPredicate<T>): T | undefined =>
// @ts-expect-error not sure why T is incompatible
find(this.orderedData, predicate);
/**
@@ -607,7 +612,6 @@ export default abstract class Store<T extends Model> {
* @param predicate A function that returns true if the item matches, or an object with the properties to match.
*/
filter = (predicate: ListPredicate<T>): T[] =>
// @ts-expect-error not sure why T is incompatible
filter(this.orderedData, predicate);
/**
-1
View File
@@ -336,7 +336,6 @@ export type Permission = {
divider?: boolean;
};
// TODO: Can we make this type driven by the @Field decorator
export type Properties<C> = {
[
Property in keyof C as C[Property] extends JSONValue ? Property : never
-2
View File
@@ -1,7 +1,5 @@
// import original module declarations
import "styled-components";
// and extend them!
declare module "styled-components" {
interface CodeTheme {
code: string;
+3 -2
View File
@@ -277,13 +277,14 @@ class ApiClient {
"BadGatewayError",
err,
{
path,
url: urlToFetch,
requestTime: Math.round(timeEnd - timeStart),
responseText: text,
responseHeaders: Object.fromEntries(response.headers.entries()),
},
// Grouped by endpoint, as the stack trace is identical for every 502.
["BadGatewayError", path]
// Grouped together, as the message varies by endpoint and response body.
["BadGatewayError"]
);
throw err;
}
+1 -1
View File
@@ -13,7 +13,7 @@
* The original libraries are no longer maintained.
*/
/* eslint-disable */
/* oxlint-disable */
// ---------------------------------------------------------------------------
// dom-utils: matches
+2 -2
View File
@@ -85,7 +85,6 @@
"@koa/router": "^15.7.0",
"@koa/send": "^6.0.0",
"@linear/sdk": "^97.0.0",
"@mermaid-js/layout-elk": "0.2.2",
"@modelcontextprotocol/sdk": "^1.31.0",
"@noble/hashes": "^2.4.0",
"@node-oauth/oauth2-server": "^5.3.0",
@@ -162,6 +161,7 @@
"is-printable-key-event": "^1.0.0",
"iso-639-3": "^3.0.1",
"js-yaml": "^4.3.2",
"js.foresight": "^4.2.1",
"jsdom": "^22.1.0",
"jsonwebtoken": "^9.0.3",
"katex": "^0.18.2",
@@ -180,7 +180,6 @@
"markdown-it": "^14.3.2",
"markdown-it-container": "^3.0.0",
"markdown-it-emoji": "^3.0.0",
"mermaid": "11.17.1",
"mime-types": "^3.0.2",
"mobx": "^6.16.1",
"mobx-react": "^9.2.2",
@@ -197,6 +196,7 @@
"passport-oauth2": "^1.8.0",
"passport-slack-oauth2": "^1.2.0",
"patch-package": "^8.0.1",
"pele": "1.6.0",
"pg": "^8.23.0",
"pg-tsquery": "^8.4.2",
"pluralize": "^8.0.0",
+1 -1
View File
@@ -83,7 +83,7 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) {
tenant: env.AZURE_TENANT_ID ? env.AZURE_TENANT_ID : undefined,
passReqToCallback: true,
resource: env.AZURE_RESOURCE_APP_ID,
// @ts-expect-error StateStore
// @ts-expect-error Strategy typings target Express and do not match koa-passport usage
store: new StateStore(),
scope: scopes,
},
+1 -1
View File
@@ -51,7 +51,7 @@ if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) {
clientSecret: env.DISCORD_CLIENT_SECRET,
passReqToCallback: true,
scope,
// @ts-expect-error custom state store
// @ts-expect-error Strategy typings target Express and do not match koa-passport usage
store: new StateStore(),
state: true,
callbackURL: `${env.URL}/auth/${config.id}.callback`,
+1 -1
View File
@@ -50,7 +50,7 @@ if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {
clientSecret: env.GOOGLE_CLIENT_SECRET,
callbackURL: `${env.URL}/auth/${config.id}.callback`,
passReqToCallback: true,
// @ts-expect-error StateStore
// @ts-expect-error Strategy typings target Express and do not match koa-passport usage
store: new StateStore(),
scope: scopes,
},
+1 -1
View File
@@ -63,7 +63,7 @@ export function createOIDCRouter(
callbackURL: `${env.URL}/auth/${config.id}.callback`,
passReqToCallback: true,
scope: env.OIDC_SCOPES,
// @ts-expect-error custom state store
// @ts-expect-error Strategy typings target Express and do not match koa-passport usage
store: new StateStore(endpoints.pkce),
state: true,
pkce: endpoints.pkce ?? false,
-1
View File
@@ -349,7 +349,6 @@ router.post(
const { verified, authenticationInfo } = verification;
if (verified && authenticationInfo) {
// Update counter
passkey.counter = authenticationInfo.newCounter;
passkey.lastActiveAt = new Date();
await passkey.save({ silent: true });
@@ -623,7 +623,6 @@ export default class PostgresSearchProvider extends BaseSearchProvider {
return sequelizeReadOnly.transaction(
(transaction) =>
Document.unscoped().count({
// @ts-expect-error Types are incorrect for count
replacements,
where,
transaction,
+1 -1
View File
@@ -54,7 +54,7 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) {
clientSecret: env.SLACK_CLIENT_SECRET,
callbackURL: SlackUtils.callbackUrl(),
passReqToCallback: true,
// @ts-expect-error StateStore
// @ts-expect-error Strategy typings target Express and do not match koa-passport usage
store: new StateStore(),
scope: scopes,
},
+2 -2
View File
@@ -8,8 +8,8 @@ PluginManager.add([
...config,
type: Hook.Settings,
value: {
group: "Workspace",
after: "Shared Links",
group: "Developer",
after: "Applications",
icon: Icon,
description:
"Automate downstream workflows with real-time JSON POSTs, subscribe to events in Outline so external systems can react instantly.",
@@ -65,7 +65,6 @@ router.post(
() =>
WebhookSubscription.count({
where,
// @ts-expect-error Types are incorrect for count
replacements,
}) as unknown as Promise<number>
);
+10 -1
View File
@@ -247,7 +247,16 @@ async function accountProvisioner(
};
}
async function provisionFirstCollection(
/**
* Creates the default "Welcome" collection and onboarding documents for a
* newly created team.
*
* @param ctx the request context.
* @param team the team to provision the collection for.
* @param user the user that will be recorded as the creator.
* @returns a promise that resolves when the collection has been created.
*/
export async function provisionFirstCollection(
ctx: APIContext,
team: Team,
user: User
+91
View File
@@ -1,4 +1,6 @@
import { faker } from "@faker-js/faker";
import { DocumentPermission } from "@shared/types";
import { UserMembership } from "@server/models";
import {
buildCollection,
buildDocument,
@@ -237,6 +239,95 @@ describe("shareLoader", () => {
expect(result.parentShare?.id).toEqual(parentShare.id);
});
it("should not return parent collection share when user cannot read the collection", async () => {
const admin = await buildUser();
const member = await buildUser({ teamId: admin.teamId });
const collection = await buildCollection({
permission: null,
userId: admin.id,
teamId: admin.teamId,
});
const document = await buildDocument({
collectionId: collection.id,
userId: admin.id,
teamId: admin.teamId,
});
await UserMembership.create({
userId: member.id,
documentId: document.id,
permission: DocumentPermission.Read,
createdById: admin.id,
});
const [, share] = await Promise.all([
buildShare({
userId: admin.id,
teamId: admin.teamId,
collectionId: collection.id,
}),
buildShare({
userId: admin.id,
teamId: admin.teamId,
documentId: document.id,
}),
]);
const result = await loadShareWithParent({
documentId: document.id,
user: member,
});
expect(result.share.id).toEqual(share.id);
expect(result.parentShare).toBeNull();
});
it("should not return parent document share when user cannot read the parent document", async () => {
const admin = await buildUser();
const member = await buildUser({ teamId: admin.teamId });
const collection = await buildCollection({
permission: null,
userId: admin.id,
teamId: admin.teamId,
});
const document = await buildDocument({
collectionId: collection.id,
userId: admin.id,
teamId: admin.teamId,
});
const childDocument = await buildDocument({
parentDocumentId: document.id,
collectionId: collection.id,
userId: admin.id,
teamId: admin.teamId,
});
await UserMembership.create({
userId: member.id,
documentId: childDocument.id,
permission: DocumentPermission.Read,
createdById: admin.id,
});
const [, share] = await Promise.all([
buildShare({
includeChildDocuments: true,
userId: admin.id,
teamId: admin.teamId,
documentId: document.id,
}),
buildShare({
userId: admin.id,
teamId: admin.teamId,
documentId: childDocument.id,
}),
]);
const result = await loadShareWithParent({
documentId: childDocument.id,
user: member,
});
expect(result.share.id).toEqual(share.id);
expect(result.parentShare).toBeNull();
});
it("should throw error when the requested document is not part of the share (includeChildDocuments = true)", async () => {
const user = await buildUser();
const collection = await buildCollection({
+9 -2
View File
@@ -208,7 +208,11 @@ export async function loadShareWithParent({
});
// prefer collection share if it exists and user has read access.
if (collectionShare && can(user, "read", collectionShare)) {
if (
collectionShare &&
can(user, "read", collectionShare) &&
can(user, "read", collectionShare.collection)
) {
parentShare = collectionShare;
} else {
const parentDocIds = docCollection.getDocumentParents(documentId);
@@ -229,7 +233,10 @@ export async function loadShareWithParent({
})
: null;
parentShare = allParentShares?.find((s) => can(user, "read", s)) ?? null;
parentShare =
allParentShares?.find(
(s) => can(user, "read", s) && can(user, "read", s.document)
) ?? null;
}
}
+3 -10
View File
@@ -1,4 +1,4 @@
import type { WhereOptions } from "sequelize";
import type { ModelStatic, WhereOptions } from "sequelize";
import Logger from "@server/logging/Logger";
import { traceFunction } from "@server/logging/tracing";
import type { Team } from "@server/models";
@@ -213,20 +213,13 @@ async function destroyTeamData(team: Team) {
});
}
interface BatchDestroyable {
findAllInBatches: typeof Model.findAllInBatches;
destroy(options: {
where: { id: string[] };
force: boolean;
}): Promise<number>;
}
/**
* Permanently deletes every row of a model matching the where clause, in
* batches of ids so that each statement is short and locks few rows.
*/
async function destroyInBatches(
model: BatchDestroyable,
model: ModelStatic<Model & { id: string }> &
Pick<typeof Model, "findAllInBatches">,
where: WhereOptions
): Promise<void> {
await model.findAllInBatches<Model & { id: string }>(
+6 -5
View File
@@ -1,13 +1,14 @@
import { Hook, PluginManager } from "@server/utils/PluginManager";
import { requireDirectory } from "@server/utils/fs";
import { createLazyRegistry } from "@server/utils/lazyRegistry";
import type { Concrete } from "@shared/types";
import type BaseEmail from "./BaseEmail";
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- registry of heterogeneous template Props subtypes; BaseEmail<EmailProps> isn't assignable from BaseEmail<Subtype>.
const emails = createLazyRegistry<typeof BaseEmail<any>>(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const registry: Record<string, typeof BaseEmail<any>> = {};
requireDirectory<{ default: typeof BaseEmail }>(__dirname).forEach(
// oxlint-disable-next-line @typescript-eslint/no-explicit-any -- registry of heterogeneous template Props subtypes; BaseEmail<EmailProps> isn't assignable from BaseEmail<Subtype>.
const emails = createLazyRegistry<Concrete<typeof BaseEmail<any>>>(() => {
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
const registry: Record<string, Concrete<typeof BaseEmail<any>>> = {};
requireDirectory<{ default: (typeof registry)[string] }>(__dirname).forEach(
([module, id]) => {
if (id === "index") {
return;
+11
View File
@@ -221,6 +221,17 @@ export class Environment {
10
);
/**
* The time in milliseconds that a redis connection can stay unavailable
* before the process exits, so that the process manager can restart it.
*/
@IsNumber()
@Min(1000)
public REDIS_UNAVAILABLE_TIMEOUT = parseInt(
environment.REDIS_UNAVAILABLE_TIMEOUT || "300000",
10
);
/**
* The fully qualified, external facing domain name of the server.
* If not set, will be derived from HEROKU_APP_NAME for Heroku deployments.
+39 -58
View File
@@ -9,6 +9,7 @@ import {
buildApiKey,
buildOAuthAuthentication,
} from "@server/test/factories";
import { buildMockContext } from "@server/test/support";
import { AuthenticationType } from "@server/types";
import auth from "./authentication";
@@ -19,14 +20,13 @@ describe("Authentication middleware", () => {
const user = await buildUser();
const authMiddleware = auth();
await authMiddleware(
{
// @ts-expect-error mock request
buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
},
state,
cache: {},
},
}),
vi.fn()
);
expect(state.auth.user.id).toEqual(user.id);
@@ -39,14 +39,13 @@ describe("Authentication middleware", () => {
try {
await authMiddleware(
{
// @ts-expect-error mock request
buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}error`),
},
state,
cache: {},
},
}),
vi.fn()
);
} catch (e) {
@@ -63,14 +62,13 @@ describe("Authentication middleware", () => {
try {
await authMiddleware(
{
// @ts-expect-error mock request
buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
},
state,
cache: {},
},
}),
vi.fn()
);
} catch (e) {
@@ -86,14 +84,13 @@ describe("Authentication middleware", () => {
const authMiddleware = auth();
const key = await buildApiKey({ userId: user.id });
await authMiddleware(
{
// @ts-expect-error mock request
buildMockContext({
request: {
get: vi.fn(() => `Bearer ${key.value}`),
},
state,
cache: {},
},
}),
vi.fn()
);
expect(state.auth.user.id).toEqual(user.id);
@@ -108,16 +105,15 @@ describe("Authentication middleware", () => {
});
await authMiddleware(
{
buildMockContext({
originalUrl: "/api/auth.info",
// @ts-expect-error mock request
request: {
url: "/auth.info",
get: vi.fn(() => `Bearer ${key.value}`),
},
state,
cache: {},
},
}),
vi.fn()
);
expect(state.auth.user.id).toEqual(user.id);
@@ -134,16 +130,15 @@ describe("Authentication middleware", () => {
try {
await authMiddleware(
{
buildMockContext({
originalUrl: "/api/documents.create",
// @ts-expect-error mock request
request: {
url: "/documents.create",
get: vi.fn(() => `Bearer ${key.value}`),
},
state,
cache: {},
},
}),
vi.fn()
);
throw new Error("Expected error to be thrown");
@@ -162,14 +157,13 @@ describe("Authentication middleware", () => {
try {
await authMiddleware(
{
// @ts-expect-error mock request
buildMockContext({
request: {
get: vi.fn(() => `Bearer ${randomString(38)}`),
},
state,
cache: {},
},
}),
vi.fn()
);
} catch (e) {
@@ -189,16 +183,15 @@ describe("Authentication middleware", () => {
});
await authMiddleware(
{
buildMockContext({
originalUrl: "/api/users.info",
// @ts-expect-error mock request
request: {
url: "/users.info",
get: vi.fn(() => `Bearer ${authentication.accessToken}`),
},
state,
cache: {},
},
}),
vi.fn()
);
expect(state.auth.user.id).toEqual(user.id);
@@ -215,16 +208,15 @@ describe("Authentication middleware", () => {
try {
await authMiddleware(
{
buildMockContext({
originalUrl: "/api/documents.create",
// @ts-expect-error mock request
request: {
url: "/documents.create",
get: vi.fn(() => `Bearer ${authentication.accessToken}`),
},
state,
cache: {},
},
}),
vi.fn()
);
} catch (e) {
@@ -244,11 +236,10 @@ describe("Authentication middleware", () => {
});
try {
await authMiddleware(
{
buildMockContext({
originalUrl: "/api/users.info",
request: {
url: "/users.info",
// @ts-expect-error mock request
get: vi.fn(() => null),
body: {
token: authentication.accessToken,
@@ -256,7 +247,7 @@ describe("Authentication middleware", () => {
},
state,
cache: {},
},
}),
vi.fn()
);
} catch (e) {
@@ -273,14 +264,13 @@ describe("Authentication middleware", () => {
try {
await authMiddleware(
{
// @ts-expect-error mock request
buildMockContext({
request: {
get: vi.fn(() => "error"),
},
state,
cache: {},
},
}),
vi.fn()
);
} catch (e) {
@@ -295,18 +285,16 @@ describe("Authentication middleware", () => {
const user = await buildUser();
const authMiddleware = auth();
await authMiddleware(
{
buildMockContext({
request: {
// @ts-expect-error mock request
get: vi.fn(() => null),
},
// @ts-expect-error mock cookies
cookies: {
get: vi.fn(() => user.getSessionToken()),
},
state,
cache: {},
},
}),
vi.fn()
);
expect(state.auth.user.id).toEqual(user.id);
@@ -319,9 +307,8 @@ describe("Authentication middleware", () => {
await expect(
authMiddleware(
{
buildMockContext({
request: {
// @ts-expect-error mock request
get: vi.fn(() => null),
query: {
token: user.getSessionToken(),
@@ -329,7 +316,7 @@ describe("Authentication middleware", () => {
},
state,
cache: {},
},
}),
vi.fn()
)
).rejects.toThrow(
@@ -344,9 +331,8 @@ describe("Authentication middleware", () => {
await expect(
authMiddleware(
{
buildMockContext({
request: {
// @ts-expect-error mock request
get: vi.fn(() => null),
body: {
token: user.getSessionToken(),
@@ -354,7 +340,7 @@ describe("Authentication middleware", () => {
},
state,
cache: {},
},
}),
vi.fn()
)
).rejects.toThrow(
@@ -367,9 +353,8 @@ describe("Authentication middleware", () => {
const user = await buildUser();
const authMiddleware = auth();
await authMiddleware(
{
buildMockContext({
request: {
// @ts-expect-error mock request
get: vi.fn(() => null),
query: {
token: user.getTransferToken(),
@@ -377,7 +362,7 @@ describe("Authentication middleware", () => {
},
state,
cache: {},
},
}),
vi.fn()
);
expect(state.auth.user.id).toEqual(user.id);
@@ -395,14 +380,13 @@ describe("Authentication middleware", () => {
try {
await authMiddleware(
{
// @ts-expect-error mock request
buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
},
state,
cache: {},
},
}),
vi.fn()
);
} catch (err) {
@@ -425,14 +409,13 @@ describe("Authentication middleware", () => {
try {
await authMiddleware(
{
// @ts-expect-error mock request
buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
},
state,
cache: {},
},
}),
vi.fn()
);
} catch (err) {
@@ -455,8 +438,7 @@ describe("Authentication middleware", () => {
skip: (ctx) => !!ctx.query.sig,
});
await authMiddleware(
{
// @ts-expect-error mock request
buildMockContext({
request: {
get: vi.fn(() => `Bearer ${apiKey.value}`),
},
@@ -464,7 +446,7 @@ describe("Authentication middleware", () => {
originalUrl: "/api/files.get?sig=signature",
state,
cache: {},
},
}),
next
);
expect(next).toHaveBeenCalled();
@@ -480,15 +462,14 @@ describe("Authentication middleware", () => {
skip: (ctx) => !!ctx.query.sig,
});
await authMiddleware(
{
// @ts-expect-error mock request
buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
},
query: {},
state,
cache: {},
},
}),
next
);
expect(next).toHaveBeenCalled();
+6 -17
View File
@@ -1,4 +1,5 @@
import type { Socket } from "net";
import { buildMockContext } from "@server/test/support";
import timeout from "./timeout";
describe("Timeout middleware", () => {
@@ -21,11 +22,7 @@ describe("Timeout middleware", () => {
const next = vi.fn();
const middleware = timeout(newTimeout);
await middleware(
// @ts-expect-error mock context
ctx,
next
);
await middleware(buildMockContext(ctx), next);
// Should have set the new timeout
expect(setTimeout).toHaveBeenCalledWith(newTimeout);
@@ -55,13 +52,9 @@ describe("Timeout middleware", () => {
const next = vi.fn().mockRejectedValue(error);
const middleware = timeout(newTimeout);
await expect(
middleware(
// @ts-expect-error mock context
ctx,
next
)
).rejects.toThrow("Test error");
await expect(middleware(buildMockContext(ctx), next)).rejects.toThrow(
"Test error"
);
// Should have set the new timeout
expect(setTimeout).toHaveBeenCalledWith(newTimeout);
@@ -89,11 +82,7 @@ describe("Timeout middleware", () => {
const next = vi.fn();
const middleware = timeout(newTimeout);
await middleware(
// @ts-expect-error mock context
ctx,
next
);
await middleware(buildMockContext(ctx), next);
// Should have set the new timeout
expect(setTimeout).toHaveBeenCalledWith(newTimeout);
-176
View File
@@ -1,176 +0,0 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable("teams", {
id: {
type: "UUID",
allowNull: false,
primaryKey: true,
},
name: {
type: "CHARACTER VARYING",
allowNull: true,
},
slackId: {
type: "CHARACTER VARYING",
allowNull: true,
unique: true,
},
slackData: {
type: "JSONB",
allowNull: true,
},
createdAt: {
type: "TIMESTAMP WITH TIME ZONE",
allowNull: false,
},
updatedAt: {
type: "TIMESTAMP WITH TIME ZONE",
allowNull: false,
},
});
await queryInterface.createTable("atlases", {
id: {
type: "UUID",
allowNull: false,
primaryKey: true,
},
name: {
type: "CHARACTER VARYING",
allowNull: true,
},
description: {
type: "CHARACTER VARYING",
allowNull: true,
},
type: {
type: "CHARACTER VARYING",
allowNull: true,
},
navigationTree: {
type: "JSONB",
allowNull: true,
},
createdAt: {
type: "TIMESTAMP WITH TIME ZONE",
allowNull: false,
},
updatedAt: {
type: "TIMESTAMP WITH TIME ZONE",
allowNull: false,
},
teamId: {
type: "UUID",
allowNull: false,
},
});
await queryInterface.createTable("users", {
id: {
type: "UUID",
allowNull: false,
primaryKey: true,
},
email: {
type: "CHARACTER VARYING",
allowNull: false,
},
username: {
type: "CHARACTER VARYING",
allowNull: false,
},
name: {
type: "CHARACTER VARYING",
allowNull: false,
},
isAdmin: {
type: "BOOLEAN",
allowNull: true,
defaultValue: false,
},
slackAccessToken: {
type: "bytea",
allowNull: true,
},
slackId: {
type: "CHARACTER VARYING",
unique: true,
allowNull: false,
},
slackData: {
type: "JSONB",
allowNull: true,
},
jwtSecret: {
type: "bytea",
allowNull: true,
},
createdAt: {
type: "TIMESTAMP WITH TIME ZONE",
allowNull: false,
},
updatedAt: {
type: "TIMESTAMP WITH TIME ZONE",
allowNull: false,
},
teamId: {
type: "UUID",
allowNull: true,
},
});
await queryInterface.createTable("documents", {
id: {
type: "UUID",
allowNull: false,
primaryKey: true,
},
urlId: {
type: "CHARACTER VARYING",
allowNull: false,
unique: true,
},
private: {
type: "BOOLEAN",
allowNull: false,
defaultValue: true,
},
title: {
type: "CHARACTER VARYING",
allowNull: false,
},
text: {
type: "TEXT",
allowNull: true,
},
html: {
type: "TEXT",
allowNull: true,
},
preview: {
type: "TEXT",
allowNull: true,
},
createdAt: {
type: "TIMESTAMP WITH TIME ZONE",
allowNull: false,
},
updatedAt: {
type: "TIMESTAMP WITH TIME ZONE",
allowNull: false,
},
userId: {
type: "UUID",
allowNull: true,
},
atlasId: {
type: "UUID",
allowNull: true,
},
teamId: {
type: "UUID",
allowNull: true,
},
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropAllTables();
},
};
@@ -1,11 +0,0 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn("documents", "parentDocumentId", {
type: Sequelize.UUID,
allowNull: true,
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn("documents", "parentDocumentId");
},
};
@@ -1,23 +0,0 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addIndex("documents", ["urlId"]);
await queryInterface.addIndex("documents", ["id", "atlasId"]);
await queryInterface.addIndex("documents", ["id", "teamId"]);
await queryInterface.addIndex("documents", ["parentDocumentId", "atlasId"]);
await queryInterface.addIndex("atlases", ["id", "teamId"]);
await queryInterface.addIndex("teams", ["slackId"]);
await queryInterface.addIndex("users", ["slackId"]);
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeIndex("documents", ["urlId"]);
await queryInterface.removeIndex("documents", ["id", "atlasId"]);
await queryInterface.removeIndex("documents", ["id", "teamId"]);
await queryInterface.removeIndex("documents", [
"parentDocumentId",
"atlasId",
]);
await queryInterface.removeIndex("atlases", ["id", "teamId"]);
await queryInterface.removeIndex("teams", ["slackId"]);
await queryInterface.removeIndex("users", ["slackId"]);
},
};
@@ -1,66 +0,0 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable("revisions", {
id: {
type: "UUID",
allowNull: false,
primaryKey: true,
},
title: {
type: "CHARACTER VARYING",
allowNull: false,
},
text: {
type: "TEXT",
allowNull: true,
},
html: {
type: "TEXT",
allowNull: true,
},
preview: {
type: "TEXT",
allowNull: true,
},
createdAt: {
type: "TIMESTAMP WITH TIME ZONE",
allowNull: false,
},
updatedAt: {
type: "TIMESTAMP WITH TIME ZONE",
allowNull: false,
},
userId: {
type: "UUID",
allowNull: false,
references: {
model: "users",
},
},
documentId: {
type: "UUID",
allowNull: false,
references: {
model: "documents",
onDelete: "CASCADE",
},
},
});
await queryInterface.addColumn("documents", "lastModifiedById", {
type: "UUID",
allowNull: false,
references: {
model: "users",
},
});
await queryInterface.addColumn("documents", "revisionCount", {
type: "INTEGER",
defaultValue: 0,
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable("revisions");
await queryInterface.removeColumn("documents", "lastModifiedById");
await queryInterface.removeColumn("documents", "revisionCount");
},
};
@@ -1,41 +0,0 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
const searchDocument = `
ALTER TABLE documents ADD COLUMN "searchVector" tsvector;
CREATE INDEX documents_tsv_idx ON documents USING gin("searchVector");
CREATE FUNCTION documents_search_trigger() RETURNS trigger AS $$
begin
new."searchVector" :=
setweight(to_tsvector('english', coalesce(new.title, '')),'A') ||
setweight(to_tsvector('english', coalesce(new.text, '')), 'C');
return new;
end
$$ LANGUAGE plpgsql;
CREATE TRIGGER documents_tsvectorupdate BEFORE INSERT OR UPDATE
ON documents FOR EACH ROW EXECUTE PROCEDURE documents_search_trigger();
`;
const searchCollection = `
ALTER TABLE atlases ADD COLUMN "searchVector" tsvector;
CREATE INDEX atlases_tsv_idx ON atlases USING gin("searchVector");
CREATE FUNCTION atlases_search_trigger() RETURNS trigger AS $$
begin
new."searchVector" :=
setweight(to_tsvector('english', coalesce(new.name, '')),'A') ||
setweight(to_tsvector('english', coalesce(new.description, '')), 'C');
return new;
end
$$ LANGUAGE plpgsql;
CREATE TRIGGER atlases_tsvectorupdate BEFORE INSERT OR UPDATE
ON atlases FOR EACH ROW EXECUTE PROCEDURE atlases_search_trigger();
`;
await queryInterface.sequelize.query(searchDocument);
await queryInterface.sequelize.query(searchCollection);
},
down: async (queryInterface, Sequelize) => {
// TODO?
},
};
@@ -1,11 +0,0 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn("atlases", "creatorId", {
type: Sequelize.UUID,
allowNull: true,
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn("atlases", "creatorId");
},
};
@@ -1,16 +0,0 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn("atlases", "deletedAt", {
type: Sequelize.DATE,
allowNull: true,
});
await queryInterface.addColumn("documents", "deletedAt", {
type: Sequelize.DATE,
allowNull: true,
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn("atlases", "deletedAt");
await queryInterface.removeColumn("documents", "deletedAt");
},
};
@@ -1,51 +0,0 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
// Remove old indeces
await queryInterface.removeIndex("documents", ["urlId"]);
await queryInterface.removeIndex("documents", ["id", "atlasId"]);
await queryInterface.removeIndex("documents", ["id", "teamId"]);
await queryInterface.removeIndex("documents", [
"parentDocumentId",
"atlasId",
]);
await queryInterface.removeIndex("atlases", ["id", "teamId"]);
// Add new ones
await queryInterface.addIndex("documents", ["id", "deletedAt"]);
await queryInterface.addIndex("documents", ["urlId", "deletedAt"]);
await queryInterface.addIndex("documents", ["id", "atlasId", "deletedAt"]);
await queryInterface.addIndex("documents", ["id", "teamId", "deletedAt"]);
await queryInterface.addIndex("documents", [
"parentDocumentId",
"atlasId",
"deletedAt",
]);
await queryInterface.addIndex("atlases", ["id", "deletedAt"]);
await queryInterface.addIndex("atlases", ["id", "teamId", "deletedAt"]);
},
down: async (queryInterface, Sequelize) => {
await queryInterface.addIndex("documents", ["urlId"]);
await queryInterface.addIndex("documents", ["id", "atlasId"]);
await queryInterface.addIndex("documents", ["id", "teamId"]);
await queryInterface.addIndex("documents", ["parentDocumentId", "atlasId"]);
await queryInterface.addIndex("atlases", ["id", "teamId"]);
await queryInterface.removeIndex("documents", ["id", "deletedAt"]);
await queryInterface.removeIndex("documents", ["urlId", "deletedAt"]);
await queryInterface.removeIndex("documents", [
"id",
"atlasId",
"deletedAt",
]);
await queryInterface.removeIndex("documents", [
"id",
"teamId",
"deletedAt",
]);
await queryInterface.removeIndex("documents", [
"parentDocumentId",
"atlasId",
"deletedAt",
]);
await queryInterface.removeIndex("atlases", ["id", "deletedAt"]);
await queryInterface.removeIndex("atlases", ["id", "teamId", "deletedAt"]);
},
};
@@ -1,14 +0,0 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn("documents", "createdById", {
type: "UUID",
allowNull: true,
references: {
model: "users",
},
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn("documents", "createdById");
},
};
Loaded 100 of 465 files, more files were not shown because too many files have changed in this diff. Show more