This commit is contained in:
hmacr committed 2024-06-27 04:10:02 +05:30
1 parent 943ec40ab0
commit 43c99f4033
13 files changed
+313 -180

No files matched your search

+2 -2
View File
@@ -37,10 +37,10 @@ import DocumentMove from "~/scenes/DocumentMove";
import DocumentPermanentDelete from "~/scenes/DocumentPermanentDelete";
import DocumentPublish from "~/scenes/DocumentPublish";
import DeleteDocumentsInTrash from "~/scenes/Trash/components/DeleteDocumentsInTrash";
import DocumentTemplatizeDialog from "~/components/DocumentTemplatizeDialog";
import DuplicateDialog from "~/components/DuplicateDialog";
import SharePopover from "~/components/Sharing/Document";
import { getHeaderExpandedKey } from "~/components/Sidebar/components/Header";
import DocumentTemplatizeDialog from "~/components/TemplatizeDialog";
import { createAction } from "~/actions";
import { DocumentSection, TrashSection } from "~/actions/sections";
import env from "~/env";
@@ -758,7 +758,7 @@ export const moveTemplateToWorkspace = createAction({
}
await document.move({
template: true,
collectionId: null,
});
}
},
+22
View File
@@ -0,0 +1,22 @@
import React from "react";
import styled from "styled-components";
import Flex from "~/components/Flex";
const Label = ({ icon, value }: { icon: React.ReactNode; value: string }) => (
<Flex align="center" gap={4}>
<IconWrapper>{icon}</IconWrapper>
{value}
</Flex>
);
const IconWrapper = styled.span`
display: flex;
justify-content: center;
align-items: center;
height: 24px;
width: 24px;
overflow: hidden;
flex-shrink: 0;
`;
export default Label;
@@ -0,0 +1,124 @@
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import styled from "styled-components";
import { AvatarSize } from "~/components/Avatar/Avatar";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import InputSelect, { Option } from "~/components/InputSelect";
import TeamLogo from "~/components/TeamLogo";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import Label from "./Label";
type Props = {
id: string;
defaultCollectionId?: string | null;
onSelect: (collectionId: string | null) => void;
};
const SelectLocation = ({ id, defaultCollectionId, onSelect }: Props) => {
const { t } = useTranslation();
const team = useCurrentTeam();
const { collections, policies } = useStores();
const can = usePolicy(team);
const [fetching, setFetching] = useState(false);
const [fetchError, setFetchError] = useState();
const workspaceOption: Option | null = can.createDocument
? {
label: (
<Label
icon={<TeamLogo model={team} size={AvatarSize.Toast} />}
value={t("Workspace")}
/>
),
value: "workspace",
}
: null;
const collectionOptions = React.useMemo(
() =>
collections.orderedData.reduce<Option[]>((options, collection) => {
const can = policies.abilities(collection.id);
if (can.createDocument) {
options.push({
label: (
<Label
icon={<CollectionIcon collection={collection} />}
value={collection.name}
/>
),
value: collection.id,
});
}
return options;
}, []),
[collections.orderedData, policies]
);
const options = workspaceOption
? collectionOptions.length
? [
workspaceOption,
...collectionOptions.map((opt, idx) => {
if (idx !== 0) {
return opt;
}
opt.divider = true;
return opt;
}),
]
: [workspaceOption]
: collectionOptions;
const handleSelection = React.useCallback(
(value: string | null) => {
onSelect(value === "workspace" ? null : value);
},
[onSelect]
);
React.useEffect(() => {
async function fetchData() {
if (!collections.isLoaded && !fetching && !fetchError) {
try {
setFetching(true);
await collections.fetchPage({
limit: 100,
});
} catch (error) {
toast.error(
t("Collections could not be loaded, please reload the app")
);
setFetchError(error);
} finally {
setFetching(false);
}
}
}
void fetchData();
}, [fetchError, t, fetching, collections]);
if (fetching || !options.length) {
return null;
}
return (
<StyledSelect
id={id}
value={defaultCollectionId ?? "workspace"}
options={options}
onChange={handleSelection}
ariaLabel={t("Location")}
/>
);
};
const StyledSelect = styled(InputSelect)`
width: 220px;
`;
export default SelectLocation;
@@ -4,12 +4,14 @@ import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import { useHistory } from "react-router-dom";
import { toast } from "sonner";
import styled from "styled-components";
import ConfirmationDialog from "~/components/ConfirmationDialog";
import Flex from "~/components/Flex";
import Switch from "~/components/Switch";
import Text from "~/components/Text";
import useStores from "~/hooks/useStores";
import { documentPath } from "~/utils/routeHelpers";
import Flex from "./Flex";
import Switch from "./Switch";
import Text from "./Text";
import SelectLocation from "./SelectLocation";
type Props = {
documentId: string;
@@ -23,7 +25,9 @@ function DocumentTemplatizeDialog({ documentId }: Props) {
invariant(document, "Document must exist");
const [publish, setPublish] = React.useState(true);
const [workspace, setWorkspace] = React.useState(false);
const [collectionId, setCollectionId] = React.useState(
document.collectionId ?? null
);
const handlePublishChange = React.useCallback(
(ev: React.ChangeEvent<HTMLInputElement>) => {
@@ -32,20 +36,16 @@ function DocumentTemplatizeDialog({ documentId }: Props) {
[]
);
const handleWorkspaceChange = React.useCallback(
(ev: React.ChangeEvent<HTMLInputElement>) => {
setWorkspace(ev.target.checked);
},
[]
);
const handleSubmit = React.useCallback(async () => {
const template = await document?.templatize({ publish, workspace });
const template = await document?.templatize({
collectionId,
publish,
});
if (template) {
history.push(documentPath(template));
toast.success(t("Template created, go ahead and customize it"));
}
}, [document, history, t, publish, workspace]);
}, [t, document, history, collectionId, publish]);
return (
<ConfirmationDialog
@@ -76,20 +76,23 @@ function DocumentTemplatizeDialog({ documentId }: Props) {
onChange={handlePublishChange}
/>
</Text>
<Text>
<Switch
name="workspace"
label={t("Workspace")}
note={t(
"Save the template within the workspace to enable sharing across collections."
)}
checked={workspace}
onChange={handleWorkspaceChange}
<Flex justify="space-between">
<Location>
<label htmlFor={"templateLocation"}>{t("Location")}</label>
</Location>
<SelectLocation
id={"templateLocation"}
defaultCollectionId={collectionId}
onSelect={setCollectionId}
/>
</Text>
</Flex>
</Flex>
</ConfirmationDialog>
);
}
const Location = styled(Text)`
margin-top: 3px;
`;
export default observer(DocumentTemplatizeDialog);
+17 -8
View File
@@ -28,12 +28,14 @@ function NewTemplateMenu() {
});
}, [collections]);
const workspaceItem: MenuItem = {
type: "route",
to: newTemplatePath(),
title: t("Save in workspace"),
icon: <TeamLogo model={team} />,
};
const workspaceItem: MenuItem | null = can.createDocument
? {
type: "route",
to: newTemplatePath(),
title: t("Save in workspace"),
icon: <TeamLogo model={team} />,
}
: null;
const collectionItems = React.useMemo(
() =>
@@ -58,7 +60,6 @@ function NewTemplateMenu() {
() =>
collectionItems.length
? [
{ type: "separator" },
{ type: "heading", title: t("Choose a collection") },
...collectionItems,
]
@@ -66,7 +67,15 @@ function NewTemplateMenu() {
[t, collectionItems]
);
const items = [workspaceItem, ...collectionItemsWithHeader];
const items = workspaceItem
? collectionItemsWithHeader.length
? [
workspaceItem,
{ type: "separator" } as MenuItem,
...collectionItemsWithHeader,
]
: [workspaceItem]
: collectionItemsWithHeader;
if (!can.createDocument || items.length === 0) {
return null;
+12 -39
View File
@@ -42,22 +42,15 @@ function TemplatesMenu({ onSelectTemplate, document }: Props) {
const templates = documents.templates.filter((tmpl) => tmpl.publishedAt);
const workspaceTemplates = templates
.filter((tmpl) => tmpl.isWorkspaceTemplate)
.map(templateToMenuItem);
const templatesInCollection = templates
const collectionItems = templates
.filter(
(tmpl) =>
!tmpl.isWorkspaceTemplate && tmpl.collectionId === document.collectionId
)
.map(templateToMenuItem);
const otherTemplates = templates
.filter(
(tmpl) =>
!tmpl.isWorkspaceTemplate && tmpl.collectionId !== document.collectionId
)
const workspaceTemplates = templates
.filter((tmpl) => tmpl.isWorkspaceTemplate)
.map(templateToMenuItem);
const workspaceItems: MenuItem[] = React.useMemo(
@@ -68,35 +61,15 @@ function TemplatesMenu({ onSelectTemplate, document }: Props) {
[t, workspaceTemplates]
);
const collectionItemsWithHeader: MenuItem[] = React.useMemo(
() =>
templatesInCollection.length
? [
{ type: "separator" },
{ type: "heading", title: t("This collection") },
...templatesInCollection,
]
: [],
[t, templatesInCollection]
);
const otherItemsWithHeader: MenuItem[] = React.useMemo(
() =>
otherTemplates.length
? [
{ type: "separator" },
{ type: "heading", title: t("Other collections") },
...otherTemplates,
]
: [],
[t, otherTemplates]
);
const items: MenuItem[] = [
...workspaceItems,
...collectionItemsWithHeader,
...otherItemsWithHeader,
];
const items = collectionItems
? workspaceItems.length
? [
...collectionItems,
{ type: "separator" } as MenuItem,
...workspaceItems,
]
: collectionItems
: workspaceItems;
if (!items.length) {
return null;
+7 -14
View File
@@ -496,12 +496,12 @@ export default class Document extends ParanoidModel {
@action
templatize = ({
collectionId,
publish,
workspace,
}: {
collectionId: string | null;
publish: boolean;
workspace: boolean;
}) => this.store.templatize({ id: this.id, publish, workspace });
}) => this.store.templatize({ id: this.id, collectionId, publish });
@action
save = async (
@@ -528,17 +528,10 @@ export default class Document extends ParanoidModel {
}
};
move = (
options:
| {
template: true;
collectionId?: string;
}
| {
collectionId: string;
parentDocumentId?: string;
}
) => this.store.move({ documentId: this.id, ...options });
move = (options: {
collectionId?: string | null;
parentDocumentId?: string;
}) => this.store.move({ documentId: this.id, ...options });
duplicate = (options?: {
title?: string;
+1 -9
View File
@@ -70,15 +70,7 @@ function DocumentMove({ document }: Props) {
if (type === "document") {
await document.move({ collectionId, parentDocumentId });
} else {
const options = document.template
? {
template: true,
collectionId,
}
: {
collectionId,
};
await document.move(options);
await document.move({ collectionId });
}
toast.success(t("Document moved"));
+17 -26
View File
@@ -459,12 +459,12 @@ export default class DocumentsStore extends Store<Document> {
@action
templatize = async ({
id,
collectionId,
publish,
workspace,
}: {
id: string;
collectionId: string | null;
publish: boolean;
workspace: boolean;
}): Promise<Document | null | undefined> => {
const doc: Document | null | undefined = this.data.get(id);
invariant(doc, "Document should exist");
@@ -475,8 +475,8 @@ export default class DocumentsStore extends Store<Document> {
const res = await client.post("/documents.templatize", {
id,
collectionId,
publish,
workspace,
});
invariant(res?.data, "Document not available");
this.addPolicies(res.policies);
@@ -556,34 +556,25 @@ export default class DocumentsStore extends Store<Document> {
};
@action
move = async (
options:
| {
template: true;
documentId: string;
collectionId?: string;
}
| {
documentId: string;
collectionId: string;
parentDocumentId?: string | null;
index?: number | null;
}
) => {
this.movingDocumentId = options.documentId;
const template = "template" in options ? options.template : undefined;
const parentDocumentId =
"parentDocumentId" in options ? options.parentDocumentId : undefined;
const index = "index" in options ? options.index : undefined;
move = async ({
documentId,
collectionId,
parentDocumentId,
index,
}: {
documentId: string;
collectionId?: string | null;
parentDocumentId?: string | null;
index?: number | null;
}) => {
this.movingDocumentId = documentId;
try {
const res = await client.post("/documents.move", {
id: options.documentId,
collectionId: options.collectionId,
id: documentId,
collectionId,
parentDocumentId,
index,
template,
});
invariant(res?.data, "Data not available");
res.data.documents.forEach(this.add);
+55 -36
View File
@@ -1941,19 +1941,6 @@ describe("#documents.templatize", () => {
expect(res.status).toBe(400);
expect(body.message).toBe("publish: Required");
});
it("should require workspace", async () => {
const user = await buildUser();
const res = await server.post("/api/documents.templatize", {
body: {
token: user.getJwtToken(),
id: "random-id",
publish: true,
},
});
const body = await res.json();
expect(res.status).toBe(400);
expect(body.message).toBe("workspace: Required");
});
it("should create a published non-workspace template", async () => {
const user = await buildUser();
const collection = await buildCollection({
@@ -1969,14 +1956,14 @@ describe("#documents.templatize", () => {
body: {
token: user.getJwtToken(),
id: document.id,
collectionId: collection.id,
publish: true,
workspace: false,
},
});
const body = await res.json();
expect(res.status).toBe(200);
expect(body.data.publishedAt).toBeTruthy();
expect(body.data.collectionId).toEqual(document.collectionId);
expect(body.data.collectionId).toEqual(collection.id);
});
it("should create a published workspace template", async () => {
const user = await buildUser();
@@ -1994,7 +1981,6 @@ describe("#documents.templatize", () => {
token: user.getJwtToken(),
id: document.id,
publish: true,
workspace: true,
},
});
const body = await res.json();
@@ -2017,14 +2003,14 @@ describe("#documents.templatize", () => {
body: {
token: user.getJwtToken(),
id: document.id,
collectionId: collection.id,
publish: false,
workspace: false,
},
});
const body = await res.json();
expect(res.status).toBe(200);
expect(body.data.publishedAt).toBeNull();
expect(body.data.collectionId).toEqual(document.collectionId);
expect(body.data.collectionId).toEqual(collection.id);
});
it("should create a draft workspace template", async () => {
const user = await buildUser();
@@ -2042,7 +2028,6 @@ describe("#documents.templatize", () => {
token: user.getJwtToken(),
id: document.id,
publish: false,
workspace: true,
},
});
const body = await res.json();
@@ -2050,6 +2035,34 @@ describe("#documents.templatize", () => {
expect(body.data.publishedAt).toBeNull();
expect(body.data.collectionId).toBeNull();
});
it("should create a template in a different collection", async () => {
const user = await buildUser();
const collection = await buildCollection({
createdById: user.id,
teamId: user.teamId,
});
const anotherCollection = await buildCollection({
createdById: user.id,
teamId: user.teamId,
});
const document = await buildDocument({
userId: user.id,
teamId: user.teamId,
collectionId: collection.id,
});
const res = await server.post("/api/documents.templatize", {
body: {
token: user.getJwtToken(),
id: document.id,
collectionId: anotherCollection.id,
publish: true,
},
});
const body = await res.json();
expect(res.status).toBe(200);
expect(body.data.publishedAt).toBeTruthy();
expect(body.data.collectionId).toEqual(anotherCollection.id);
});
});
describe("#documents.archived", () => {
@@ -2406,23 +2419,6 @@ describe("#documents.move", () => {
expect(body.message).toEqual("id: Required");
});
it("should require collectionId for non-template", async () => {
const user = await buildUser();
const document = await buildDocument({
userId: user.id,
teamId: user.teamId,
});
const res = await server.post("/api/documents.move", {
body: {
token: user.getJwtToken(),
id: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toEqual("collectionId is required to move a document");
});
it("should fail for invalid index", async () => {
const user = await buildUser();
const collection = await buildCollection({
@@ -2493,6 +2489,29 @@ describe("#documents.move", () => {
expect(body.policies[0].abilities.move).toEqual(true);
});
it("should move the template without collectionId", async () => {
const user = await buildUser();
const collection = await buildCollection({
teamId: user.teamId,
});
const document = await buildDocument({
userId: user.id,
teamId: user.teamId,
collectionId: collection.id,
template: true,
});
const res = await server.post("/api/documents.move", {
body: {
token: user.getJwtToken(),
id: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.documents[0].collectionId).toBeNull();
expect(body.policies[0].abilities.move).toEqual(true);
});
it("should not allow moving the document to a collection the user cannot access", async () => {
const user = await buildUser();
const document = await buildDocument({
+19 -3
View File
@@ -932,7 +932,7 @@ router.post(
validate(T.DocumentsTemplatizeSchema),
transaction(),
async (ctx: APIContext<T.DocumentsTemplatizeReq>) => {
const { id, publish, workspace } = ctx.input.body;
const { id, collectionId, publish } = ctx.input.body;
const { user } = ctx.state.auth;
const { transaction } = ctx.state;
@@ -943,10 +943,19 @@ router.post(
authorize(user, "update", original);
if (collectionId) {
const collection = await Collection.scope({
method: ["withMembership", user.id],
}).findByPk(collectionId, { transaction });
authorize(user, "createDocument", collection);
} else {
authorize(user, "createDocument", user.team);
}
const document = await Document.create(
{
editorVersion: original.editorVersion,
collectionId: workspace ? null : original.collectionId,
collectionId,
teamId: original.teamId,
publishedAt: publish ? new Date() : null,
lastModifiedById: user.id,
@@ -1150,12 +1159,19 @@ router.post(
});
authorize(user, "move", document);
invariant(
collectionId || document.template,
"collectionId is required to move a document"
);
if (collectionId) {
const collection = await Collection.scope({
method: ["withMembership", user.id],
}).findByPk(collectionId, { transaction });
authorize(user, "updateDocument", collection);
} else if (document.isWorkspaceTemplate) {
}
if (document.isWorkspaceTemplate) {
authorize(user, "updateDocument", user.team);
}
+6 -13
View File
@@ -211,10 +211,10 @@ export type DocumentsDuplicateReq = z.infer<typeof DocumentsDuplicateSchema>;
export const DocumentsTemplatizeSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Id of the collection inside which the template should be created */
collectionId: z.string().nullish(),
/** Whether the new template should be published */
publish: z.boolean(),
/** Whether the new template should be created at the workspace level */
workspace: z.boolean(),
}),
});
@@ -278,24 +278,17 @@ export type DocumentsUpdateReq = z.infer<typeof DocumentsUpdateSchema>;
export const DocumentsMoveSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Id of collection to which the doc is supposed to be moved */
collectionId: z.string().uuid().optional(),
collectionId: z.string().uuid().nullish(),
/** Parent Id, in case if the doc is moved to a new parent */
parentDocumentId: z.string().uuid().nullish(),
/** Helps evaluate the new index in collection structure upon move */
index: z.number().gte(0).optional(),
/** Whether this should be considered a template */
template: z.boolean().optional(),
}),
})
.refine((req) => !(req.body.parentDocumentId === req.body.id), {
message: "infinite loop detected, cannot nest a document inside itself",
})
.refine((req) => req.body.collectionId || req.body.template, {
message: "collectionId is required to move a document",
});
}).refine((req) => !(req.body.parentDocumentId === req.body.id), {
message: "infinite loop detected, cannot nest a document inside itself",
});
export type DocumentsMoveReq = z.infer<typeof DocumentsMoveSchema>;
+5 -7
View File
@@ -200,16 +200,12 @@
"{{ completed }} task done": "{{ completed }} task done",
"{{ completed }} task done_plural": "{{ completed }} tasks done",
"{{ completed }} of {{ total }} tasks": "{{ completed }} of {{ total }} tasks",
"Template created, go ahead and customize it": "Template created, go ahead and customize it",
"Creating a template from <em>{{titleWithDefault}}</em> is a non-destructive action – we'll make a copy of the document and turn it into a template that can be used as a starting point for new documents.": "Creating a template from <em>{{titleWithDefault}}</em> is a non-destructive action – we'll make a copy of the document and turn it into a template that can be used as a starting point for new documents.",
"Published": "Published",
"Create a published template that's available for use immediately.": "Create a published template that's available for use immediately.",
"Save the template within the workspace to enable sharing across collections.": "Save the template within the workspace to enable sharing across collections.",
"Currently editing": "Currently editing",
"Currently viewing": "Currently viewing",
"Viewed {{ timeAgo }}": "Viewed {{ timeAgo }}",
"Copy of {{ documentName }}": "Copy of {{ documentName }}",
"Title": "Title",
"Published": "Published",
"Include nested documents": "Include nested documents",
"Module failed to load": "Module failed to load",
"Loading Failed": "Loading Failed",
@@ -352,6 +348,10 @@
"No results": "No results",
"Previous page": "Previous page",
"Next page": "Next page",
"Template created, go ahead and customize it": "Template created, go ahead and customize it",
"Creating a template from <em>{{titleWithDefault}}</em> is a non-destructive action – we'll make a copy of the document and turn it into a template that can be used as a starting point for new documents.": "Creating a template from <em>{{titleWithDefault}}</em> is a non-destructive action – we'll make a copy of the document and turn it into a template that can be used as a starting point for new documents.",
"Create a published template that's available for use immediately.": "Create a published template that's available for use immediately.",
"Location": "Location",
"Admins can manage the workspace and access billing.": "Admins can manage the workspace and access billing.",
"Editors can create, edit, and comment on documents.": "Editors can create, edit, and comment on documents.",
"Viewers can only view and comment on documents.": "Viewers can only view and comment on documents.",
@@ -498,8 +498,6 @@
"Contents": "Contents",
"Headings you add to the document will appear here": "Headings you add to the document will appear here",
"Table of contents": "Table of contents",
"This collection": "This collection",
"Other collections": "Other collections",
"Change name": "Change name",
"Suspend user": "Suspend user",
"An error occurred while sending the invite": "An error occurred while sending the invite",