mirror of
https://github.com/outline/outline.git
synced 2026-12-01 01:14:11 +03:00
Merge branch 'main' into feat/customize-retention
The superseded cleanup task picked up two fixes on main before it was removed here, both carried over to the tasks that replace it: - Select the batch from the read replica, as the permanent deleter already does. - Retry with exponential backoff so a deadlocked run recovers once the partition window has passed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
359 files changed
+11266
-4807
No files matched your search
@@ -4,7 +4,6 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
NODE_ENV: test
|
||||
|
||||
@@ -125,32 +125,6 @@
|
||||
"react-hooks/exhaustive-deps": "error"
|
||||
},
|
||||
"plugins": ["eslint", "oxc", "react", "typescript", "import"]
|
||||
},
|
||||
{
|
||||
"files": ["shared/**/*.{js,jsx,ts,tsx}"],
|
||||
"rules": {
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
"paths": [
|
||||
{
|
||||
"name": "prosemirror-tables",
|
||||
"importNames": [
|
||||
"addRowBefore",
|
||||
"addRowAfter",
|
||||
"addColumnBefore",
|
||||
"addColumnAfter"
|
||||
],
|
||||
"message": "Use the wrappers from shared/editor/commands/table instead, which respect the target index and place the cursor in the inserted cell."
|
||||
},
|
||||
{
|
||||
"name": "sonner",
|
||||
"message": "Do not import a toast library within shared; surface notifications through the onNotice callback so shared code stays decoupled from the app's toast implementation."
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -3,7 +3,7 @@ Business Source License 1.1
|
||||
Parameters
|
||||
|
||||
Licensor: General Outline, Inc.
|
||||
Licensed Work: Outline 1.9.1
|
||||
Licensed Work: Outline 1.10.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-07-13
|
||||
Change Date: 2030-09-01
|
||||
|
||||
Change License: Apache License, Version 2.0
|
||||
|
||||
|
||||
@@ -16,6 +16,18 @@
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
"paths": [
|
||||
{
|
||||
"name": "prosemirror-tables",
|
||||
"importNames": [
|
||||
"addRowBefore",
|
||||
"addRowAfter",
|
||||
"addColumnBefore",
|
||||
"addColumnAfter"
|
||||
],
|
||||
"message": "Use the wrappers from shared/editor/commands/table instead, which respect the target index and place the cursor in the inserted cell."
|
||||
}
|
||||
],
|
||||
"patterns": [
|
||||
{
|
||||
"group": ["mime-types"],
|
||||
|
||||
@@ -1364,7 +1364,8 @@ export const searchDocumentsForQueryActionFactory = (query: string) =>
|
||||
priority: -1,
|
||||
icon: <SearchIcon />,
|
||||
to: searchPath({ query }),
|
||||
visible: ({ location }) => location.pathname !== searchPath(),
|
||||
visible: ({ location, isMCP }) =>
|
||||
!isMCP && location.pathname !== searchPath(),
|
||||
});
|
||||
|
||||
export const moveDocumentToCollection = createAction({
|
||||
|
||||
@@ -55,6 +55,7 @@ export const navigateToRecentSearchQueryActionFactory = (
|
||||
name: searchQuery.query,
|
||||
analyticsName: "Navigate to recent search query",
|
||||
icon: <SearchIcon />,
|
||||
visible: ({ isMCP }) => !isMCP,
|
||||
to: searchPath({ query: searchQuery.query }),
|
||||
});
|
||||
|
||||
|
||||
@@ -94,7 +94,7 @@ export const deleteRevision = createAction({
|
||||
dangerous: true,
|
||||
visible: ({ activeDocumentId }) =>
|
||||
!!activeDocumentId && stores.policies.abilities(activeDocumentId).update,
|
||||
perform: async ({ t, event, location, activeDocumentId }) => {
|
||||
perform: async ({ t, event, location, activeDocumentId, sidebarContext }) => {
|
||||
event?.preventDefault();
|
||||
if (!activeDocumentId) {
|
||||
return;
|
||||
@@ -113,7 +113,7 @@ export const deleteRevision = createAction({
|
||||
const revision = stores.revisions.get(revisionId);
|
||||
await revision?.delete();
|
||||
toast.success(t("This version of the document was deleted"));
|
||||
history.push(documentHistoryPath(document));
|
||||
history.push(documentHistoryPath(document), { sidebarContext });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { createAction } from "~/actions";
|
||||
import { DocumentsSection, NavigationSection } from "~/actions/sections";
|
||||
|
||||
/**
|
||||
* Actions that are only registered as WebMCP tools, never in menus or the
|
||||
* command bar. Names and descriptions are intentionally not translated as
|
||||
* they are read by agents, not users.
|
||||
*/
|
||||
export const getCurrentContext = createAction({
|
||||
name: "Get current context",
|
||||
analyticsName: "Get current context",
|
||||
section: NavigationSection,
|
||||
description:
|
||||
"Returns the user's current location in the app as JSON, including the active document and collection if any.",
|
||||
mcp: {},
|
||||
perform: ({ stores, location }) => {
|
||||
const document = stores.documents.active;
|
||||
const collection = stores.collections.active;
|
||||
|
||||
return JSON.stringify({
|
||||
path: location.pathname,
|
||||
user: stores.auth.user
|
||||
? { id: stores.auth.user.id, name: stores.auth.user.name }
|
||||
: undefined,
|
||||
document: document
|
||||
? {
|
||||
id: document.id,
|
||||
title: document.titleWithDefault,
|
||||
path: document.url,
|
||||
}
|
||||
: undefined,
|
||||
collection: collection
|
||||
? { id: collection.id, name: collection.name, path: collection.path }
|
||||
: undefined,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const searchWorkspace = createAction({
|
||||
name: "Search workspace",
|
||||
analyticsName: "Search workspace",
|
||||
section: DocumentsSection,
|
||||
description:
|
||||
"Searches all documents the user can access and returns the top matches as JSON, each with an id, title, path, and a snippet of matching context.",
|
||||
mcp: {
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
query: {
|
||||
type: "string",
|
||||
description: "The text to search for.",
|
||||
},
|
||||
},
|
||||
required: ["query"],
|
||||
},
|
||||
},
|
||||
perform: async ({ stores, mcpArgs }) => {
|
||||
const query = typeof mcpArgs?.query === "string" ? mcpArgs.query : "";
|
||||
if (!query) {
|
||||
return "A query argument is required.";
|
||||
}
|
||||
|
||||
const results = await stores.documents.search({ query, limit: 10 });
|
||||
|
||||
return JSON.stringify(
|
||||
results.map((result) => ({
|
||||
id: result.document.id,
|
||||
title: result.document.titleWithDefault,
|
||||
path: result.document.url,
|
||||
context: result.context,
|
||||
}))
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const rootWebMCPActions = [getCurrentContext, searchWorkspace];
|
||||
@@ -56,7 +56,9 @@ export function createAction(
|
||||
? "button"
|
||||
: context.isCommandBar
|
||||
? "commandbar"
|
||||
: "contextmenu",
|
||||
: context.isMCP
|
||||
? "webmcp"
|
||||
: "contextmenu",
|
||||
});
|
||||
}
|
||||
return definition.perform(context);
|
||||
@@ -355,6 +357,10 @@ export async function performAction(
|
||||
|
||||
if (result instanceof Promise) {
|
||||
return result.catch((err: Error) => {
|
||||
// WebMCP callers surface errors to the agent instead of a toast.
|
||||
if (context.isMCP) {
|
||||
throw err;
|
||||
}
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ const ActionButton = React.forwardRef<HTMLButtonElement, Props>(
|
||||
const button = (
|
||||
<button
|
||||
{...rest}
|
||||
aria-label={label}
|
||||
aria-label={typeof label === "string" ? label : undefined}
|
||||
disabled={disabled || executing}
|
||||
ref={ref}
|
||||
onClick={
|
||||
|
||||
@@ -11,7 +11,7 @@ type Props = {
|
||||
};
|
||||
|
||||
// TODO: Refactor this component to allow injection from plugins
|
||||
const Analytics: React.FC = ({ children }: Props) => {
|
||||
const Analytics: React.FC<Props> = ({ children }: Props) => {
|
||||
// Google Analytics 3
|
||||
React.useEffect(() => {
|
||||
if (!env.GOOGLE_ANALYTICS_ID?.startsWith("UA-")) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { RovingTabIndexProvider } from "@getoutline/react-roving-tabindex";
|
||||
import { observer } from "mobx-react";
|
||||
import * as React from "react";
|
||||
|
||||
type Props = React.HTMLAttributes<HTMLDivElement> & {
|
||||
type Props = Omit<React.HTMLAttributes<HTMLDivElement>, "children"> & {
|
||||
children: () => React.ReactNode;
|
||||
onEscape?: (ev: React.KeyboardEvent<HTMLDivElement>) => void;
|
||||
items: unknown[];
|
||||
|
||||
@@ -8,8 +8,10 @@ import Layout from "~/components/Layout";
|
||||
import RegisterKeyDown from "~/components/RegisterKeyDown";
|
||||
import { RightSidebarProvider } from "~/components/RightSidebarContext";
|
||||
import Sidebar from "~/components/Sidebar";
|
||||
import { rootWebMCPActions } from "~/actions/definitions/webmcp";
|
||||
import useCurrentTeam from "~/hooks/useCurrentTeam";
|
||||
import useKeyDown from "~/hooks/useKeyDown";
|
||||
import useWebMCPActions from "~/hooks/useWebMCPActions";
|
||||
import { usePostLoginPath } from "~/hooks/useLastVisitedPath";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useStores from "~/hooks/useStores";
|
||||
@@ -36,7 +38,7 @@ type Props = {
|
||||
children?: React.ReactNode;
|
||||
};
|
||||
|
||||
const AuthenticatedLayout: React.FC = ({ children }: Props) => {
|
||||
const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => {
|
||||
const { ui, auth } = useStores();
|
||||
const location = useLocation();
|
||||
const layoutRef = React.useRef<HTMLDivElement>(null);
|
||||
@@ -45,6 +47,7 @@ const AuthenticatedLayout: React.FC = ({ children }: Props) => {
|
||||
const [spendPostLoginPath] = usePostLoginPath();
|
||||
|
||||
useKeyDown(".", () => ui.toggleCollapsedSidebar(), { metaKey: true });
|
||||
useWebMCPActions(rootWebMCPActions);
|
||||
|
||||
const goToSearch = (ev: KeyboardEvent) => {
|
||||
if (!ev.metaKey && !ev.ctrlKey) {
|
||||
|
||||
@@ -194,7 +194,7 @@ const Button = <T extends React.ElementType = "button">(
|
||||
{...rest}
|
||||
>
|
||||
<Inner hasIcon={hasIcon} hasText={hasText} disclosure={disclosure}>
|
||||
{hasIcon && ic}
|
||||
{hasIcon && typeof ic !== "function" && ic}
|
||||
{hasText && <Label hasIcon={hasIcon}>{children || value}</Label>}
|
||||
{disclosure && <StyledDisclosureIcon />}
|
||||
</Inner>
|
||||
|
||||
@@ -3,6 +3,8 @@ import { observer } from "mobx-react";
|
||||
import { useState, useMemo, useEffect, useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type Document from "~/models/Document";
|
||||
import type User from "~/models/User";
|
||||
import type { AvatarProps } from "~/components/Avatar";
|
||||
import { AvatarSize, AvatarWithPresence } from "~/components/Avatar";
|
||||
import DocumentViews from "~/components/DocumentViews";
|
||||
import Facepile from "~/components/Facepile";
|
||||
@@ -118,7 +120,7 @@ function Collaborators(props: Props) {
|
||||
);
|
||||
|
||||
const renderAvatar = useCallback(
|
||||
({ model: collaborator, ...rest }) => {
|
||||
({ model: collaborator, ...rest }: AvatarProps & { model: User }) => {
|
||||
const isPresent = presentIds.has(collaborator.id);
|
||||
const isEditing = editingIds.has(collaborator.id);
|
||||
const isObserving = observingUserId === collaborator.id;
|
||||
|
||||
@@ -52,7 +52,7 @@ type Props = {
|
||||
children?: React.ReactNode;
|
||||
};
|
||||
|
||||
const KBarPortal: React.FC = ({ children }: Props) => {
|
||||
const KBarPortal: React.FC<Props> = ({ children }: Props) => {
|
||||
const { showing } = useKBar((state) => ({
|
||||
showing: state.visualState !== "hidden",
|
||||
}));
|
||||
|
||||
@@ -34,7 +34,7 @@ type Props = {
|
||||
children?: React.ReactNode;
|
||||
};
|
||||
|
||||
const KBarPortal: React.FC = ({ children }: Props) => {
|
||||
const KBarPortal: React.FC<Props> = ({ children }: Props) => {
|
||||
const { showing } = useKBar((state) => ({
|
||||
showing: state.visualState !== "hidden",
|
||||
}));
|
||||
|
||||
@@ -46,6 +46,7 @@ const useRecentDocumentActions = (count = recentDocumentCount) => {
|
||||
name: item.titleWithDefault,
|
||||
analyticsName: "Recently viewed document",
|
||||
section: RecentSection,
|
||||
visible: ({ isMCP }) => !isMCP,
|
||||
description: documentBreadcrumbText(item, t),
|
||||
icon: item.icon ? (
|
||||
<Icon
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
|
||||
const plainTextCache = new LRUCache<{ updatedAt: string; text: string }>({
|
||||
max: 100,
|
||||
storage: "memory",
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -36,7 +36,10 @@ const useTemplatesAction = () => {
|
||||
<NewDocumentIcon />
|
||||
),
|
||||
keywords: "create",
|
||||
visible: ({ currentTeamId, activeCollectionId, stores }) => {
|
||||
visible: ({ currentTeamId, activeCollectionId, stores, isMCP }) => {
|
||||
if (isMCP) {
|
||||
return false;
|
||||
}
|
||||
if (activeCollectionId) {
|
||||
return (
|
||||
stores.policies.abilities(activeCollectionId).createDocument &&
|
||||
|
||||
@@ -317,10 +317,13 @@ const DocumentLink = styled(Link)<{
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
// data-state is set by the context menu trigger, so the treatment stays
|
||||
// active while the menu is open
|
||||
&:${hover},
|
||||
&:active,
|
||||
&:focus,
|
||||
&:focus-within {
|
||||
&:focus-within,
|
||||
&[data-state="open"] {
|
||||
transform: ${(props) => (props.$isDragging ? "scale(1.1)" : "scale(1.08)")}
|
||||
rotate(-2deg);
|
||||
box-shadow: ${(props) =>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { action, computed, observable } from "mobx";
|
||||
import { action, computed, makeObservable, observable } from "mobx";
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { createContext, useContext, useMemo } from "react";
|
||||
import type { Node } from "prosemirror-model";
|
||||
@@ -28,6 +28,10 @@ class DocumentContext {
|
||||
@observable
|
||||
headings: Heading[] = [];
|
||||
|
||||
constructor() {
|
||||
makeObservable(this);
|
||||
}
|
||||
|
||||
@computed
|
||||
get hasHeadings() {
|
||||
// Headings inside tables are not listed in the table of contents.
|
||||
@@ -77,7 +81,7 @@ class DocumentContext {
|
||||
|
||||
/** The ProseMirror document currently held by the editor */
|
||||
@observable.ref
|
||||
private editorDoc: Node | undefined;
|
||||
private editorDoc: Node | undefined = undefined;
|
||||
|
||||
private updateHeadings() {
|
||||
const currHeadings = this.editor?.getHeadings() ?? [];
|
||||
|
||||
@@ -5,13 +5,13 @@ import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router-dom";
|
||||
import styled from "styled-components";
|
||||
import { s, ellipsis } from "@shared/styles";
|
||||
import { ellipsis } from "@shared/styles";
|
||||
import type Document from "~/models/Document";
|
||||
import type Revision from "~/models/Revision";
|
||||
import DocumentBreadcrumb from "~/components/DocumentBreadcrumb";
|
||||
import DocumentTasks from "~/components/DocumentTasks";
|
||||
import Flex from "~/components/Flex";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
import { MetaButton, Separator, metaStyles } from "~/components/HeaderMeta";
|
||||
import Time from "~/components/Time";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import useStores from "~/hooks/useStores";
|
||||
@@ -86,7 +86,9 @@ const DocumentMeta: React.FC<Props> = ({
|
||||
<span>
|
||||
{revision.createdBy?.id === user.id
|
||||
? t("You updated")
|
||||
: t("{{ userName }} updated", { userName })}{" "}
|
||||
: t("{{ userName }} updated", {
|
||||
userName: revision.createdBy?.name ?? t("Unknown"),
|
||||
})}{" "}
|
||||
<Time dateTime={revision.createdAt} addSuffix />
|
||||
</span>
|
||||
);
|
||||
@@ -229,42 +231,12 @@ const DocumentMeta: React.FC<Props> = ({
|
||||
);
|
||||
};
|
||||
|
||||
/** A button that visually matches the surrounding meta text. */
|
||||
export const MetaButton = styled(NudeButton)`
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
width: auto;
|
||||
height: auto;
|
||||
border-radius: 0;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: inherit;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
`;
|
||||
|
||||
export const Separator = styled.span`
|
||||
padding: 0 0.4em;
|
||||
|
||||
&::after {
|
||||
content: "•";
|
||||
}
|
||||
`;
|
||||
|
||||
const Strong = styled.strong`
|
||||
font-weight: 550;
|
||||
`;
|
||||
|
||||
const Container = styled(Flex)<{ $rtl?: boolean }>`
|
||||
justify-content: ${(props) => (props.$rtl ? "flex-end" : "flex-start")};
|
||||
color: ${s("textTertiary")};
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
${metaStyles}
|
||||
`;
|
||||
|
||||
const Viewed = styled.span`
|
||||
|
||||
@@ -5,7 +5,7 @@ import { errToString } from "@shared/utils/error";
|
||||
import { s, ellipsis } from "@shared/styles";
|
||||
import EventBoundary from "@shared/components/EventBoundary";
|
||||
|
||||
type Props = Omit<React.HTMLAttributes<HTMLInputElement>, "onSubmit"> & {
|
||||
type Props = Omit<React.InputHTMLAttributes<HTMLInputElement>, "onSubmit"> & {
|
||||
/** A callback when the title is submitted. */
|
||||
onSubmit: (title: string) => Promise<void> | void;
|
||||
/** A callback when the editing status changes. */
|
||||
|
||||
+25
-76
@@ -1,22 +1,17 @@
|
||||
import { difference } from "es-toolkit/compat";
|
||||
import { observer } from "mobx-react";
|
||||
import { DOMParser as ProsemirrorDOMParser } from "prosemirror-model";
|
||||
import { TextSelection } from "prosemirror-state";
|
||||
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 insertFiles from "@shared/editor/commands/insertFiles";
|
||||
import EditorContainer from "@shared/editor/components/Styles";
|
||||
import { AttachmentPreset } from "@shared/types";
|
||||
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
|
||||
import { getDataTransferFiles } from "@shared/utils/files";
|
||||
import { AttachmentValidation } from "@shared/validations";
|
||||
import ClickablePadding from "~/components/ClickablePadding";
|
||||
import ErrorBoundary from "~/components/ErrorBoundary";
|
||||
import PlaceholderDocument from "~/components/PlaceholderDocument";
|
||||
import type { Props as EditorProps, Editor as SharedEditor } from "~/editor";
|
||||
import { toastNotice } from "~/editor/toastNotice";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import useEditorClickHandlers from "~/hooks/useEditorClickHandlers";
|
||||
import useEmbeds from "~/hooks/useEmbeds";
|
||||
@@ -135,61 +130,9 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
|
||||
}, [localRef]);
|
||||
|
||||
const handleDrop = React.useCallback(
|
||||
(event: React.DragEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const files = getDataTransferFiles(event);
|
||||
|
||||
const view = localRef?.current?.view;
|
||||
if (!view) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find a valid position at the end of the document to insert our content
|
||||
const pos = TextSelection.near(
|
||||
view.state.doc.resolve(view.state.doc.nodeSize - 2)
|
||||
).from;
|
||||
|
||||
// If there are no files in the drop event attempt to parse the html
|
||||
// as a fragment and insert it at the end of the document
|
||||
if (files.length === 0) {
|
||||
const text =
|
||||
event.dataTransfer.getData("text/html") ||
|
||||
event.dataTransfer.getData("text/plain");
|
||||
|
||||
const dom = new DOMParser().parseFromString(text, "text/html");
|
||||
|
||||
view.dispatch(
|
||||
view.state.tr.insert(
|
||||
pos,
|
||||
ProsemirrorDOMParser.fromSchema(view.state.schema).parse(dom)
|
||||
)
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Insert all files as attachments if any of the files are not images.
|
||||
const isAttachment = files.some(
|
||||
(file) => !AttachmentValidation.imageContentTypes.includes(file.type)
|
||||
);
|
||||
|
||||
return insertFiles(view, event, pos, files, {
|
||||
uploadFile: handleUploadFile,
|
||||
onFileUploadStart: handleFileUploadStart,
|
||||
onFileUploadStop: handleFileUploadStop,
|
||||
onFileUploadProgress: handleFileUploadProgress,
|
||||
onNotice: toastNotice,
|
||||
isAttachment,
|
||||
});
|
||||
},
|
||||
[
|
||||
localRef,
|
||||
handleFileUploadStart,
|
||||
handleFileUploadStop,
|
||||
handleFileUploadProgress,
|
||||
handleUploadFile,
|
||||
]
|
||||
(event: React.DragEvent<HTMLDivElement>) =>
|
||||
localRef.current?.insertDroppedContent(event),
|
||||
[]
|
||||
);
|
||||
|
||||
// see: https://stackoverflow.com/a/50233827/192065
|
||||
@@ -287,21 +230,27 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
|
||||
</div>
|
||||
</EditorContainer>
|
||||
) : (
|
||||
<LazyLoadedEditor
|
||||
key={props.extensions?.length || 0}
|
||||
ref={mergeRefs([ref, localRef, handleRefChanged])}
|
||||
uploadFile={handleUploadFile}
|
||||
embeds={embeds}
|
||||
userPreferences={preferences}
|
||||
{...props}
|
||||
onClickLink={handleClickLink}
|
||||
onChange={handleChange}
|
||||
onFileUploadStart={handleFileUploadStart}
|
||||
onFileUploadStop={handleFileUploadStop}
|
||||
onFileUploadProgress={handleFileUploadProgress}
|
||||
placeholder={props.placeholder || ""}
|
||||
defaultValue={props.defaultValue || ""}
|
||||
/>
|
||||
// The boundary must live between the lazy editor and any ancestor
|
||||
// with effects or refs. If the suspension reached an outer boundary
|
||||
// React 18 would hide mounted ancestors and destroy their effects,
|
||||
// re-running provider setup and ref callbacks in a loop.
|
||||
<React.Suspense fallback={<PlaceholderDocument delay={500} />}>
|
||||
<LazyLoadedEditor
|
||||
key={props.extensions?.length || 0}
|
||||
ref={mergeRefs([ref, localRef, handleRefChanged])}
|
||||
uploadFile={handleUploadFile}
|
||||
embeds={embeds}
|
||||
userPreferences={preferences}
|
||||
{...props}
|
||||
onClickLink={handleClickLink}
|
||||
onChange={handleChange}
|
||||
onFileUploadStart={handleFileUploadStart}
|
||||
onFileUploadStop={handleFileUploadStop}
|
||||
onFileUploadProgress={handleFileUploadProgress}
|
||||
placeholder={props.placeholder || ""}
|
||||
defaultValue={props.defaultValue || ""}
|
||||
/>
|
||||
</React.Suspense>
|
||||
)}
|
||||
{props.editorStyle?.paddingBottom && !props.readOnly && (
|
||||
<ClickablePadding
|
||||
|
||||
@@ -29,6 +29,14 @@ const topHandlerNames = [
|
||||
const isWithinEditor = (target: EventTarget | null): boolean =>
|
||||
target instanceof Element && Boolean(target.closest(".ProseMirror"));
|
||||
|
||||
// A file dragged over an element marked `data-drop-area`, which accepts native
|
||||
// file drops itself. react-dnd never tracks these drags, so its handlers would
|
||||
// otherwise reject them.
|
||||
const isFileOverDropArea = (event: DragEvent): boolean =>
|
||||
Boolean(event.dataTransfer?.types.includes("Files")) &&
|
||||
event.target instanceof Element &&
|
||||
Boolean(event.target.closest("[data-drop-area]"));
|
||||
|
||||
/**
|
||||
* An HTML5 drag-and-drop backend that ignores drag events originating within the
|
||||
* rich text editor so that ProseMirror can handle them itself.
|
||||
@@ -57,7 +65,7 @@ export const EditorAwareHTML5Backend: BackendFactory = (
|
||||
const original = handlers[name];
|
||||
if (typeof original === "function") {
|
||||
handlers[name] = (event: DragEvent) => {
|
||||
if (isWithinEditor(event.target)) {
|
||||
if (isWithinEditor(event.target) || isFileOverDropArea(event)) {
|
||||
return;
|
||||
}
|
||||
// A drag that began or entered the page over the editor is never
|
||||
|
||||
@@ -8,7 +8,7 @@ import Input, { LabelText } from "~/components/Input";
|
||||
import Text from "~/components/Text";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { uploadFile } from "~/utils/files";
|
||||
import { compressImage } from "~/utils/compressImage";
|
||||
import { ImageHelper } from "~/utils/ImageHelper";
|
||||
import { generateEmojiNameFromFilename } from "~/utils/emoji";
|
||||
import { useEmojiFileUpload, EmojiImageDropZone } from "./Components";
|
||||
|
||||
@@ -55,7 +55,7 @@ export function EmojiCreateDialog({ onSubmit }: Props) {
|
||||
const fileToUpload =
|
||||
file.type === "image/gif"
|
||||
? file
|
||||
: await compressImage(file, {
|
||||
: await ImageHelper.compress(file, {
|
||||
maxHeight: 64,
|
||||
maxWidth: 64,
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ import Text from "~/components/Text";
|
||||
import type Emoji from "~/models/Emoji";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { uploadFile } from "~/utils/files";
|
||||
import { compressImage } from "~/utils/compressImage";
|
||||
import { ImageHelper } from "~/utils/ImageHelper";
|
||||
import { useEmojiFileUpload, EmojiImageDropZone } from "./Components";
|
||||
|
||||
interface Props {
|
||||
@@ -38,7 +38,7 @@ export function EmojiReplaceDialog({ emoji, onSubmit }: Props) {
|
||||
const fileToUpload =
|
||||
file.type === "image/gif"
|
||||
? file
|
||||
: await compressImage(file, {
|
||||
: await ImageHelper.compress(file, {
|
||||
maxHeight: 64,
|
||||
maxWidth: 64,
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { observable } from "mobx";
|
||||
import { makeObservable, observable } from "mobx";
|
||||
import { observer } from "mobx-react";
|
||||
import * as React from "react";
|
||||
import type { TFunction } from "i18next";
|
||||
@@ -25,7 +25,7 @@ interface OwnProps {
|
||||
/** Whether to show a title heading. */
|
||||
showTitle?: boolean;
|
||||
/** The wrapping component to use. */
|
||||
component?: React.ComponentType | string;
|
||||
component?: React.ComponentType<React.PropsWithChildren> | string;
|
||||
/** Children rendered when no error is present. */
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
@@ -40,7 +40,7 @@ const ERROR_TRACKING_WINDOW_MS = 5 * 60 * 1000; // 5 minutes
|
||||
@observer
|
||||
class ErrorBoundaryClass extends React.Component<Props> {
|
||||
@observable
|
||||
error: Error | null | undefined;
|
||||
error: Error | null | undefined = undefined;
|
||||
|
||||
@observable
|
||||
showDetails = false;
|
||||
@@ -48,6 +48,11 @@ class ErrorBoundaryClass extends React.Component<Props> {
|
||||
@observable
|
||||
isRepeatedError = false;
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
makeObservable(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.checkForPreviousErrors();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { observer } from "mobx-react";
|
||||
import { ArchiveIcon, CodeIcon } from "outline-icons";
|
||||
import { ArchiveIcon, CodeIcon, GlobeIcon } from "outline-icons";
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import styled from "styled-components";
|
||||
@@ -72,6 +72,12 @@ export const ExportDialog = observer(({ collection, onSubmit }: Props) => {
|
||||
value: FileOperationFormat.MarkdownZip,
|
||||
icon: <MarkdownIcon />,
|
||||
},
|
||||
{
|
||||
title: "Open Knowledge Format",
|
||||
extension: ".okf.zip",
|
||||
value: FileOperationFormat.OKFZip,
|
||||
icon: <GlobeIcon />,
|
||||
},
|
||||
{
|
||||
title: "HTML",
|
||||
extension: ".html.zip",
|
||||
|
||||
@@ -69,7 +69,7 @@ const FilterOptions = ({
|
||||
: "";
|
||||
|
||||
const renderItem = React.useCallback(
|
||||
(option) => {
|
||||
(option: TFilterOption) => {
|
||||
const handleClick = () => {
|
||||
onSelect(option.key);
|
||||
setOpen(false);
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import styled, { css } from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import { s } from "@shared/styles";
|
||||
import Flex from "~/components/Flex";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
|
||||
/** A dot separating two pieces of meta information. */
|
||||
export const Separator = styled.span`
|
||||
padding: 0 0.4em;
|
||||
|
||||
&::after {
|
||||
content: "•";
|
||||
}
|
||||
`;
|
||||
|
||||
/** A button that visually matches the surrounding meta text. */
|
||||
export const MetaButton = styled(NudeButton)`
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
width: auto;
|
||||
height: auto;
|
||||
border-radius: 0;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: inherit;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
`;
|
||||
|
||||
/** Lays out a line of meta information about a document or collection. */
|
||||
export const metaStyles = css<{ $rtl?: boolean }>`
|
||||
justify-content: ${(props) => (props.$rtl ? "flex-end" : "flex-start")};
|
||||
color: ${s("textTertiary")};
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
`;
|
||||
|
||||
/**
|
||||
* Additional styles for a line of meta information rendered directly beneath a
|
||||
* page title. Composed by `HeaderMeta`, and applied directly by consumers that
|
||||
* style an existing meta component rather than rendering their own.
|
||||
*/
|
||||
export const headerMetaStyles = css`
|
||||
margin: -12px 0 2em 0;
|
||||
font-size: 14px;
|
||||
position: relative;
|
||||
user-select: none;
|
||||
z-index: 1;
|
||||
|
||||
${breakpoint("mobile", "tablet")`
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
line-height: 1.6;
|
||||
|
||||
${Separator} {
|
||||
display: none;
|
||||
}
|
||||
`}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
cursor: var(--pointer);
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
@media print {
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
|
||||
/**
|
||||
* A line of meta information rendered directly beneath a page title, stacking
|
||||
* into a list on mobile and hidden when printing.
|
||||
*/
|
||||
export const HeaderMeta = styled(Flex)<{ $rtl?: boolean }>`
|
||||
${metaStyles}
|
||||
${headerMetaStyles}
|
||||
`;
|
||||
@@ -30,7 +30,7 @@ function InputSearch(
|
||||
} = props;
|
||||
|
||||
const handleFocus = React.useCallback(
|
||||
(event) => {
|
||||
(event: React.FocusEvent<HTMLInputElement>) => {
|
||||
setIsFocused(true);
|
||||
onFocus?.(event);
|
||||
},
|
||||
@@ -38,7 +38,7 @@ function InputSearch(
|
||||
);
|
||||
|
||||
const handleBlur = React.useCallback(
|
||||
(event) => {
|
||||
(event: React.FocusEvent<HTMLInputElement>) => {
|
||||
setIsFocused(false);
|
||||
onBlur?.(event);
|
||||
},
|
||||
|
||||
@@ -9,7 +9,7 @@ type Props = {
|
||||
/**
|
||||
* Asyncronously load required polyfills. Should wrap the React tree.
|
||||
*/
|
||||
export const LazyPolyfill: React.FC = ({ children }: Props) => {
|
||||
export const LazyPolyfill: React.FC<Props> = ({ children }: Props) => {
|
||||
const [isLoaded, setIsLoaded] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
|
||||
@@ -132,7 +132,7 @@ const ListItem = (
|
||||
as={NavLink}
|
||||
to={to}
|
||||
>
|
||||
{content}
|
||||
{(match) => content(!!match)}
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { action, computed, observable } from "mobx";
|
||||
import { action, computed, makeObservable, observable } from "mobx";
|
||||
|
||||
/**
|
||||
* Holds the ephemeral multi-selection state for a single list of models.
|
||||
@@ -10,6 +10,10 @@ import { action, computed, observable } from "mobx";
|
||||
export class ModelSelection {
|
||||
private ids = observable.set<string>();
|
||||
|
||||
constructor() {
|
||||
makeObservable(this);
|
||||
}
|
||||
|
||||
/** Ordered identifiers of the list, used to resolve shift-click ranges. */
|
||||
private order: string[] = [];
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { LocationDescriptor, LocationDescriptorObject } from "history";
|
||||
import * as React from "react";
|
||||
import { type match, NavLink, Route } from "react-router-dom";
|
||||
|
||||
type Props = React.ComponentProps<typeof NavLink> & {
|
||||
type Props = Omit<React.ComponentProps<typeof NavLink>, "children"> & {
|
||||
children?: (
|
||||
match:
|
||||
| match<{
|
||||
|
||||
@@ -22,7 +22,7 @@ type Props = {
|
||||
children?: React.ReactNode;
|
||||
};
|
||||
|
||||
const NotificationsPopover: React.FC = ({ children }: Props) => {
|
||||
const NotificationsPopover: React.FC<Props> = ({ children }: Props) => {
|
||||
const { t } = useTranslation();
|
||||
const { notifications } = useStores();
|
||||
const shouldOpen = isTruthyQueryValue(useConsumeQueryParam("notifications"));
|
||||
|
||||
@@ -5,33 +5,31 @@ import { InputSelect } from "../InputSelect";
|
||||
/**
|
||||
* An input that allows a choice of OAuth client type.
|
||||
*/
|
||||
export const InputClientType = React.forwardRef(
|
||||
(
|
||||
props: Omit<React.ComponentProps<typeof InputSelect>, "options" | "label">,
|
||||
ref: React.Ref<HTMLButtonElement>
|
||||
) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<InputSelect
|
||||
{...props}
|
||||
label={t("Client type")}
|
||||
ref={ref}
|
||||
style={{ marginBottom: "1em" }}
|
||||
options={[
|
||||
{
|
||||
type: "item",
|
||||
label: t("Confidential"),
|
||||
value: "confidential",
|
||||
description: t("Suitable for server-side applications"),
|
||||
},
|
||||
{
|
||||
type: "item",
|
||||
label: t("Public"),
|
||||
value: "public",
|
||||
description: t("Suitable for client-side or mobile applications"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
export const InputClientType = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
Omit<React.ComponentPropsWithoutRef<typeof InputSelect>, "options" | "label">
|
||||
>((props, ref) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<InputSelect
|
||||
{...props}
|
||||
label={t("Client type")}
|
||||
ref={ref}
|
||||
style={{ marginBottom: "1em" }}
|
||||
options={[
|
||||
{
|
||||
type: "item",
|
||||
label: t("Confidential"),
|
||||
value: "confidential",
|
||||
description: t("Suitable for server-side applications"),
|
||||
},
|
||||
{
|
||||
type: "item",
|
||||
label: t("Public"),
|
||||
value: "public",
|
||||
description: t("Suitable for client-side or mobile applications"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
});
|
||||
@@ -2,12 +2,18 @@ import { useEffect } from "react";
|
||||
import { useTheme } from "styled-components";
|
||||
import { light } from "@shared/styles/theme";
|
||||
|
||||
/**
|
||||
* Synchronizes browser page colors with the active application theme.
|
||||
*
|
||||
* @returns null.
|
||||
*/
|
||||
export default function PageTheme() {
|
||||
const theme = useTheme();
|
||||
const { background, isDark } = theme;
|
||||
|
||||
useEffect(() => {
|
||||
// theme-color adjusts the title bar color for desktop PWA
|
||||
const themeElement = document.querySelector('meta[name="theme-color"]');
|
||||
// theme-color adjusts the browser chrome for installed PWAs
|
||||
const themeElements = document.querySelectorAll('meta[name="theme-color"]');
|
||||
|
||||
// color-scheme controls user-agent controls, scrollbars and the page canvas
|
||||
const colorSchemeElement = document.querySelector(
|
||||
@@ -19,17 +25,19 @@ export default function PageTheme() {
|
||||
if (document.body) {
|
||||
document.body.style.background = background;
|
||||
}
|
||||
themeElement?.setAttribute("content", background);
|
||||
themeElements.forEach((element) => {
|
||||
element.setAttribute("content", background);
|
||||
});
|
||||
colorSchemeElement?.setAttribute("content", isDark ? "dark" : "light");
|
||||
};
|
||||
|
||||
applyTheme(theme.background, theme.isDark);
|
||||
applyTheme(background, isDark);
|
||||
|
||||
const handleChange = (event: MediaQueryListEvent) => {
|
||||
if (event.matches) {
|
||||
applyTheme(light.background, false);
|
||||
} else {
|
||||
applyTheme(theme.background, theme.isDark);
|
||||
applyTheme(background, isDark);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -39,7 +47,7 @@ export default function PageTheme() {
|
||||
const mediaQuery = window.matchMedia("print");
|
||||
mediaQuery.addEventListener("change", handleChange);
|
||||
return () => mediaQuery.removeEventListener("change", handleChange);
|
||||
}, [theme]);
|
||||
}, [background, isDark]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -92,6 +92,7 @@ function SearchActions() {
|
||||
keywords: searchQuery,
|
||||
analyticsName: "Open search result",
|
||||
section: SearchResultsSection,
|
||||
visible: ({ isMCP }) => !isMCP,
|
||||
priority: toActionPriority(index, results.length),
|
||||
icon: <SearchResultIcon document={result.document} />,
|
||||
badge: result.document.isArchived ? (
|
||||
|
||||
@@ -137,7 +137,7 @@ function SharePopover({
|
||||
}, [pendingIds, prevPendingIds]);
|
||||
|
||||
const handleQuery = React.useCallback(
|
||||
(event) => {
|
||||
(event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
showPicker();
|
||||
setQuery(event.target.value);
|
||||
},
|
||||
|
||||
@@ -8,6 +8,7 @@ import styled, { useTheme } from "styled-components";
|
||||
import { s } from "@shared/styles";
|
||||
import { DocumentPermission } from "@shared/types";
|
||||
import type Document from "~/models/Document";
|
||||
import type User from "~/models/User";
|
||||
import type UserMembership from "~/models/UserMembership";
|
||||
import { GroupAvatar } from "~/components/Avatar";
|
||||
import InputMemberPermissionSelect from "~/components/InputMemberPermissionSelect";
|
||||
@@ -41,7 +42,7 @@ function DocumentMemberList({ document, invitedInSession }: Props) {
|
||||
const theme = useTheme();
|
||||
|
||||
const handleRemoveUser = React.useCallback(
|
||||
async (item) => {
|
||||
async (item: User) => {
|
||||
try {
|
||||
await userMemberships.delete({
|
||||
documentId: document.id,
|
||||
@@ -65,7 +66,7 @@ function DocumentMemberList({ document, invitedInSession }: Props) {
|
||||
);
|
||||
|
||||
const handleUpdateUser = React.useCallback(
|
||||
async (userToUpdate, permission) => {
|
||||
async (userToUpdate: User, permission: DocumentPermission) => {
|
||||
try {
|
||||
await userMemberships.create({
|
||||
documentId: document.id,
|
||||
|
||||
@@ -253,7 +253,7 @@ function SharePopover({
|
||||
);
|
||||
|
||||
const handleQuery = React.useCallback(
|
||||
(event) => {
|
||||
(event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
showPicker();
|
||||
setQuery(event.target.value);
|
||||
},
|
||||
|
||||
@@ -26,8 +26,8 @@ export const SearchInput = React.forwardRef(function SearchInput_(
|
||||
const isMobile = useMobile();
|
||||
|
||||
const focusInput = React.useCallback(
|
||||
(event) => {
|
||||
if (event.target.closest("button")) {
|
||||
(event: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (event.target instanceof Element && event.target.closest("button")) {
|
||||
return;
|
||||
}
|
||||
inputRef.current?.focus();
|
||||
|
||||
@@ -29,7 +29,7 @@ import Tooltip from "~/components/Tooltip";
|
||||
import env from "~/env";
|
||||
import { useMenuAction } from "~/hooks/useMenuAction";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { compressImage } from "~/utils/compressImage";
|
||||
import { ImageHelper } from "~/utils/ImageHelper";
|
||||
import { uploadFile } from "~/utils/files";
|
||||
import {
|
||||
Popover,
|
||||
@@ -90,7 +90,7 @@ function ShareSettingsPopover({ share, children }: Props) {
|
||||
|
||||
setIsUploading(true);
|
||||
try {
|
||||
const compressed = await compressImage(file, {
|
||||
const compressed = await ImageHelper.compress(file, {
|
||||
maxHeight: 512,
|
||||
maxWidth: 512,
|
||||
});
|
||||
|
||||
@@ -60,7 +60,8 @@ const Sidebar = React.forwardRef<HTMLDivElement, Props>(function Sidebar_(
|
||||
const user = useCurrentUser({ rejectOnEmpty: false });
|
||||
const isMobile = useMobile();
|
||||
const width = ui.sidebarWidth;
|
||||
const collapsed = ui.sidebarIsClosed && canCollapse;
|
||||
const sidebarIsClosed = ui.sidebarIsClosed;
|
||||
const collapsed = sidebarIsClosed && canCollapse;
|
||||
const maxWidth = theme.sidebarMaxWidth;
|
||||
const minWidth = theme.sidebarResizeMinWidth;
|
||||
const direction = useDirection();
|
||||
@@ -149,7 +150,7 @@ const Sidebar = React.forwardRef<HTMLDivElement, Props>(function Sidebar_(
|
||||
|
||||
const handlePointerActivity = React.useCallback(
|
||||
(event: React.PointerEvent) => {
|
||||
if (ui.sidebarIsClosed) {
|
||||
if (sidebarIsClosed) {
|
||||
// don't reveal while a button is held, e.g. selecting text near the edge
|
||||
if (event.buttons !== 0) {
|
||||
return;
|
||||
@@ -162,11 +163,11 @@ const Sidebar = React.forwardRef<HTMLDivElement, Props>(function Sidebar_(
|
||||
setPointerMoved(true);
|
||||
}
|
||||
},
|
||||
[ui.sidebarIsClosed]
|
||||
[sidebarIsClosed]
|
||||
);
|
||||
|
||||
const handlePointerLeave = React.useCallback(
|
||||
(ev) => {
|
||||
(ev: React.PointerEvent) => {
|
||||
if (hasPointerMoved) {
|
||||
// clear any previous timeout
|
||||
if (hoverTimeoutRef.current) {
|
||||
@@ -193,11 +194,11 @@ const Sidebar = React.forwardRef<HTMLDivElement, Props>(function Sidebar_(
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (ui.sidebarIsClosed) {
|
||||
if (sidebarIsClosed) {
|
||||
setHovering(false);
|
||||
setPointerMoved(false);
|
||||
}
|
||||
}, [ui.sidebarIsClosed]);
|
||||
}, [sidebarIsClosed]);
|
||||
|
||||
// Reset stale hover state when the sidebar becomes visible after being
|
||||
// hidden via display:none (e.g. returning from settings). Without this, a
|
||||
@@ -315,7 +316,7 @@ const Sidebar = React.forwardRef<HTMLDivElement, Props>(function Sidebar_(
|
||||
)}
|
||||
<ResizeBorder
|
||||
onMouseDown={handleMouseDown}
|
||||
onDoubleClick={ui.sidebarIsClosed ? undefined : handleReset}
|
||||
onDoubleClick={sidebarIsClosed ? undefined : handleReset}
|
||||
/>
|
||||
</Container>
|
||||
{ui.mobileSidebarVisible && <Backdrop onClick={handleCloseSidebar} />}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { isUndefined } from "es-toolkit/compat";
|
||||
import { observer } from "mobx-react";
|
||||
import { ArchiveIcon } from "outline-icons";
|
||||
import type * as React from "react";
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Flex from "@shared/components/Flex";
|
||||
@@ -24,6 +25,8 @@ function ArchiveLink() {
|
||||
|
||||
const [disclosure, setDisclosure] = useState<boolean>(false);
|
||||
const [expanded, setExpanded] = useState<boolean | undefined>();
|
||||
const archivedCollections = collections.archived;
|
||||
const hasArchivedCollections = archivedCollections.length > 0;
|
||||
|
||||
const { data, loading, error } = useRequest(collections.fetchArchived, true);
|
||||
|
||||
@@ -34,8 +37,8 @@ function ArchiveLink() {
|
||||
}, [data, loading, error]);
|
||||
|
||||
useEffect(() => {
|
||||
setDisclosure(collections.archived.length > 0);
|
||||
}, [collections.archived]);
|
||||
setDisclosure(hasArchivedCollections);
|
||||
}, [hasArchivedCollections]);
|
||||
|
||||
useEffect(() => {
|
||||
if (disclosure && isUndefined(expanded)) {
|
||||
@@ -43,11 +46,14 @@ function ArchiveLink() {
|
||||
}
|
||||
}, [disclosure, expanded]);
|
||||
|
||||
const handleDisclosureClick = useCallback((ev) => {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
setExpanded((e) => !e);
|
||||
}, []);
|
||||
const handleDisclosureClick = useCallback(
|
||||
(ev: React.MouseEvent<HTMLElement>) => {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
setExpanded((e) => !e);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
setExpanded(true);
|
||||
@@ -78,7 +84,7 @@ function ArchiveLink() {
|
||||
<PaginatedList<Collection>
|
||||
aria-label={t("Archived collections")}
|
||||
fetch={collections.fetchArchived}
|
||||
items={collections.archived}
|
||||
items={archivedCollections}
|
||||
loading={<PlaceholderCollections />}
|
||||
renderError={(props) => <StyledError {...props} />}
|
||||
renderItem={(item) => (
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type * as React from "react";
|
||||
import { useState, useCallback } from "react";
|
||||
import type Collection from "~/models/Collection";
|
||||
import useStores from "~/hooks/useStores";
|
||||
@@ -14,11 +15,14 @@ export function ArchivedCollectionLink({ collection, depth = 0 }: Props) {
|
||||
const { documents } = useStores();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
const handleDisclosureClick = useCallback((ev) => {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
setExpanded((e) => !e);
|
||||
}, []);
|
||||
const handleDisclosureClick = useCallback(
|
||||
(ev: React.MouseEvent<HTMLElement>) => {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
setExpanded((e) => !e);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
setExpanded(true);
|
||||
|
||||
@@ -227,7 +227,9 @@ function CollectionRow({
|
||||
);
|
||||
|
||||
return (
|
||||
<ActionContextProvider value={{ activeModels: [collection] }}>
|
||||
<ActionContextProvider
|
||||
value={{ activeModels: [collection], sidebarContext }}
|
||||
>
|
||||
<Relative ref={mergedRef}>
|
||||
<DropToImport collectionId={collection.id}>
|
||||
{sidebarLinkElement}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Location } from "history";
|
||||
import { observer } from "mobx-react";
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { match } from "react-router";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import scrollIntoView from "scroll-into-view-if-needed";
|
||||
import Icon from "@shared/components/Icon";
|
||||
@@ -275,7 +276,7 @@ const DocumentLinkInner = observer(function DocumentLinkInner({
|
||||
|
||||
const isActiveCheck = React.useCallback(
|
||||
(
|
||||
match,
|
||||
match: match | null,
|
||||
location: Location<{
|
||||
sidebarContext?: SidebarContextType;
|
||||
}>
|
||||
|
||||
@@ -284,6 +284,7 @@ function DocumentRow({
|
||||
<ActionContextProvider
|
||||
value={{
|
||||
activeModels: document ? [document] : [],
|
||||
sidebarContext,
|
||||
}}
|
||||
>
|
||||
<Relative ref={parentRef}>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import fractionalIndex from "fractional-index";
|
||||
import { observer } from "mobx-react";
|
||||
import type * as React from "react";
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import type { DropTargetMonitor } from "react-dnd";
|
||||
import { useDrop, useDrag } from "react-dnd";
|
||||
@@ -99,7 +100,7 @@ function DraggableCollectionLink({
|
||||
]);
|
||||
|
||||
const handleDisclosureClick = useCallback(
|
||||
(ev) => {
|
||||
(ev?: React.MouseEvent<HTMLElement>) => {
|
||||
ev?.preventDefault();
|
||||
setExpanded((e) => {
|
||||
const willExpand = !e;
|
||||
|
||||
@@ -28,7 +28,7 @@ const GroupLink: React.FC<Props> = ({ group }) => {
|
||||
useSidebarDisclosureState();
|
||||
|
||||
const handleDisclosureClick = React.useCallback(
|
||||
(ev) => {
|
||||
(ev?: React.MouseEvent<HTMLElement>) => {
|
||||
ev?.preventDefault();
|
||||
setExpanded((e) => {
|
||||
const willExpand = !e;
|
||||
|
||||
@@ -2,6 +2,7 @@ import fractionalIndex from "fractional-index";
|
||||
import type { Location } from "history";
|
||||
import { observer } from "mobx-react";
|
||||
import * as React from "react";
|
||||
import type { match } from "react-router";
|
||||
import { IconType, NotificationEventType } from "@shared/types";
|
||||
import { determineIconType } from "@shared/utils/icon";
|
||||
import type GroupMembership from "~/models/GroupMembership";
|
||||
@@ -140,8 +141,10 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) {
|
||||
useDropToReorderUserMembership(getIndex);
|
||||
|
||||
const isActive = React.useCallback(
|
||||
(match, location: Location<{ sidebarContext?: SidebarContextType }>) =>
|
||||
!!match && location.state?.sidebarContext === sidebarContext,
|
||||
(
|
||||
match: match | null,
|
||||
location: Location<{ sidebarContext?: SidebarContextType }>
|
||||
) => !!match && location.state?.sidebarContext === sidebarContext,
|
||||
[sidebarContext]
|
||||
);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { action, observable } from "mobx";
|
||||
import { action, makeObservable, observable } from "mobx";
|
||||
import { createContext, useContext, useEffect, useState } from "react";
|
||||
import type { NavigationNode } from "@shared/types";
|
||||
|
||||
@@ -46,6 +46,10 @@ export class SidebarExpansionState {
|
||||
@observable
|
||||
expandedIds = new Set<string>();
|
||||
|
||||
constructor() {
|
||||
makeObservable(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a given node is currently expanded.
|
||||
*
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Location } from "history";
|
||||
import { observer } from "mobx-react";
|
||||
import * as React from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import type { match } from "react-router";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import styled from "styled-components";
|
||||
import { type NavigationNode, UserPreference } from "@shared/types";
|
||||
@@ -174,7 +175,10 @@ const StarredDocumentLink = observer(function StarredDocumentLink({
|
||||
});
|
||||
|
||||
const isActive = React.useCallback(
|
||||
(match, location: Location<{ sidebarContext?: SidebarContextType }>) => {
|
||||
(
|
||||
match: match | null,
|
||||
location: Location<{ sidebarContext?: SidebarContextType }>
|
||||
) => {
|
||||
if (location.state?.sidebarContext !== sidebarContext) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import Text from "~/components/Text";
|
||||
import { undraggableOnDesktop } from "~/styles";
|
||||
|
||||
interface Props extends Omit<
|
||||
React.ComponentProps<typeof RadixSwitch.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof RadixSwitch.Root>,
|
||||
"checked" | "onCheckedChange" | "onChange"
|
||||
> {
|
||||
/** Width of the switch. Defaults to 32. */
|
||||
|
||||
@@ -69,12 +69,12 @@ type Props = {
|
||||
* multiple tab bars on screen at once don't share the "underline" layoutId and
|
||||
* animate between each other. Only needed when composing `Tab` outside of `Tabs`.
|
||||
*/
|
||||
export const TabsGroup: React.FC = ({ children }: Props) => {
|
||||
export const TabsGroup: React.FC<Props> = ({ children }: Props) => {
|
||||
const layoutGroupId = React.useMemo(() => uniqueId("tabs-"), []);
|
||||
return <LayoutGroup id={layoutGroupId}>{children}</LayoutGroup>;
|
||||
};
|
||||
|
||||
export const Tabs: React.FC = ({ children }: Props) => {
|
||||
export const Tabs: React.FC<Props> = ({ children }: Props) => {
|
||||
const ref = React.useRef<HTMLElement>(null);
|
||||
const [shadowVisible, setShadow] = React.useState(false);
|
||||
const { width } = useWindowSize();
|
||||
|
||||
@@ -13,7 +13,7 @@ type Props = {
|
||||
children?: React.ReactNode;
|
||||
};
|
||||
|
||||
const Theme: React.FC = ({ children }: Props) => {
|
||||
const Theme: React.FC<Props> = ({ children }: Props) => {
|
||||
const { auth, ui } = useStores();
|
||||
const { i18n } = useTranslation();
|
||||
const theme = useBuildTheme(
|
||||
|
||||
@@ -792,6 +792,10 @@ function useNotificationHandlers() {
|
||||
}
|
||||
);
|
||||
|
||||
socket.on("notifications.delete", (event: WebsocketEntityDeletedEvent) => {
|
||||
notifications.remove(event.modelId);
|
||||
});
|
||||
|
||||
socket.on(
|
||||
"subscriptions.create",
|
||||
(event: PartialExcept<Subscription, "id">) => {
|
||||
|
||||
@@ -121,7 +121,7 @@ function BlockMenu(props: Props) {
|
||||
return [...baseItems, { name: "separator" } as MenuItem, templateMenuItem];
|
||||
}, [t, elementRef, templateMenuItem]);
|
||||
|
||||
const renderMenuItem = useCallback(
|
||||
const renderMenuItem = useCallback<SuggestionsMenuProps["renderMenuItem"]>(
|
||||
(item, _index, options) => (
|
||||
<SuggestionsMenuItem
|
||||
{...options}
|
||||
|
||||
@@ -93,7 +93,9 @@ function DocumentMenu({ search = "", isActive, ...rest }: Props) {
|
||||
]
|
||||
: [];
|
||||
|
||||
const renderMenuItem = useCallback(
|
||||
const renderMenuItem = useCallback<
|
||||
SuggestionsMenuProps<MentionMenuItem>["renderMenuItem"]
|
||||
>(
|
||||
(item, _index, options) => (
|
||||
<SuggestionsMenuItem
|
||||
{...options}
|
||||
|
||||
@@ -59,7 +59,9 @@ const EmojiMenu = (props: Props) => {
|
||||
[search, emojis.orderedData]
|
||||
);
|
||||
|
||||
const renderMenuItem = useCallback(
|
||||
const renderMenuItem = useCallback<
|
||||
SuggestionsMenuProps<Emoji>["renderMenuItem"]
|
||||
>(
|
||||
(item, _index, options) => (
|
||||
<EmojiMenuItem {...options} title={item.description} emoji={item.emoji} />
|
||||
),
|
||||
|
||||
@@ -30,6 +30,7 @@ import { HStack } from "~/components/primitives/HStack";
|
||||
|
||||
type KeyboardShortcutsProps = {
|
||||
open: boolean;
|
||||
inputRef: React.RefObject<HTMLInputElement>;
|
||||
handleOpen: ({ withReplace }: { withReplace: boolean }) => void;
|
||||
handleCaseSensitive: () => void;
|
||||
handleRegex: () => void;
|
||||
@@ -37,6 +38,7 @@ type KeyboardShortcutsProps = {
|
||||
|
||||
function useKeyboardShortcuts({
|
||||
open,
|
||||
inputRef,
|
||||
handleOpen,
|
||||
handleCaseSensitive,
|
||||
handleRegex,
|
||||
@@ -45,8 +47,8 @@ function useKeyboardShortcuts({
|
||||
useKeyDown(
|
||||
(ev) =>
|
||||
isModKey(ev) &&
|
||||
!open &&
|
||||
ev.code === "KeyF" &&
|
||||
(!open || ev.altKey || document.activeElement !== inputRef.current) &&
|
||||
// Keyboard handler is through the AppMenu on Desktop v1.2.0+
|
||||
!(Desktop.bridge && "onFindInPage" in Desktop.bridge),
|
||||
(ev) => {
|
||||
@@ -272,7 +274,7 @@ export default function FindAndReplace({
|
||||
);
|
||||
|
||||
const handleReplace = React.useCallback(
|
||||
(ev) => {
|
||||
(ev: React.SyntheticEvent) => {
|
||||
if (readOnly) {
|
||||
return;
|
||||
}
|
||||
@@ -283,7 +285,7 @@ export default function FindAndReplace({
|
||||
);
|
||||
|
||||
const handleReplaceAll = React.useCallback(
|
||||
(ev) => {
|
||||
(ev: React.SyntheticEvent) => {
|
||||
if (readOnly) {
|
||||
return;
|
||||
}
|
||||
@@ -318,8 +320,23 @@ export default function FindAndReplace({
|
||||
[handleReplace]
|
||||
);
|
||||
|
||||
const handleEscape = React.useCallback(
|
||||
(ev: KeyboardEvent) => {
|
||||
if (!searchTerm) {
|
||||
return;
|
||||
}
|
||||
|
||||
ev.preventDefault();
|
||||
debouncedFind.cancel();
|
||||
setSearchTerm("");
|
||||
editor.commands.clearSearch();
|
||||
},
|
||||
[debouncedFind, editor.commands, searchTerm]
|
||||
);
|
||||
|
||||
useKeyboardShortcuts({
|
||||
open: localOpen,
|
||||
inputRef,
|
||||
handleOpen,
|
||||
handleCaseSensitive,
|
||||
handleRegex,
|
||||
@@ -414,11 +431,9 @@ export default function FindAndReplace({
|
||||
width={0}
|
||||
minWidth={420}
|
||||
scrollable={false}
|
||||
onPointerDownOutside={() => setLocalOpen(false)}
|
||||
onFocusOutside={(event) => {
|
||||
event.preventDefault();
|
||||
inputRef.current?.focus();
|
||||
}}
|
||||
onEscapeKeyDown={handleEscape}
|
||||
onPointerDownOutside={(ev) => ev.preventDefault()}
|
||||
onFocusOutside={(ev) => ev.preventDefault()}
|
||||
style={{ marginRight: 16, marginTop: 60 }}
|
||||
>
|
||||
<Content column>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { transparentize } from "polished";
|
||||
import { NodeSelection } from "prosemirror-state";
|
||||
import { selectedRect } from "prosemirror-tables";
|
||||
import * as React from "react";
|
||||
@@ -6,7 +7,7 @@ import styled, { css, keyframes } from "styled-components";
|
||||
import { isCode } from "@shared/editor/lib/isCode";
|
||||
import { findParentNode } from "@shared/editor/queries/findParentNode";
|
||||
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
|
||||
import { depths, s } from "@shared/styles";
|
||||
import { depths, hairline, s } from "@shared/styles";
|
||||
import { HEADER_HEIGHT } from "~/components/Header";
|
||||
import { Portal } from "~/components/Portal";
|
||||
import useEventListener from "~/hooks/useEventListener";
|
||||
@@ -246,6 +247,7 @@ const FloatingToolbar = React.forwardRef(function FloatingToolbar_(
|
||||
) {
|
||||
const menuRef = ref || React.createRef<HTMLDivElement>();
|
||||
const [isSelectingText, setSelectingText] = React.useState(false);
|
||||
const raisedClickAt = React.useRef(0);
|
||||
|
||||
let position = usePosition({
|
||||
menuRef,
|
||||
@@ -268,23 +270,61 @@ const FloatingToolbar = React.forwardRef(function FloatingToolbar_(
|
||||
});
|
||||
|
||||
const isMobile = useMobile();
|
||||
const isMobileToolbarVisible = isMobile && !!props.active && position.visible;
|
||||
const isMobileToolbarVisible = isMobile && !!props.active && !!props.children;
|
||||
|
||||
// Keep the mobile toolbar glued to the top of the on-screen keyboard. The
|
||||
// hook tracks the visual viewport directly — see its implementation for the
|
||||
// iOS specifics.
|
||||
useKeyboardStickyOffset(menuRef, isMobileToolbarVisible);
|
||||
|
||||
// Tapping the bar must not move focus out of the editor, that would dismiss
|
||||
// the on-screen keyboard and take the bar down with it. Mousedown is the
|
||||
// event that assigns focus, and a tap dispatches it only after pointerup.
|
||||
const handleMouseDown = (event: React.MouseEvent) => {
|
||||
if (
|
||||
event.target instanceof Element &&
|
||||
!event.target.closest("input, textarea, [contenteditable='true']")
|
||||
) {
|
||||
event.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
// Canceling that mousedown cancels the tap's click with it, so the click is
|
||||
// raised here instead, from the pointerup that comes before both.
|
||||
const handlePointerUp = (event: React.PointerEvent) => {
|
||||
if (event.pointerType === "mouse") {
|
||||
return;
|
||||
}
|
||||
|
||||
const button =
|
||||
event.target instanceof Element ? event.target.closest("button") : null;
|
||||
if (button) {
|
||||
raisedClickAt.current = event.timeStamp;
|
||||
button.click();
|
||||
}
|
||||
};
|
||||
|
||||
// A browser that delivers the tap's click anyway must not act twice.
|
||||
const handleClickCapture = (event: React.MouseEvent) => {
|
||||
if (event.isTrusted && event.timeStamp - raisedClickAt.current < 500) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
};
|
||||
|
||||
if (isMobile) {
|
||||
if (isMobileToolbarVisible) {
|
||||
// Vertical position (above the keyboard) is owned entirely by
|
||||
// useKeyboardStickyOffset, which writes the transform directly.
|
||||
return (
|
||||
<ReactPortal>
|
||||
<MobileWrapper ref={menuRef}>
|
||||
{props.children && (
|
||||
<MobileBackground>{props.children}</MobileBackground>
|
||||
)}
|
||||
<MobileWrapper
|
||||
ref={menuRef}
|
||||
onMouseDown={handleMouseDown}
|
||||
onPointerUp={handlePointerUp}
|
||||
onClickCapture={handleClickCapture}
|
||||
>
|
||||
<MobileBackground>{props.children}</MobileBackground>
|
||||
</MobileWrapper>
|
||||
</ReactPortal>
|
||||
);
|
||||
@@ -351,6 +391,7 @@ const MobileWrapper = styled.div`
|
||||
right: 0;
|
||||
width: 100vw;
|
||||
box-sizing: border-box;
|
||||
padding: 0 16px 4px;
|
||||
z-index: ${depths.editorToolbar};
|
||||
will-change: transform;
|
||||
|
||||
@@ -359,19 +400,27 @@ const MobileWrapper = styled.div`
|
||||
}
|
||||
`;
|
||||
|
||||
// A rounded bar floating clear of the edges of the screen, with the buttons
|
||||
// inside clipped to its corners as they scroll.
|
||||
const MobileBackground = styled.div`
|
||||
padding: 10px 6px;
|
||||
height: 60px;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
padding: 4px;
|
||||
min-height: 48px;
|
||||
overflow: hidden;
|
||||
background-color: ${s("menuBackground")};
|
||||
border-top: 1px solid ${s("divider")};
|
||||
box-shadow: ${s("menuShadow")};
|
||||
border-radius: 24px;
|
||||
${(props) => hairline(props.theme.divider)}
|
||||
|
||||
&:after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 100px;
|
||||
background-color: ${s("menuBackground")};
|
||||
// The frosted glass of the iOS accessory bars.
|
||||
@supports (backdrop-filter: blur(20px)) or
|
||||
(-webkit-backdrop-filter: blur(20px)) {
|
||||
backdrop-filter: blur(20px) saturate(180%);
|
||||
background-color: ${(props) =>
|
||||
transparentize(0.2, props.theme.menuBackground)};
|
||||
}
|
||||
`;
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import styled from "styled-components";
|
||||
import Flex from "@shared/components/Flex";
|
||||
import Text from "@shared/components/Text";
|
||||
import { resolvePDFDimensions } from "@shared/editor/lib/pdf";
|
||||
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
|
||||
import { extraArea } from "@shared/styles";
|
||||
import Input, { NativeInput, Outline } from "~/components/Input";
|
||||
@@ -29,9 +30,13 @@ export function MediaDimension() {
|
||||
|
||||
// This component will be rendered for specific media nodes like image, video or pdfs (NodeSelection types).
|
||||
const node = (selection as NodeSelection).node;
|
||||
const nodeType = node.type.name,
|
||||
width = node.attrs.width as number,
|
||||
height = node.attrs.height as number;
|
||||
const nodeType = node.type.name;
|
||||
const nodeWidth = node.attrs.width as number | null | undefined;
|
||||
const nodeHeight = node.attrs.height as number | null | undefined;
|
||||
const { width, height } =
|
||||
nodeType === "attachment"
|
||||
? resolvePDFDimensions(nodeWidth, nodeHeight)
|
||||
: { width: nodeWidth ?? 0, height: nodeHeight ?? 0 };
|
||||
|
||||
const [localDimension, setLocalDimension] = useState<Dimension>(() => ({
|
||||
width: width ? String(width) : "",
|
||||
@@ -222,9 +227,14 @@ export function MediaDimension() {
|
||||
isDraggingRef.current = isDragging;
|
||||
}
|
||||
|
||||
const dimensions =
|
||||
nodeType === "attachment"
|
||||
? resolvePDFDimensions(newWidth)
|
||||
: { width: newWidth, height: newHeight };
|
||||
|
||||
setLocalDimension({
|
||||
width: newWidth ? String(newWidth) : "",
|
||||
height: newHeight ? String(newHeight) : "",
|
||||
width: dimensions.width ? String(dimensions.width) : "",
|
||||
height: dimensions.height ? String(dimensions.height) : "",
|
||||
changed: "none",
|
||||
});
|
||||
};
|
||||
@@ -233,7 +243,7 @@ export function MediaDimension() {
|
||||
return () => {
|
||||
window.removeEventListener("media-drag-resize", handleDragResize);
|
||||
};
|
||||
}, []);
|
||||
}, [nodeType]);
|
||||
|
||||
// hacky debounce for checking error.
|
||||
useEffect(() => {
|
||||
|
||||
@@ -250,7 +250,9 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) {
|
||||
[t, users, documentId, groups]
|
||||
);
|
||||
|
||||
const renderMenuItem = useCallback(
|
||||
const renderMenuItem = useCallback<
|
||||
SuggestionsMenuProps<MentionMenuItem>["renderMenuItem"]
|
||||
>(
|
||||
(item, _index, options) => (
|
||||
<SuggestionsMenuItem
|
||||
{...options}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isEqual } from "es-toolkit/compat";
|
||||
import { action, computed, observable } from "mobx";
|
||||
import { action, computed, makeObservable, observable } from "mobx";
|
||||
import type { FunctionComponent, ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
@@ -27,6 +27,7 @@ export class NodeViewRenderer<T extends object> implements PortalRenderer {
|
||||
props: T
|
||||
) {
|
||||
this.props = props;
|
||||
makeObservable(this);
|
||||
}
|
||||
|
||||
@computed
|
||||
|
||||
@@ -33,8 +33,10 @@ interface EmbedCheckState {
|
||||
export const PasteMenu = observer(({ pastedText, embeds, ...props }: Props) => {
|
||||
const items = useItems({ pastedText, embeds });
|
||||
|
||||
const renderMenuItem = useCallback(
|
||||
(item, _index, options) => <SuggestionsMenuItem {...options} {...item} />,
|
||||
const renderMenuItem = useCallback<SuggestionsMenuProps["renderMenuItem"]>(
|
||||
(item, _index, options) => (
|
||||
<SuggestionsMenuItem {...options} {...item} title={item.title} />
|
||||
),
|
||||
[]
|
||||
);
|
||||
|
||||
|
||||
@@ -35,6 +35,8 @@ type Props = {
|
||||
isTemplate: boolean;
|
||||
/** Whether the toolbar is currently active/visible */
|
||||
isActive: boolean;
|
||||
/** Whether the editor currently holds focus */
|
||||
isEditorFocused: boolean;
|
||||
/** The current selection */
|
||||
selection?: Selection;
|
||||
/** Whether the editor is in read-only mode */
|
||||
@@ -66,11 +68,16 @@ enum Toolbar {
|
||||
}
|
||||
|
||||
export function SelectionToolbar(props: Props) {
|
||||
const { readOnly = false } = props;
|
||||
const { readOnly = false, isEditorFocused } = props;
|
||||
const { view, extensions, commands, selectionToolbarMenus } = useEditor();
|
||||
const menuRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const isMobile = useMobile();
|
||||
const isActive = props.isActive || isMobile;
|
||||
|
||||
// On mobile the toolbar is docked above the on-screen keyboard, so it stays
|
||||
// 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;
|
||||
const [autoFocusLinkInput, setAutoFocusLinkInput] = React.useState(false);
|
||||
const isDragging = useIsDragging(state);
|
||||
@@ -324,7 +331,8 @@ export function SelectionToolbar(props: Props) {
|
||||
onEscape={() => setActiveToolbar(Toolbar.Menu)}
|
||||
onClickOutside={handleClickOutsideLinkEditor}
|
||||
/>
|
||||
) : activeToolbar === Toolbar.Menu && items.length ? (
|
||||
) : (activeToolbar === Toolbar.Menu || isMobileEditing) &&
|
||||
items.length ? (
|
||||
<ToolbarMenu items={items} {...rest} />
|
||||
) : null}
|
||||
</FloatingToolbar>
|
||||
|
||||
@@ -378,36 +378,45 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) {
|
||||
);
|
||||
|
||||
const handleClickItem = React.useCallback(
|
||||
(item) => {
|
||||
(item: MenuItem | EmbedDescriptor) => {
|
||||
if (item.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
props.onSelect?.(item);
|
||||
|
||||
const attrs = typeof item.attrs === "function" ? undefined : item.attrs;
|
||||
|
||||
switch (item.name) {
|
||||
case "link":
|
||||
case "link": {
|
||||
insertNode({
|
||||
...item,
|
||||
...(item as MenuItem),
|
||||
name: "mention",
|
||||
});
|
||||
const mention = attrs as
|
||||
| { label?: string; modelId?: string; nested?: boolean }
|
||||
| undefined;
|
||||
void editorProps.onCreateLink?.(
|
||||
{
|
||||
title: item.attrs.label,
|
||||
id: item.attrs.modelId,
|
||||
title: mention?.label,
|
||||
id: mention?.modelId,
|
||||
},
|
||||
!!item.attrs.nested
|
||||
!!mention?.nested
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "image":
|
||||
return triggerFilePick(
|
||||
AttachmentValidation.imageContentTypes.join(", "),
|
||||
item.attrs
|
||||
attrs
|
||||
);
|
||||
case "video":
|
||||
return triggerFilePick("video/*", item.attrs);
|
||||
return triggerFilePick("video/*", attrs);
|
||||
case "attachment":
|
||||
return triggerFilePick(item.attrs?.accept ?? "*", item.attrs);
|
||||
return triggerFilePick(
|
||||
(attrs?.accept as string | undefined) ?? "*",
|
||||
attrs
|
||||
);
|
||||
case "embed":
|
||||
return triggerLinkInput(item);
|
||||
default:
|
||||
|
||||
@@ -44,7 +44,7 @@ function SuggestionsMenuItem({
|
||||
}: Props) {
|
||||
const portal = usePortalContext();
|
||||
const ref = React.useCallback(
|
||||
(node) => {
|
||||
(node: HTMLButtonElement | null) => {
|
||||
if (selected && node) {
|
||||
scrollIntoView(node, {
|
||||
scrollMode: "if-needed",
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import styled from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import * as Toolbar from "@radix-ui/react-toolbar";
|
||||
import { closeHistory } from "@shared/editor/lib/closeHistory";
|
||||
import type { MenuItem } from "@shared/editor/types";
|
||||
import { MenuItemGroup, type MenuItem } from "@shared/editor/types";
|
||||
import { hideScrollbars, s } from "@shared/styles";
|
||||
import { TooltipProvider } from "~/components/TooltipContext";
|
||||
import useMobile from "~/hooks/useMobile";
|
||||
import type { MenuItem as TMenuItem } from "~/types";
|
||||
import { mapMenuItems } from "../menus/mapMenuItems";
|
||||
import { useEditor } from "./EditorContext";
|
||||
@@ -70,6 +71,7 @@ function ToolbarDropdown(props: ToolbarDropdownProps) {
|
||||
<Menu open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<MenuTrigger>
|
||||
<ToolbarButton
|
||||
data-group={item.group}
|
||||
aria-label={item.label ? undefined : item.tooltip}
|
||||
disabled={item.disabled}
|
||||
>
|
||||
@@ -94,6 +96,31 @@ function ToolbarMenu(props: Props) {
|
||||
const { commands, view } = useEditor();
|
||||
const { items } = props;
|
||||
const { state } = view;
|
||||
const isMobile = useMobile();
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
const hasSelection = !state.selection.empty;
|
||||
|
||||
// On mobile the toolbar is a single bar holding both the text and the block
|
||||
// controls, wider than the screen. It scrolls to the group that suits the
|
||||
// selection – text controls once there is a selection, block controls for a
|
||||
// bare cursor – leaving the other group one swipe away.
|
||||
const didScroll = useRef(false);
|
||||
useEffect(() => {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!isMobile || !wrapper) {
|
||||
return;
|
||||
}
|
||||
|
||||
const target = wrapper.querySelector(
|
||||
`[data-group="${hasSelection ? MenuItemGroup.inline : MenuItemGroup.block}"]`
|
||||
);
|
||||
target?.scrollIntoView({
|
||||
block: "nearest",
|
||||
inline: "start",
|
||||
behavior: didScroll.current ? "smooth" : "auto",
|
||||
});
|
||||
didScroll.current = true;
|
||||
}, [isMobile, hasSelection]);
|
||||
|
||||
const handleClick = (item: MenuItem) => () => {
|
||||
if (!item.name) {
|
||||
@@ -117,10 +144,12 @@ function ToolbarMenu(props: Props) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Toolbar.Root asChild>
|
||||
<FlexibleWrapper>
|
||||
<FlexibleWrapper ref={wrapperRef}>
|
||||
{items.map((item, index) => {
|
||||
if (item.name === "separator" && item.visible !== false) {
|
||||
return <ToolbarSeparator key={index} />;
|
||||
// The mobile bar spaces its buttons evenly instead, as dividers
|
||||
// would eat into the room for them.
|
||||
return isMobile ? null : <ToolbarSeparator key={index} />;
|
||||
}
|
||||
if (item.visible === false || (!item.skipIcon && !item.icon)) {
|
||||
return null;
|
||||
@@ -152,6 +181,7 @@ function ToolbarMenu(props: Props) {
|
||||
) : (
|
||||
<Toolbar.Button asChild>
|
||||
<ToolbarButton
|
||||
data-group={item.group}
|
||||
onClick={handleClick(item)}
|
||||
active={isActive && !item.label}
|
||||
aria-label={item.label ? undefined : item.tooltip}
|
||||
@@ -182,7 +212,28 @@ const FlexibleWrapper = styled.div`
|
||||
justify-content: space-evenly;
|
||||
align-items: center;
|
||||
overflow-x: auto;
|
||||
gap: 10px;
|
||||
scroll-padding-inline-start: 4px;
|
||||
padding: 0;
|
||||
|
||||
// Six buttons and half of the seventh fill the width – the half button is
|
||||
// what tells the user that the bar scrolls. Whatever is left over becomes
|
||||
// the space between them, so the first and last sit hard against the ends
|
||||
// and the bar keeps an even margin all round.
|
||||
gap: 0 calc((100% - 20px) / 6 - 40px);
|
||||
|
||||
> * {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex: 0 0 auto;
|
||||
min-width: 40px;
|
||||
}
|
||||
|
||||
> * > button {
|
||||
min-width: 40px;
|
||||
height: 40px;
|
||||
justify-content: center;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
${hideScrollbars()}
|
||||
`}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { action } from "mobx";
|
||||
import { PlusIcon } from "outline-icons";
|
||||
import { Plugin } from "prosemirror-state";
|
||||
import { Decoration, DecorationSet } from "prosemirror-view";
|
||||
import ReactDOM from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import type { WidgetProps } from "@shared/editor/lib/Extension";
|
||||
import { PlaceholderPlugin } from "@shared/editor/plugins/PlaceholderPlugin";
|
||||
import { findParentNode } from "@shared/editor/queries/findParentNode";
|
||||
@@ -29,7 +29,7 @@ export default class BlockMenuExtension extends Suggestion {
|
||||
const button = document.createElement("button");
|
||||
button.className = "block-menu-trigger";
|
||||
button.type = "button";
|
||||
ReactDOM.render(<PlusIcon />, button);
|
||||
createRoot(button).render(<PlusIcon />);
|
||||
|
||||
return [
|
||||
...super.plugins,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { escapeRegExp } from "es-toolkit/compat";
|
||||
import { observable } from "mobx";
|
||||
import { action, makeObservable, observable } from "mobx";
|
||||
import type { Node } from "prosemirror-model";
|
||||
import type { Command } from "prosemirror-state";
|
||||
import { Plugin, PluginKey } from "prosemirror-state";
|
||||
@@ -7,6 +7,7 @@ import { Decoration, DecorationSet } from "prosemirror-view";
|
||||
import scrollIntoView from "scroll-into-view-if-needed";
|
||||
import type { WidgetProps } from "@shared/editor/lib/Extension";
|
||||
import Extension from "@shared/editor/lib/Extension";
|
||||
import { expandCodeBlockAt } from "@shared/editor/nodes/CodeFence";
|
||||
import { Action, toggleFoldPluginKey } from "@shared/editor/nodes/ToggleBlock";
|
||||
import { isToggleBlock } from "@shared/editor/queries/toggleBlock";
|
||||
import { ancestors } from "@shared/editor/utils";
|
||||
@@ -43,7 +44,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
keys(): Record<string, Command> {
|
||||
return {
|
||||
Escape: () => {
|
||||
if (!this.searchTerm) {
|
||||
if (!this.searchTerm || this.open) {
|
||||
return false;
|
||||
}
|
||||
this.handleEscape();
|
||||
@@ -106,7 +107,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
}
|
||||
|
||||
public replace(replace: string): Command {
|
||||
return (state, dispatch) => {
|
||||
return action<Command>((state, dispatch) => {
|
||||
// Redo the search to ensure we have the latest results, the document may
|
||||
// have changed underneath us since the last search.
|
||||
this.search(state.doc);
|
||||
@@ -121,11 +122,11 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
dispatch?.(state.tr.insertText(replace, from, to).setMeta(pluginKey, {}));
|
||||
|
||||
return true;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
public replaceAll(replace: string): Command {
|
||||
return (state, dispatch) => {
|
||||
return action<Command>((state, dispatch) => {
|
||||
// Redo the search to ensure we have the latest results, the document may
|
||||
// have changed underneath us since the last search.
|
||||
this.search(state.doc);
|
||||
@@ -144,7 +145,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
|
||||
dispatch?.(tr);
|
||||
return true;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
public find(
|
||||
@@ -152,7 +153,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
caseSensitive = this.options.caseSensitive,
|
||||
regexEnabled = this.options.regexEnabled
|
||||
): Command {
|
||||
return (state, dispatch) => {
|
||||
return action<Command>((state, dispatch) => {
|
||||
this.options.caseSensitive = caseSensitive;
|
||||
this.options.regexEnabled = regexEnabled;
|
||||
this.searchTerm = regexEnabled ? searchTerm : escapeRegExp(searchTerm);
|
||||
@@ -164,11 +165,11 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
this.scrollToCurrentMatch();
|
||||
|
||||
return true;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
public clear(): Command {
|
||||
return (state, dispatch) => {
|
||||
return action<Command>((state, dispatch) => {
|
||||
this.searchTerm = "";
|
||||
this.currentResultIndex = 0;
|
||||
this.results = [];
|
||||
@@ -176,14 +177,14 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
|
||||
dispatch?.(state.tr.setMeta(pluginKey, {}));
|
||||
return true;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
public openFindAndReplace(): Command {
|
||||
return (state, dispatch) => {
|
||||
return action<Command>((state, dispatch) => {
|
||||
dispatch?.(state.tr.setMeta(pluginKey, { open: true }));
|
||||
return true;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -204,7 +205,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
}
|
||||
|
||||
private goToMatch(direction: number): Command {
|
||||
return (state, dispatch) => {
|
||||
return action<Command>((state, dispatch) => {
|
||||
if (!this.results.length) {
|
||||
return false;
|
||||
}
|
||||
@@ -228,7 +229,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
this.expandCollapsedCodeBlockForCurrentMatch();
|
||||
this.scrollToCurrentMatch();
|
||||
return true;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private scrollToCurrentMatch() {
|
||||
@@ -316,7 +317,8 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
return;
|
||||
}
|
||||
|
||||
this.editor.commands.expandCodeBlockAt(result.from);
|
||||
const view = this.editor.view;
|
||||
expandCodeBlockAt(result.from)(view.state, view.dispatch, view);
|
||||
}
|
||||
|
||||
private rebaseNextResult(replace: string, index: number, lastOffset = 0) {
|
||||
@@ -339,6 +341,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
return offset;
|
||||
}
|
||||
|
||||
@action
|
||||
private search(doc: Node) {
|
||||
this.results = [];
|
||||
const mergedTextNodes: (
|
||||
@@ -583,7 +586,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
};
|
||||
|
||||
private handleDocumentKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape" || !this.searchTerm) {
|
||||
if (event.key !== "Escape" || !this.searchTerm || this.open) {
|
||||
return;
|
||||
}
|
||||
if (event.defaultPrevented) {
|
||||
@@ -642,7 +645,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
|
||||
if (action) {
|
||||
if (action.open) {
|
||||
this.open = true;
|
||||
this.handleOpen();
|
||||
}
|
||||
this.search(tr.doc);
|
||||
return generation + 1;
|
||||
@@ -705,7 +708,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
|
||||
if (action) {
|
||||
if (action.open) {
|
||||
this.open = true;
|
||||
this.handleOpen();
|
||||
}
|
||||
return this.createDecorationSet(tr.doc);
|
||||
}
|
||||
@@ -731,15 +734,16 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
totalResults={this.results.length}
|
||||
readOnly={readOnly}
|
||||
open={this.open}
|
||||
onOpen={() => {
|
||||
this.open = true;
|
||||
}}
|
||||
onClose={() => {
|
||||
this.open = false;
|
||||
}}
|
||||
onOpen={this.handleOpen}
|
||||
onClose={this.handleClose}
|
||||
/>
|
||||
);
|
||||
|
||||
constructor(options: Partial<FindAndReplaceOptions> = {}) {
|
||||
super(options);
|
||||
makeObservable(this);
|
||||
}
|
||||
|
||||
@observable
|
||||
private open = false;
|
||||
|
||||
@@ -750,4 +754,14 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
private currentResultIndex = 0;
|
||||
|
||||
private searchTerm = "";
|
||||
|
||||
@action.bound
|
||||
private handleOpen() {
|
||||
this.open = true;
|
||||
}
|
||||
|
||||
@action.bound
|
||||
private handleClose() {
|
||||
this.open = false;
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
} from "y-prosemirror";
|
||||
import * as Y from "yjs";
|
||||
import Extension from "@shared/editor/lib/Extension";
|
||||
import type { MultiplayerState } from "@shared/editor/lib/multiplayer";
|
||||
import type { MultiplayerOperations } from "@shared/editor/lib/multiplayer";
|
||||
import {
|
||||
isRemoteTransaction,
|
||||
multiplayerPluginKey,
|
||||
@@ -124,6 +124,18 @@ export default class Multiplayer extends Extension<MultiplayerOptions> {
|
||||
// mapping, this avoids stored mappings for clients that never made a change
|
||||
doc.on("afterTransaction", assignUser);
|
||||
|
||||
const multiplayer: MultiplayerOperations = {
|
||||
isRemoteTransaction: (tr) => {
|
||||
const meta = tr.getMeta(ySyncPluginKey);
|
||||
|
||||
// This logic seems to be flipped? But it's correct.
|
||||
return !!meta?.isChangeOrigin;
|
||||
},
|
||||
stopCapturing: (state) => {
|
||||
yUndoPluginKey.getState(state)?.undoManager?.stopCapturing();
|
||||
},
|
||||
};
|
||||
|
||||
return [
|
||||
ySyncPlugin(type),
|
||||
yCursorPlugin(provider.awareness, {
|
||||
@@ -133,22 +145,9 @@ export default class Multiplayer extends Extension<MultiplayerOptions> {
|
||||
yUndoPlugin(),
|
||||
// Facade plugin that exposes the collaboration operations to shared
|
||||
// code without a static dependency on the collaboration libraries.
|
||||
new Plugin<MultiplayerState>({
|
||||
new Plugin({
|
||||
key: multiplayerPluginKey,
|
||||
state: {
|
||||
init: (): MultiplayerState => ({
|
||||
isRemoteTransaction: (tr) => {
|
||||
const meta = tr.getMeta(ySyncPluginKey);
|
||||
|
||||
// This logic seems to be flipped? But it's correct.
|
||||
return !!meta?.isChangeOrigin;
|
||||
},
|
||||
stopCapturing: (state) => {
|
||||
yUndoPluginKey.getState(state)?.undoManager?.stopCapturing();
|
||||
},
|
||||
}),
|
||||
apply: (_tr, value) => value,
|
||||
},
|
||||
multiplayer,
|
||||
props: {
|
||||
handleScrollToSelection: (view) =>
|
||||
isRemoteTransaction(view.state.tr, view.state),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { action, observable } from "mobx";
|
||||
import { action, makeObservable, observable } from "mobx";
|
||||
import type { EditorState, Selection } from "prosemirror-state";
|
||||
import { NodeSelection, Plugin, TextSelection } from "prosemirror-state";
|
||||
import type { EditorView } from "prosemirror-view";
|
||||
@@ -42,6 +42,11 @@ export default class SelectionToolbarExtension extends Extension {
|
||||
];
|
||||
}
|
||||
|
||||
constructor(options: Partial<object> = {}) {
|
||||
super(options);
|
||||
makeObservable(this);
|
||||
}
|
||||
|
||||
@observable
|
||||
state: Selection | boolean = false;
|
||||
|
||||
|
||||
+64
-1
@@ -9,7 +9,11 @@ import { gapCursor } from "prosemirror-gapcursor";
|
||||
import type { InputRule } from "prosemirror-inputrules";
|
||||
import { keymap } from "prosemirror-keymap";
|
||||
import type { NodeSpec, MarkSpec } from "prosemirror-model";
|
||||
import { Schema, Node as ProsemirrorNode } from "prosemirror-model";
|
||||
import {
|
||||
Schema,
|
||||
Node as ProsemirrorNode,
|
||||
DOMParser as ProsemirrorDOMParser,
|
||||
} from "prosemirror-model";
|
||||
import type { Plugin, Transaction } from "prosemirror-state";
|
||||
import { EditorState, Selection, TextSelection } from "prosemirror-state";
|
||||
import type { MarkdownParser } from "prosemirror-markdown";
|
||||
@@ -36,6 +40,7 @@ import { inputRules } from "@shared/editor/lib/inputRules";
|
||||
import type { MarkdownSerializer } from "@shared/editor/lib/markdown/serializer";
|
||||
import { isRemoteTransaction } from "@shared/editor/lib/multiplayer";
|
||||
import textBetween from "@shared/editor/lib/textBetween";
|
||||
import { findNearestPos } from "@shared/editor/queries/findNearestPos";
|
||||
import { basicExtensions as extensions } from "@shared/editor/nodes";
|
||||
import type ReactNode from "@shared/editor/nodes/ReactNode";
|
||||
import type {
|
||||
@@ -52,6 +57,8 @@ import { HeadingPrefixStyle } from "@shared/types";
|
||||
import { headingPrefixPluginKey } from "@shared/editor/extensions/HeadingPrefix";
|
||||
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
|
||||
import EventEmitter from "@shared/utils/events";
|
||||
import { getDataTransferFiles } from "@shared/utils/files";
|
||||
import { AttachmentValidation } from "@shared/validations";
|
||||
import type Document from "~/models/Document";
|
||||
import Flex from "~/components/Flex";
|
||||
import { PortalContext } from "~/components/Portal";
|
||||
@@ -267,6 +274,7 @@ export class Editor extends React.PureComponent<
|
||||
*/
|
||||
public componentDidMount() {
|
||||
this.init();
|
||||
this.handleEditorInit();
|
||||
window.addEventListener("theme-changed", this.dispatchThemeChanged);
|
||||
|
||||
if (this.props.scrollTo) {
|
||||
@@ -745,6 +753,57 @@ export class Editor extends React.PureComponent<
|
||||
this.props
|
||||
);
|
||||
|
||||
/**
|
||||
* Insert the content of a drop event at the position nearest to where it
|
||||
* occurred. Intended for drops that land outside of the editor itself.
|
||||
*
|
||||
* @param event The drop event.
|
||||
*/
|
||||
public insertDroppedContent = (event: React.DragEvent<HTMLElement>) => {
|
||||
const { view } = this;
|
||||
if (!view.editable) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const pos = findNearestPos(view, {
|
||||
left: event.clientX,
|
||||
top: event.clientY,
|
||||
});
|
||||
const files = getDataTransferFiles(event);
|
||||
|
||||
// Without files, attempt to parse the payload as an HTML fragment.
|
||||
if (files.length === 0) {
|
||||
const text =
|
||||
event.dataTransfer.getData("text/html") ||
|
||||
event.dataTransfer.getData("text/plain");
|
||||
if (!text) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dom = new DOMParser().parseFromString(text, "text/html");
|
||||
view.dispatch(
|
||||
view.state.tr.insert(
|
||||
pos,
|
||||
ProsemirrorDOMParser.fromSchema(view.state.schema).parse(dom)
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Insert all files as attachments if any of the files are not images.
|
||||
const isAttachment = files.some(
|
||||
(file) => !AttachmentValidation.imageContentTypes.includes(file.type)
|
||||
);
|
||||
|
||||
return insertFiles(view, event, pos, files, {
|
||||
...this.props,
|
||||
isAttachment,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns true if the trimmed content of the editor is an empty string.
|
||||
*
|
||||
@@ -927,6 +986,8 @@ export class Editor extends React.PureComponent<
|
||||
};
|
||||
|
||||
private handleEditorDestroy = () => {
|
||||
this.isInitialized = false;
|
||||
|
||||
if (!this.props.onDestroy) {
|
||||
return;
|
||||
}
|
||||
@@ -1031,6 +1092,8 @@ export class Editor extends React.PureComponent<
|
||||
rtl={isRTL}
|
||||
readOnly={readOnly}
|
||||
selection={this.view.state.selection}
|
||||
storedMarks={this.view.state.storedMarks}
|
||||
isEditorFocused={this.state.isEditorFocused}
|
||||
/>
|
||||
))}
|
||||
<Observer>
|
||||
|
||||
+191
-163
@@ -32,7 +32,11 @@ import { isInList } from "@shared/editor/queries/isInList";
|
||||
import { isListActive } from "@shared/editor/queries/isListActive";
|
||||
import { isMarkActive } from "@shared/editor/queries/isMarkActive";
|
||||
import { isNodeActive } from "@shared/editor/queries/isNodeActive";
|
||||
import type { MenuItem, SelectionContext } from "@shared/editor/types";
|
||||
import {
|
||||
MenuItemGroup,
|
||||
type MenuItem,
|
||||
type SelectionContext,
|
||||
} from "@shared/editor/types";
|
||||
import { metaDisplay } from "@shared/utils/keyboard";
|
||||
import { t } from "i18next";
|
||||
import CircleIcon from "~/components/Icons/CircleIcon";
|
||||
@@ -65,15 +69,18 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
isEmpty,
|
||||
isInCode,
|
||||
isInCodeBlock,
|
||||
isInList: isList,
|
||||
isTableCell,
|
||||
} = ctx;
|
||||
|
||||
const highlight = getMarksBetween(
|
||||
state.selection.from,
|
||||
state.selection.to,
|
||||
state
|
||||
).find(({ mark }) => mark.type === state.schema.marks.highlight);
|
||||
// With a cursor rather than a range the highlight that matters is the one
|
||||
// that will be applied to the text typed next, which is not in the document.
|
||||
const highlight = isEmpty
|
||||
? (state.storedMarks || state.selection.$from.marks()).find(
|
||||
(mark) => mark.type === schema.marks.highlight
|
||||
)
|
||||
: getMarksBetween(state.selection.from, state.selection.to, state).find(
|
||||
({ mark }) => mark.type === schema.marks.highlight
|
||||
)?.mark;
|
||||
|
||||
const cellSelectionHasBackground = isTableCell
|
||||
? hasNodeAttrMarkCellSelection(
|
||||
@@ -83,47 +90,191 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
: false;
|
||||
|
||||
const selectedCellsColorSet = getColorSetForSelectedCells(state.selection);
|
||||
const canFormat = !isInCodeBlock;
|
||||
|
||||
const canFormatInline = !isInCodeBlock && (!isMobile || !isEmpty);
|
||||
const canFormatBlock = !isInCodeBlock && (!isMobile || isEmpty);
|
||||
|
||||
// The block controls come first, so they are the ones on screen with a bare
|
||||
// cursor and the bar scrolls right to the text controls for a selection.
|
||||
return [
|
||||
{
|
||||
name: "placeholder",
|
||||
tooltip: t("Placeholder"),
|
||||
icon: <InputIcon />,
|
||||
active: isMarkActive(schema.marks.placeholder),
|
||||
visible: isTemplate && (!isMobile || !isEmpty),
|
||||
name: "heading",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Heading"),
|
||||
shortcut: `⇧+Ctrl+1`,
|
||||
icon: <Heading1Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 1 }),
|
||||
attrs: { level: 1 },
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "heading",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Subheading"),
|
||||
shortcut: `⇧+Ctrl+2`,
|
||||
icon: <Heading2Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 2 }),
|
||||
attrs: { level: 2 },
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "heading",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Subheading"),
|
||||
shortcut: `⇧+Ctrl+3`,
|
||||
icon: <Heading3Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 3 }),
|
||||
attrs: { level: 3 },
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "blockquote",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Quote"),
|
||||
shortcut: `${metaDisplay}+]`,
|
||||
icon: <BlockQuoteIcon />,
|
||||
active: isNodeActive(schema.nodes.blockquote),
|
||||
attrs: { level: 2 },
|
||||
visible: !isInCodeBlock && !isTableCell,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
visible: isTemplate && (!isMobile || !isEmpty),
|
||||
},
|
||||
{
|
||||
name: "mergeCells",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Merge cells"),
|
||||
icon: <TableMergeCellsIcon />,
|
||||
visible: isMultipleCellSelection(state),
|
||||
},
|
||||
{
|
||||
name: "splitCell",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Split cell"),
|
||||
icon: <TableSplitCellsIcon />,
|
||||
visible: isMergedCellSelection(state),
|
||||
},
|
||||
{
|
||||
name: "container_toggle",
|
||||
group: MenuItemGroup.block,
|
||||
icon: <CollapseIcon />,
|
||||
tooltip: t("Toggle block"),
|
||||
active: isNodeActive(schema.nodes.container_toggle),
|
||||
attrs: { id: uuidv4() },
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
},
|
||||
{
|
||||
name: "checkbox_list",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Todo list"),
|
||||
shortcut: `⇧+Ctrl+7`,
|
||||
icon: <TodoListIcon />,
|
||||
keywords: "checklist checkbox task",
|
||||
active: isListActive(schema.nodes.checkbox_list),
|
||||
visible: !isInCodeBlock && !isTableCell,
|
||||
},
|
||||
{
|
||||
name: "bullet_list",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Bulleted list"),
|
||||
shortcut: `⇧+Ctrl+8`,
|
||||
icon: <BulletedListIcon />,
|
||||
active: isListActive(schema.nodes.bullet_list),
|
||||
visible: !isInCodeBlock && !isTableCell,
|
||||
},
|
||||
{
|
||||
name: "ordered_list",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Ordered list"),
|
||||
shortcut: `⇧+Ctrl+9`,
|
||||
icon: <OrderedListIcon />,
|
||||
active: isListActive(schema.nodes.ordered_list),
|
||||
visible: !isInCodeBlock && !isTableCell,
|
||||
},
|
||||
{
|
||||
name: "outdentList",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Outdent"),
|
||||
shortcut: `⇧+Tab`,
|
||||
icon: <OutdentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) &&
|
||||
isInList(state, { types: ["ordered_list", "bullet_list"] }),
|
||||
},
|
||||
{
|
||||
name: "indentList",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Indent"),
|
||||
shortcut: `Tab`,
|
||||
icon: <IndentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) &&
|
||||
isInList(state, { types: ["ordered_list", "bullet_list"] }),
|
||||
},
|
||||
{
|
||||
name: "outdentCheckboxList",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Outdent"),
|
||||
shortcut: `⇧+Tab`,
|
||||
icon: <OutdentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) && isInList(state, { types: ["checkbox_list"] }),
|
||||
},
|
||||
{
|
||||
name: "indentCheckboxList",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Indent"),
|
||||
shortcut: `Tab`,
|
||||
icon: <IndentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) && isInList(state, { types: ["checkbox_list"] }),
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
visible: !isInCodeBlock,
|
||||
},
|
||||
{
|
||||
name: "placeholder",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Placeholder"),
|
||||
icon: <InputIcon />,
|
||||
active: isMarkActive(schema.marks.placeholder),
|
||||
visible: isTemplate,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
visible: isTemplate,
|
||||
},
|
||||
{
|
||||
name: "strong",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Bold"),
|
||||
shortcut: `${metaDisplay}+B`,
|
||||
icon: <BoldIcon />,
|
||||
active: isMarkActive(schema.marks.strong),
|
||||
visible: canFormatInline,
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "em",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Italic"),
|
||||
shortcut: `${metaDisplay}+I`,
|
||||
icon: <ItalicIcon />,
|
||||
active: isMarkActive(schema.marks.em),
|
||||
visible: canFormatInline,
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "strikethrough",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Strikethrough"),
|
||||
shortcut: `${metaDisplay}+D`,
|
||||
icon: <StrikethroughIcon />,
|
||||
active: isMarkActive(schema.marks.strikethrough),
|
||||
visible: canFormatInline,
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Background color"),
|
||||
icon:
|
||||
getColorSetForSelectedCells(state.selection).size > 1 ? (
|
||||
@@ -137,7 +288,7 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
) : (
|
||||
<PaletteIcon />
|
||||
),
|
||||
visible: !isInCode && (!isMobile || !isEmpty) && isTableCell,
|
||||
visible: !isInCode && isTableCell,
|
||||
children: (): MenuItem[] => {
|
||||
const documentTableColors = getDocumentTableBackgroundColors(state);
|
||||
|
||||
@@ -216,21 +367,22 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
},
|
||||
},
|
||||
{
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Highlight"),
|
||||
shortcut: `${metaDisplay}+⇧+H`,
|
||||
icon: highlight ? (
|
||||
<CircleIcon
|
||||
color={highlight.mark.attrs.color || Highlight.presetColors[0].hex}
|
||||
color={highlight.attrs.color || Highlight.presetColors[0].hex}
|
||||
/>
|
||||
) : (
|
||||
<HighlightIcon />
|
||||
),
|
||||
active: () => !!highlight,
|
||||
visible: !isInCode && (!isMobile || !isEmpty) && !isTableCell,
|
||||
visible: !isInCode && !isTableCell,
|
||||
children: (): MenuItem[] => {
|
||||
const documentHighlightColors = getDocumentHighlightColors(state);
|
||||
|
||||
const currentHighlightColor = highlight?.mark.attrs.color;
|
||||
const currentHighlightColor = highlight?.attrs.color;
|
||||
const nonPresetDocumentColors = documentHighlightColors.filter(
|
||||
(color: string) =>
|
||||
!Highlight.isPresetColor(color) && color !== currentHighlightColor
|
||||
@@ -244,7 +396,7 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
label: t("None"),
|
||||
icon: <DottedCircleIcon retainColor color="transparent" />,
|
||||
active: () => false,
|
||||
attrs: { color: highlight.mark.attrs.color },
|
||||
attrs: { color: highlight.attrs.color },
|
||||
},
|
||||
]
|
||||
: []),
|
||||
@@ -256,22 +408,19 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
attrs: { color: preset.hex },
|
||||
})),
|
||||
...(highlight &&
|
||||
highlight.mark.attrs.color &&
|
||||
!Highlight.isPresetColor(highlight.mark.attrs.color)
|
||||
highlight.attrs.color &&
|
||||
!Highlight.isPresetColor(highlight.attrs.color)
|
||||
? [
|
||||
{
|
||||
name: "highlight",
|
||||
label: highlight.mark.attrs.color,
|
||||
label: highlight.attrs.color,
|
||||
icon: (
|
||||
<CircleIcon
|
||||
retainColor
|
||||
color={highlight.mark.attrs.color}
|
||||
/>
|
||||
<CircleIcon retainColor color={highlight.attrs.color} />
|
||||
),
|
||||
active: isMarkActive(schema.marks.highlight, {
|
||||
color: highlight.mark.attrs.color,
|
||||
color: highlight.attrs.color,
|
||||
}),
|
||||
attrs: { color: highlight.mark.attrs.color },
|
||||
attrs: { color: highlight.attrs.color },
|
||||
},
|
||||
]
|
||||
: []),
|
||||
@@ -290,8 +439,7 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
content: (
|
||||
<HighlightColorPicker
|
||||
activeColor={
|
||||
highlight?.mark.attrs.color ||
|
||||
Highlight.presetColors[0].hex
|
||||
highlight?.attrs.color || Highlight.presetColors[0].hex
|
||||
}
|
||||
/>
|
||||
),
|
||||
@@ -307,136 +455,12 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
},
|
||||
{
|
||||
name: "code_inline",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Code"),
|
||||
shortcut: `${metaDisplay}+E`,
|
||||
icon: <CodeIcon />,
|
||||
active: isMarkActive(schema.marks.code_inline),
|
||||
visible: canFormatInline,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
visible: !isInCodeBlock,
|
||||
},
|
||||
{
|
||||
name: "heading",
|
||||
tooltip: t("Heading"),
|
||||
shortcut: `⇧+Ctrl+1`,
|
||||
icon: <Heading1Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 1 }),
|
||||
attrs: { level: 1 },
|
||||
visible: canFormatBlock,
|
||||
},
|
||||
{
|
||||
name: "heading",
|
||||
tooltip: t("Subheading"),
|
||||
shortcut: `⇧+Ctrl+2`,
|
||||
icon: <Heading2Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 2 }),
|
||||
attrs: { level: 2 },
|
||||
visible: canFormatBlock,
|
||||
},
|
||||
{
|
||||
name: "heading",
|
||||
tooltip: t("Subheading"),
|
||||
shortcut: `⇧+Ctrl+3`,
|
||||
icon: <Heading3Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 3 }),
|
||||
attrs: { level: 3 },
|
||||
visible: canFormatBlock,
|
||||
},
|
||||
{
|
||||
name: "blockquote",
|
||||
tooltip: t("Quote"),
|
||||
shortcut: `${metaDisplay}+]`,
|
||||
icon: <BlockQuoteIcon />,
|
||||
active: isNodeActive(schema.nodes.blockquote),
|
||||
attrs: { level: 2 },
|
||||
visible: !isInCodeBlock && !isTableCell && (!isMobile || isEmpty),
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
},
|
||||
{
|
||||
name: "mergeCells",
|
||||
tooltip: t("Merge cells"),
|
||||
icon: <TableMergeCellsIcon />,
|
||||
visible: isMultipleCellSelection(state),
|
||||
},
|
||||
{
|
||||
name: "splitCell",
|
||||
tooltip: t("Split cell"),
|
||||
icon: <TableSplitCellsIcon />,
|
||||
visible: isMergedCellSelection(state),
|
||||
},
|
||||
{
|
||||
name: "container_toggle",
|
||||
icon: <CollapseIcon />,
|
||||
tooltip: t("Toggle block"),
|
||||
active: isNodeActive(schema.nodes.container_toggle),
|
||||
attrs: { id: uuidv4() },
|
||||
visible: canFormatBlock,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
},
|
||||
{
|
||||
name: "checkbox_list",
|
||||
tooltip: t("Todo list"),
|
||||
shortcut: `⇧+Ctrl+7`,
|
||||
icon: <TodoListIcon />,
|
||||
keywords: "checklist checkbox task",
|
||||
active: isListActive(schema.nodes.checkbox_list),
|
||||
visible: !isInCodeBlock && !isTableCell && (!isList || !isTouch),
|
||||
},
|
||||
{
|
||||
name: "bullet_list",
|
||||
tooltip: t("Bulleted list"),
|
||||
shortcut: `⇧+Ctrl+8`,
|
||||
icon: <BulletedListIcon />,
|
||||
active: isListActive(schema.nodes.bullet_list),
|
||||
visible: !isInCodeBlock && !isTableCell && (!isList || !isTouch),
|
||||
},
|
||||
{
|
||||
name: "ordered_list",
|
||||
tooltip: t("Ordered list"),
|
||||
shortcut: `⇧+Ctrl+9`,
|
||||
icon: <OrderedListIcon />,
|
||||
active: isListActive(schema.nodes.ordered_list),
|
||||
visible: !isInCodeBlock && !isTableCell && (!isList || !isTouch),
|
||||
},
|
||||
{
|
||||
name: "outdentList",
|
||||
tooltip: t("Outdent"),
|
||||
shortcut: `⇧+Tab`,
|
||||
icon: <OutdentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) &&
|
||||
isInList(state, { types: ["ordered_list", "bullet_list"] }),
|
||||
},
|
||||
{
|
||||
name: "indentList",
|
||||
tooltip: t("Indent"),
|
||||
shortcut: `Tab`,
|
||||
icon: <IndentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) &&
|
||||
isInList(state, { types: ["ordered_list", "bullet_list"] }),
|
||||
},
|
||||
{
|
||||
name: "outdentCheckboxList",
|
||||
tooltip: t("Outdent"),
|
||||
shortcut: `⇧+Tab`,
|
||||
icon: <OutdentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) && isInList(state, { types: ["checkbox_list"] }),
|
||||
},
|
||||
{
|
||||
name: "indentCheckboxList",
|
||||
tooltip: t("Indent"),
|
||||
shortcut: `Tab`,
|
||||
icon: <IndentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) && isInList(state, { types: ["checkbox_list"] }),
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
@@ -444,15 +468,18 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
},
|
||||
{
|
||||
name: "addLink",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Create link"),
|
||||
shortcut: `${metaDisplay}+K`,
|
||||
icon: <LinkIcon />,
|
||||
attrs: { href: "" },
|
||||
active: isMarkActive(schema.marks.link, undefined, { exact: true }),
|
||||
visible: canFormatInline,
|
||||
// A link cannot be made without text to attach it to.
|
||||
visible: canFormat && !isEmpty,
|
||||
},
|
||||
{
|
||||
name: "comment",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Comment"),
|
||||
shortcut: `${metaDisplay}+⌥+M`,
|
||||
icon: <CommentIcon />,
|
||||
@@ -462,7 +489,6 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
{ resolved: false },
|
||||
{ exact: true }
|
||||
),
|
||||
visible: !isMobile || !isEmpty,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
@@ -470,9 +496,11 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
},
|
||||
{
|
||||
name: "copyToClipboard",
|
||||
group: MenuItemGroup.inline,
|
||||
icon: <CopyIcon />,
|
||||
tooltip: t("Copy"),
|
||||
shortcut: `${metaDisplay}+C`,
|
||||
// Copy acts on the selected text, so it has nothing to do without one.
|
||||
visible: isInCode && !isInCodeBlock && (!isMobile || !isEmpty),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -67,7 +67,7 @@ export const ActionContextProvider = observer(function ActionContextProvider_({
|
||||
// navigation does not invalidate the context value. Action perform/visible
|
||||
// callbacks see the current location at call time via history.location,
|
||||
// which react-router updates on every navigation.
|
||||
const history = useHistory();
|
||||
const history = useHistory<{ sidebarContext?: SidebarContextType }>();
|
||||
|
||||
const {
|
||||
activeModels: valueModels,
|
||||
@@ -174,7 +174,6 @@ export const ActionContextProvider = observer(function ActionContextProvider_({
|
||||
...(isMenu !== undefined ? { isMenu } : {}),
|
||||
...(isCommandBar !== undefined ? { isCommandBar } : {}),
|
||||
...(isButton !== undefined ? { isButton } : {}),
|
||||
...(sidebarContext !== undefined ? { sidebarContext } : {}),
|
||||
...(event !== undefined ? { event } : {}),
|
||||
activeCollectionId,
|
||||
activeDocumentId,
|
||||
@@ -193,6 +192,18 @@ export const ActionContextProvider = observer(function ActionContextProvider_({
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
// The sidebar context is carried in location state, so fall back to the
|
||||
// current location when no ancestor provider supplies one. A getter for the
|
||||
// same reason as `location` above.
|
||||
Object.defineProperty(result, "sidebarContext", {
|
||||
get: () =>
|
||||
sidebarContext ??
|
||||
parentContext?.sidebarContext ??
|
||||
history.location.state?.sidebarContext,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
return result;
|
||||
}, [
|
||||
parentContext,
|
||||
|
||||
@@ -1,88 +1,83 @@
|
||||
import { useMemo } from "react";
|
||||
import type { NavigationNode } from "@shared/types";
|
||||
import type { CollectionSort, NavigationNode } from "@shared/types";
|
||||
import { NavigationNodeType } from "@shared/types";
|
||||
import { sortNavigationNodes } from "@shared/utils/collections";
|
||||
import type Collection from "~/models/Collection";
|
||||
import { useComputed } from "~/hooks/useComputed";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import type Collection from "~/models/Collection";
|
||||
|
||||
/**
|
||||
* React hook that modifies the document structure
|
||||
* of all collections present in store. Adds extra attributes
|
||||
* like type, depth and parent to each of the nodes in document
|
||||
* structure.
|
||||
* React hook that returns the document structure of all collections in the
|
||||
* store as navigation trees. Each node is a copy of the node in the store with
|
||||
* extra attributes added – type, collectionId, depth, and parent.
|
||||
*
|
||||
* @return {NavigationNode[]} collectionTrees root collection nodes of modified trees
|
||||
* @returns the root node of each collection tree.
|
||||
*/
|
||||
export default function useCollectionTrees(): NavigationNode[] {
|
||||
const { collections } = useStores();
|
||||
|
||||
const getCollectionTree = (collection: Collection): NavigationNode => {
|
||||
const addType = (node: NavigationNode): NavigationNode => {
|
||||
if (node.children.length > 0) {
|
||||
node.children = node.children.map(addType);
|
||||
}
|
||||
return useComputed(
|
||||
() => collections.orderedData.map(getCollectionTree),
|
||||
[collections]
|
||||
);
|
||||
}
|
||||
|
||||
node.type = node.type ? node.type : NavigationNodeType.Document;
|
||||
return node;
|
||||
};
|
||||
|
||||
const addParent = (
|
||||
node: NavigationNode,
|
||||
parent: NavigationNode | null = null
|
||||
): NavigationNode => {
|
||||
if (node.children.length > 0) {
|
||||
node.children = node.children.map((child) => addParent(child, node));
|
||||
}
|
||||
|
||||
node.parent = parent;
|
||||
return node;
|
||||
};
|
||||
|
||||
const addDepth = (node: NavigationNode, depth = 0): NavigationNode => {
|
||||
if (node.children.length > 0) {
|
||||
node.children = node.children.map((child) =>
|
||||
addDepth(child, depth + 1)
|
||||
);
|
||||
}
|
||||
|
||||
node.depth = depth;
|
||||
return node;
|
||||
};
|
||||
|
||||
const addCollectionId = (
|
||||
node: NavigationNode,
|
||||
collectionId = collection.id
|
||||
): NavigationNode => {
|
||||
if (node.children.length > 0) {
|
||||
node.children = node.children.map((child) =>
|
||||
addCollectionId(child, collectionId)
|
||||
);
|
||||
}
|
||||
|
||||
node.collectionId = collectionId;
|
||||
return node;
|
||||
};
|
||||
|
||||
const collectionNode: NavigationNode = {
|
||||
id: collection.id,
|
||||
title: collection.name,
|
||||
url: collection.path,
|
||||
type: NavigationNodeType.Collection,
|
||||
children: collection.documents
|
||||
? sortNavigationNodes(collection.documents, collection.sort, true)
|
||||
: [],
|
||||
parent: null,
|
||||
};
|
||||
|
||||
return addParent(addCollectionId(addDepth(addType(collectionNode), 1)));
|
||||
/**
|
||||
* Builds the navigation tree for a collection.
|
||||
*
|
||||
* @param collection The collection to build the tree for.
|
||||
* @returns the root node of the collection tree.
|
||||
*/
|
||||
function getCollectionTree(collection: Collection): NavigationNode {
|
||||
const root: NavigationNode = {
|
||||
id: collection.id,
|
||||
title: collection.name,
|
||||
url: collection.path,
|
||||
type: NavigationNodeType.Collection,
|
||||
collectionId: collection.id,
|
||||
depth: 1,
|
||||
parent: null,
|
||||
children: [],
|
||||
};
|
||||
|
||||
const key = collections.orderedData.map((o) => o.documents?.length).join("-");
|
||||
const collectionTrees = useMemo(
|
||||
() => collections.orderedData.map(getCollectionTree),
|
||||
// oxlint-disable-next-line react-hooks/exhaustive-deps
|
||||
[collections.orderedData, key]
|
||||
root.children = annotateNodes(
|
||||
collection.documents ?? [],
|
||||
collection.sort,
|
||||
root
|
||||
);
|
||||
|
||||
return collectionTrees;
|
||||
return root;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the given nodes and their descendants in sorted order, adding the
|
||||
* attributes needed to traverse and render the tree.
|
||||
*
|
||||
* @param nodes The nodes to copy.
|
||||
* @param sort The sort of the collection the nodes belong to.
|
||||
* @param parent The node that the given nodes are children of.
|
||||
* @returns the copied nodes.
|
||||
*/
|
||||
function annotateNodes(
|
||||
nodes: NavigationNode[],
|
||||
sort: CollectionSort,
|
||||
parent: NavigationNode
|
||||
): NavigationNode[] {
|
||||
if (!nodes.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return sortNavigationNodes(nodes, sort, false).map((node) => {
|
||||
const annotated: NavigationNode = {
|
||||
...node,
|
||||
type: node.type ?? NavigationNodeType.Document,
|
||||
collectionId: parent.collectionId,
|
||||
depth: (parent.depth ?? 0) + 1,
|
||||
parent,
|
||||
children: [],
|
||||
};
|
||||
|
||||
annotated.children = annotateNodes(node.children ?? [], sort, annotated);
|
||||
|
||||
return annotated;
|
||||
});
|
||||
}
|
||||
@@ -4,10 +4,12 @@ import { useLocation } from "react-router-dom";
|
||||
import { actionToKBar } from "~/actions";
|
||||
import type { ActionVariant } from "~/types";
|
||||
import useActionContext from "./useActionContext";
|
||||
import useWebMCPActions from "./useWebMCPActions";
|
||||
|
||||
/**
|
||||
* Hook to add actions to the command bar while the hook is inside a mounted
|
||||
* component.
|
||||
* component. The same actions are also exposed as WebMCP tools in supported
|
||||
* browsers.
|
||||
*
|
||||
* @param actions actions to make available
|
||||
*/
|
||||
@@ -20,6 +22,8 @@ export default function useCommandBarActions(
|
||||
isCommandBar: true,
|
||||
});
|
||||
|
||||
useWebMCPActions(actions, additionalDeps);
|
||||
|
||||
const registerable = flattenDeep(
|
||||
actions.map((action) => actionToKBar(action, context))
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import { patchLocation } from "~/utils/history";
|
||||
import useQuery from "./useQuery";
|
||||
|
||||
/**
|
||||
@@ -20,13 +21,13 @@ export default function useConsumeQueryParam(name: string): string | null {
|
||||
if (value && !consumedRef.current) {
|
||||
consumedRef.current = true;
|
||||
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const location = history.location;
|
||||
const params = new URLSearchParams(location.search);
|
||||
params.delete(name);
|
||||
const search = params.toString();
|
||||
history.replace({
|
||||
pathname: window.location.pathname,
|
||||
search: search ? `?${search}` : "",
|
||||
});
|
||||
history.replace(
|
||||
patchLocation(location, { search: search ? `?${search}` : "" })
|
||||
);
|
||||
}
|
||||
}, [value, name, history]);
|
||||
|
||||
|
||||
@@ -45,6 +45,8 @@ import { useTemplateMenuActions } from "./useTemplateMenuActions";
|
||||
type Props = {
|
||||
/** Document ID for which the actions are generated */
|
||||
documentId: string;
|
||||
/** Whether the document is currently being viewed */
|
||||
isViewing?: boolean;
|
||||
/** Invoked when the "Find and replace" menu item is clicked */
|
||||
onFindAndReplace?: () => void;
|
||||
/** Invoked when the "Rename" menu item is clicked */
|
||||
@@ -55,6 +57,7 @@ type Props = {
|
||||
|
||||
export function useDocumentMenuAction({
|
||||
documentId,
|
||||
isViewing = false,
|
||||
onFindAndReplace,
|
||||
onRename,
|
||||
onSelectTemplate,
|
||||
@@ -106,7 +109,7 @@ export function useDocumentMenuAction({
|
||||
openDocumentComments,
|
||||
openDocumentHistory,
|
||||
openDocumentInsights,
|
||||
toggleDocumentStats,
|
||||
...(isViewing ? [toggleDocumentStats] : []),
|
||||
openDocumentInSplit,
|
||||
openDocumentInDesktop,
|
||||
presentDocument,
|
||||
@@ -118,6 +121,14 @@ export function useDocumentMenuAction({
|
||||
permanentlyDeleteDocument,
|
||||
leaveDocument,
|
||||
]),
|
||||
[t, isMobile, templateMenuActions, documentId, onFindAndReplace, onRename]
|
||||
[
|
||||
t,
|
||||
isMobile,
|
||||
isViewing,
|
||||
templateMenuActions,
|
||||
documentId,
|
||||
onFindAndReplace,
|
||||
onRename,
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { formatNumber } from "~/utils/language";
|
||||
import useUserLocale from "./useUserLocale";
|
||||
import { unicodeCLDRtoBCP47 } from "@shared/utils/date";
|
||||
import { formatNumber } from "@shared/utils/language";
|
||||
import useUserLocale from "./useUserLocale";
|
||||
|
||||
/**
|
||||
* Hook that returns a function to format numbers based on the user's locale.
|
||||
|
||||
+11
-3
@@ -38,10 +38,18 @@ const useHover = ({ ref, duration }: Props): boolean => {
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
if (ref.current) {
|
||||
ref.current.onmouseenter = onMouseEnter;
|
||||
ref.current.onmouseleave = onMouseLeave;
|
||||
const element = ref.current;
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
|
||||
element.addEventListener("mouseenter", onMouseEnter);
|
||||
element.addEventListener("mouseleave", onMouseLeave);
|
||||
|
||||
return () => {
|
||||
element.removeEventListener("mouseenter", onMouseEnter);
|
||||
element.removeEventListener("mouseleave", onMouseLeave);
|
||||
};
|
||||
}, [ref, onMouseEnter, onMouseLeave]);
|
||||
|
||||
return hovered;
|
||||
|
||||
@@ -23,7 +23,7 @@ export default function useImportDocument(
|
||||
const { t } = useTranslation();
|
||||
const history = useHistory();
|
||||
const handleFiles = useCallback(
|
||||
async (files = []) => {
|
||||
async (files: File[] = []) => {
|
||||
if (importingLock) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -13,12 +13,13 @@ import { getSafeAreaInsets } from "@shared/utils/browser";
|
||||
* translates the element upwards by that amount so it always rests on top of
|
||||
* the keyboard.
|
||||
*
|
||||
* The transform is re-applied after every render (so a parent re-render cannot
|
||||
* clobber it) and on visual viewport `resize`/`scroll` events. A short-lived
|
||||
* `requestAnimationFrame` loop tracks the keyboard's open/close animation so
|
||||
* the element glides with it rather than snapping into place once the
|
||||
* transition settles. Writes go directly to the node's style to avoid React
|
||||
* re-render latency during the animation.
|
||||
* The measurement is repeated every frame while enabled. A keyboard changes
|
||||
* height without warning – a predictive text strip or an accessory bar comes
|
||||
* and goes, one keyboard type replaces another – and not every change is
|
||||
* announced by a viewport event, so an element positioned once from an event
|
||||
* can be left behind the keyboard. Writes go straight to the node's style, and
|
||||
* only when the offset changes, so a frame that measures the same keyboard
|
||||
* costs a handful of property reads.
|
||||
*
|
||||
* @param ref A ref to the fixed-position element to keep pinned.
|
||||
* @param enabled Whether the behavior should be active.
|
||||
@@ -27,6 +28,13 @@ export default function useKeyboardStickyOffset(
|
||||
ref: React.RefObject<HTMLElement>,
|
||||
enabled: boolean
|
||||
) {
|
||||
const applied = React.useRef<number | null>(null);
|
||||
|
||||
// Reading the layout viewport height can force a layout, so it is measured
|
||||
// when it changes rather than on every frame.
|
||||
const safeAreaBottom = React.useRef(0);
|
||||
const layoutHeight = React.useRef(0);
|
||||
|
||||
const apply = React.useCallback(() => {
|
||||
const viewport = window.visualViewport;
|
||||
const node = ref.current;
|
||||
@@ -41,55 +49,46 @@ export default function useKeyboardStickyOffset(
|
||||
// clears the home indicator.
|
||||
const keyboardInset = Math.max(
|
||||
0,
|
||||
window.innerHeight - (viewport.offsetTop + viewport.height)
|
||||
);
|
||||
const offset = Math.round(
|
||||
Math.max(keyboardInset, getSafeAreaInsets().bottom)
|
||||
layoutHeight.current - (viewport.offsetTop + viewport.height)
|
||||
);
|
||||
const offset = Math.round(Math.max(keyboardInset, safeAreaBottom.current));
|
||||
|
||||
node.style.transform = `translate3d(0, ${-offset}px, 0)`;
|
||||
if (offset !== applied.current) {
|
||||
applied.current = offset;
|
||||
node.style.transform = `translate3d(0, ${-offset}px, 0)`;
|
||||
}
|
||||
}, [ref, enabled]);
|
||||
|
||||
// Re-apply after every render, before paint, so the keyboard-aware transform
|
||||
// survives parent re-renders and there is no flash on first mount.
|
||||
React.useLayoutEffect(apply);
|
||||
// Re-apply after every render, before paint, so the transform survives a
|
||||
// parent re-render and there is no flash on first mount.
|
||||
React.useLayoutEffect(() => {
|
||||
safeAreaBottom.current = getSafeAreaInsets().bottom;
|
||||
layoutHeight.current = window.innerHeight;
|
||||
applied.current = null;
|
||||
apply();
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
const viewport = window.visualViewport;
|
||||
if (!enabled || !viewport) {
|
||||
if (!enabled || !window.visualViewport) {
|
||||
return;
|
||||
}
|
||||
|
||||
let frame = 0;
|
||||
let trackUntil = 0;
|
||||
const handleResize = () => {
|
||||
layoutHeight.current = window.innerHeight;
|
||||
safeAreaBottom.current = getSafeAreaInsets().bottom;
|
||||
};
|
||||
window.addEventListener("resize", handleResize);
|
||||
window.addEventListener("orientationchange", handleResize);
|
||||
|
||||
const tick = (now: number) => {
|
||||
let frame = requestAnimationFrame(function tick() {
|
||||
apply();
|
||||
frame = now < trackUntil ? requestAnimationFrame(tick) : 0;
|
||||
};
|
||||
|
||||
const schedule = () => {
|
||||
// Keep re-measuring for a short window so the element follows the
|
||||
// keyboard animation rather than jumping once it settles.
|
||||
trackUntil = performance.now() + 350;
|
||||
if (!frame) {
|
||||
frame = requestAnimationFrame(tick);
|
||||
}
|
||||
};
|
||||
|
||||
viewport.addEventListener("resize", schedule);
|
||||
viewport.addEventListener("scroll", schedule);
|
||||
window.addEventListener("focusin", schedule);
|
||||
window.addEventListener("orientationchange", schedule);
|
||||
frame = requestAnimationFrame(tick);
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (frame) {
|
||||
cancelAnimationFrame(frame);
|
||||
}
|
||||
viewport.removeEventListener("resize", schedule);
|
||||
viewport.removeEventListener("scroll", schedule);
|
||||
window.removeEventListener("focusin", schedule);
|
||||
window.removeEventListener("orientationchange", schedule);
|
||||
cancelAnimationFrame(frame);
|
||||
window.removeEventListener("resize", handleResize);
|
||||
window.removeEventListener("orientationchange", handleResize);
|
||||
};
|
||||
}, [enabled, apply]);
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import { isNumber } from "es-toolkit/compat";
|
||||
import { useRef } from "react";
|
||||
|
||||
/** Minimum distance in pixels that a touch must travel to count as a swipe. */
|
||||
const MinSwipeDistance = 40;
|
||||
|
||||
type Props = {
|
||||
onSwipeRight: () => void;
|
||||
onSwipeLeft: () => void;
|
||||
@@ -47,6 +50,12 @@ export default function useSwipe({
|
||||
const dx = touchXEnd.current - touchXStart.current;
|
||||
const dy = touchYEnd.current - touchYStart.current;
|
||||
|
||||
// Ignore small movements so that a tap, or the start of a gesture, is not
|
||||
// mistaken for a swipe.
|
||||
if (Math.max(Math.abs(dx), Math.abs(dy)) < MinSwipeDistance) {
|
||||
return;
|
||||
}
|
||||
|
||||
const swipeRight = dx > 0 && Math.abs(dy) < Math.abs(dx);
|
||||
if (swipeRight) {
|
||||
resetTouchPoints();
|
||||
|
||||
@@ -27,4 +27,9 @@ describe("getTextStats", () => {
|
||||
it("rounds reading time up to a minute for short text", () => {
|
||||
expect(getTextStats("Hello world").readingTime).toBe(1);
|
||||
});
|
||||
|
||||
it("rounds reading time up to the next minute for long text", () => {
|
||||
expect(getTextStats("word ".repeat(500)).readingTime).toBe(3);
|
||||
expect(getTextStats("word ".repeat(400)).readingTime).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@ export function getTextStats(text: string) {
|
||||
words,
|
||||
characters: text.length,
|
||||
paragraphs: countParagraphs(text),
|
||||
readingTime: words ? Math.max(1, Math.floor(words / 200)) : 0,
|
||||
readingTime: Math.ceil(words / 200),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { snakeCase } from "es-toolkit";
|
||||
import * as React from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { TeamPreference } from "@shared/types";
|
||||
import { toError } from "@shared/utils/error";
|
||||
import { performAction, resolve } from "~/actions";
|
||||
import type {
|
||||
ActionContext,
|
||||
ActionGroup,
|
||||
ActionSeparator,
|
||||
ActionVariant,
|
||||
ActionWithChildren,
|
||||
} from "~/types";
|
||||
import {
|
||||
isModelContextSupported,
|
||||
registerModelContextTool,
|
||||
} from "~/utils/ModelContext";
|
||||
import useActionContext from "./useActionContext";
|
||||
import useStores from "./useStores";
|
||||
|
||||
type PerformableAction = Exclude<ActionVariant, ActionWithChildren>;
|
||||
|
||||
/**
|
||||
* Hook to expose actions as WebMCP tools while the hook is inside a mounted
|
||||
* component. Tools are unregistered automatically on unmount or navigation.
|
||||
*
|
||||
* @param actions actions to make available as tools.
|
||||
*/
|
||||
export default function useWebMCPActions(
|
||||
actions: ActionVariant[],
|
||||
additionalDeps: React.DependencyList = []
|
||||
) {
|
||||
const location = useLocation();
|
||||
const { auth } = useStores();
|
||||
const context = useActionContext({ isMCP: true });
|
||||
|
||||
const enabled =
|
||||
isModelContextSupported() && !!auth.team?.getPreference(TeamPreference.MCP);
|
||||
|
||||
const performable = enabled ? flattenActions(actions, context) : [];
|
||||
const toolNames = performable.map((action) =>
|
||||
snakeCase(action.analyticsName ?? "")
|
||||
);
|
||||
|
||||
// Refs keep `execute` callbacks working against the latest context and
|
||||
// action list without re-registering tools on every render.
|
||||
const contextRef = React.useRef(context);
|
||||
contextRef.current = context;
|
||||
const performableRef = React.useRef(performable);
|
||||
performableRef.current = performable;
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!enabled || performableRef.current.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
for (const action of performableRef.current) {
|
||||
const ctx = contextRef.current;
|
||||
const name = snakeCase(action.analyticsName ?? "");
|
||||
const title = resolve<React.ReactNode>(action.name, ctx);
|
||||
const description =
|
||||
resolve<string | undefined>(action.description, ctx) ??
|
||||
(typeof title === "string" ? title : action.analyticsName);
|
||||
|
||||
if (!name || !description) {
|
||||
continue;
|
||||
}
|
||||
|
||||
registerModelContextTool(
|
||||
{
|
||||
name,
|
||||
description,
|
||||
inputSchema: action.mcp?.inputSchema,
|
||||
execute: async (args) => {
|
||||
try {
|
||||
const result = await performAction(action, {
|
||||
...contextRef.current,
|
||||
mcpArgs: args,
|
||||
});
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text:
|
||||
typeof result === "string"
|
||||
? result
|
||||
: result === undefined
|
||||
? "Done"
|
||||
: JSON.stringify(result),
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [{ type: "text", text: toError(err).message }],
|
||||
};
|
||||
}
|
||||
},
|
||||
},
|
||||
controller.signal
|
||||
);
|
||||
}
|
||||
|
||||
return () => controller.abort();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [enabled, toolNames.join(","), location.pathname, ...additionalDeps]);
|
||||
}
|
||||
|
||||
function flattenActions(
|
||||
actions: (ActionVariant | ActionGroup | ActionSeparator)[],
|
||||
context: ActionContext
|
||||
): PerformableAction[] {
|
||||
const result: PerformableAction[] = [];
|
||||
|
||||
for (const action of actions) {
|
||||
if (action.type === "action_separator") {
|
||||
continue;
|
||||
}
|
||||
if (action.type === "action_group") {
|
||||
result.push(...flattenActions(action.actions, context));
|
||||
continue;
|
||||
}
|
||||
if (resolve<boolean>(action.visible, context) === false) {
|
||||
continue;
|
||||
}
|
||||
if (action.variant === "action_with_children") {
|
||||
const children = resolve<
|
||||
(ActionVariant | ActionGroup | ActionSeparator)[]
|
||||
>(action.children, context);
|
||||
result.push(...flattenActions(children, context));
|
||||
continue;
|
||||
}
|
||||
if (action.variant === "action" && action.dangerous) {
|
||||
continue;
|
||||
}
|
||||
if (action.analyticsName) {
|
||||
result.push(action);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
+13
-5
@@ -7,7 +7,8 @@ import { KBarProvider } from "kbar";
|
||||
import { Provider } from "mobx-react";
|
||||
import { configure as configureMobx } from "mobx";
|
||||
import { StrictMode } from "react";
|
||||
import { render } from "react-dom";
|
||||
import type { Root } from "react-dom/client";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { HelmetProvider } from "react-helmet-async";
|
||||
import { Router } from "react-router-dom";
|
||||
import stores from "~/stores";
|
||||
@@ -41,15 +42,21 @@ initI18n(env.DEFAULT_LANGUAGE);
|
||||
// React-mounted listener, such as kbar's Enter handler.
|
||||
initSplitViewNavigation(history);
|
||||
|
||||
const element = window.document.getElementById("root");
|
||||
// The dev server can evaluate this module twice (plain and HMR-timestamped
|
||||
// URL). Unlike ReactDOM.render, createRoot must not be called twice on the
|
||||
// same container, so the root is stored on the element and reused.
|
||||
interface RootElement extends HTMLElement {
|
||||
__reactRoot?: Root;
|
||||
}
|
||||
|
||||
const element: RootElement | null = window.document.getElementById("root");
|
||||
|
||||
if (env.SENTRY_DSN) {
|
||||
initSentry(history);
|
||||
}
|
||||
|
||||
configureMobx({
|
||||
// TODO: Enable these options and fix any resulting warnings
|
||||
// enforceActions: env.isDevelopment ? "always" : "never",
|
||||
enforceActions: env.isDevelopment ? "observed" : "never",
|
||||
computedRequiresReaction: true,
|
||||
isolateGlobalState: true,
|
||||
});
|
||||
@@ -97,7 +104,8 @@ if (element) {
|
||||
</StrictMode>
|
||||
);
|
||||
|
||||
render(<App />, element);
|
||||
element.__reactRoot ??= createRoot(element);
|
||||
element.__reactRoot.render(<App />);
|
||||
}
|
||||
|
||||
window.addEventListener("load", async () => {
|
||||
|
||||
@@ -21,7 +21,7 @@ type Props = {
|
||||
children?: React.ReactNode;
|
||||
};
|
||||
|
||||
const AccountMenu: React.FC = ({ children }: Props) => {
|
||||
const AccountMenu: React.FC<Props> = ({ children }: Props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const actions = React.useMemo(
|
||||
|
||||
@@ -129,6 +129,7 @@ function DocumentMenu({
|
||||
|
||||
const rootAction = useDocumentMenuAction({
|
||||
documentId: document.id,
|
||||
isViewing: showDisplayOptions,
|
||||
onFindAndReplace,
|
||||
onRename,
|
||||
onSelectTemplate,
|
||||
|
||||
@@ -19,7 +19,7 @@ type Props = {
|
||||
children?: React.ReactNode;
|
||||
};
|
||||
|
||||
const TeamMenu: React.FC = ({ children }: Props) => {
|
||||
const TeamMenu: React.FC<Props> = ({ children }: Props) => {
|
||||
const { t } = useTranslation();
|
||||
const context = useActionContext({ isMenu: true });
|
||||
|
||||
|
||||
@@ -9,6 +9,11 @@ import type { Searchable } from "./interfaces/Searchable";
|
||||
class ApiKey extends Model implements Searchable {
|
||||
static modelName = "ApiKey";
|
||||
|
||||
constructor(fields: Record<string, unknown>, store: Model["store"]) {
|
||||
super(fields, store);
|
||||
this.initialize(fields);
|
||||
}
|
||||
|
||||
/** The human-readable name of this API key */
|
||||
@Field
|
||||
@observable
|
||||
@@ -17,17 +22,14 @@ class ApiKey extends Model implements Searchable {
|
||||
/** A list of scopes that this API key has access to. If empty, the key has full access. */
|
||||
@Field
|
||||
@observable
|
||||
scope?: string[];
|
||||
|
||||
scope?: string[] = undefined;
|
||||
/** An optional datetime that the API key expires. */
|
||||
@Field
|
||||
@observable
|
||||
expiresAt?: string;
|
||||
|
||||
expiresAt?: string = undefined;
|
||||
/** Timestamp that the API key was last used. */
|
||||
@observable
|
||||
lastActiveAt?: string;
|
||||
|
||||
lastActiveAt?: string = undefined;
|
||||
/** The user who this API key belongs to. */
|
||||
@Relation(() => User)
|
||||
user: User;
|
||||
|
||||
@@ -8,6 +8,11 @@ import type AuthenticationProvidersStore from "~/stores/AuthenticationProvidersS
|
||||
class AuthenticationProvider extends Model {
|
||||
static modelName = "AuthenticationProvider";
|
||||
|
||||
constructor(fields: Record<string, unknown>, store: Model["store"]) {
|
||||
super(fields, store);
|
||||
this.initialize(fields);
|
||||
}
|
||||
|
||||
displayName: string;
|
||||
|
||||
name: string;
|
||||
@@ -27,7 +32,7 @@ class AuthenticationProvider extends Model {
|
||||
|
||||
@Field
|
||||
@observable
|
||||
settings: AuthenticationProviderSettings | undefined;
|
||||
settings: AuthenticationProviderSettings | undefined = undefined;
|
||||
|
||||
@computed
|
||||
get isActive() {
|
||||
|
||||
+20
-13
@@ -1,5 +1,12 @@
|
||||
import invariant from "invariant";
|
||||
import { action, comparer, computed, observable, runInAction } from "mobx";
|
||||
import {
|
||||
action,
|
||||
comparer,
|
||||
computed,
|
||||
observable,
|
||||
override,
|
||||
runInAction,
|
||||
} from "mobx";
|
||||
import {
|
||||
type CollectionPermission,
|
||||
type FileOperationFormat,
|
||||
@@ -19,6 +26,11 @@ import { AfterChange } from "./decorators/Lifecycle";
|
||||
export default class Collection extends ParanoidModel {
|
||||
static modelName = "Collection";
|
||||
|
||||
constructor(fields: Record<string, unknown>, store: CollectionsStore) {
|
||||
super(fields, store);
|
||||
this.initialize(fields);
|
||||
}
|
||||
|
||||
store: CollectionsStore;
|
||||
|
||||
/** The name of the collection. */
|
||||
@@ -39,13 +51,11 @@ export default class Collection extends ParanoidModel {
|
||||
/** The color to use for the collection icon and other highlights. */
|
||||
@Field
|
||||
@observable
|
||||
color?: string | null;
|
||||
|
||||
color?: string | null = undefined;
|
||||
/** The default permission for workspace users. */
|
||||
@Field
|
||||
@observable
|
||||
permission?: CollectionPermission;
|
||||
|
||||
permission?: CollectionPermission = undefined;
|
||||
/**
|
||||
* Whether public sharing is enabled for the collection. Note this can also be disabled at the
|
||||
* workspace level.
|
||||
@@ -77,12 +87,10 @@ export default class Collection extends ParanoidModel {
|
||||
*/
|
||||
@Field
|
||||
@observable
|
||||
commenting?: boolean | null;
|
||||
|
||||
commenting?: boolean | null = undefined;
|
||||
/** The child documents of the collection. */
|
||||
@observable
|
||||
documents?: NavigationNode[];
|
||||
|
||||
documents?: NavigationNode[] = undefined;
|
||||
/** @deprecated Use path instead. */
|
||||
@observable
|
||||
url: string;
|
||||
@@ -101,8 +109,7 @@ export default class Collection extends ParanoidModel {
|
||||
* User who archived the collection.
|
||||
*/
|
||||
@observable
|
||||
archivedBy?: User;
|
||||
|
||||
archivedBy?: User = undefined;
|
||||
@computed
|
||||
get searchContent(): string {
|
||||
return this.name;
|
||||
@@ -214,7 +221,7 @@ export default class Collection extends ParanoidModel {
|
||||
return !!this.archivedAt;
|
||||
}
|
||||
|
||||
@computed
|
||||
@override
|
||||
get isDeleted() {
|
||||
return !!this.deletedAt;
|
||||
}
|
||||
@@ -244,7 +251,7 @@ export default class Collection extends ParanoidModel {
|
||||
});
|
||||
invariant(res?.data, "Data should be available");
|
||||
|
||||
runInAction("Collection#fetchDocuments", () => {
|
||||
runInAction(() => {
|
||||
this.documents = res.data;
|
||||
});
|
||||
} finally {
|
||||
|
||||
Loaded 100 of 359 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user