mirror of
https://github.com/outline/outline.git
synced 2026-12-05 10:45:07 +03:00
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
This commit is contained in:
1 parent
0cdb0a0336
commit
2845d76085
14 files changed
+377
-38
No files matched your search
@@ -9,6 +9,7 @@ import Button from "~/components/Button";
|
||||
import Switch from "~/components/Switch";
|
||||
import Text from "~/components/Text";
|
||||
import useCollectionTrees from "~/hooks/useCollectionTrees";
|
||||
import useCurrentTeam from "~/hooks/useCurrentTeam";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { FlexContainer, Footer } from "./Components";
|
||||
import DocumentExplorer from "./DocumentExplorer";
|
||||
@@ -22,10 +23,12 @@ type Props = {
|
||||
function DocumentCopy({ document, onSubmit }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { policies } = useStores();
|
||||
const team = useCurrentTeam();
|
||||
const collectionTrees = useCollectionTrees();
|
||||
const [publish, setPublish] = React.useState<boolean>(!!document.publishedAt);
|
||||
const [copying, setCopying] = React.useState<boolean>(false);
|
||||
const [recursive, setRecursive] = React.useState<boolean>(true);
|
||||
const [comments, setComments] = React.useState<boolean>(false);
|
||||
const [selectedPath, selectPath] = React.useState<NavigationNode | null>(
|
||||
null
|
||||
);
|
||||
@@ -51,6 +54,7 @@ function DocumentCopy({ document, onSubmit }: Props) {
|
||||
const result = await document.duplicate({
|
||||
publish,
|
||||
recursive,
|
||||
comments: team.commentingEnabled && comments,
|
||||
title: document.title,
|
||||
collectionId: path.collectionId,
|
||||
...(path.type === "document" ? { parentDocumentId: path.id } : {}),
|
||||
@@ -96,6 +100,17 @@ function DocumentCopy({ document, onSubmit }: Props) {
|
||||
/>
|
||||
</Text>
|
||||
)}
|
||||
{team.commentingEnabled && (
|
||||
<Text size="small">
|
||||
<Switch
|
||||
name="comments"
|
||||
label={t("Include comments")}
|
||||
labelPosition="right"
|
||||
checked={comments}
|
||||
onChange={setComments}
|
||||
/>
|
||||
</Text>
|
||||
)}
|
||||
</OptionsContainer>
|
||||
<Footer justify="space-between" align="center" gap={8}>
|
||||
<Text ellipsis type="secondary">
|
||||
|
||||
@@ -91,6 +91,8 @@ export default class Document extends ArchivableModel implements Searchable {
|
||||
createdByName?: string;
|
||||
/** The name of the file this document was imported from. */
|
||||
fileName?: string;
|
||||
/** The id of the document this document was duplicated from. */
|
||||
originalDocumentId?: string;
|
||||
};
|
||||
|
||||
@computed
|
||||
@@ -686,6 +688,7 @@ export default class Document extends ArchivableModel implements Searchable {
|
||||
title?: string;
|
||||
publish?: boolean;
|
||||
recursive?: boolean;
|
||||
comments?: boolean;
|
||||
collectionId?: string | null;
|
||||
parentDocumentId?: string;
|
||||
}) => this.store.duplicate(this, options);
|
||||
|
||||
@@ -237,7 +237,11 @@ function DataLoader({ match, children }: Props) {
|
||||
// Prevents unauthorized request to load share information for the document
|
||||
// when viewing a public share link
|
||||
if (can.read && !document.isDeleted && !revisionId) {
|
||||
if (team.commentingEnabled && !isJustCreated) {
|
||||
// A duplicate can be created with copies of the original's comments.
|
||||
if (
|
||||
team.commentingEnabled &&
|
||||
(!isJustCreated || document.sourceMetadata?.originalDocumentId)
|
||||
) {
|
||||
void comments.fetchAll({
|
||||
documentId: document.id,
|
||||
limit: 100,
|
||||
|
||||
@@ -611,6 +611,7 @@ export default class DocumentsStore extends Store<Document> {
|
||||
title?: string;
|
||||
publish?: boolean;
|
||||
recursive?: boolean;
|
||||
comments?: boolean;
|
||||
}
|
||||
): Promise<Document[]> => {
|
||||
const res = await client.post("/documents.duplicate", {
|
||||
|
||||
@@ -2,10 +2,11 @@ import { randomUUID } from "node:crypto";
|
||||
import { MentionType } from "@shared/types";
|
||||
import { createContext } from "@server/context";
|
||||
import env from "@server/env";
|
||||
import { Document } from "@server/models";
|
||||
import { Comment, Document, Event } from "@server/models";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import {
|
||||
buildCollection,
|
||||
buildComment,
|
||||
buildDocument,
|
||||
buildDraftDocument,
|
||||
buildUser,
|
||||
@@ -439,6 +440,141 @@ describe("documentDuplicator", () => {
|
||||
expect(response[0].text).not.toContain(original.urlId);
|
||||
});
|
||||
|
||||
describe("comments", () => {
|
||||
const setup = async () => {
|
||||
const user = await buildUser();
|
||||
const original = await buildDocument({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
});
|
||||
const thread = await buildComment({
|
||||
userId: user.id,
|
||||
documentId: original.id,
|
||||
});
|
||||
const reply = await buildComment({
|
||||
userId: user.id,
|
||||
documentId: original.id,
|
||||
parentCommentId: thread.id,
|
||||
});
|
||||
const commentMark = (id: string) => ({
|
||||
type: "comment",
|
||||
attrs: { id, userId: user.id },
|
||||
});
|
||||
await original.update({
|
||||
content: {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "hello",
|
||||
marks: [commentMark(thread.id), commentMark(randomUUID())],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
return { user, original, thread, reply };
|
||||
};
|
||||
|
||||
const marksOf = (document: Document) =>
|
||||
document.content?.content?.[0].content?.[0].marks ?? [];
|
||||
|
||||
it("should not copy comments or comment marks by default", async () => {
|
||||
const { user, original } = await setup();
|
||||
|
||||
const [duplicated] = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection: original.collection,
|
||||
})
|
||||
);
|
||||
|
||||
expect(marksOf(duplicated)).toHaveLength(0);
|
||||
expect(
|
||||
await Comment.count({ where: { documentId: duplicated.id } })
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
it("should copy comments and remap comment marks with comments=true", async () => {
|
||||
const { user, original, thread, reply } = await setup();
|
||||
|
||||
const [duplicated] = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection: original.collection,
|
||||
comments: true,
|
||||
})
|
||||
);
|
||||
|
||||
const copies = await Comment.unscoped().findAll({
|
||||
where: { documentId: duplicated.id },
|
||||
order: [["createdAt", "ASC"]],
|
||||
});
|
||||
expect(copies).toHaveLength(2);
|
||||
const [threadCopy, replyCopy] = copies;
|
||||
expect(threadCopy.id).not.toEqual(thread.id);
|
||||
expect(threadCopy.createdById).toEqual(user.id);
|
||||
expect(threadCopy.data).toEqual(thread.data);
|
||||
expect(threadCopy.createdAt).toEqual(thread.createdAt);
|
||||
expect(threadCopy.updatedAt).toEqual(thread.updatedAt);
|
||||
expect(replyCopy.parentCommentId).toEqual(threadCopy.id);
|
||||
expect(replyCopy.data).toEqual(reply.data);
|
||||
|
||||
// The mark of the copied thread is remapped, the orphaned mark is dropped.
|
||||
expect(marksOf(duplicated)).toEqual([
|
||||
{
|
||||
type: "comment",
|
||||
attrs: expect.objectContaining({ id: threadCopy.id }),
|
||||
},
|
||||
]);
|
||||
expect(await Comment.count({ where: { documentId: original.id } })).toBe(
|
||||
2
|
||||
);
|
||||
|
||||
const event = await Event.findOne({
|
||||
where: { name: "comments.create", modelId: threadCopy.id },
|
||||
});
|
||||
expect(event?.data).toEqual({ source: "duplicate" });
|
||||
});
|
||||
|
||||
it("should copy a reply created before its thread with comments=true", async () => {
|
||||
const user = await buildUser();
|
||||
const original = await buildDocument({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
});
|
||||
const thread = await buildComment({
|
||||
userId: user.id,
|
||||
documentId: original.id,
|
||||
});
|
||||
await buildComment({
|
||||
userId: user.id,
|
||||
documentId: original.id,
|
||||
parentCommentId: thread.id,
|
||||
createdAt: new Date(thread.createdAt.getTime() - 1000),
|
||||
});
|
||||
|
||||
const [duplicated] = await withContext(user, (ctx) =>
|
||||
documentDuplicator(ctx, {
|
||||
document: original,
|
||||
collection: original.collection,
|
||||
comments: true,
|
||||
})
|
||||
);
|
||||
|
||||
const copies = await Comment.unscoped().findAll({
|
||||
where: { documentId: duplicated.id },
|
||||
});
|
||||
const threadCopy = copies.find((comment) => !comment.parentCommentId);
|
||||
const replyCopy = copies.find((comment) => comment.parentCommentId);
|
||||
expect(replyCopy?.parentCommentId).toEqual(threadCopy?.id);
|
||||
});
|
||||
});
|
||||
|
||||
it("should copy fullWidth property when duplicating document", async () => {
|
||||
const user = await buildUser();
|
||||
const original = await buildDocument({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { Op } from "sequelize";
|
||||
import { Collection, Document } from "@server/models";
|
||||
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";
|
||||
@@ -21,6 +21,8 @@ type Props = {
|
||||
publish?: boolean;
|
||||
/** Whether to duplicate child documents */
|
||||
recursive?: boolean;
|
||||
/** Whether to duplicate comments */
|
||||
comments?: boolean;
|
||||
};
|
||||
|
||||
type ManyProps = {
|
||||
@@ -68,13 +70,22 @@ type DuplicateItem = {
|
||||
*/
|
||||
export default async function documentDuplicator(
|
||||
ctx: Context,
|
||||
{ document, collection, parentDocumentId, title, publish, recursive }: Props
|
||||
{
|
||||
document,
|
||||
collection,
|
||||
parentDocumentId,
|
||||
title,
|
||||
publish,
|
||||
recursive,
|
||||
comments,
|
||||
}: Props
|
||||
): Promise<Document[]> {
|
||||
return duplicateRoots(ctx, {
|
||||
roots: [{ document, title, parentDocumentId }],
|
||||
collection,
|
||||
publish,
|
||||
recursive,
|
||||
comments,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -105,11 +116,13 @@ async function duplicateRoots(
|
||||
collection,
|
||||
publish,
|
||||
recursive,
|
||||
comments,
|
||||
}: {
|
||||
roots: Root[];
|
||||
collection?: Collection | null;
|
||||
publish?: boolean;
|
||||
recursive?: boolean;
|
||||
comments?: boolean;
|
||||
}
|
||||
): Promise<Document[]> {
|
||||
const newDocuments: Document[] = [];
|
||||
@@ -218,6 +231,23 @@ async function duplicateRoots(
|
||||
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,
|
||||
@@ -230,9 +260,20 @@ async function duplicateRoots(
|
||||
preferences: original.preferences,
|
||||
title: item.title,
|
||||
content: ProsemirrorHelper.replaceDocumentReferences(
|
||||
ProsemirrorHelper.removeMarks(DocumentHelper.toProsemirror(original), [
|
||||
"comment",
|
||||
]),
|
||||
// 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: {
|
||||
@@ -241,6 +282,32 @@ async function duplicateRoots(
|
||||
},
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { buildGroup, buildUser } from "@server/test/factories";
|
||||
import {
|
||||
buildComment,
|
||||
buildDocument,
|
||||
buildGroup,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import CommentCreatedNotificationsTask from "../tasks/CommentCreatedNotificationsTask";
|
||||
import GroupUserNotificationsTask from "../tasks/GroupUserNotificationsTask";
|
||||
import NotificationsProcessor from "./NotificationsProcessor";
|
||||
|
||||
@@ -49,4 +55,51 @@ describe("NotificationsProcessor", () => {
|
||||
expect(schedule).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("comment created", () => {
|
||||
let schedule: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
schedule = vi.spyOn(
|
||||
CommentCreatedNotificationsTask.prototype,
|
||||
"schedule"
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
schedule.mockRestore();
|
||||
});
|
||||
|
||||
const perform = async (data?: { source: "duplicate" }) => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
});
|
||||
const comment = await buildComment({
|
||||
userId: user.id,
|
||||
documentId: document.id,
|
||||
});
|
||||
|
||||
await new NotificationsProcessor().perform({
|
||||
name: "comments.create",
|
||||
modelId: comment.id,
|
||||
documentId: document.id,
|
||||
teamId: user.teamId,
|
||||
actorId: user.id,
|
||||
ip,
|
||||
data,
|
||||
});
|
||||
};
|
||||
|
||||
it("should schedule notifications for a new comment", async () => {
|
||||
await perform();
|
||||
expect(schedule).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should not schedule notifications for a duplicated comment", async () => {
|
||||
await perform({ source: "duplicate" });
|
||||
expect(schedule).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -159,6 +159,14 @@ export default class NotificationsProcessor extends BaseProcessor {
|
||||
}
|
||||
|
||||
async commentCreated(event: CommentEvent) {
|
||||
// never send notifications for comments copied with a duplicated document
|
||||
if (
|
||||
event.name === "comments.create" &&
|
||||
event.data?.source === "duplicate"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
await new CommentCreatedNotificationsTask().schedule(event);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { yDocToProsemirrorJSON } from "y-prosemirror";
|
||||
import * as Y from "yjs";
|
||||
import {
|
||||
CollectionPermission,
|
||||
CommentingAccess,
|
||||
DocumentPermission,
|
||||
ExportContentType,
|
||||
FileOperationFormat,
|
||||
@@ -9958,6 +9959,23 @@ describe("#documents.duplicate", () => {
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
|
||||
it("should fail with status 403 when copying comments and commenting is disabled", async () => {
|
||||
const team = await buildTeam();
|
||||
team.setPreference(TeamPreference.Commenting, CommentingAccess.None);
|
||||
await team.save();
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
const document = await buildDocument({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const res = await server.post("/api/documents.duplicate", user, {
|
||||
body: { id: document.id, comments: true },
|
||||
});
|
||||
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
|
||||
it("should duplicate a document with fullWidth property", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
|
||||
@@ -1446,8 +1446,15 @@ router.post(
|
||||
transaction(),
|
||||
async (ctx: Context<T.DocumentsDuplicateReq>) => {
|
||||
const { transaction } = ctx;
|
||||
const { id, title, publish, recursive, collectionId, parentDocumentId } =
|
||||
ctx.input.body;
|
||||
const {
|
||||
id,
|
||||
title,
|
||||
publish,
|
||||
recursive,
|
||||
comments,
|
||||
collectionId,
|
||||
parentDocumentId,
|
||||
} = ctx.input.body;
|
||||
const { user } = ctx.auth;
|
||||
|
||||
const document = await Document.findByPk(id, {
|
||||
@@ -1456,6 +1463,10 @@ router.post(
|
||||
});
|
||||
authorize(user, "duplicate", document);
|
||||
|
||||
if (comments) {
|
||||
authorize(user, "listComments", user.team);
|
||||
}
|
||||
|
||||
let collection: Collection | null | undefined;
|
||||
|
||||
if (parentDocumentId) {
|
||||
@@ -1504,6 +1515,7 @@ router.post(
|
||||
title,
|
||||
publish,
|
||||
recursive,
|
||||
comments,
|
||||
parentDocumentId,
|
||||
});
|
||||
|
||||
|
||||
@@ -370,6 +370,8 @@ export const DocumentsDuplicateSchema = BaseSchema.extend({
|
||||
title: z.string().optional(),
|
||||
/** Whether child documents should also be duplicated */
|
||||
recursive: z.boolean().optional(),
|
||||
/** Whether comments should also be duplicated */
|
||||
comments: z.boolean().optional(),
|
||||
/** Whether the new document should be published */
|
||||
publish: z.boolean().optional(),
|
||||
/** Id of the collection to which the document should be copied */
|
||||
|
||||
@@ -460,6 +460,10 @@ export type CommentEvent =
|
||||
modelId: string;
|
||||
documentId: string;
|
||||
actorId: string;
|
||||
data?: {
|
||||
/** Set when the comment was copied from another document. */
|
||||
source?: "duplicate";
|
||||
};
|
||||
})
|
||||
| CommentUpdateEvent
|
||||
| (BaseEvent<Comment> & {
|
||||
|
||||
@@ -360,6 +360,7 @@
|
||||
"Document copied": "Document copied",
|
||||
"Couldn’t copy the document. Try again?": "Couldn’t copy the document. Try again?",
|
||||
"Include nested documents": "Include nested documents",
|
||||
"Include comments": "Include comments",
|
||||
"Copy to <em>{{ location }}</em>": "Copy to <em>{{ location }}</em>",
|
||||
"Copying": "Copying",
|
||||
"Search collections & documents": "Search collections & documents",
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Schema } from "prosemirror-model";
|
||||
import type { Node } from "prosemirror-model";
|
||||
import { HeadingSlugger } from "../editor/lib/headingToSlug";
|
||||
import textBetween from "../editor/lib/textBetween";
|
||||
import type { ProsemirrorData } from "../types";
|
||||
import type { ProsemirrorData, ProsemirrorMark } from "../types";
|
||||
import { hashString } from "./string";
|
||||
import { TextHelper } from "./TextHelper";
|
||||
import env from "../env";
|
||||
@@ -51,6 +51,45 @@ export const attachmentPublicRegex =
|
||||
/public\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/(?<id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi;
|
||||
|
||||
export class ProsemirrorHelper {
|
||||
/**
|
||||
* Maps every mark in the document, including marks stored in node attrs.
|
||||
* Mark lists left empty are omitted, matching the schema default.
|
||||
*
|
||||
* @param doc the prosemirror document or JSON data.
|
||||
* @param fn returns the replacement for a mark, or undefined to remove it.
|
||||
* @returns the document data with marks mapped.
|
||||
*/
|
||||
static mapMarks(
|
||||
doc: Node | ProsemirrorData,
|
||||
fn: (mark: ProsemirrorMark) => ProsemirrorMark | undefined
|
||||
): ProsemirrorData {
|
||||
const json = "toJSON" in doc ? (doc.toJSON() as ProsemirrorData) : doc;
|
||||
const mapAll = (marks: ProsemirrorMark[]) =>
|
||||
marks.flatMap((mark) => fn(mark) ?? []);
|
||||
|
||||
function mapMarksInner(node: ProsemirrorData) {
|
||||
// Node.toJSON shares attrs with the node, so replace them rather than mutate.
|
||||
if (node.marks) {
|
||||
const remaining = mapAll(node.marks);
|
||||
if (remaining.length) {
|
||||
node.marks = remaining;
|
||||
} else {
|
||||
delete node.marks;
|
||||
}
|
||||
}
|
||||
if (node.attrs?.marks) {
|
||||
const remaining = mapAll(node.attrs.marks as ProsemirrorMark[]);
|
||||
node.attrs = {
|
||||
...node.attrs,
|
||||
marks: remaining.length ? remaining : undefined,
|
||||
};
|
||||
}
|
||||
node.content?.forEach(mapMarksInner);
|
||||
return node;
|
||||
}
|
||||
return mapMarksInner(json);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove specific mark types from all nodes in the document. Mark lists left
|
||||
* empty are omitted, matching the schema default.
|
||||
@@ -60,34 +99,10 @@ export class ProsemirrorHelper {
|
||||
* @returns the document data with specified marks removed.
|
||||
*/
|
||||
static removeMarks(doc: Node | ProsemirrorData, marks: string[]) {
|
||||
const json = "toJSON" in doc ? (doc.toJSON() as ProsemirrorData) : doc;
|
||||
const markSet = new Set(marks);
|
||||
|
||||
function removeMarksInner(node: ProsemirrorData) {
|
||||
// Node.toJSON shares attrs with the node, so replace them rather than mutate.
|
||||
if (node.marks) {
|
||||
const remaining = node.marks.filter((mark) => !markSet.has(mark.type));
|
||||
if (remaining.length) {
|
||||
node.marks = remaining;
|
||||
} else {
|
||||
delete node.marks;
|
||||
}
|
||||
}
|
||||
if (node.attrs?.marks) {
|
||||
const remaining = (node.attrs.marks as { type: string }[]).filter(
|
||||
(mark) => !markSet.has(mark.type)
|
||||
);
|
||||
node.attrs = {
|
||||
...node.attrs,
|
||||
marks: remaining.length ? remaining : undefined,
|
||||
};
|
||||
}
|
||||
if (node.content) {
|
||||
node.content.forEach(removeMarksInner);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
return removeMarksInner(json);
|
||||
return ProsemirrorHelper.mapMarks(doc, (mark) =>
|
||||
markSet.has(mark.type) ? undefined : mark
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user