Files
outline/server/commands/documentDuplicator.ts
T
Tom Moor 2845d76085 feat: Option to include comments when duplicating a document (#14880)
* feat: Option to include comments when duplicating a document

* refactor: Share mark walking between removeMarks and comment remapping

* fix: Copy thread roots first and notify nobody about duplicated comments
2026-12-04 21:44:32 -05:00

345 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { randomUUID } from "node:crypto";
import { Op } from "sequelize";
import { Collection, Comment, Document } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
import type { DocumentReference } from "@server/models/helpers/ProsemirrorHelper";
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
import type { Context } from "@server/types";
import { generateUrlId } from "@server/utils/url";
import documentCreator from "./documentCreator";
type Props = {
/** The document to duplicate */
document: Document;
/** The collection to add the duplicated document to */
collection?: Collection | null;
/** Override of the parent document to add the duplicate to */
parentDocumentId?: string;
/** Override of the duplicated document title */
title?: string;
/** Override of the duplicated document publish state */
publish?: boolean;
/** Whether to duplicate child documents */
recursive?: boolean;
/** Whether to duplicate comments */
comments?: boolean;
};
type ManyProps = {
/** The documents to duplicate, in the order they should be created */
documents: Document[];
/** The collection to add the duplicated documents to */
collection?: Collection | null;
/** Override of the duplicated documents publish state */
publish?: boolean;
/** Whether to duplicate child documents */
recursive?: boolean;
};
/** A document to duplicate, and where its duplicate should be placed. */
type Root = {
/** The document to duplicate */
document: Document;
/** Override of the duplicated document title */
title?: string;
/** Override of the parent document to add the duplicate to */
parentDocumentId?: string;
};
/** A document to duplicate, with the identifiers assigned to its duplicate. */
type DuplicateItem = {
/** The document being duplicated */
original: Document;
/** The id assigned to the duplicate */
id: string;
/** The url identifier assigned to the duplicate */
urlId: string;
/** The title of the duplicate */
title: string;
/** The children to duplicate under the duplicate */
children: DuplicateItem[];
};
/**
* Duplicates a document, optionally including its child documents. Links
* between the duplicated documents are remapped to point at the copies.
*
* @param ctx the context containing the acting user and transaction.
* @param props the document to duplicate and optional overrides.
* @returns the duplicated documents.
*/
export default async function documentDuplicator(
ctx: Context,
{
document,
collection,
parentDocumentId,
title,
publish,
recursive,
comments,
}: Props
): Promise<Document[]> {
return duplicateRoots(ctx, {
roots: [{ document, title, parentDocumentId }],
collection,
publish,
recursive,
comments,
});
}
/**
* Duplicates several documents as one unit, so that links between them are
* remapped to the copies no matter which of the documents they cross between.
*
* @param ctx the context containing the acting user and transaction.
* @param props the documents to duplicate and optional overrides.
* @returns the duplicated documents.
*/
export async function documentsDuplicator(
ctx: Context,
{ documents, collection, publish, recursive }: ManyProps
): Promise<Document[]> {
return duplicateRoots(ctx, {
roots: documents.map((document) => ({ document })),
collection,
publish,
recursive,
});
}
async function duplicateRoots(
ctx: Context,
{
roots,
collection,
publish,
recursive,
comments,
}: {
roots: Root[];
collection?: Collection | null;
publish?: boolean;
recursive?: boolean;
comments?: boolean;
}
): Promise<Document[]> {
const newDocuments: Document[] = [];
const references = new Map<string, DocumentReference>();
const originalCollections = new Map<string, Collection | null>();
async function originalCollectionFor(original: Document) {
const collectionId = original.collectionId;
if (!collectionId) {
return null;
}
if (!originalCollections.has(collectionId)) {
originalCollections.set(
collectionId,
await Collection.findByPk(collectionId, {
attributes: {
include: ["documentStructure"],
},
})
);
}
return originalCollections.get(collectionId) ?? null;
}
async function buildItem(
original: Document,
originalCollection: Collection | null,
titleOverride?: string
): Promise<DuplicateItem> {
const id = randomUUID();
const urlId = generateUrlId();
const itemTitle = titleOverride ?? original.title;
const reference = {
id,
path: Document.getPath({ title: itemTitle, urlId }),
};
references.set(original.id, reference);
references.set(original.urlId, reference);
return {
original,
id,
urlId,
title: itemTitle,
children: recursive
? await buildChildItems(original, originalCollection)
: [],
};
}
async function buildChildItems(
original: Document,
originalCollection: Collection | null
) {
// Structural fields only – content is re-fetched per document in
// `duplicateItem`, so a large tree isn't held in memory at once.
const childDocuments = await original.findChildDocuments(
ctx,
{
archivedAt: original.archivedAt
? {
[Op.ne]: null,
}
: {
[Op.eq]: null,
},
// Drafts are private to their author, so only the actor's own are copied.
[Op.or]: [
{ publishedAt: { [Op.ne]: null } },
{ createdById: ctx.auth.user.id },
],
},
{
attributes: { exclude: ["state", "content", "text"] },
}
);
const [tree] =
(await originalCollection?.structureFor(ctx.auth.user, {
documentId: original.id,
transaction: ctx.transaction,
})) ?? [];
const sorted = DocumentHelper.sortDocumentsByStructure(
childDocuments,
tree?.children ?? []
).reverse(); // we have to reverse since the child documents will be added in reverse order
const items: DuplicateItem[] = [];
for (const childDocument of sorted) {
items.push(await buildItem(childDocument, originalCollection));
}
return items;
}
async function duplicateItem(
item: DuplicateItem,
options: { parentDocumentId?: string; publish: boolean }
) {
const original =
item.original.dataValues.content !== undefined
? item.original
: await Document.findByPk(item.original.id, {
transaction: ctx.transaction,
rejectOnEmpty: true,
});
const loadedComments = comments
? await Comment.unscoped().findAll({
where: { documentId: original.id },
order: [["createdAt", "ASC"]],
transaction: ctx.transaction,
})
: [];
// Thread roots first, as a reply can only be created once its parent exists.
const originalComments = [
...loadedComments.filter((comment) => !comment.parentCommentId),
...loadedComments.filter((comment) => comment.parentCommentId),
];
const commentIds = new Map(
originalComments.map((comment) => [comment.id, randomUUID()])
);
const duplicated = await documentCreator(ctx, {
id: item.id,
urlId: item.urlId,
parentDocumentId: options.parentDocumentId,
publish: options.publish,
collectionId: collection?.id,
icon: original.icon,
color: original.color,
fullWidth: original.fullWidth,
preferences: original.preferences,
title: item.title,
content: ProsemirrorHelper.replaceDocumentReferences(
// Comment marks follow their copied comment, the rest are dropped.
ProsemirrorHelper.mapMarks(
DocumentHelper.toProsemirror(original),
(mark) => {
if (mark.type !== "comment") {
return mark;
}
const id =
typeof mark.attrs?.id === "string"
? commentIds.get(mark.attrs.id)
: undefined;
return id ? { ...mark, attrs: { ...mark.attrs, id } } : undefined;
}
),
references
),
sourceMetadata: {
...original.sourceMetadata,
originalDocumentId: original.id,
},
});
for (const comment of originalComments) {
await Comment.createWithCtx(
ctx,
{
id: commentIds.get(comment.id),
documentId: duplicated.id,
parentCommentId: comment.parentCommentId
? commentIds.get(comment.parentCommentId)
: undefined,
data: ProsemirrorHelper.replaceDocumentReferences(
comment.data,
references
),
createdById: comment.createdById,
createdAt: comment.createdAt,
updatedAt: comment.updatedAt,
resolvedAt: comment.resolvedAt,
resolvedById: comment.resolvedById,
},
// The source stops the event from notifying anyone about the copy.
{ data: { source: "duplicate" } },
// Silent keeps the given updatedAt, so copies are not shown as edited.
{ silent: true }
);
}
duplicated.collection = collection ?? null;
newDocuments.push(duplicated);
for (const child of item.children) {
await duplicateItem(child, {
...options,
parentDocumentId: duplicated.id,
});
}
}
// The identifiers of every duplicate are assigned before any content is
// written so that links between the documents being duplicated can be
// remapped to the copies, leaving the duplicate self-contained.
const items: DuplicateItem[] = [];
for (const root of roots) {
items.push(
await buildItem(
root.document,
await originalCollectionFor(root.document),
root.title
)
);
}
for (const [index, item] of items.entries()) {
await duplicateItem(item, {
parentDocumentId: roots[index].parentDocumentId,
publish: publish ?? !!roots[index].document.publishedAt,
});
}
return newDocuments;
}