Merge main

This commit is contained in:
Tom Moor committed 2024-10-21 19:04:38 -04:00
commit 5f8a754cd9
208 files changed
+5053 -1895

No files matched your search

+1 -2
View File
@@ -108,8 +108,7 @@ jobs:
executor: docker-publisher
steps:
- checkout
- setup_remote_docker:
version: 20.10.6
- setup_remote_docker
- run:
name: Install Docker buildx
command: |
+84 -3
View File
@@ -1,8 +1,10 @@
import {
ArchiveIcon,
CollectionIcon,
EditIcon,
PadlockIcon,
PlusIcon,
RestoreIcon,
SearchIcon,
ShapesIcon,
StarredIcon,
@@ -10,11 +12,13 @@ import {
UnstarredIcon,
} from "outline-icons";
import * as React from "react";
import { toast } from "sonner";
import stores from "~/stores";
import Collection from "~/models/Collection";
import { CollectionEdit } from "~/components/Collection/CollectionEdit";
import { CollectionNew } from "~/components/Collection/CollectionNew";
import CollectionDeleteDialog from "~/components/CollectionDeleteDialog";
import ConfirmationDialog from "~/components/ConfirmationDialog";
import DynamicCollectionIcon from "~/components/Icons/CollectionIcon";
import SharePopover from "~/components/Sharing/Collection/SharePopover";
import { getHeaderExpandedKey } from "~/components/Sidebar/components/Header";
@@ -129,9 +133,20 @@ export const searchInCollection = createAction({
analyticsName: "Search collection",
section: ActiveCollectionSection,
icon: <SearchIcon />,
visible: ({ activeCollectionId }) =>
!!activeCollectionId &&
stores.policies.abilities(activeCollectionId).readDocument,
visible: ({ activeCollectionId }) => {
if (!activeCollectionId) {
return false;
}
const collection = stores.collections.get(activeCollectionId);
if (!collection?.isActive) {
return false;
}
return stores.policies.abilities(activeCollectionId).readDocument;
},
perform: ({ activeCollectionId }) => {
history.push(searchPath(undefined, { collectionId: activeCollectionId }));
},
@@ -190,6 +205,72 @@ export const unstarCollection = createAction({
},
});
export const archiveCollection = createAction({
name: ({ t }) => `${t("Archive")}…`,
analyticsName: "Archive collection",
section: CollectionSection,
icon: <ArchiveIcon />,
visible: ({ activeCollectionId, stores }) => {
if (!activeCollectionId) {
return false;
}
return !!stores.policies.abilities(activeCollectionId).archive;
},
perform: async ({ activeCollectionId, stores, t }) => {
const { dialogs, collections } = stores;
if (!activeCollectionId) {
return;
}
const collection = collections.get(activeCollectionId);
if (!collection) {
return;
}
dialogs.openModal({
title: t("Archive collection"),
content: (
<ConfirmationDialog
onSubmit={async () => {
await collection.archive();
toast.success(t("Collection archived"));
}}
submitText={t("Archive")}
savingText={`${t("Archiving")}…`}
>
{t(
"Archiving this collection will also archive all documents within it. Documents from the collection will no longer be visible in search results."
)}
</ConfirmationDialog>
),
});
},
});
export const restoreCollection = createAction({
name: ({ t }) => t("Restore"),
analyticsName: "Restore collection",
section: CollectionSection,
icon: <RestoreIcon />,
visible: ({ activeCollectionId, stores }) => {
if (!activeCollectionId) {
return false;
}
return !!stores.policies.abilities(activeCollectionId).restore;
},
perform: async ({ activeCollectionId, stores, t }) => {
if (!activeCollectionId) {
return;
}
const collection = stores.collections.get(activeCollectionId);
if (!collection) {
return;
}
await collection.restore();
toast.success(t("Collection restored"));
},
});
export const deleteCollection = createAction({
name: ({ t }) => `${t("Delete")}…`,
analyticsName: "Delete collection",
-4
View File
@@ -358,8 +358,6 @@ export const shareDocument = createAction({
}
const document = stores.documents.get(activeDocumentId);
const share = stores.shares.getByDocumentId(activeDocumentId);
const sharedParent = stores.shares.getByDocumentParents(activeDocumentId);
if (!document) {
return;
}
@@ -370,8 +368,6 @@ export const shareDocument = createAction({
content: (
<SharePopover
document={document}
share={share}
sharedParent={sharedParent}
onRequestClose={stores.dialogs.closeAllModals}
visible
/>
+6 -2
View File
@@ -1,5 +1,5 @@
import { LocationDescriptor } from "history";
import { ExpandedIcon } from "outline-icons";
import { DisclosureIcon } from "outline-icons";
import { darken, lighten, transparentize } from "polished";
import * as React from "react";
import styled from "styled-components";
@@ -189,10 +189,14 @@ const Button = <T extends React.ElementType = "button">(
<Inner hasIcon={hasIcon} hasText={hasText} disclosure={disclosure}>
{hasIcon && ic}
{hasText && <Label hasIcon={hasIcon}>{children || value}</Label>}
{disclosure && <ExpandedIcon />}
{disclosure && <StyledDisclosureIcon />}
</Inner>
</RealButton>
);
};
const StyledDisclosureIcon = styled(DisclosureIcon)`
opacity: 0.8;
`;
export default React.forwardRef(Button);
+45
View File
@@ -0,0 +1,45 @@
import { ArchiveIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import Collection from "~/models/Collection";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import { MenuInternalLink } from "~/types";
import { archivePath, collectionPath } from "~/utils/routeHelpers";
import Breadcrumb from "./Breadcrumb";
type Props = {
collection: Collection;
};
export const CollectionBreadcrumb: React.FC<Props> = ({ collection }) => {
const { t } = useTranslation();
const items = React.useMemo(() => {
const collectionNode: MenuInternalLink = {
type: "route",
title: collection.name,
icon: <CollectionIcon collection={collection} expanded />,
to: collectionPath(collection.path),
};
const category: MenuInternalLink | undefined = collection.isArchived
? {
type: "route",
icon: <ArchiveIcon />,
title: t("Archive"),
to: archivePath(),
}
: undefined;
const output = [];
if (category) {
output.push(category);
}
output.push(collectionNode);
return output;
}, [collection, t]);
return <Breadcrumb items={items} highlightFirstItem />;
};
+7 -5
View File
@@ -21,11 +21,13 @@ function ConfirmMoveDialog({ collection, item, ...rest }: Props) {
const { documents, dialogs, collections } = useStores();
const { t } = useTranslation();
const prevCollection = collections.get(item.collectionId!);
const accessMapping = {
[CollectionPermission.ReadWrite]: t("view and edit access"),
[CollectionPermission.Read]: t("view only access"),
null: t("no access"),
};
const accessMapping: Record<Partial<CollectionPermission> | "null", string> =
{
[CollectionPermission.Admin]: t("manage access"),
[CollectionPermission.ReadWrite]: t("view and edit access"),
[CollectionPermission.Read]: t("view only access"),
null: t("no access"),
};
const handleSubmit = async () => {
await documents.move({
+1 -1
View File
@@ -35,7 +35,7 @@ function ConnectionStatus() {
};
const message = ui.multiplayerErrorCode
? codeToMessage[ui.multiplayerErrorCode]
? codeToMessage[ui.multiplayerErrorCode as keyof typeof codeToMessage]
: undefined;
return ui.multiplayerStatus === "connecting" ||
@@ -71,7 +71,7 @@ const GridTemplate = (
<IconButton
key={item.name}
onClick={() => onIconSelect({ id: item.name, value: item.name })}
delay={item.delay}
style={{ "--delay": `${item.delay}ms` } as React.CSSProperties}
>
<Icon as={IconLibrary.getComponent(item.name)} color={item.color}>
{item.initial}
@@ -7,7 +7,6 @@ export const IconButton = styled(NudeButton)<{ delay?: number }>`
width: 32px;
height: 32px;
padding: 4px;
--delay: ${({ delay }) => delay && `${delay}ms`};
&: ${hover} {
background: ${s("listItemHoverBackground")};
+6 -6
View File
@@ -198,7 +198,7 @@ const IconPicker = ({
{...tab}
id={TAB_NAMES["Icon"]}
aria-label={t("Icons")}
active={tab.selectedId === TAB_NAMES["Icon"]}
$active={tab.selectedId === TAB_NAMES["Icon"]}
>
{t("Icons")}
</StyledTab>
@@ -206,7 +206,7 @@ const IconPicker = ({
{...tab}
id={TAB_NAMES["Emoji"]}
aria-label={t("Emojis")}
active={tab.selectedId === TAB_NAMES["Emoji"]}
$active={tab.selectedId === TAB_NAMES["Emoji"]}
>
{t("Emojis")}
</StyledTab>
@@ -273,7 +273,7 @@ const TabActionsWrapper = styled(Flex)`
border-bottom: 1px solid ${s("inputBorder")};
`;
const StyledTab = styled(Tab)<{ active: boolean }>`
const StyledTab = styled(Tab)<{ $active: boolean }>`
position: relative;
font-weight: 500;
font-size: 14px;
@@ -282,15 +282,15 @@ const StyledTab = styled(Tab)<{ active: boolean }>`
border: 0;
padding: 8px 12px;
user-select: none;
color: ${({ active }) => (active ? s("textSecondary") : s("textTertiary"))};
color: ${({ $active }) => ($active ? s("textSecondary") : s("textTertiary"))};
transition: color 100ms ease-in-out;
&: ${hover} {
color: ${s("textSecondary")};
}
${({ active }) =>
active &&
${({ $active }) =>
$active &&
css`
&:after {
content: "";
+7 -1
View File
@@ -1,6 +1,8 @@
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { $Diff } from "utility-types";
import { s } from "@shared/styles";
import { CollectionPermission } from "@shared/types";
import { EmptySelectValue } from "~/types";
import InputSelect, { Props, Option, InputSelectRef } from "./InputSelect";
@@ -19,7 +21,7 @@ function InputSelectPermission(
const { t } = useTranslation();
return (
<InputSelect
<Select
ref={ref}
label={t("Permission")}
options={[
@@ -45,4 +47,8 @@ function InputSelectPermission(
);
}
const Select = styled(InputSelect)`
color: ${s("textSecondary")};
`;
export default React.forwardRef(InputSelectPermission);
+6 -3
View File
@@ -39,12 +39,15 @@ const LocaleTime: React.FC<Props> = ({
relative,
tooltipDelay,
}: Props) => {
const userLocale: string = useUserLocale() || "";
const dateFormatLong = {
const userLocale = useUserLocale();
const dateFormatLong: Record<string, string> = {
en_US: "MMMM do, yyyy h:mm a",
fr_FR: "'Le 'd MMMM yyyy 'à' H:mm",
};
const formatLocaleLong = dateFormatLong[userLocale] ?? "MMMM do, yyyy h:mm a";
const formatLocaleLong =
(userLocale ? dateFormatLong[userLocale] : undefined) ??
"MMMM do, yyyy h:mm a";
// @ts-expect-error fallback to formatLocaleLong
const formatLocale = format?.[userLocale] ?? formatLocaleLong;
const [_, setMinutesMounted] = React.useState(0); // eslint-disable-line @typescript-eslint/no-unused-vars
const callback = React.useRef<() => void>();
+2 -1
View File
@@ -19,7 +19,8 @@ export interface PaginatedItem {
}
type Props<T> = WithTranslation &
RootStore & {
RootStore &
React.HTMLAttributes<HTMLDivElement> & {
fetch?: (
options: Record<string, any> | undefined
) => Promise<T[] | undefined> | undefined;
@@ -1,4 +1,3 @@
import invariant from "invariant";
import debounce from "lodash/debounce";
import isEmpty from "lodash/isEmpty";
import { observer } from "mobx-react";
@@ -17,7 +16,6 @@ import Input, { NativeInput } from "~/components/Input";
import Switch from "~/components/Switch";
import env from "~/env";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import { AvatarSize } from "../../Avatar";
import CopyToClipboard from "../../CopyToClipboard";
import NudeButton from "../../NudeButton";
@@ -39,7 +37,6 @@ type Props = {
};
function PublicAccess({ document, share, sharedParent }: Props) {
const { shares } = useStores();
const { t } = useTranslation();
const theme = useTheme();
const [validationError, setValidationError] = React.useState("");
@@ -55,18 +52,15 @@ function PublicAccess({ document, share, sharedParent }: Props) {
const handlePublishedChange = React.useCallback(
async (event) => {
const share = shares.getByDocumentId(document.id);
invariant(share, "Share must exist");
try {
await share.save({
await share?.save({
published: event.currentTarget.checked,
});
} catch (err) {
toast.error(err.message);
}
},
[document.id, shares]
[share]
);
const handleUrlChange = React.useMemo(
@@ -8,7 +8,6 @@ import { toast } from "sonner";
import { DocumentPermission } from "@shared/types";
import Document from "~/models/Document";
import Group from "~/models/Group";
import Share from "~/models/Share";
import User from "~/models/User";
import { Avatar, GroupAvatar, AvatarSize } from "~/components/Avatar";
import NudeButton from "~/components/NudeButton";
@@ -32,26 +31,19 @@ import { AccessControlList } from "./AccessControlList";
type Props = {
/** The document to share. */
document: Document;
/** The existing share model, if any. */
share: Share | null | undefined;
/** The existing share parent model, if any. */
sharedParent: Share | null | undefined;
/** Callback fired when the popover requests to be closed. */
onRequestClose: () => void;
/** Whether the popover is visible. */
visible: boolean;
};
function SharePopover({
document,
share,
sharedParent,
onRequestClose,
visible,
}: Props) {
function SharePopover({ document, onRequestClose, visible }: Props) {
const team = useCurrentTeam();
const { t } = useTranslation();
const can = usePolicy(document);
const { shares } = useStores();
const share = shares.getByDocumentId(document.id);
const sharedParent = shares.getByDocumentParents(document.id);
const [hasRendered, setHasRendered] = React.useState(visible);
const { users, userMemberships, groups, groupMemberships } = useStores();
const [query, setQuery] = React.useState("");
+7 -7
View File
@@ -133,16 +133,16 @@ function AppSidebar() {
<Section>
<SharedWithMe />
</Section>
<Section auto>
<Section>
<Collections />
</Section>
{can.createDocument && (
<Section auto>
<ArchiveLink />
</Section>
)}
<Section>
{can.createDocument && (
<>
<ArchiveLink />
<TrashLink />
</>
)}
{can.createDocument && <TrashLink />}
<SidebarAction action={inviteUser} />
</Section>
</Scrollable>
@@ -1,41 +1,101 @@
import isUndefined from "lodash/isUndefined";
import { observer } from "mobx-react";
import { ArchiveIcon } from "outline-icons";
import * as React from "react";
import { useDrop } from "react-dnd";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import Flex from "@shared/components/Flex";
import Collection from "~/models/Collection";
import PaginatedList from "~/components/PaginatedList";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import { archivePath } from "~/utils/routeHelpers";
import SidebarLink, { DragObject } from "./SidebarLink";
import { useDropToArchive } from "../hooks/useDragAndDrop";
import { ArchivedCollectionLink } from "./ArchivedCollectionLink";
import { StyledError } from "./Collections";
import PlaceholderCollections from "./PlaceholderCollections";
import Relative from "./Relative";
import SidebarLink from "./SidebarLink";
function ArchiveLink() {
const { policies, documents } = useStores();
const { collections } = useStores();
const { t } = useTranslation();
const [{ isDocumentDropping }, dropToArchiveDocument] = useDrop({
accept: "document",
drop: async (item: DragObject) => {
const document = documents.get(item.id);
await document?.archive();
toast.success(t("Document archived"));
},
canDrop: (item) => policies.abilities(item.id).archive,
collect: (monitor) => ({
isDocumentDropping: monitor.isOver(),
}),
});
const [disclosure, setDisclosure] = React.useState<boolean>(false);
const [expanded, setExpanded] = React.useState<boolean | undefined>();
const { request, data, loading, error } = useRequest(
collections.fetchArchived,
true
);
React.useEffect(() => {
if (!isUndefined(data) && !loading && isUndefined(error)) {
setDisclosure(data.length > 0);
}
}, [data, loading, error]);
React.useEffect(() => {
setDisclosure(collections.archived.length > 0);
}, [collections.archived]);
React.useEffect(() => {
if (disclosure && isUndefined(expanded)) {
setExpanded(false);
}
}, [disclosure]);
React.useEffect(() => {
if (expanded) {
void request();
}
}, [expanded, request]);
const handleDisclosureClick = React.useCallback((ev) => {
ev.preventDefault();
ev.stopPropagation();
setExpanded((e) => !e);
}, []);
const handleClick = React.useCallback(() => {
setExpanded(true);
}, []);
const [{ isOverArchiveSection, isDragging }, dropToArchiveRef] =
useDropToArchive();
return (
<div ref={dropToArchiveDocument}>
<SidebarLink
to={archivePath()}
icon={<ArchiveIcon open={isDocumentDropping} />}
exact={false}
label={t("Archive")}
active={documents.active?.isArchived && !documents.active?.isDeleted}
isActiveDrop={isDocumentDropping}
/>
</div>
<Flex column>
<div ref={dropToArchiveRef}>
<SidebarLink
to={archivePath()}
icon={<ArchiveIcon open={isOverArchiveSection && isDragging} />}
exact={false}
label={t("Archive")}
isActiveDrop={isOverArchiveSection && isDragging}
depth={0}
expanded={disclosure ? expanded : undefined}
onDisclosureClick={handleDisclosureClick}
onClick={handleClick}
/>
</div>
{expanded === true ? (
<Relative>
<PaginatedList
aria-label={t("Archived collections")}
items={collections.archived}
loading={<PlaceholderCollections />}
renderError={(props) => <StyledError {...props} />}
renderItem={(item: Collection) => (
<ArchivedCollectionLink
key={item.id}
depth={1}
collection={item}
/>
)}
/>
</Relative>
) : null}
</Flex>
);
}
@@ -0,0 +1,47 @@
import * as React from "react";
import Collection from "~/models/Collection";
import useStores from "~/hooks/useStores";
import CollectionLink from "./CollectionLink";
import CollectionLinkChildren from "./CollectionLinkChildren";
import Relative from "./Relative";
type Props = {
collection: Collection;
depth?: number;
};
export function ArchivedCollectionLink({ collection, depth }: Props) {
const { documents } = useStores();
const [expanded, setExpanded] = React.useState(false);
const handleDisclosureClick = React.useCallback((ev) => {
ev.preventDefault();
ev.stopPropagation();
setExpanded((e) => !e);
}, []);
const handleClick = React.useCallback(() => {
setExpanded(true);
}, []);
return (
<>
<CollectionLink
depth={depth ? depth : 0}
collection={collection}
expanded={expanded}
activeDocument={documents.active}
onDisclosureClick={handleDisclosureClick}
onClick={handleClick}
/>
<Relative>
<CollectionLinkChildren
collection={collection}
expanded={expanded}
prefetchDocument={documents.prefetchDocument}
/>
</Relative>
</>
);
}
@@ -4,7 +4,6 @@ import { PlusIcon } from "outline-icons";
import * as React from "react";
import { useDrop } from "react-dnd";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import { CollectionValidation } from "@shared/validations";
import Collection from "~/models/Collection";
import Document from "~/models/Document";
@@ -30,6 +29,8 @@ type Props = {
onDisclosureClick: (ev?: React.MouseEvent<HTMLButtonElement>) => void;
activeDocument: Document | undefined;
isDraggingAnyCollection?: boolean;
depth?: number;
onClick?: () => void;
};
const CollectionLink: React.FC<Props> = ({
@@ -37,13 +38,14 @@ const CollectionLink: React.FC<Props> = ({
expanded,
onDisclosureClick,
isDraggingAnyCollection,
depth,
onClick,
}: Props) => {
const { dialogs, documents, collections } = useStores();
const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean();
const [isEditing, setIsEditing] = React.useState(false);
const can = usePolicy(collection);
const { t } = useTranslation();
const history = useHistory();
const sidebarContext = useSidebarContext();
const editableTitleRef = React.useRef<RefHandle>(null);
@@ -52,9 +54,8 @@ const CollectionLink: React.FC<Props> = ({
await collection.save({
name,
});
history.replace(collection.path, history.location.state);
},
[collection, history]
[collection]
);
// Drop to re-parent document
@@ -115,6 +116,7 @@ const CollectionLink: React.FC<Props> = ({
<Relative ref={drop}>
<DropToImport collectionId={collection.id}>
<SidebarLink
onClick={onClick}
to={{
pathname: collection.path,
state: { sidebarContext },
@@ -140,7 +142,7 @@ const CollectionLink: React.FC<Props> = ({
/>
}
exact={false}
depth={0}
depth={depth ? depth : 0}
menu={
!isEditing &&
!isDraggingAnyCollection && (
@@ -55,7 +55,7 @@ function Collections() {
<PaginatedList
options={params}
aria-label={t("Collections")}
items={collections.orderedData}
items={collections.allActive}
loading={<PlaceholderCollections />}
heading={
isDraggingAnyCollection ? (
@@ -84,7 +84,7 @@ function Collections() {
);
}
const StyledError = styled(Error)`
export const StyledError = styled(Error)`
font-size: 15px;
padding: 0 8px;
`;
@@ -41,16 +41,6 @@ function EditableTitle(
setIsEditing(true);
}, []);
const handleKeyDown = React.useCallback(
(event) => {
if (event.key === "Escape") {
setIsEditing(false);
setValue(originalValue);
}
},
[originalValue]
);
const stopPropagation = React.useCallback((event) => {
event.preventDefault();
event.stopPropagation();
@@ -63,6 +53,7 @@ function EditableTitle(
const handleSave = React.useCallback(
async (ev) => {
ev.preventDefault();
ev.stopPropagation();
setIsEditing(false);
const trimmedValue = value.trim();
@@ -85,6 +76,22 @@ function EditableTitle(
[originalValue, value, onSubmit]
);
const handleKeyDown = React.useCallback(
async (ev) => {
if (ev.nativeEvent.isComposing) {
return;
}
if (ev.key === "Escape") {
setIsEditing(false);
setValue(originalValue);
}
if (ev.key === "Enter") {
await handleSave(ev);
}
},
[handleSave, originalValue]
);
React.useEffect(() => {
onEditing?.(isEditing);
}, [onEditing, isEditing]);
@@ -149,6 +149,7 @@ export function useDragDocument(
icon: icon ? <Icon value={icon} color={color} /> : undefined,
collectionId: document?.collectionId || "",
} as DragObject),
canDrag: () => !!document?.isActive,
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
@@ -245,6 +246,7 @@ export function useDropToReparentDocument(
!!pathToNode &&
!pathToNode.includes(monitor.getItem().id) &&
item.id !== node.id &&
!!document?.isActive &&
policies.abilities(node.id).update &&
policies.abilities(item.id).move,
hover: (_item, monitor) => {
@@ -297,6 +299,8 @@ export function useDropToReorderDocument(
const { t } = useTranslation();
const { documents, collections, dialogs, policies } = useStores();
const document = documents.get(node.id);
return useDrop<
DragObject,
Promise<void>,
@@ -304,7 +308,11 @@ export function useDropToReorderDocument(
>({
accept: "document",
canDrop: (item: DragObject) => {
if (item.id === node.id || !policies.abilities(item.id)?.move) {
if (
item.id === node.id ||
!policies.abilities(item.id)?.move ||
!document?.isActive
) {
return false;
}
@@ -427,3 +435,44 @@ export function useDropToReorderUserMembership(getIndex?: () => string) {
}),
});
}
/**
* Hook for shared logic that allows dropping documents and collections onto archive section
*/
export function useDropToArchive() {
const accept = ["document", "collection"];
const { documents, collections, policies } = useStores();
const { t } = useTranslation();
return useDrop<
DragObject,
Promise<void>,
{ isOverArchiveSection: boolean; isDragging: boolean }
>({
accept,
drop: async (item, monitor) => {
const type = monitor.getItemType();
let model;
if (type === "collection") {
model = collections.get(item.id);
} else {
model = documents.get(item.id);
}
if (model) {
await model.archive();
toast.success(
type === "collection"
? t("Collection archived")
: t("Document archived")
);
}
},
canDrop: (item) => policies.abilities(item.id).archive,
collect: (monitor) => ({
isOverArchiveSection: !!monitor.isOver(),
isDragging: monitor.canDrop(),
}),
});
}
+49
View File
@@ -337,6 +337,13 @@ class WebsocketProvider extends React.Component<Props> {
});
this.socket.on("comments.update", (event: PartialExcept<Comment, "id">) => {
const comment = comments.get(event.id);
// Existing policy becomes invalid when the resolution status has changed and we don't have the latest version.
if (comment?.resolvedAt !== event.resolvedAt) {
policies.remove(event.id);
}
comments.add(event);
});
@@ -407,6 +414,48 @@ class WebsocketProvider extends React.Component<Props> {
})
);
this.socket.on(
"collections.archive",
async (event: PartialExcept<Collection, "id">) => {
const collectionId = event.id;
// Fetch collection to update policies
await collections.fetch(collectionId, { force: true });
documents.unarchivedInCollection(collectionId).forEach(
action((doc) => {
if (!doc.publishedAt) {
// draft is to be detached from collection, not archived
doc.collectionId = null;
} else {
doc.archivedAt = event.archivedAt as string;
}
policies.remove(doc.id);
})
);
}
);
this.socket.on(
"collections.restore",
async (event: PartialExcept<Collection, "id">) => {
const collectionId = event.id;
documents
.archivedInCollection(collectionId, {
archivedAt: event.archivedAt as string,
})
.forEach(
action((doc) => {
doc.archivedAt = null;
policies.remove(doc.id);
})
);
// Fetch collection to update policies
await collections.fetch(collectionId, { force: true });
}
);
this.socket.on("teams.update", (event: PartialExcept<Team, "id">) => {
if ("sharing" in event && event.sharing !== auth.team?.sharing) {
documents.all.forEach((document) => {
+47 -49
View File
@@ -1,31 +1,51 @@
import { Provider } from "mobx-react";
import { Node as ProsemirrorNode } from "prosemirror-model";
import { EditorView, Decoration } from "prosemirror-view";
import * as React from "react";
import ReactDOM from "react-dom";
import { ThemeProvider } from "styled-components";
import { FunctionComponent } from "react";
import Extension from "@shared/editor/lib/Extension";
import { ComponentProps } from "@shared/editor/types";
import stores from "~/stores";
import { Editor } from "~/editor";
import { NodeViewRenderer } from "./NodeViewRenderer";
type Component = (props: ComponentProps) => React.ReactElement;
type ComponentViewConstructor = {
/** The editor instance. */
editor: Editor;
/** The extension the view belongs to. */
extension: Extension;
/** The node that the view is responsible for. */
node: ProsemirrorNode;
/** The editor view instance. */
view: EditorView;
/** A function that returns the current position of the node. */
getPos: () => number;
/** The decorations applied to the node. */
decorations: Decoration[];
};
export default class ComponentView {
component: Component;
/** The React component to render. */
component: FunctionComponent<ComponentProps>;
/** The editor instance. */
editor: Editor;
/** The extension the view belongs to. */
extension: Extension;
/** The node that the view is responsible for. */
node: ProsemirrorNode;
/** The editor view instance. */
view: EditorView;
/** A function that returns the current position of the node. */
getPos: () => number;
/** The decorations applied to the node. */
decorations: Decoration[];
/** The renderer instance. */
renderer: NodeViewRenderer<ComponentProps>;
/** Whether the node is selected. */
isSelected = false;
/** The DOM element that the node is rendered into. */
dom: HTMLElement | null;
// See https://prosemirror.net/docs/ref/#view.NodeView
constructor(
component: Component,
component: FunctionComponent<ComponentProps>,
{
editor,
extension,
@@ -33,14 +53,7 @@ export default class ComponentView {
view,
getPos,
decorations,
}: {
editor: Editor;
extension: Extension;
node: ProsemirrorNode;
view: EditorView;
getPos: () => number;
decorations: Decoration[];
}
}: ComponentViewConstructor
) {
this.component = component;
this.editor = editor;
@@ -54,53 +67,33 @@ export default class ComponentView {
: document.createElement("div");
this.dom.classList.add(`component-${node.type.name}`);
this.renderer = new NodeViewRenderer(this.dom, this.component, this.props);
this.renderElement();
window.addEventListener("theme-changed", this.renderElement);
window.addEventListener("location-changed", this.renderElement);
// Add the renderer to the editor's set of renderers so that it is included in the React tree.
this.editor.renderers.add(this.renderer);
}
renderElement = () => {
const { theme } = this.editor.props;
const children = this.component({
theme,
node: this.node,
view: this.view,
isSelected: this.isSelected,
isEditable: this.view.editable,
getPos: this.getPos,
});
ReactDOM.render(
<Provider {...stores}>
<ThemeProvider theme={theme}>{children}</ThemeProvider>
</Provider>,
this.dom
);
};
update(node: ProsemirrorNode) {
if (node.type !== this.node.type) {
return false;
}
this.node = node;
this.renderElement();
this.renderer.updateProps(this.props);
return true;
}
selectNode() {
if (this.view.editable) {
this.isSelected = true;
this.renderElement();
this.renderer.updateProps(this.props);
}
}
deselectNode() {
if (this.view.editable) {
this.isSelected = false;
this.renderElement();
this.renderer.updateProps(this.props);
}
}
@@ -109,16 +102,21 @@ export default class ComponentView {
}
destroy() {
window.removeEventListener("theme-changed", this.renderElement);
window.removeEventListener("location-changed", this.renderElement);
if (this.dom) {
ReactDOM.unmountComponentAtNode(this.dom);
}
this.editor.renderers.delete(this.renderer);
this.dom = null;
}
ignoreMutation() {
return true;
}
get props() {
return {
node: this.node,
view: this.view,
isSelected: this.isSelected,
isEditable: this.view.editable,
getPos: this.getPos,
} as ComponentProps;
}
}
+1
View File
@@ -29,6 +29,7 @@ const EmojiMenu = (props: Props) => {
.map((item) => {
// We snake_case the shortcode for backwards compatability with gemoji to
// avoid multiple formats being written into documents.
// @ts-expect-error emojiMartToGemoji key
const shortcode = snakeCase(emojiMartToGemoji[item.id] || item.id);
const emoji = item.value;
@@ -0,0 +1,28 @@
import isEqual from "lodash/isEqual";
import { action, computed, observable } from "mobx";
import React, { FunctionComponent } from "react";
import { createPortal } from "react-dom";
export class NodeViewRenderer<T extends object> {
@observable public props: T;
public constructor(
public element: HTMLElement,
private Component: FunctionComponent,
props: T
) {
this.props = props;
}
@computed
public get content() {
return createPortal(<this.Component {...this.props} />, this.element);
}
@action
public updateProps(props: T) {
if (!isEqual(props, this.props)) {
this.props = props;
}
}
}
+5 -4
View File
@@ -1,3 +1,4 @@
import deburr from "lodash/deburr";
import escapeRegExp from "lodash/escapeRegExp";
import { observable } from "mobx";
import { Node } from "prosemirror-model";
@@ -243,11 +244,11 @@ export default class FindAndReplaceExtension extends Extension {
});
mergedTextNodes.forEach(({ text = "", pos }) => {
const search = this.findRegExp;
let m;
try {
while ((m = search.exec(text))) {
let m;
const search = this.findRegExp;
while ((m = search.exec(deburr(text)))) {
if (m[0] === "") {
break;
}
+1 -1
View File
@@ -8,7 +8,7 @@ export default class MentionMenuExtension extends Suggestion {
get defaultOptions() {
return {
// ported from https://github.com/tc39/proposal-regexp-unicode-property-escapes#unicode-aware-version-of-w
openRegex: /(?:^|\s|\()@([\p{L}\p{M}\d]+)?$/u,
openRegex: /(?:^|\s|\()@([\p{L}\p{M}\d\s{1}]+)?$/u,
closeRegex: /(?:^|\s|\()@(([\p{L}\p{M}\d]*\s{2})|(\s+[\p{L}\p{M}\d]+))$/u,
};
}
+65 -3
View File
@@ -1,13 +1,23 @@
import isEqual from "lodash/isEqual";
import { keymap } from "prosemirror-keymap";
import {
ySyncPlugin,
yCursorPlugin,
yUndoPlugin,
undo,
redo,
} from "@getoutline/y-prosemirror";
import { keymap } from "prosemirror-keymap";
} from "y-prosemirror";
import * as Y from "yjs";
import Extension from "@shared/editor/lib/Extension";
import { Second } from "@shared/utils/time";
type UserAwareness = {
user?: {
id: string;
};
anchor: object;
head: object;
};
export default class Multiplayer extends Extension {
get name() {
@@ -18,6 +28,7 @@ export default class Multiplayer extends Extension {
const { user, provider, document: doc } = this.options;
const type = doc.get("default", Y.XmlFragment);
// Assign a user to a client ID once they've made a change and then remove the listener
const assignUser = (tr: Y.Transaction) => {
const clientIds = Array.from(doc.store.clients.keys());
@@ -32,6 +43,54 @@ export default class Multiplayer extends Extension {
}
};
const userAwarenessCache = new Map<
string,
{ aw: UserAwareness; changedAt: Date }
>();
// The opacity of a remote user's selection.
const selectionOpacity = 70;
// The time in milliseconds after which a remote user's selection will be hidden.
const selectionTimeout = 10 * Second.ms;
// We're hijacking this method to store the last time a user's awareness changed as a side
// effect, and otherwise behaving as the default.
const awarenessStateFilter = (
currentClientId: number,
userClientId: number,
aw: UserAwareness
) => {
if (currentClientId === userClientId) {
return false;
}
const userId = aw.user?.id;
const cached = userId ? userAwarenessCache.get(userId) : undefined;
if (!cached || !isEqual(cached?.aw, aw)) {
if (userId) {
userAwarenessCache.set(userId, { aw, changedAt: new Date() });
}
}
return true;
};
// Override the default selection builder to add a background color to the selection
// only if the user's awareness has changed recently – this stops selections from lingering.
const selectionBuilder = (u: { id: string; color: string }) => {
const cached = userAwarenessCache.get(u.id);
const opacity =
!cached || cached?.changedAt > new Date(Date.now() - selectionTimeout)
? selectionOpacity
: 0;
return {
style: `background-color: ${u.color}${opacity}`,
class: "ProseMirror-yjs-selection",
};
};
provider.setAwarenessField("user", user);
// only once an actual change has been made do we add the userId <> clientId
@@ -40,7 +99,10 @@ export default class Multiplayer extends Extension {
return [
ySyncPlugin(type),
yCursorPlugin(provider.awareness),
yCursorPlugin(provider.awareness, {
awarenessStateFilter,
selectionBuilder,
}),
yUndoPlugin(),
keymap({
"Mod-z": undo,
+4 -1
View File
@@ -38,7 +38,7 @@ import Mark from "@shared/editor/marks/Mark";
import { basicExtensions as extensions } from "@shared/editor/nodes";
import Node from "@shared/editor/nodes/Node";
import ReactNode from "@shared/editor/nodes/ReactNode";
import { EventType } from "@shared/editor/types";
import { ComponentProps, EventType } from "@shared/editor/types";
import { ProsemirrorData, UserPreferences } from "@shared/types";
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
import EventEmitter from "@shared/utils/events";
@@ -50,6 +50,7 @@ import ComponentView from "./components/ComponentView";
import EditorContext from "./components/EditorContext";
import { SearchResult } from "./components/LinkEditor";
import LinkToolbar from "./components/LinkToolbar";
import { NodeViewRenderer } from "./components/NodeViewRenderer";
import SelectionToolbar from "./components/SelectionToolbar";
import WithTheme from "./components/WithTheme";
@@ -192,6 +193,7 @@ export class Editor extends React.PureComponent<
};
widgets: { [name: string]: (props: WidgetProps) => React.ReactElement };
renderers: Set<NodeViewRenderer<ComponentProps>> = new Set();
nodes: { [name: string]: NodeSpec };
marks: { [name: string]: MarkSpec };
commands: Record<string, CommandFactory>;
@@ -838,6 +840,7 @@ export class Editor extends React.PureComponent<
Object.values(this.widgets).map((Widget, index) => (
<Widget key={String(index)} rtl={isRTL} readOnly={readOnly} />
))}
{Array.from(this.renderers).map((view) => view.content)}
</Flex>
</EditorContext.Provider>
</PortalContext.Provider>
+5 -1
View File
@@ -14,7 +14,10 @@ export default function codeMenuItems(
): MenuItem[] {
const node = state.selection.$from.node();
const allLanguages = Object.entries(LANGUAGES);
const allLanguages = Object.entries(LANGUAGES) as [
keyof typeof LANGUAGES,
string
][];
const frequentLanguages = getFrequentCodeLanguages();
const frequentLangMenuItems = frequentLanguages.map((value) => {
@@ -49,6 +52,7 @@ export default function codeMenuItems(
visible: !readOnly,
name: "code_block",
icon: <ExpandedIcon />,
// @ts-expect-error We have a fallback for incorrect mapping
label: LANGUAGES[node.attrs.language ?? "none"],
children: languageMenuItems,
},
+11 -1
View File
@@ -1,4 +1,4 @@
import { AlignFullWidthIcon, TrashIcon } from "outline-icons";
import { AlignFullWidthIcon, DownloadIcon, TrashIcon } from "outline-icons";
import { EditorState } from "prosemirror-state";
import * as React from "react";
import { isNodeActive } from "@shared/editor/queries/isNodeActive";
@@ -32,5 +32,15 @@ export default function tableMenuItems(
tooltip: dictionary.deleteTable,
icon: <TrashIcon />,
},
{
name: "separator",
},
{
name: "exportTable",
tooltip: dictionary.exportAsCSV,
label: "CSV",
attrs: { format: "csv", fileName: `${window.document.title}.csv` },
icon: <DownloadIcon />,
},
];
}
+1
View File
@@ -77,6 +77,7 @@ export default function useDictionary() {
sortAsc: t("Sort ascending"),
sortDesc: t("Sort descending"),
table: t("Table"),
exportAsCSV: t("Export as CSV"),
toggleHeader: t("Toggle header"),
mathInline: t("Math inline (LaTeX)"),
mathBlock: t("Math block (LaTeX)"),
+2 -9
View File
@@ -3,16 +3,9 @@ import useCurrentUser from "./useCurrentUser";
/**
* Returns the user's locale, or undefined if the user is not logged in.
*
* @param languageCode Whether to only return the language code
* @returns The user's locale, or undefined if the user is not logged in
*/
export default function useUserLocale(languageCode?: boolean) {
export default function useUserLocale() {
const user = useCurrentUser({ rejectOnEmpty: false });
if (!user?.language) {
return undefined;
}
const { language } = user;
return languageCode ? language.split("_")[0] : language;
return user?.language;
}
-6
View File
@@ -32,12 +32,6 @@ void PluginManager.loadPlugins();
initI18n(env.DEFAULT_LANGUAGE);
const element = window.document.getElementById("root");
history.listen(() => {
requestAnimationFrame(() =>
window.dispatchEvent(new Event("location-changed"))
);
});
if (env.SENTRY_DSN) {
initSentry(history);
}
+4
View File
@@ -29,6 +29,8 @@ import {
unstarCollection,
searchInCollection,
createTemplate,
archiveCollection,
restoreCollection,
} from "~/actions/definitions/collections";
import useActionContext from "~/hooks/useActionContext";
import useCurrentTeam from "~/hooks/useCurrentTeam";
@@ -151,6 +153,7 @@ function CollectionMenu({
const canUserInTeam = usePolicy(team);
const items: MenuItem[] = React.useMemo(
() => [
actionToMenuItem(restoreCollection, context),
actionToMenuItem(starCollection, context),
actionToMenuItem(unstarCollection, context),
{
@@ -224,6 +227,7 @@ function CollectionMenu({
onClick: handleExport,
icon: <ExportIcon />,
},
actionToMenuItem(archiveCollection, context),
actionToMenuItem(searchInCollection, context),
{
type: "separator",
+1 -1
View File
@@ -75,7 +75,7 @@ function CommentMenu({
title: `${t("Edit")}…`,
icon: <EditIcon />,
onClick: onEdit,
visible: can.update,
visible: can.update && !comment.isResolved,
},
actionToMenuItem(
resolveCommentFactory({
+4 -5
View File
@@ -215,8 +215,8 @@ const MenuContent: React.FC<MenuContentProps> = ({
type: "button",
title: t("Restore"),
visible:
((document.isWorkspaceTemplate || !!collection) && can.restore) ||
!!can.unarchive,
!!(document.isWorkspaceTemplate || collection?.isActive) &&
!!(can.restore || can.unarchive),
onClick: (ev) => handleRestore(ev),
icon: <RestoreIcon />,
},
@@ -224,9 +224,8 @@ const MenuContent: React.FC<MenuContentProps> = ({
type: "submenu",
title: t("Restore"),
visible:
!document.isWorkspaceTemplate &&
!collection &&
!!can.restore &&
!(document.isWorkspaceTemplate || collection?.isActive) &&
!!(can.restore || can.unarchive) &&
restoreItems.length !== 0,
style: {
left: -170,
+4 -1
View File
@@ -16,10 +16,13 @@ class ApiKey extends ParanoidModel {
@observable
expiresAt?: string;
/** An optional datetime that the API key was last used at. */
/** Timestamp that the API key was last used. */
@observable
lastActiveAt?: string;
/** The user ID that the API key belongs to. */
userId: string;
/** The plain text value of the API key, only available on creation. */
value: string;
+31
View File
@@ -80,6 +80,18 @@ export default class Collection extends ParanoidModel {
@observable
urlId: string;
/**
* The date and time the collection was archived.
*/
@observable
archivedAt: string;
/**
* User who archived the collection.
*/
@observable
archivedBy?: User;
/** Returns whether the collection is empty, or undefined if not loaded. */
@computed
get isEmpty(): boolean | undefined {
@@ -154,6 +166,21 @@ export default class Collection extends ParanoidModel {
.filter(Boolean);
}
@computed
get isArchived() {
return !!this.archivedAt;
}
@computed
get isDeleted() {
return !!this.deletedAt;
}
@computed
get isActive() {
return !this.isArchived && !this.isDeleted;
}
fetchDocuments = async (options?: { force: boolean }) => {
if (this.isFetching) {
return;
@@ -314,6 +341,10 @@ export default class Collection extends ParanoidModel {
@action
unstar = async () => this.store.unstar(this);
archive = () => this.store.archive(this);
restore = () => this.store.restore(this);
export = (format: FileOperationFormat, includeAttachments: boolean) =>
client.post("/collections.export", {
id: this.id,
+2 -2
View File
@@ -99,8 +99,8 @@ class Comment extends Model {
* Whether the comment is resolved
*/
@computed
public get isResolved() {
return !!this.resolvedAt;
public get isResolved(): boolean {
return !!this.resolvedAt || !!this.parentComment?.isResolved;
}
/**
+3 -1
View File
@@ -643,7 +643,9 @@ export default class Document extends ArchivableModel {
nodes: extensionManager.nodes,
marks: extensionManager.marks,
});
const markdown = serializer.serialize(Node.fromJSON(schema, this.data));
const markdown = serializer.serialize(Node.fromJSON(schema, this.data), {
softBreak: true,
});
return markdown;
};
+6 -2
View File
@@ -1,5 +1,9 @@
import { computed, observable } from "mobx";
import { FileOperationFormat, FileOperationType } from "@shared/types";
import {
FileOperationFormat,
FileOperationState,
FileOperationType,
} from "@shared/types";
import { bytesToHumanReadable } from "@shared/utils/files";
import User from "./User";
import Model from "./base/Model";
@@ -10,7 +14,7 @@ class FileOperation extends Model {
id: string;
@observable
state: string;
state: FileOperationState;
name: string;
+2 -1
View File
@@ -11,6 +11,7 @@ import {
UserRole,
} from "@shared/types";
import type { NotificationSettings } from "@shared/types";
import { locales } from "@shared/utils/date";
import { client } from "~/utils/ApiClient";
import Document from "./Document";
import Group from "./Group";
@@ -39,7 +40,7 @@ class User extends ParanoidModel {
@Field
@observable
language: string;
language: keyof typeof locales;
@Field
@observable
+1 -1
View File
@@ -3,5 +3,5 @@ import ParanoidModel from "./ParanoidModel";
export default abstract class ArchivableModel extends ParanoidModel {
@observable
archivedAt: string | undefined;
archivedAt: string | null;
}
+3 -1
View File
@@ -40,6 +40,7 @@ export default abstract class Model {
* @returns A promise that resolves when loading is complete.
*/
async loadRelations(
this: Model,
options: { withoutPolicies?: boolean } = {}
): Promise<any> {
const relations = getRelationsForModelClass(
@@ -62,7 +63,7 @@ export default abstract class Model {
if ("fetch" in store) {
const id = this[properties.idKey];
if (id) {
promises.push(store.fetch(id));
promises.push(store.fetch(id as string));
}
}
}
@@ -145,6 +146,7 @@ export default abstract class Model {
if (key === "initialized") {
continue;
}
// @ts-expect-error TODO
this[key] = data[key];
} catch (error) {
Logger.warn(`Error setting ${key} on model`, error);
+1 -1
View File
@@ -17,7 +17,7 @@ type RelationOptions<T = Model> = {
type RelationProperties<T = Model> = {
/** The name of the property on the model that stores the ID of the relation. */
idKey: string;
idKey: keyof T;
/** A function that returns the class of the relation. */
relationClassResolver: () => typeof Model;
/** Options for the relation. */
@@ -43,8 +43,12 @@ const MembershipPreview = ({ collection, limit = 8 }: Props) => {
memberships.fetchPage(options),
groupMemberships.fetchPage(options),
]);
setUsersCount(users[PAGINATION_SYMBOL].total);
setGroupsCount(groups[PAGINATION_SYMBOL].total);
if (users[PAGINATION_SYMBOL]) {
setUsersCount(users[PAGINATION_SYMBOL].total);
}
if (groups[PAGINATION_SYMBOL]) {
setGroupsCount(groups[PAGINATION_SYMBOL].total);
}
} finally {
setIsLoading(false);
}
@@ -0,0 +1,29 @@
import { ArchiveIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import Collection from "~/models/Collection";
import ErrorBoundary from "~/components/ErrorBoundary";
import Notice from "~/components/Notice";
import Time from "~/components/Time";
type Props = {
collection: Collection;
};
export default function Notices({ collection }: Props) {
const { t } = useTranslation();
return (
<ErrorBoundary>
{collection.isArchived && !collection.isDeleted && (
<Notice icon={<ArchiveIcon />}>
{t("Archived by {{userName}}", {
userName: collection.archivedBy?.name ?? t("Unknown"),
})}
&nbsp;
<Time dateTime={collection.archivedAt} addSuffix />
</Notice>
)}
</ErrorBoundary>
);
}
+46 -19
View File
@@ -13,11 +13,13 @@ import {
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { s } from "@shared/styles";
import { StatusFilter } from "@shared/types";
import { colorPalette } from "@shared/utils/collections";
import Collection from "~/models/Collection";
import Search from "~/scenes/Search";
import { Action } from "~/components/Actions";
import CenteredContent from "~/components/CenteredContent";
import { CollectionBreadcrumb } from "~/components/CollectionBreadcrumb";
import CollectionDescription from "~/components/CollectionDescription";
import Heading from "~/components/Heading";
import Icon, { IconTitleWrapper } from "~/components/Icon";
@@ -28,6 +30,7 @@ import PaginatedDocumentList from "~/components/PaginatedDocumentList";
import PinnedDocuments from "~/components/PinnedDocuments";
import PlaceholderText from "~/components/PlaceholderText";
import Scene from "~/components/Scene";
import Subheading from "~/components/Subheading";
import Tab from "~/components/Tab";
import Tabs from "~/components/Tabs";
import { editCollection } from "~/actions/definitions/collections";
@@ -41,6 +44,7 @@ import Actions from "./components/Actions";
import DropToImport from "./components/DropToImport";
import Empty from "./components/Empty";
import MembershipPreview from "./components/MembershipPreview";
import Notices from "./components/Notices";
import ShareButton from "./components/ShareButton";
const IconPicker = React.lazy(() => import("~/components/IconPicker"));
@@ -132,7 +136,9 @@ function CollectionScene() {
centered={false}
textTitle={collection.name}
left={
collection.isEmpty ? undefined : (
collection.isArchived ? (
<CollectionBreadcrumb collection={collection} />
) : collection.isEmpty ? undefined : (
<InputSearchPage
source="collection"
placeholder={`${t("Search in collection")}…`}
@@ -163,6 +169,7 @@ function CollectionScene() {
collectionId={collection.id}
>
<CenteredContent withStickyHeader>
<Notices collection={collection} />
<CollectionHeading>
<IconTitleWrapper>
{can.update ? (
@@ -192,26 +199,28 @@ function CollectionScene() {
<CollectionDescription collection={collection} />
<Documents>
<Tabs>
<Tab to={collectionPath(collection.path)} exact>
{t("Documents")}
</Tab>
<Tab to={collectionPath(collection.path, "updated")} exact>
{t("Recently updated")}
</Tab>
<Tab to={collectionPath(collection.path, "published")} exact>
{t("Recently published")}
</Tab>
<Tab to={collectionPath(collection.path, "old")} exact>
{t("Least recently updated")}
</Tab>
<Tab to={collectionPath(collection.path, "alphabetical")} exact>
{t("A–Z")}
</Tab>
</Tabs>
{!collection.isArchived && (
<Tabs>
<Tab to={collectionPath(collection.path)} exact>
{t("Documents")}
</Tab>
<Tab to={collectionPath(collection.path, "updated")} exact>
{t("Recently updated")}
</Tab>
<Tab to={collectionPath(collection.path, "published")} exact>
{t("Recently published")}
</Tab>
<Tab to={collectionPath(collection.path, "old")} exact>
{t("Least recently updated")}
</Tab>
<Tab to={collectionPath(collection.path, "alphabetical")} exact>
{t("A–Z")}
</Tab>
</Tabs>
)}
{collection.isEmpty ? (
<Empty collection={collection} />
) : (
) : !collection.isArchived ? (
<Switch>
<Route path={collectionPath(collection.path, "alphabetical")}>
<PaginatedDocumentList
@@ -279,6 +288,24 @@ function CollectionScene() {
/>
</Route>
</Switch>
) : (
<Switch>
<Route path={collectionPath(collection.path)} exact>
<PaginatedDocumentList
documents={documents.archivedInCollection(collection.id)}
fetch={documents.fetchPage}
heading={<Subheading sticky>{t("Documents")}</Subheading>}
options={{
collectionId: collection.id,
parentDocumentId: null,
sort: collection.sort.field,
direction: collection.sort.direction,
statusFilter: [StatusFilter.Archived],
}}
showParentDocuments
/>
</Route>
</Switch>
)}
</Documents>
</CenteredContent>
@@ -80,6 +80,8 @@ function CommentThread({
});
const can = usePolicy(document);
const canReply = can.comment && !thread.isResolved;
const highlightedCommentMarks = editor
?.getComments()
.filter((comment) => comment.id === thread.id);
@@ -105,7 +107,7 @@ function CommentThread({
const handleClickThread = () => {
history.replace({
// Clear any commentId from the URL when explicitly focusing a thread
search: "",
search: thread.isResolved ? "resolved=" : "",
pathname: location.pathname.replace(/\/history$/, ""),
state: { commentId: thread.id },
});
@@ -214,7 +216,7 @@ function CommentThread({
))}
<ResizingHeightContainer hideOverflow={false} ref={replyRef}>
{(focused || draft || commentsInThread.length === 0) && can.comment && (
{(focused || draft || commentsInThread.length === 0) && canReply && (
<Fade timing={100}>
<CommentForm
onSaveDraft={onSaveDraft}
@@ -232,7 +234,7 @@ function CommentThread({
</Fade>
)}
</ResizingHeightContainer>
{!focused && !recessed && !draft && can.comment && (
{!focused && !recessed && !draft && canReply && (
<Reply onClick={() => setAutoFocus(true)}>{t("Reply")}…</Reply>
)}
</Thread>
+2 -2
View File
@@ -41,7 +41,7 @@ import DocumentMenu from "~/menus/DocumentMenu";
import NewChildDocumentMenu from "~/menus/NewChildDocumentMenu";
import TableOfContentsMenu from "~/menus/TableOfContentsMenu";
import TemplatesMenu from "~/menus/TemplatesMenu";
import { metaDisplay } from "~/utils/keyboard";
import { altDisplay, metaDisplay } from "~/utils/keyboard";
import { documentEditPath } from "~/utils/routeHelpers";
import ObservingBanner from "./ObservingBanner";
import PublicBreadcrumb from "./PublicBreadcrumb";
@@ -124,7 +124,7 @@ function DocumentHeader({
? t("Show contents")
: `${t("Show contents")} (${t("available when headings are added")})`
}
shortcut="ctrl+alt+h"
shortcut={`ctrl+${altDisplay}+h`}
delay={250}
placement="bottom"
>
@@ -53,8 +53,6 @@ function ShareButton({ document }: Props) {
>
<SharePopover
document={document}
share={share}
sharedParent={sharedParent}
onRequestClose={popover.hide}
visible={popover.visible}
/>
+3 -2
View File
@@ -71,10 +71,11 @@ function Invite({ onSubmit }: Props) {
[onSubmit, invites, role, t, users]
);
const handleChange = React.useCallback((ev, index) => {
const handleChange = React.useCallback((ev, index: number) => {
setInvites((prevInvites) => {
const newInvites = [...prevInvites];
newInvites[index][ev.target.name] = ev.target.value;
newInvites[index][ev.target.name as keyof InviteRequest] =
ev.target.value;
return newInvites;
});
}, []);
+70 -54
View File
@@ -57,7 +57,9 @@ function Search(props: Props) {
const recentSearchesRef = React.useRef<HTMLDivElement | null>(null);
// filters
const query = decodeURIComponentSafe(routeMatch.params.term ?? "");
const query = decodeURIComponentSafe(
routeMatch.params.term ?? params.get("query") ?? ""
);
const collectionId = params.get("collectionId") ?? undefined;
const userId = params.get("userId") ?? undefined;
const documentId = params.get("documentId") ?? undefined;
@@ -117,7 +119,12 @@ function Search(props: Props) {
const updateLocation = (query: string) => {
history.replace({
pathname: searchPath(query),
search: location.search,
search: queryString.stringify(
{ ...queryString.parse(location.search), query: undefined },
{
skipEmptyString: true,
}
),
});
};
@@ -134,7 +141,7 @@ function Search(props: Props) {
history.replace({
pathname: location.pathname,
search: queryString.stringify(
{ ...queryString.parse(location.search), ...search },
{ ...queryString.parse(location.search), query: undefined, ...search },
{
skipEmptyString: true,
}
@@ -201,59 +208,68 @@ function Search(props: Props) {
</div>
)}
<ResultsWrapper column auto>
<SearchInput
key={query ? "search" : "recent"}
ref={searchInputRef}
placeholder={`${
documentId
? t("Search in document")
: collectionId
? t("Search in collection")
: t("Search")
}…`}
onKeyDown={handleKeyDown}
defaultValue={query}
/>
<form
method="GET"
action={searchPath()}
onSubmit={(ev) => ev.preventDefault()}
>
<SearchInput
name="query"
key={query ? "search" : "recent"}
ref={searchInputRef}
placeholder={`${
documentId
? t("Search in document")
: collectionId
? t("Search in collection")
: t("Search")
}…`}
onKeyDown={handleKeyDown}
defaultValue={query}
/>
{(query || hasFilters) && (
<Filters>
{document && (
<DocumentFilter
document={document}
onClick={() => {
handleFilterChange({ documentId: undefined });
}}
{(query || hasFilters) && (
<Filters>
{document && (
<DocumentFilter
document={document}
onClick={() => {
handleFilterChange({ documentId: undefined });
}}
/>
)}
<DocumentTypeFilter
statusFilter={statusFilter}
onSelect={({ statusFilter }) =>
handleFilterChange({ statusFilter })
}
/>
)}
<DocumentTypeFilter
statusFilter={statusFilter}
onSelect={({ statusFilter }) =>
handleFilterChange({ statusFilter })
}
/>
<CollectionFilter
collectionId={collectionId}
onSelect={(collectionId) => handleFilterChange({ collectionId })}
/>
<UserFilter
userId={userId}
onSelect={(userId) => handleFilterChange({ userId })}
/>
<DateFilter
dateFilter={dateFilter}
onSelect={(dateFilter) => handleFilterChange({ dateFilter })}
/>
<SearchTitlesFilter
width={26}
height={14}
label={t("Search titles only")}
onChange={(ev: React.ChangeEvent<HTMLInputElement>) => {
handleFilterChange({ titleFilter: ev.target.checked });
}}
checked={titleFilter}
/>
</Filters>
)}
<CollectionFilter
collectionId={collectionId}
onSelect={(collectionId) =>
handleFilterChange({ collectionId })
}
/>
<UserFilter
userId={userId}
onSelect={(userId) => handleFilterChange({ userId })}
/>
<DateFilter
dateFilter={dateFilter}
onSelect={(dateFilter) => handleFilterChange({ dateFilter })}
/>
<SearchTitlesFilter
width={26}
height={14}
label={t("Search titles only")}
onChange={(ev: React.ChangeEvent<HTMLInputElement>) => {
handleFilterChange({ titleFilter: ev.target.checked });
}}
checked={titleFilter}
/>
</Filters>
)}
</form>
{query ? (
<>
{error ? (
+4 -4
View File
@@ -4,10 +4,10 @@ import styled, { useTheme } from "styled-components";
import { s } from "@shared/styles";
import Flex from "~/components/Flex";
type Props = React.HTMLAttributes<HTMLInputElement> & {
defaultValue?: string;
placeholder?: string;
};
interface Props extends React.HTMLAttributes<HTMLInputElement> {
name: string;
defaultValue: string;
}
function SearchInput(
{ defaultValue, ...rest }: Props,
+4 -1
View File
@@ -13,12 +13,14 @@ import Text from "~/components/Text";
import { createApiKey } from "~/actions/definitions/apiKeys";
import useActionContext from "~/hooks/useActionContext";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useCurrentUser from "~/hooks/useCurrentUser";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import ApiKeyListItem from "./components/ApiKeyListItem";
function ApiKeys() {
const team = useCurrentTeam();
const user = useCurrentUser();
const { t } = useTranslation();
const { apiKeys } = useStores();
const can = usePolicy(team);
@@ -79,7 +81,8 @@ function ApiKeys() {
</Text>
<PaginatedList
fetch={apiKeys.fetchPage}
items={apiKeys.orderedData}
items={apiKeys.personalApiKeys}
options={{ userId: user.id }}
heading={<h2>{t("Personal keys")}</h2>}
renderItem={(apiKey: ApiKey) => (
<ApiKeyListItem
+3 -1
View File
@@ -62,7 +62,9 @@ function Members() {
filter,
role,
});
setTotalPages(Math.ceil(response[PAGINATION_SYMBOL].total / limit));
if (response[PAGINATION_SYMBOL]) {
setTotalPages(Math.ceil(response[PAGINATION_SYMBOL].total / limit));
}
setUserIds(response.map((u: User) => u.id));
} finally {
setIsLoading(false);
+3 -1
View File
@@ -47,7 +47,9 @@ function Shares() {
sort,
direction,
});
setTotalPages(Math.ceil(response[PAGINATION_SYMBOL].total / limit));
if (response[PAGINATION_SYMBOL]) {
setTotalPages(Math.ceil(response[PAGINATION_SYMBOL].total / limit));
}
setShareIds(response.map((u: Share) => u.id));
} finally {
setIsLoading(false);
@@ -38,7 +38,7 @@ const FileOperationListItem = ({ fileOperation }: Props) => {
[FileOperationState.Error]: t("Failed"),
};
const iconMapping = {
const iconMapping: Record<FileOperationState, React.JSX.Element> = {
[FileOperationState.Creating]: <Spinner />,
[FileOperationState.Uploading]: <Spinner />,
[FileOperationState.Expired]: <ArchiveIcon color={theme.textTertiary} />,
@@ -46,8 +46,9 @@ const FileOperationListItem = ({ fileOperation }: Props) => {
[FileOperationState.Error]: <WarningIcon color={theme.danger} />,
};
const formatMapping = {
const formatMapping: Record<FileOperationFormat, string> = {
[FileOperationFormat.JSON]: "JSON",
[FileOperationFormat.Notion]: "Notion",
[FileOperationFormat.MarkdownZip]: "Markdown",
[FileOperationFormat.HTMLZip]: "HTML",
[FileOperationFormat.PDF]: "PDF",
+9
View File
@@ -1,3 +1,4 @@
import { computed } from "mobx";
import ApiKey from "~/models/ApiKey";
import RootStore from "./RootStore";
import Store, { RPCAction } from "./base/Store";
@@ -8,4 +9,12 @@ export default class ApiKeysStore extends Store<ApiKey> {
constructor(rootStore: RootStore) {
super(rootStore, ApiKey);
}
@computed
get personalApiKeys() {
const userId = this.rootStore.auth.user?.id;
return userId
? this.orderedData.filter((key) => key.userId === userId)
: [];
}
}
+83 -3
View File
@@ -1,11 +1,16 @@
import invariant from "invariant";
import find from "lodash/find";
import isEmpty from "lodash/isEmpty";
import orderBy from "lodash/orderBy";
import sortBy from "lodash/sortBy";
import { computed, action } from "mobx";
import { CollectionPermission, FileOperationFormat } from "@shared/types";
import { computed, action, runInAction } from "mobx";
import {
CollectionPermission,
CollectionStatusFilter,
FileOperationFormat,
} from "@shared/types";
import Collection from "~/models/Collection";
import { Properties } from "~/types";
import { PaginationParams, Properties } from "~/types";
import { client } from "~/utils/ApiClient";
import RootStore from "./RootStore";
import Store from "./base/Store";
@@ -27,6 +32,11 @@ export default class CollectionsStore extends Store<Collection> {
: undefined;
}
@computed
get allActive() {
return this.orderedData.filter((c) => c.isActive);
}
@computed
get orderedData(): Collection[] {
let collections = Array.from(this.data.values());
@@ -97,6 +107,30 @@ export default class CollectionsStore extends Store<Collection> {
}
};
@action
archive = async (collection: Collection) => {
const res = await client.post("/collections.archive", {
id: collection.id,
});
runInAction("Collection#archive", () => {
invariant(res?.data, "Data should be available");
this.add(res.data);
this.addPolicies(res.policies);
});
};
@action
restore = async (collection: Collection) => {
const res = await client.post("/collections.restore", {
id: collection.id,
});
runInAction("Collection#restore", () => {
invariant(res?.data, "Data should be available");
this.add(res.data);
this.addPolicies(res.policies);
});
};
async update(params: Properties<Collection>): Promise<Collection> {
const result = await super.update(params);
@@ -119,6 +153,52 @@ export default class CollectionsStore extends Store<Collection> {
return model;
}
@action
fetchNamedPage = async (
request = "list",
options:
| (PaginationParams & { statusFilter: CollectionStatusFilter[] })
| undefined
): Promise<Collection[]> => {
this.isFetching = true;
try {
const res = await client.post(`/collections.${request}`, options);
invariant(res?.data, "Collection list not available");
runInAction("CollectionsStore#fetchNamedPage", () => {
res.data.forEach(this.add);
this.addPolicies(res.policies);
this.isLoaded = true;
});
return res.data;
} finally {
this.isFetching = false;
}
};
@action
fetchArchived = async (options?: PaginationParams): Promise<Collection[]> =>
this.fetchNamedPage("list", {
...options,
statusFilter: [CollectionStatusFilter.Archived],
});
@computed
get archived(): Collection[] {
return orderBy(this.orderedData, "archivedAt", "desc").filter(
(c) => c.isArchived && !c.isDeleted
);
}
@computed
get publicCollections() {
return this.orderedData.filter(
(collection) =>
collection.permission &&
Object.values(CollectionPermission).includes(collection.permission)
);
}
star = async (collection: Collection, index?: string) => {
await this.rootStore.stars.create({
collectionId: collection.id,
+39 -2
View File
@@ -121,6 +121,33 @@ export default class DocumentsStore extends Store<Document> {
);
}
archivedInCollection(
collectionId: string,
options?: { archivedAt: string }
): Document[] {
const filterCond = (document: Document) =>
options
? document.collectionId === collectionId &&
document.isArchived &&
document.archivedAt === options.archivedAt &&
!document.isDeleted
: document.collectionId === collectionId &&
document.isArchived &&
!document.isDeleted;
return filter(this.orderedData, filterCond);
}
unarchivedInCollection(collectionId: string): Document[] {
return filter(
this.orderedData,
(document) =>
document.collectionId === collectionId &&
!document.isArchived &&
!document.isDeleted
);
}
templatesInCollection(collectionId: string): Document[] {
return orderBy(
filter(
@@ -313,8 +340,18 @@ export default class DocumentsStore extends Store<Document> {
};
@action
fetchArchived = async (options?: PaginationParams): Promise<Document[]> =>
this.fetchNamedPage("archived", options);
fetchArchived = async (options?: PaginationParams): Promise<Document[]> => {
const archivedInResponse = await this.fetchNamedPage("archived", options);
const archivedInMemory = this.archived;
archivedInMemory.forEach((docInMemory) => {
!archivedInResponse.find(
(docInResponse) => docInResponse.id === docInMemory.id
) && this.remove(docInMemory.id);
});
return archivedInResponse;
};
@action
fetchDeleted = async (options?: PaginationParams): Promise<Document[]> =>
+7 -3
View File
@@ -5,7 +5,11 @@ import GroupMembership from "~/models/GroupMembership";
import { PaginationParams } from "~/types";
import { client } from "~/utils/ApiClient";
import RootStore from "./RootStore";
import Store, { PAGINATION_SYMBOL, RPCAction } from "./base/Store";
import Store, {
PAGINATION_SYMBOL,
PaginatedResponse,
RPCAction,
} from "./base/Store";
export default class GroupMembershipsStore extends Store<GroupMembership> {
actions = [RPCAction.Create, RPCAction.Delete];
@@ -24,7 +28,7 @@ export default class GroupMembershipsStore extends Store<GroupMembership> {
documentId?: string;
collectionId?: string;
groupId?: string;
}): Promise<GroupMembership[]> => {
}): Promise<PaginatedResponse<GroupMembership>> => {
this.isFetching = true;
try {
@@ -41,7 +45,7 @@ export default class GroupMembershipsStore extends Store<GroupMembership> {
: await client.post(`/groupMemberships.list`, params);
invariant(res?.data, "Data not available");
let response: GroupMembership[] = [];
let response: PaginatedResponse<GroupMembership> = [];
runInAction(`GroupMembershipsStore#fetchPage`, () => {
res.data.groups?.forEach(this.rootStore.groups.add);
res.data.documents?.forEach(this.rootStore.documents.add);
+7 -3
View File
@@ -5,7 +5,11 @@ import Membership from "~/models/Membership";
import { PaginationParams } from "~/types";
import { client } from "~/utils/ApiClient";
import RootStore from "./RootStore";
import Store, { PAGINATION_SYMBOL, RPCAction } from "./base/Store";
import Store, {
PAGINATION_SYMBOL,
PaginatedResponse,
RPCAction,
} from "./base/Store";
export default class MembershipsStore extends Store<Membership> {
actions = [RPCAction.Create, RPCAction.Delete];
@@ -17,14 +21,14 @@ export default class MembershipsStore extends Store<Membership> {
@action
fetchPage = async (
params: (PaginationParams & { id?: string }) | undefined
): Promise<Membership[]> => {
): Promise<PaginatedResponse<Membership>> => {
this.isFetching = true;
try {
const res = await client.post(`/collections.memberships`, params);
invariant(res?.data, "Data not available");
let response: Membership[] = [];
let response: PaginatedResponse<Membership> = [];
runInAction(`MembershipsStore#fetchPage`, () => {
res.data.users.forEach(this.rootStore.users.add);
response = res.data.memberships.map(this.add);
+10 -9
View File
@@ -102,14 +102,11 @@ export default class RootStore {
*
* @param modelName
*/
public getStoreForModelName<K extends keyof RootStore>(
modelName: string
): RootStore[K] {
public getStoreForModelName<K extends keyof RootStore>(modelName: string) {
const storeName = this.getStoreNameForModelName(modelName);
const store = this[storeName];
invariant(store, `No store found for model name "${modelName}"`);
return store;
return store as RootStore[K];
}
/**
@@ -118,8 +115,9 @@ export default class RootStore {
public clear() {
Object.getOwnPropertyNames(this)
.filter((key) => ["auth", "ui"].includes(key) === false)
.forEach((key) => {
this[key]?.clear?.();
.forEach((key: keyof RootStore) => {
// @ts-expect-error clear exists on all stores
"clear" in this[key] && this[key].clear();
});
}
@@ -128,7 +126,10 @@ export default class RootStore {
*
* @param StoreClass
*/
private registerStore<T = typeof Store>(StoreClass: T, name?: string) {
private registerStore<T = typeof Store>(
StoreClass: T,
name?: keyof RootStore
) {
// @ts-expect-error TS thinks we are instantiating an abstract class.
const store = new StoreClass(this);
const storeName = name ?? this.getStoreNameForModelName(store.modelName);
@@ -136,6 +137,6 @@ export default class RootStore {
}
private getStoreNameForModelName(modelName: string) {
return pluralize(lowerFirst(modelName));
return pluralize(lowerFirst(modelName)) as keyof RootStore;
}
}
+7 -1
View File
@@ -1,8 +1,10 @@
import { action, autorun, computed, observable } from "mobx";
import { flushSync } from "react-dom";
import { light as defaultTheme } from "@shared/styles/theme";
import Storage from "@shared/utils/Storage";
import Document from "~/models/Document";
import type { ConnectionStatus } from "~/scenes/Document/components/MultiplayerEditor";
import { startViewTransition } from "~/utils/viewTransition";
import type RootStore from "./RootStore";
const UI_STORE = "UI_STORE";
@@ -140,7 +142,11 @@ class UiStore {
@action
setTheme = (theme: Theme) => {
this.theme = theme;
startViewTransition(() => {
flushSync(() => {
this.theme = theme;
});
});
Storage.set("theme", this.theme);
};
+24 -11
View File
@@ -17,7 +17,6 @@ import { LifecycleManager } from "~/models/decorators/Lifecycle";
import { getInverseRelationsForModelClass } from "~/models/decorators/Relation";
import type { PaginationParams, PartialExcept, Properties } from "~/types";
import { client } from "~/utils/ApiClient";
import Logger from "~/utils/Logger";
import { AuthorizationError, NotFoundError } from "~/utils/errors";
export enum RPCAction {
@@ -29,10 +28,19 @@ export enum RPCAction {
Count = "count",
}
export type FetchPageParams = PaginationParams & Record<string, any>;
export const PAGINATION_SYMBOL = Symbol.for("pagination");
export type PaginatedResponse<T> = T[] & {
[PAGINATION_SYMBOL]?: {
total: number;
limit: number;
offset: number;
nextPath: string;
};
};
export type FetchPageParams = PaginationParams & Record<string, any>;
export default abstract class Store<T extends Model> {
@observable
data: Map<string, T> = new Map();
@@ -129,6 +137,7 @@ export default abstract class Store<T extends Model> {
if (deleteBehavior === "cascade") {
store.remove(item.id);
} else if (deleteBehavior === "null") {
// @ts-expect-error TODO
item[relation.idKey] = null;
}
});
@@ -166,6 +175,7 @@ export default abstract class Store<T extends Model> {
if (archiveBehavior === "cascade") {
store.addToArchive(item);
} else if (archiveBehavior === "null") {
// @ts-expect-error TODO
item[relation.idKey] = null;
}
});
@@ -316,7 +326,9 @@ export default abstract class Store<T extends Model> {
}
@action
fetchPage = async (params?: FetchPageParams | undefined): Promise<T[]> => {
fetchPage = async (
params?: FetchPageParams | undefined
): Promise<PaginatedResponse<T>> => {
if (!this.actions.includes(RPCAction.List)) {
throw new Error(`Cannot list ${this.modelName}`);
}
@@ -327,7 +339,7 @@ export default abstract class Store<T extends Model> {
const res = await client.post(`/${this.apiEndpoint}.list`, params);
invariant(res?.data, "Data not available");
let response: T[] = [];
let response: PaginatedResponse<T> = [];
runInAction(`list#${this.modelName}`, () => {
this.addPolicies(res.policies);
@@ -343,15 +355,16 @@ export default abstract class Store<T extends Model> {
};
@action
fetchAll = async (params?: Record<string, any>): Promise<T[]> => {
fetchAll = async (
params?: Record<string, any>
): Promise<PaginatedResponse<T>> => {
const limit = params?.limit ?? Pagination.defaultLimit;
const response = await this.fetchPage({ ...params, limit });
if (!response[PAGINATION_SYMBOL]) {
Logger.warn("Pagination information not available in response", {
params,
});
}
invariant(
response[PAGINATION_SYMBOL],
"Pagination information not available in response"
);
const pages = Math.ceil(response[PAGINATION_SYMBOL].total / limit);
const fetchPages = [];
+3 -2
View File
@@ -17,13 +17,14 @@ import {
getCurrentTimeAsString,
unicodeCLDRtoBCP47,
dateLocale,
locales,
} from "@shared/utils/date";
import User from "~/models/User";
export function dateToHeading(
dateTime: string,
t: TFunction,
userLocale: string | null | undefined
userLocale: keyof typeof locales | undefined
) {
const date = Date.parse(dateTime);
const now = new Date();
@@ -84,7 +85,7 @@ export function dateToHeading(
export function dateToExpiry(
dateTime: string,
t: TFunction,
userLocale: string | null | undefined
userLocale: keyof typeof locales | null | undefined
) {
const date = Date.parse(dateTime);
const now = new Date();
+2
View File
@@ -33,7 +33,9 @@ export default function download(
// reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
// @ts-expect-error this is weird code
x = [x, m];
// @ts-expect-error this is weird code
m = x[0];
// @ts-expect-error this is weird code
x = x[1];
}
+2 -2
View File
@@ -1,5 +1,5 @@
import { i18n } from "i18next";
import { unicodeCLDRtoBCP47 } from "@shared/utils/date";
import { locales, unicodeCLDRtoBCP47 } from "@shared/utils/date";
import Desktop from "./Desktop";
/**
@@ -25,7 +25,7 @@ export function formatNumber(number: number, locale: string) {
export function detectLanguage() {
const [ln, r] = navigator.language.split("-");
const region = (r || ln).toUpperCase();
return `${ln}_${region}`;
return `${ln}_${region}` as keyof typeof locales;
}
/**
+1 -1
View File
@@ -19,5 +19,5 @@ export function getVisibilityListener(): string {
}
export function getPageVisible(): boolean {
return !document[hidden];
return !document[hidden as keyof Document];
}
+3 -1
View File
@@ -25,7 +25,9 @@ export function settingsPath(section?: string): string {
}
export function commentPath(document: Document, comment: Comment): string {
return `${documentPath(document)}?commentId=${comment.id}`;
return `${documentPath(document)}?commentId=${comment.id}${
comment.isResolved ? "&resolved=" : ""
}`;
}
export function collectionPath(url: string, section?: string): string {
+13
View File
@@ -0,0 +1,13 @@
/**
* A simple wrapper around the startViewTransition API, if it exists. Otherwise
* it will just call the callback immediately.
*
* @param callback The callback to call inside the view transition.
*/
export const startViewTransition = (callback: UpdateCallback) => {
if (self.document.startViewTransition) {
self.document.startViewTransition(callback);
} else {
callback();
}
};
-1
View File
@@ -1,4 +1,3 @@
version: "3"
services:
redis:
image: redis
+12 -12
View File
@@ -58,7 +58,7 @@
"@babel/plugin-transform-class-properties": "^7.24.7",
"@babel/plugin-transform-destructuring": "^7.24.8",
"@babel/plugin-transform-regenerator": "^7.24.7",
"@babel/preset-env": "^7.24.7",
"@babel/preset-env": "^7.25.8",
"@babel/preset-react": "^7.24.7",
"@benrbray/prosemirror-math": "^0.2.2",
"@bull-board/api": "^4.2.2",
@@ -73,7 +73,6 @@
"@fortawesome/free-solid-svg-icons": "^6.5.2",
"@fortawesome/react-fontawesome": "^0.2.2",
"@getoutline/react-roving-tabindex": "^3.2.4",
"@getoutline/y-prosemirror": "^1.0.18",
"@hocuspocus/extension-throttle": "1.1.2",
"@hocuspocus/provider": "1.1.2",
"@hocuspocus/server": "1.1.2",
@@ -100,7 +99,7 @@
"class-validator": "^0.14.1",
"command-score": "^0.1.2",
"compressorjs": "^1.2.1",
"cookie": "^0.6.0",
"cookie": "^0.7.0",
"copy-to-clipboard": "^3.3.3",
"core-js": "^3.37.0",
"crypto-js": "^4.2.0",
@@ -111,7 +110,7 @@
"dotenv": "^16.4.5",
"email-providers": "^1.14.0",
"emoji-mart": "^5.6.0",
"emoji-regex": "^10.3.0",
"emoji-regex": "^10.4.0",
"es6-error": "^4.1.1",
"fast-deep-equal": "^3.1.3",
"fetch-retry": "^5.0.6",
@@ -159,7 +158,7 @@
"node-fetch": "2.7.0",
"nodemailer": "^6.9.14",
"octokit": "^3.2.1",
"outline-icons": "^3.8.0",
"outline-icons": "^3.10.0",
"oy-vey": "^0.12.1",
"passport": "^0.7.0",
"passport-google-oauth2": "^0.2.0",
@@ -179,7 +178,7 @@
"prosemirror-inputrules": "^1.4.0",
"prosemirror-keymap": "^1.2.2",
"prosemirror-markdown": "^1.13.0",
"prosemirror-model": "^1.22.3",
"prosemirror-model": "^1.23.0",
"prosemirror-schema-list": "^1.4.1",
"prosemirror-state": "^1.4.3",
"prosemirror-tables": "^1.4.0",
@@ -239,11 +238,12 @@
"utility-types": "^3.10.0",
"uuid": "^8.3.2",
"validator": "13.12.0",
"vite": "^5.3.1",
"vite": "^5.4.8",
"vite-plugin-pwa": "^0.20.3",
"winston": "^3.13.0",
"ws": "^7.5.10",
"y-indexeddb": "^9.0.11",
"y-prosemirror": "^1.2.12",
"y-protocols": "^1.0.6",
"yauzl": "^2.10.0",
"yjs": "^13.6.1",
@@ -296,7 +296,7 @@
"@types/quoted-printable": "^1.0.2",
"@types/randomstring": "^1.3.0",
"@types/react": "^17.0.34",
"@types/react-avatar-editor": "^13.0.2",
"@types/react-avatar-editor": "^13.0.3",
"@types/react-color": "^3.0.12",
"@types/react-dom": "^17.0.11",
"@types/react-helmet": "^6.1.11",
@@ -329,7 +329,7 @@
"babel-plugin-tsconfig-paths-module-resolver": "^1.0.4",
"browserslist-to-esbuild": "^1.2.0",
"concurrently": "^8.2.2",
"discord-api-types": "^0.37.101",
"discord-api-types": "^0.37.102",
"eslint": "^8.57.0",
"eslint-config-prettier": "^8.10.0",
"eslint-import-resolver-typescript": "^3.6.3",
@@ -347,14 +347,14 @@
"jest-environment-jsdom": "^29.7.0",
"jest-fetch-mock": "^3.0.3",
"lint-staged": "^13.3.0",
"nodemon": "^3.1.4",
"nodemon": "^3.1.7",
"postinstall-postinstall": "^2.1.0",
"prettier": "^2.8.8",
"react-refresh": "^0.14.0",
"rimraf": "^2.5.4",
"rollup-plugin-webpack-stats": "^0.4.1",
"terser": "^5.32.0",
"typescript": "^5.4.5",
"typescript": "^5.6.3",
"vite-plugin-static-copy": "^0.17.0",
"yarn-deduplicate": "^6.0.2"
},
@@ -362,7 +362,7 @@
"body-scroll-lock": "^4.0.0-beta.0",
"d3": "^7.0.0",
"debug": "4.3.4",
"node-fetch": "^2.6.12",
"node-fetch": "^2.7.0",
"js-yaml": "^3.14.1",
"qs": "6.9.7",
"rollup": "^4.5.1"
+2 -2
View File
@@ -69,9 +69,9 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) {
);
}
if (!organizationResponse) {
if (!organizationResponse?.value?.length) {
throw MicrosoftGraphError(
"Unable to load organization info from Microsoft Graph API"
`Unable to load organization info from Microsoft Graph API: ${organizationResponse.error?.message}`
);
}
+3 -4
View File
@@ -18,10 +18,9 @@ class AzurePluginEnvironment extends Environment {
);
@IsOptional()
@CannotUseWithout("AZURE_CLIENT_ID")
public AZURE_RESOURCE_APP_ID = this.toOptionalString(
environment.AZURE_RESOURCE_APP_ID
);
public AZURE_RESOURCE_APP_ID =
this.toOptionalString(environment.AZURE_RESOURCE_APP_ID) ??
"00000003-0000-0000-c000-000000000000";
@IsOptional()
@CannotUseWithout("AZURE_CLIENT_ID")
+6
View File
@@ -74,6 +74,12 @@ if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {
if (!domain && !team) {
const userExists = await User.count({
where: { email: profile.email.toLowerCase() },
include: [
{
association: "team",
required: true,
},
],
});
// Users cannot create a team with personal gmail accounts
@@ -40,7 +40,7 @@ function SlackListItem({ integration, collection }: Props) {
toast.success(t("Settings saved"));
};
const mapping = {
const mapping: Record<string, string> = {
"documents.publish": t("document published"),
"documents.update": t("document updated"),
};
+5 -2
View File
@@ -79,7 +79,10 @@ router.post(
return;
}
// get content for unfurled links
const unfurls = {};
const unfurls: Record<
string,
{ title: string; text: string; color?: string | undefined }
> = {};
for (const link of event.links) {
const documentId = parseDocumentSlug(link.url);
@@ -109,7 +112,7 @@ router.post(
unfurls[link.url] = {
title: doc.title,
text: doc.getSummary(),
color: doc.collection?.color,
color: doc.collection?.color ?? undefined,
};
}
}
+1 -1
View File
@@ -74,7 +74,7 @@ export class SlackUtils {
redirectUri = SlackUtils.callbackUrl()
): string {
const baseUrl = SlackUtils.authBaseUrl;
const params = {
const params: Record<string, string> = {
client_id: env.SLACK_CLIENT_ID,
scope: scopes ? scopes.join(" ") : "",
redirect_uri: redirectUri,
+2
View File
@@ -90,6 +90,7 @@ router.get(
contentType = attachment.contentType;
}
ctx.set("Accept-Ranges", "bytes");
ctx.set("Cache-Control", cacheHeader);
ctx.set("Content-Type", contentType);
ctx.attachment(fileName, {
@@ -104,6 +105,7 @@ router.get(
const range = getByteRange(ctx, stats.size);
if (range) {
ctx.status = 206;
ctx.set("Content-Length", String(range.end - range.start + 1));
ctx.set(
"Content-Range",
@@ -85,7 +85,10 @@ describe("DeliverWebhookTask", () => {
event,
});
const headers = fetchMock.mock.calls[0]![1]!.headers!;
const headers = fetchMock.mock.calls[0]![1]!.headers! as Record<
string,
string
>;
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(headers["Outline-Signature"]).toMatch(/^t=[0-9]+,s=[a-z0-9]+$/);
@@ -161,6 +161,8 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
case "collections.delete":
case "collections.move":
case "collections.permission_changed":
case "collections.archive":
case "collections.restore":
await this.handleCollectionEvent(subscription, event);
return;
case "collections.add_user":
@@ -690,7 +692,7 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
"user-agent": `Outline-Webhooks${
env.VERSION ? `/${env.VERSION.slice(0, 7)}` : ""
}`,
};
} as Record<string, string>;
const signature = subscription.signature(JSON.stringify(requestBody));
if (signature) {
@@ -1,7 +1,7 @@
import { yDocToProsemirrorJSON } from "@getoutline/y-prosemirror";
import isEqual from "fast-deep-equal";
import uniq from "lodash/uniq";
import { Node } from "prosemirror-model";
import { yDocToProsemirrorJSON } from "y-prosemirror";
import * as Y from "yjs";
import { ProsemirrorData } from "@shared/types";
import { schema, serializer } from "@server/editor";
+4 -1
View File
@@ -90,7 +90,10 @@ async function findAvailableSubdomain(team: Team, requestedSubdomain: string) {
let append = 0;
for (;;) {
const existing = await Team.findOne({ where: { subdomain } });
const existing = await Team.findOne({
where: { subdomain },
paranoid: false,
});
if (existing) {
// subdomain was invalid or already used, try another
@@ -1,20 +1,31 @@
import differenceBy from "lodash/differenceBy";
import * as React from "react";
import { Document } from "@server/models";
import { Day } from "@shared/utils/time";
import { Document, Revision } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
import HTMLHelper from "@server/models/helpers/HTMLHelper";
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
import { TextHelper } from "@server/models/helpers/TextHelper";
import BaseEmail, { EmailProps } from "./BaseEmail";
import Body from "./components/Body";
import Button from "./components/Button";
import Diff from "./components/Diff";
import EmailTemplate from "./components/EmailLayout";
import EmptySpace from "./components/EmptySpace";
import Header from "./components/Header";
import Heading from "./components/Heading";
type InputProps = EmailProps & {
documentId: string;
revisionId: string | undefined;
userId: string;
actorName: string;
teamUrl: string;
};
type BeforeSend = {
document: Document;
body: string | undefined;
};
type Props = InputProps & BeforeSend;
@@ -26,13 +37,60 @@ export default class DocumentMentionedEmail extends BaseEmail<
InputProps,
BeforeSend
> {
protected async beforeSend({ documentId }: InputProps) {
protected async beforeSend({ documentId, revisionId, userId }: InputProps) {
const document = await Document.unscoped().findByPk(documentId);
if (!document) {
return false;
}
return { document };
let currDoc: Document | Revision = document;
let prevDoc: Revision | undefined;
if (revisionId) {
const revision = await Revision.findByPk(revisionId);
if (!revision) {
return false;
}
currDoc = revision;
prevDoc = (await revision.before()) ?? undefined;
}
const currMentions = DocumentHelper.parseMentions(currDoc, {
type: "user",
modelId: userId,
});
const prevMentions = prevDoc
? DocumentHelper.parseMentions(prevDoc, {
type: "user",
modelId: userId,
})
: [];
const firstNewMention = differenceBy(currMentions, prevMentions, "id")[0];
let body: string | undefined;
if (firstNewMention) {
const node = ProsemirrorHelper.getNodeForMentionEmail(
DocumentHelper.toProsemirror(currDoc),
firstNewMention
);
if (node) {
const content = await TextHelper.attachmentsToSignedUrls(
ProsemirrorHelper.toHTML(node, { centered: false }),
document.teamId,
4 * Day.seconds
);
if (content) {
// inline all css so that it works in as many email providers as possible.
body = await HTMLHelper.inlineCSS(content);
}
}
}
return { document, body };
}
protected subject({ document }: Props) {
@@ -58,7 +116,7 @@ Open Document: ${teamUrl}${document.url}
}
protected render(props: Props) {
const { document, actorName, teamUrl } = props;
const { document, actorName, teamUrl, body } = props;
const documentLink = `${teamUrl}${document.url}?ref=notification-email`;
return (
@@ -74,6 +132,15 @@ Open Document: ${teamUrl}${document.url}
{actorName} mentioned you in the document{" "}
<a href={documentLink}>{document.title}</a>.
</p>
{body && (
<>
<EmptySpace height={20} />
<Diff>
<div dangerouslySetInnerHTML={{ __html: body }} />
</Diff>
<EmptySpace height={20} />
</>
)}
<p>
<Button href={documentLink}>Open Document</Button>
</p>
+1 -1
View File
@@ -8,8 +8,8 @@ type Props = {
export default ({ children, ...rest }: Props) => {
const style = {
border: `1.5px solid ${theme.secondaryBackground}`,
borderRadius: "4px",
background: theme.secondaryBackground,
padding: ".75em 1em",
color: theme.text,
display: "block",
+2 -2
View File
@@ -2,9 +2,9 @@ import { Hook, PluginManager } from "@server/utils/PluginManager";
import { requireDirectory } from "@server/utils/fs";
import BaseEmail from "./BaseEmail";
const emails = {};
const emails: Record<string, typeof BaseEmail> = {};
requireDirectory<{ default: BaseEmail<any> }>(__dirname).forEach(
requireDirectory<{ default: typeof BaseEmail }>(__dirname).forEach(
([module, id]) => {
if (id === "index") {
return;
+2 -2
View File
@@ -127,8 +127,8 @@ async function start(_id: number, disconnect: () => void) {
}
Logger.info("lifecycle", `Starting ${name} service`);
const init = services[name];
await init(app, server, env.SERVICES);
const init = services[name as keyof typeof services];
init(app, server as https.Server, env.SERVICES);
}
server.on("error", (err) => {
+2 -9
View File
@@ -4,7 +4,6 @@ import chalk from "chalk";
import isArray from "lodash/isArray";
import isEmpty from "lodash/isEmpty";
import isObject from "lodash/isObject";
import isString from "lodash/isString";
import winston from "winston";
import env from "@server/env";
import Metrics from "@server/logging/Metrics";
@@ -226,18 +225,12 @@ class Logger {
return "[…]" as any as T;
}
if (isString(input)) {
if (sensitiveFields.some((field) => input.includes(field))) {
return "[Filtered]" as any as T;
}
}
if (isArray(input)) {
return input.map((item) => this.sanitize(item, level + 1)) as any as T;
}
if (isObject(input)) {
const output = { ...input };
const output: Record<string, any> = { ...input };
for (const key of Object.keys(output)) {
if (isObject(output[key])) {
@@ -252,7 +245,7 @@ class Logger {
output[key] = this.sanitize(output[key], level + 1);
}
}
return output;
return output as T;
}
return input;
@@ -0,0 +1,27 @@
"use strict";
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.sequelize.transaction(async (transaction) => {
await queryInterface.addColumn("collections", "archivedAt", {
type: Sequelize.DATE,
allowNull: true,
transaction,
});
await queryInterface.addIndex("collections", ["archivedAt"], {
transaction,
});
});
},
async down(queryInterface) {
await queryInterface.sequelize.transaction(async (transaction) => {
await queryInterface.removeIndex("collections", ["archivedAt"], {
transaction,
});
await queryInterface.removeColumn("collections", "archivedAt", {
transaction,
});
});
},
};
@@ -0,0 +1,18 @@
"use strict";
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn("collections", "archivedById", {
type: Sequelize.UUID,
allowNull: true,
references: {
model: "users",
},
});
},
async down(queryInterface) {
await queryInterface.removeColumn("collections", "archivedById");
},
};
+25
View File
@@ -37,6 +37,31 @@ class Backlink extends IdModel<
@ForeignKey(() => Document)
@Column(DataType.UUID)
reverseDocumentId: string;
/**
* Find all backlinks for a document that the user has access to
*
* @param documentId The document ID to find backlinks for
* @param user The user to check access for
*/
public static async findSourceDocumentIdsForUser(
documentId: string,
user: User
) {
const backlinks = await this.findAll({
attributes: ["reverseDocumentId"],
where: {
documentId,
},
});
const documents = await Document.findByIds(
backlinks.map((backlink) => backlink.reverseDocumentId),
{ userId: user.id }
);
return documents.map((doc) => doc.id);
}
}
export default Backlink;
+62 -1
View File
@@ -38,7 +38,7 @@ describe("getDocumentParents", () => {
});
const result = collection.getDocumentParents(document.id);
expect(result?.length).toBe(1);
expect(result[0]).toBe(parent.id);
expect(result ? result[0] : undefined).toBe(parent.id);
});
test("should return array of parent document ids", async () => {
@@ -175,6 +175,67 @@ describe("#addDocumentToStructure", () => {
expect(collection.documentStructure![0].children.length).toBe(2);
expect(collection.documentStructure![0].children[0].id).toBe(id);
});
test("should add the document along with its nested document(s)", async () => {
const collection = await buildCollection();
const document = await buildDocument({
title: "New doc",
teamId: collection.teamId,
});
// create a nested doc within New doc
const nestedDocument = await buildDocument({
title: "Nested doc",
parentDocumentId: document.id,
teamId: collection.teamId,
});
expect(collection.documentStructure).toBeNull();
await collection.addDocumentToStructure(document);
expect(collection.documentStructure).not.toBeNull();
expect(collection.documentStructure).toHaveLength(1);
expect(collection.documentStructure![0].id).toBe(document.id);
expect(collection.documentStructure![0].children).toHaveLength(1);
expect(collection.documentStructure![0].children[0].id).toBe(
nestedDocument.id
);
});
test("should add the document along with its archived nested document(s)", async () => {
const collection = await buildCollection();
const document = await buildDocument({
title: "New doc",
teamId: collection.teamId,
});
// create a nested doc within New doc
const nestedDocument = await buildDocument({
title: "Nested doc",
parentDocumentId: document.id,
teamId: collection.teamId,
});
nestedDocument.archivedAt = new Date();
await nestedDocument.save();
expect(collection.documentStructure).toBeNull();
await collection.addDocumentToStructure(document, undefined, {
includeArchived: true,
});
expect(collection.documentStructure).not.toBeNull();
expect(collection.documentStructure).toHaveLength(1);
expect(collection.documentStructure![0].id).toBe(document.id);
expect(collection.documentStructure![0].children).toHaveLength(1);
expect(collection.documentStructure![0].children[0].id).toBe(
nestedDocument.id
);
});
describe("options: documentJson", () => {
test("should append supplied json over document's own", async () => {
const collection = await buildCollection();
+57 -5
View File
@@ -10,6 +10,7 @@ import {
NonNullFindOptions,
InferAttributes,
InferCreationAttributes,
EmptyResultError,
} from "sequelize";
import {
Sequelize,
@@ -29,6 +30,8 @@ import {
DataType,
Length as SimpleLength,
BeforeDestroy,
IsDate,
AllowNull,
} from "sequelize-typescript";
import isUUID from "validator/lib/isUUID";
import type { CollectionSort, ProsemirrorData } from "@shared/types";
@@ -54,6 +57,10 @@ import IsHexColor from "./validators/IsHexColor";
import Length from "./validators/Length";
import NotContainsUrl from "./validators/NotContainsUrl";
type AdditionalFindOptions = {
rejectOnEmpty?: boolean | Error;
};
@Scopes(() => ({
withAllMemberships: {
include: [
@@ -99,6 +106,13 @@ import NotContainsUrl from "./validators/NotContainsUrl";
},
],
}),
withArchivedBy: () => ({
include: [
{
association: "archivedBy",
},
],
}),
withMembership: (userId: string) => {
if (!userId) {
return {};
@@ -249,6 +263,11 @@ class Collection extends ParanoidModel<
})
sort: CollectionSort;
/** Whether the collection is archived, and if so when. */
@IsDate
@Column
archivedAt: Date | null;
// getters
/**
@@ -268,6 +287,16 @@ class Collection extends ParanoidModel<
return `/collection/${slugify(this.name)}-${this.urlId}`;
}
/**
* Whether this collection is considered active or not. A collection is active if
* it has not been archived or deleted.
*
* @returns boolean
*/
get isActive(): boolean {
return !this.archivedAt && !this.deletedAt;
}
// hooks
@BeforeValidate
@@ -321,6 +350,14 @@ class Collection extends ParanoidModel<
@Column(DataType.UUID)
importId: string | null;
@BelongsTo(() => User, "archivedById")
archivedBy?: User | null;
@AllowNull
@ForeignKey(() => User)
@Column(DataType.UUID)
archivedById?: string | null;
@HasMany(() => Document, "collectionId")
documents: Document[];
@@ -390,37 +427,51 @@ class Collection extends ParanoidModel<
*/
static async findByPk(
id: Identifier,
options?: NonNullFindOptions<Collection>
options?: NonNullFindOptions<Collection> & AdditionalFindOptions
): Promise<Collection>;
static async findByPk(
id: Identifier,
options?: FindOptions<Collection>
options?: FindOptions<Collection> & AdditionalFindOptions
): Promise<Collection | null>;
static async findByPk(
id: Identifier,
options: FindOptions<Collection> = {}
options: FindOptions<Collection> & AdditionalFindOptions = {}
): Promise<Collection | null> {
if (typeof id !== "string") {
return null;
}
if (isUUID(id)) {
return this.findOne({
const collection = await this.findOne({
where: {
id,
},
...options,
rejectOnEmpty: false,
});
if (!collection && options.rejectOnEmpty) {
throw new EmptyResultError(`Collection doesn't exist with id: ${id}`);
}
return collection;
}
const match = id.match(UrlHelper.SLUG_URL_REGEX);
if (match) {
return this.findOne({
const collection = await this.findOne({
where: {
urlId: match[1],
},
...options,
rejectOnEmpty: false,
});
if (!collection && options.rejectOnEmpty) {
throw new EmptyResultError(`Collection doesn't exist with id: ${id}`);
}
return collection;
}
return null;
@@ -662,6 +713,7 @@ class Collection extends ParanoidModel<
options: FindOptions & {
save?: boolean;
documentJson?: NavigationNode;
includeArchived?: boolean;
} = {}
) {
if (!this.documentStructure) {
+74
View File
@@ -1,4 +1,5 @@
import { EmptyResultError } from "sequelize";
import { CollectionPermission } from "@shared/types";
import slugify from "@shared/utils/slugify";
import { parser } from "@server/editor";
import Document from "@server/models/Document";
@@ -8,7 +9,9 @@ import {
buildCollection,
buildTeam,
buildUser,
buildGuestUser,
} from "@server/test/factories";
import UserMembership from "./UserMembership";
beforeEach(() => {
jest.resetAllMocks();
@@ -208,6 +211,77 @@ describe("#findByPk", () => {
});
});
describe("findByIds", () => {
test("should return documents by ids", async () => {
const document1 = await buildDocument();
const document2 = await buildDocument();
const documents = await Document.findByIds([document1.id, document2.id]);
expect(documents.length).toBe(2);
});
test("should return documents filtered to user access", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const document1 = await buildDocument({ teamId: team.id });
const document2 = await buildDocument({ teamId: team.id });
const document3 = await buildDocument();
const documents = await Document.findByIds(
[document1.id, document2.id, document3.id],
{
userId: user.id,
}
);
expect(documents.length).toBe(2);
});
test("should return documents filtered to private collection access", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const collection = await buildCollection({
teamId: team.id,
permission: null,
});
const document1 = await buildDocument({
teamId: team.id,
collectionId: collection.id,
});
const document2 = await buildDocument({ teamId: team.id });
const document3 = await buildDocument();
const documents = await Document.findByIds(
[document1.id, document2.id, document3.id],
{
userId: user.id,
}
);
expect(documents.length).toBe(1);
});
test("should return documents filtered to guest access", async () => {
const team = await buildTeam();
const user = await buildGuestUser({ teamId: team.id });
const document1 = await buildDocument({ teamId: team.id });
const collection = await buildCollection({ teamId: team.id });
await UserMembership.create({
createdById: user.id,
collectionId: collection.id,
userId: user.id,
permission: CollectionPermission.Read,
});
const document2 = await buildDocument({
teamId: team.id,
collectionId: collection.id,
});
const document3 = await buildDocument();
const documents = await Document.findByIds(
[document1.id, document2.id, document3.id],
{
userId: user.id,
}
);
expect(documents.length).toBe(1);
});
});
describe("tasks", () => {
test("should return tasks keys set to 0 if check items isn't present", async () => {
const document = await buildDocument({
+159 -62
View File
@@ -733,6 +733,54 @@ class Document extends ArchivableModel<
return null;
}
/**
* Find many documents by their id, supports filtering by user memberships when `userId`
* is specified in the options.
*
* @param ids An array of document ids
* @param options FindOptions
* @returns A promise resolving to the list of documents
*/
static async findByIds(
ids: string[],
options: Omit<FindOptions<Document>, "where"> &
Omit<AdditionalFindOptions, "rejectOnEmpty"> = {}
): Promise<Document[]> {
const { userId, ...rest } = options;
const user = userId ? await User.findByPk(userId) : null;
const documents = await this.scope([
"withDrafts",
{
method: ["withCollectionPermissions", userId, rest.paranoid],
},
{
method: ["withViews", userId],
},
{
method: ["withMembership", userId],
},
]).findAll({
where: {
...(user && { teamId: user.teamId }),
id: ids,
},
...rest,
});
if (!userId) {
return documents;
}
return documents.filter(
(doc) =>
(!doc.collection?.isPrivate && !user?.isGuest) ||
(doc.collection?.memberships.length || 0) > 0 ||
doc.memberships.length > 0 ||
doc.groupMemberships.length > 0
);
}
// instance methods
/**
@@ -975,68 +1023,76 @@ class Document extends ArchivableModel<
// Moves a document from being visible to the team within a collection
// to the archived area, where it can be subsequently restored.
archive = async (user: User) => {
await this.sequelize.transaction(async (transaction: Transaction) => {
const collection = this.collectionId
? await Collection.findByPk(this.collectionId, {
transaction,
lock: transaction.LOCK.UPDATE,
})
: undefined;
archive = async (user: User, options?: FindOptions) => {
const { transaction } = { ...options };
const collection = this.collectionId
? await Collection.findByPk(this.collectionId, {
transaction,
lock: transaction?.LOCK.UPDATE,
})
: undefined;
if (collection) {
await collection.removeDocumentInStructure(this, { transaction });
if (this.collection) {
this.collection.documentStructure = collection.documentStructure;
}
if (collection) {
await collection.removeDocumentInStructure(this, { transaction });
if (this.collection) {
this.collection.documentStructure = collection.documentStructure;
}
});
}
await this.archiveWithChildren(user);
await this.archiveWithChildren(user, { transaction });
return this;
};
// Restore an archived document back to being visible to the team
unarchive = async (user: User) => {
await this.sequelize.transaction(async (transaction: Transaction) => {
const collection = this.collectionId
? await Collection.findByPk(this.collectionId, {
transaction,
lock: transaction.LOCK.UPDATE,
})
: undefined;
// check to see if the documents parent hasn't been archived also
// If it has then restore the document to the collection root.
if (this.parentDocumentId) {
const parent = await (this.constructor as typeof Document).findOne({
where: {
id: this.parentDocumentId,
},
});
if (parent?.isDraft || !parent?.isActive) {
this.parentDocumentId = null;
}
}
if (!this.template && this.publishedAt && collection) {
await collection.addDocumentToStructure(this, undefined, {
restoreTo = async (
collectionId: string,
options: FindOptions & { user: User }
) => {
const { transaction } = { ...options };
const collection = collectionId
? await Collection.findByPk(collectionId, {
transaction,
});
if (this.collection) {
this.collection.documentStructure = collection.documentStructure;
}
}
});
lock: transaction?.LOCK.UPDATE,
})
: undefined;
if (this.deletedAt) {
await this.restore();
// check to see if the documents parent hasn't been archived also
// If it has then restore the document to the collection root.
if (this.parentDocumentId) {
const parent = await (this.constructor as typeof Document).findOne({
where: {
id: this.parentDocumentId,
},
transaction,
});
if (parent?.isDraft || !parent?.isActive) {
this.parentDocumentId = null;
}
}
this.archivedAt = null;
this.lastModifiedById = user.id;
this.updatedBy = user;
await this.save();
if (!this.template && this.publishedAt && collection?.isActive) {
await collection.addDocumentToStructure(this, undefined, {
includeArchived: true,
transaction,
});
}
if (this.deletedAt) {
await this.restore({ transaction });
this.collectionId = collectionId;
await this.save({ transaction });
}
if (this.archivedAt) {
await this.restoreWithChildren(collectionId, options.user, {
transaction,
});
}
if (this.collection && collection) {
// updating the document structure in memory just in case it's later accessed somewhere
this.collection.documentStructure = collection.documentStructure;
}
return this;
};
@@ -1088,7 +1144,7 @@ class Document extends ArchivableModel<
* @returns Promise resolving to a NavigationNode
*/
toNavigationNode = async (
options?: FindOptions<Document>
options?: FindOptions<Document> & { includeArchived?: boolean }
): Promise<NavigationNode> => {
// Checking if the record is new is a performance optimization – new docs cannot have children
const childDocuments = this.isNewRecord
@@ -1097,16 +1153,24 @@ class Document extends ArchivableModel<
.unscoped()
.scope("withoutState")
.findAll({
where: {
teamId: this.teamId,
parentDocumentId: this.id,
archivedAt: {
[Op.is]: null,
},
publishedAt: {
[Op.ne]: null,
},
},
where: options?.includeArchived
? {
teamId: this.teamId,
parentDocumentId: this.id,
publishedAt: {
[Op.ne]: null,
},
}
: {
teamId: this.teamId,
parentDocumentId: this.id,
publishedAt: {
[Op.ne]: null,
},
archivedAt: {
[Op.is]: null,
},
},
transaction: options?.transaction,
});
@@ -1124,6 +1188,38 @@ class Document extends ArchivableModel<
};
};
private restoreWithChildren = async (
collectionId: string,
user: User,
options?: FindOptions<Document>
) => {
const restoreChildren = async (parentDocumentId: string) => {
const childDocuments = await (
this.constructor as typeof Document
).findAll({
where: {
parentDocumentId,
},
...options,
});
for (const child of childDocuments) {
await restoreChildren(child.id);
child.archivedAt = null;
child.lastModifiedById = user.id;
child.updatedBy = user;
child.collectionId = collectionId;
await child.save(options);
}
};
await restoreChildren(this.id);
this.archivedAt = null;
this.lastModifiedById = user.id;
this.updatedBy = user;
this.collectionId = collectionId;
return this.save(options);
};
private archiveWithChildren = async (
user: User,
options?: FindOptions<Document>
@@ -1138,6 +1234,7 @@ class Document extends ArchivableModel<
where: {
parentDocumentId,
},
...options,
});
for (const child of childDocuments) {
await archiveChildren(child.id);
+3 -2
View File
@@ -45,6 +45,7 @@ import {
} from "@shared/types";
import { UserRoleHelper } from "@shared/utils/UserRoleHelper";
import { stringToColor } from "@shared/utils/color";
import { locales } from "@shared/utils/date";
import env from "@server/env";
import DeleteAttachmentTask from "@server/queues/tasks/DeleteAttachmentTask";
import parseAttachmentIds from "@server/utils/parseAttachmentIds";
@@ -179,8 +180,8 @@ class User extends ParanoidModel<
@Default(env.DEFAULT_LANGUAGE)
@IsIn([languages])
@Column
language: string;
@Column(DataType.STRING)
language: keyof typeof locales | null;
@AllowNull
@IsUrlOrRelativePath
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff. Show more