@open-mercato/documents 0.9.1-develop.7575.1.8480826a9b → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contentSecurityPolicy.js +23 -0
- package/dist/contentSecurityPolicy.js.map +7 -0
- package/dist/modules/documents/api/[id]/comments/access-check/route.js +13 -6
- package/dist/modules/documents/api/[id]/comments/access-check/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/comments/route.js +2 -0
- package/dist/modules/documents/api/[id]/comments/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/content/route.js +2 -0
- package/dist/modules/documents/api/[id]/content/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/route.js +3 -0
- package/dist/modules/documents/api/[id]/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/shares/route.js +2 -0
- package/dist/modules/documents/api/[id]/shares/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/versions/route.js +2 -0
- package/dist/modules/documents/api/[id]/versions/route.js.map +2 -2
- package/dist/modules/documents/api/_shared.js +10 -27
- package/dist/modules/documents/api/_shared.js.map +3 -3
- package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js +3 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js +1 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js +15 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js +15 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js +20 -8
- package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js +3 -0
- package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/editorTypes.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js +46 -0
- package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js.map +7 -0
- package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js +14 -6
- package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js +3 -0
- package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js.map +2 -2
- package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js +3 -0
- package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js.map +2 -2
- package/dist/modules/documents/backend/documents/components/TemplatePreview.js +3 -0
- package/dist/modules/documents/backend/documents/components/TemplatePreview.js.map +2 -2
- package/dist/modules/documents/commands/comments.js +2 -2
- package/dist/modules/documents/commands/comments.js.map +2 -2
- package/dist/modules/documents/commands/folders.js +1 -0
- package/dist/modules/documents/commands/folders.js.map +2 -2
- package/dist/modules/documents/commands/interceptors.js +11 -0
- package/dist/modules/documents/commands/interceptors.js.map +2 -2
- package/dist/modules/documents/data/attachment-access.js +84 -0
- package/dist/modules/documents/data/attachment-access.js.map +7 -0
- package/dist/modules/documents/data/validators.js +11 -0
- package/dist/modules/documents/data/validators.js.map +2 -2
- package/dist/modules/documents/lib/actor.js +32 -0
- package/dist/modules/documents/lib/actor.js.map +7 -0
- package/dist/modules/documents/lib/collabMaterializer.js +52 -9
- package/dist/modules/documents/lib/collabMaterializer.js.map +2 -2
- package/dist/modules/documents/lib/collabPersistence.js +13 -0
- package/dist/modules/documents/lib/collabPersistence.js.map +7 -0
- package/dist/modules/documents/lib/permissions.js +35 -2
- package/dist/modules/documents/lib/permissions.js.map +2 -2
- package/dist/modules/documents/widgets/injection/related-documents/widget.client.js +3 -2
- package/dist/modules/documents/widgets/injection/related-documents/widget.client.js.map +2 -2
- package/dist/modules/documents/widgets/injection-table.js +12 -3
- package/dist/modules/documents/widgets/injection-table.js.map +2 -2
- package/dist/server/documents-collab-server.js +74 -1
- package/dist/server/documents-collab-server.js.map +2 -2
- package/jest.config.cjs +1 -1
- package/package.json +37 -37
- package/server/documents-collab-server.ts +79 -0
- package/src/contentSecurityPolicy.ts +21 -0
- package/src/modules/documents/api/[id]/comments/access-check/route.ts +13 -6
- package/src/modules/documents/api/[id]/comments/route.ts +2 -0
- package/src/modules/documents/api/[id]/content/route.ts +2 -0
- package/src/modules/documents/api/[id]/route.ts +3 -0
- package/src/modules/documents/api/[id]/shares/route.ts +2 -0
- package/src/modules/documents/api/[id]/versions/route.ts +2 -0
- package/src/modules/documents/api/_shared.ts +10 -36
- package/src/modules/documents/backend/documents/[id]/DocumentCanvas.tsx +3 -1
- package/src/modules/documents/backend/documents/[id]/DocumentEditorIsland.tsx +4 -1
- package/src/modules/documents/backend/documents/[id]/DocumentEditorSurface.tsx +19 -1
- package/src/modules/documents/backend/documents/[id]/DocumentPageClient.tsx +14 -0
- package/src/modules/documents/backend/documents/[id]/VersionHistoryPanel.tsx +23 -8
- package/src/modules/documents/backend/documents/[id]/VersionPreviewDialog.tsx +3 -0
- package/src/modules/documents/backend/documents/[id]/editorTypes.ts +1 -0
- package/src/modules/documents/backend/documents/[id]/saveCollaborativeContent.ts +43 -0
- package/src/modules/documents/backend/documents/[id]/useDocumentComments.ts +17 -7
- package/src/modules/documents/backend/documents/[id]/useDocumentEditor.ts +3 -0
- package/src/modules/documents/backend/documents/components/TemplateBodyEditor.tsx +3 -0
- package/src/modules/documents/backend/documents/components/TemplatePreview.tsx +3 -0
- package/src/modules/documents/commands/comments.ts +2 -2
- package/src/modules/documents/commands/folders.ts +1 -3
- package/src/modules/documents/commands/interceptors.ts +11 -0
- package/src/modules/documents/data/attachment-access.ts +83 -0
- package/src/modules/documents/data/validators.ts +12 -0
- package/src/modules/documents/lib/actor.ts +39 -0
- package/src/modules/documents/lib/collabMaterializer.ts +62 -11
- package/src/modules/documents/lib/collabPersistence.ts +10 -0
- package/src/modules/documents/lib/permissions.ts +52 -0
- package/src/modules/documents/widgets/injection/related-documents/widget.client.tsx +3 -2
- package/src/modules/documents/widgets/injection-table.ts +17 -3
|
@@ -134,20 +134,25 @@ function useDocumentComments({ documentId, editor, canComment, canShare }) {
|
|
|
134
134
|
);
|
|
135
135
|
if (!isCurrentSubmission()) return { cancelled: true };
|
|
136
136
|
if (!call.ok) throw new Error(t("documents.comments.error.save"));
|
|
137
|
-
const withoutAccess = readWithoutAccess(call.result);
|
|
137
|
+
const withoutAccess = readWithoutAccess(call.result).filter((user) => userIds.includes(user.userId));
|
|
138
138
|
if (withoutAccess.length === 0) return { cancelled: false };
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
139
|
+
const response = readRecord(call.result);
|
|
140
|
+
const shareableUserIds = new Set(
|
|
141
|
+
Array.isArray(response?.shareableUserIds) ? response.shareableUserIds.filter((value) => typeof value === "string").map((value) => value.toLowerCase()) : []
|
|
142
|
+
);
|
|
143
|
+
const shareableUsers = withoutAccess.filter((user) => shareableUserIds.has(user.userId));
|
|
144
|
+
if (!canShare || shareableUsers.length === 0) {
|
|
145
|
+
return { cancelled: false, grantAccessTo: [], hasUnnotifiedMentions: true };
|
|
142
146
|
}
|
|
143
147
|
const pendingMentionNames = new Map(
|
|
144
148
|
activePendingMentions.map((mention) => [mention.userId.toLowerCase(), mention.name])
|
|
145
149
|
);
|
|
146
|
-
const decision = await requestGrantAccess(
|
|
150
|
+
const decision = await requestGrantAccess(shareableUsers.map((user) => pendingMentionNames.get(user.userId) ?? user.label ?? labelFor(user.userId)));
|
|
147
151
|
if (decision === "cancel" || !isCurrentSubmission()) return { cancelled: true };
|
|
148
152
|
return {
|
|
149
153
|
cancelled: false,
|
|
150
|
-
grantAccessTo: decision === "share" ?
|
|
154
|
+
grantAccessTo: decision === "share" ? shareableUsers.map((user) => user.userId) : [],
|
|
155
|
+
hasUnnotifiedMentions: decision === "skip" || shareableUsers.length < withoutAccess.length
|
|
151
156
|
};
|
|
152
157
|
}, [activePendingMentions, canShare, documentId, labelFor, requestGrantAccess, t]);
|
|
153
158
|
const submit = React.useCallback(async () => {
|
|
@@ -182,6 +187,9 @@ function useDocumentComments({ documentId, editor, canComment, canShare }) {
|
|
|
182
187
|
mutationPayload: { body: trimmedBody, parentCommentId, mentions }
|
|
183
188
|
});
|
|
184
189
|
if (!isCurrentSubmission()) return;
|
|
190
|
+
if (grantResolution.hasUnnotifiedMentions) {
|
|
191
|
+
flash(t("documents.comments.grant.noAccessInfo"), "info");
|
|
192
|
+
}
|
|
185
193
|
resetComposer();
|
|
186
194
|
await reload();
|
|
187
195
|
} catch (error) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/documents/backend/documents/%5Bid%5D/useDocumentComments.ts"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport type { Editor } from '@tiptap/core'\nimport { apiCall, apiCallOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport {\n DOCUMENTS_COMMENT_LIST_PAGE_SIZE,\n DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT,\n} from '../../../lib/historyPolicy'\nimport { readNumber, readRecord } from '../documentUi'\nimport type { CommentAnchor } from './CommentAnchorNavigation'\nimport {\n bodyContainsPendingMention,\n findCommentById,\n readCommentItems,\n readUserLabels,\n readWithoutAccess,\n type DocumentComment,\n type PendingMention,\n type UserLabels,\n} from './commentTypes'\n\ntype CommentsState =\n | { status: 'loading' }\n | { status: 'error'; message: string }\n | { status: 'ready'; comments: DocumentComment[]; userLabels: UserLabels }\n\ntype UseDocumentCommentsInput = {\n documentId: string\n editor: Editor | null\n canComment: boolean\n canShare: boolean\n}\n\ntype GrantAccessDecision = 'share' | 'skip' | 'cancel'\n\ntype GrantAccessResolution =\n | { cancelled: true }\n | { cancelled: false; grantAccessTo?: string[] }\n\nexport function useDocumentComments({ documentId, editor, canComment, canShare }: UseDocumentCommentsInput) {\n const t = useT()\n const [state, setState] = React.useState<CommentsState>({ status: 'loading' })\n const [body, setBody] = React.useState('')\n const [pendingMentions, setPendingMentions] = React.useState<PendingMention[]>([])\n const [parentCommentId, setParentCommentId] = React.useState<string | null>(null)\n const [pendingAnchor, setPendingAnchor] = React.useState<CommentAnchor | null>(null)\n const [isSubmitting, setIsSubmitting] = React.useState(false)\n const [resolvingCommentId, setResolvingCommentId] = React.useState<string | null>(null)\n const [grantAccessNames, setGrantAccessNames] = React.useState<string[] | null>(null)\n const grantResolver = React.useRef<((decision: GrantAccessDecision) => void) | null>(null)\n const submissionContextSequence = React.useRef(0)\n const reloadSequence = React.useRef(0)\n const activeReload = React.useRef<AbortController | null>(null)\n const activeDocumentId = React.useRef<string | null>(null)\n const mutationContextId = `documents-comments:${documentId}`\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n resourceKind: string\n resourceId: string\n retryLastMutation: () => Promise<boolean>\n }>({ contextId: mutationContextId, blockedMessage: t('ui.forms.flash.saveBlocked') })\n const activePendingMentions = React.useMemo(\n () => pendingMentions.filter((mention) => bodyContainsPendingMention(body, mention)),\n [body, pendingMentions],\n )\n\n const reload = React.useCallback(async () => {\n const reloadId = ++reloadSequence.current\n const controller = new AbortController()\n activeReload.current?.abort()\n activeReload.current = controller\n const isCurrent = () => reloadSequence.current === reloadId && !controller.signal.aborted\n const documentChanged = activeDocumentId.current !== documentId\n activeDocumentId.current = documentId\n setState((current) => !documentChanged && current.status === 'ready' ? current : { status: 'loading' })\n try {\n const maxPages = Math.ceil(DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT / DOCUMENTS_COMMENT_LIST_PAGE_SIZE)\n const pathForPage = (page: number) => (\n `/api/documents/${encodeURIComponent(documentId)}/comments?page=${page}&pageSize=${DOCUMENTS_COMMENT_LIST_PAGE_SIZE}`\n )\n const firstCall = await apiCall<unknown>(pathForPage(1), { signal: controller.signal })\n if (!isCurrent()) return\n if (!firstCall.ok) {\n setState({ status: 'error', message: t('documents.comments.error.load') })\n return\n }\n\n const firstRoot = readRecord(firstCall.result)\n const totalPages = Math.min(\n maxPages,\n Math.max(1, firstRoot ? readNumber(firstRoot, 'totalPages', 'total_pages') ?? 1 : 1),\n )\n const remainingCalls = totalPages > 1\n ? await Promise.all(Array.from({ length: totalPages - 1 }, (_, index) => (\n apiCall<unknown>(pathForPage(index + 2), { signal: controller.signal })\n )))\n : []\n if (!isCurrent()) return\n if (remainingCalls.some((call) => !call.ok)) {\n setState({ status: 'error', message: t('documents.comments.error.load') })\n return\n }\n\n const calls = [firstCall, ...remainingCalls]\n const comments = [...calls].reverse().flatMap((call) => readCommentItems(call.result))\n const userLabels = calls.reduce<UserLabels>((labels, call) => ({\n ...labels,\n ...readUserLabels(call.result, t('documents.users.unknown')),\n }), {})\n setState({ status: 'ready', comments, userLabels })\n } catch (error) {\n if (isCurrent()) {\n setState({ status: 'error', message: error instanceof Error ? error.message : t('documents.comments.error.load') })\n }\n } finally {\n if (activeReload.current === controller) activeReload.current = null\n }\n }, [documentId, t])\n\n React.useEffect(() => {\n void reload()\n return () => {\n reloadSequence.current += 1\n activeReload.current?.abort()\n activeReload.current = null\n }\n }, [reload])\n\n const cancelPendingGrantAccess = React.useCallback(() => {\n const resolve = grantResolver.current\n grantResolver.current = null\n resolve?.('cancel')\n }, [])\n\n React.useEffect(() => {\n setGrantAccessNames(null)\n setIsSubmitting(false)\n return () => {\n submissionContextSequence.current += 1\n cancelPendingGrantAccess()\n }\n }, [cancelPendingGrantAccess, documentId])\n\n const labelFor = React.useCallback((userId: string) => {\n const labels = state.status === 'ready' ? state.userLabels : {}\n return labels[userId.toLowerCase()]?.label ?? t('documents.users.unknown')\n }, [state, t])\n\n const resetComposer = React.useCallback(() => {\n setBody('')\n setPendingMentions([])\n setParentCommentId(null)\n setPendingAnchor(null)\n }, [])\n\n const chooseGrantAccess = React.useCallback((share: boolean) => {\n const resolve = grantResolver.current\n grantResolver.current = null\n setGrantAccessNames(null)\n resolve?.(share ? 'share' : 'skip')\n }, [])\n\n const requestGrantAccess = React.useCallback((names: string[]) => new Promise<GrantAccessDecision>((resolve) => {\n cancelPendingGrantAccess()\n grantResolver.current = resolve\n setGrantAccessNames(names)\n }), [cancelPendingGrantAccess])\n\n const resolveGrantAccessTo = React.useCallback(async (\n isCurrentSubmission: () => boolean,\n ): Promise<GrantAccessResolution> => {\n const userIds = Array.from(new Set(activePendingMentions.map((mention) => mention.userId.toLowerCase())))\n if (userIds.length === 0) return { cancelled: false }\n // Intentionally outside useGuardedMutation: access-check is read-shaped\n // (a POST only to carry the user-id list in the body) and mutates nothing.\n const call = await apiCall<unknown>(\n `/api/documents/${encodeURIComponent(documentId)}/comments/access-check`,\n { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ userIds }) },\n )\n if (!isCurrentSubmission()) return { cancelled: true }\n if (!call.ok) throw new Error(t('documents.comments.error.save'))\n const withoutAccess = readWithoutAccess(call.result)\n if (withoutAccess.length === 0) return { cancelled: false }\n if (!canShare) {\n flash(t('documents.comments.grant.noAccessInfo'), 'info')\n return { cancelled: false, grantAccessTo: [] }\n }\n const pendingMentionNames = new Map(\n activePendingMentions.map((mention) => [mention.userId.toLowerCase(), mention.name]),\n )\n const decision = await requestGrantAccess(withoutAccess.map((user) => (\n pendingMentionNames.get(user.userId) ?? user.label ?? labelFor(user.userId)\n )))\n if (decision === 'cancel' || !isCurrentSubmission()) return { cancelled: true }\n return {\n cancelled: false,\n grantAccessTo: decision === 'share' ? withoutAccess.map((user) => user.userId) : [],\n }\n }, [activePendingMentions, canShare, documentId, labelFor, requestGrantAccess, t])\n\n const submit = React.useCallback(async () => {\n const trimmedBody = body.trim()\n if (!trimmedBody || !canComment) return\n const submissionSequence = submissionContextSequence.current\n const isCurrentSubmission = () => submissionContextSequence.current === submissionSequence\n setIsSubmitting(true)\n try {\n const grantResolution = await resolveGrantAccessTo(isCurrentSubmission)\n if (grantResolution.cancelled || !isCurrentSubmission()) return\n const anchor = pendingAnchor ?? (editor\n ? (await import('./CommentAnchorNavigation')).captureCommentAnchor(editor)\n : null)\n if (!isCurrentSubmission()) return\n const mentions = activePendingMentions.map(({ userId }) => ({ userId }))\n await runMutation({\n operation: () => apiCallOrThrow(\n `/api/documents/${encodeURIComponent(documentId)}/comments`,\n {\n method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n body: trimmedBody,\n anchor,\n parentCommentId,\n mentions,\n grantAccessTo: grantResolution.grantAccessTo,\n }),\n },\n { errorMessage: t('documents.comments.error.save') },\n ),\n context: { formId: mutationContextId, resourceKind: 'documents.document_comment', resourceId: documentId, retryLastMutation },\n mutationPayload: { body: trimmedBody, parentCommentId, mentions },\n })\n if (!isCurrentSubmission()) return\n resetComposer()\n await reload()\n } catch (error) {\n if (isCurrentSubmission()) {\n flash(error instanceof Error ? error.message : t('documents.comments.error.save'), 'error')\n }\n } finally {\n if (isCurrentSubmission()) setIsSubmitting(false)\n }\n }, [activePendingMentions, body, canComment, documentId, editor, mutationContextId, parentCommentId, pendingAnchor, reload, resetComposer, resolveGrantAccessTo, retryLastMutation, runMutation, t])\n\n const resolveComment = React.useCallback(async (comment: DocumentComment) => {\n if (!comment.canResolve) return\n setResolvingCommentId(comment.id)\n try {\n await runMutation({\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(comment.updatedAt),\n () => apiCallOrThrow(\n `/api/documents/${encodeURIComponent(documentId)}/comments`,\n { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: comment.id, resolved: comment.resolvedAt === null }) },\n { errorMessage: t('documents.comments.error.save') },\n ),\n ),\n context: { formId: mutationContextId, resourceKind: 'documents.document_comment', resourceId: comment.id, retryLastMutation },\n mutationPayload: { id: comment.id, resolved: comment.resolvedAt === null },\n })\n await reload()\n } catch (error) {\n if (!surfaceRecordConflict(error, t, { onRefresh: () => { void reload() } })) {\n flash(error instanceof Error ? error.message : t('documents.comments.error.save'), 'error')\n }\n } finally {\n setResolvingCommentId(null)\n }\n }, [documentId, mutationContextId, reload, retryLastMutation, runMutation, t])\n\n const comments = state.status === 'ready' ? state.comments : []\n const parentComment = parentCommentId ? findCommentById(comments, parentCommentId) : null\n return {\n state, comments, body, setBody, pendingMentions, setPendingMentions, parentCommentId,\n pendingAnchor, setPendingAnchor, isSubmitting, resolvingCommentId, grantAccessNames,\n chooseGrantAccess, labelFor, resetComposer, reload, submit, resolveComment,\n startReply: (comment: DocumentComment) => { setPendingAnchor(null); setParentCommentId(comment.id) },\n replyToName: parentComment ? labelFor(parentComment.authorUserId) : null,\n }\n}\n"],
|
|
5
|
-
"mappings": ";AAEA,YAAY,WAAW;AAEvB,SAAS,SAAS,gBAAgB,mCAAmC;AACrE,SAAS,0BAA0B;AACnC,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY,kBAAkB;AAEvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAoBA,SAAS,oBAAoB,EAAE,YAAY,QAAQ,YAAY,SAAS,GAA6B;AAC1G,QAAM,IAAI,KAAK;AACf,QAAM,CAAC,OAAO,QAAQ,IAAI,MAAM,SAAwB,EAAE,QAAQ,UAAU,CAAC;AAC7E,QAAM,CAAC,MAAM,OAAO,IAAI,MAAM,SAAS,EAAE;AACzC,QAAM,CAAC,iBAAiB,kBAAkB,I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BAAqB,MAAM,YAAY,CAAC,UAAoB,IAAI,QAA6B,CAAC,YAAY;AAC9G,6BAAyB;AACzB,kBAAc,UAAU;AACxB,wBAAoB,KAAK;AAAA,EAC3B,CAAC,GAAG,CAAC,wBAAwB,CAAC;AAE9B,QAAM,uBAAuB,MAAM,YAAY,OAC7C,wBACmC;AACnC,UAAM,UAAU,MAAM,KAAK,IAAI,IAAI,sBAAsB,IAAI,CAAC,YAAY,QAAQ,OAAO,YAAY,CAAC,CAAC,CAAC;AACxG,QAAI,QAAQ,WAAW,EAAG,QAAO,EAAE,WAAW,MAAM;AAGpD,UAAM,OAAO,MAAM;AAAA,MACjB,kBAAkB,mBAAmB,UAAU,CAAC;AAAA,MAChD,EAAE,QAAQ,QAAQ,SAAS,EAAE,gBAAgB,mBAAmB,GAAG,MAAM,KAAK,UAAU,EAAE,QAAQ,CAAC,EAAE;AAAA,IACvG;AACA,QAAI,CAAC,oBAAoB,EAAG,QAAO,EAAE,WAAW,KAAK;AACrD,QAAI,CAAC,KAAK,GAAI,OAAM,IAAI,MAAM,EAAE,+BAA+B,CAAC;AAChE,UAAM,gBAAgB,kBAAkB,KAAK,MAAM;
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport type { Editor } from '@tiptap/core'\nimport { apiCall, apiCallOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport {\n DOCUMENTS_COMMENT_LIST_PAGE_SIZE,\n DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT,\n} from '../../../lib/historyPolicy'\nimport { readNumber, readRecord } from '../documentUi'\nimport type { CommentAnchor } from './CommentAnchorNavigation'\nimport {\n bodyContainsPendingMention,\n findCommentById,\n readCommentItems,\n readUserLabels,\n readWithoutAccess,\n type DocumentComment,\n type PendingMention,\n type UserLabels,\n} from './commentTypes'\n\ntype CommentsState =\n | { status: 'loading' }\n | { status: 'error'; message: string }\n | { status: 'ready'; comments: DocumentComment[]; userLabels: UserLabels }\n\ntype UseDocumentCommentsInput = {\n documentId: string\n editor: Editor | null\n canComment: boolean\n canShare: boolean\n}\n\ntype GrantAccessDecision = 'share' | 'skip' | 'cancel'\n\ntype GrantAccessResolution =\n | { cancelled: true }\n | { cancelled: false; grantAccessTo?: string[]; hasUnnotifiedMentions?: boolean }\n\nexport function useDocumentComments({ documentId, editor, canComment, canShare }: UseDocumentCommentsInput) {\n const t = useT()\n const [state, setState] = React.useState<CommentsState>({ status: 'loading' })\n const [body, setBody] = React.useState('')\n const [pendingMentions, setPendingMentions] = React.useState<PendingMention[]>([])\n const [parentCommentId, setParentCommentId] = React.useState<string | null>(null)\n const [pendingAnchor, setPendingAnchor] = React.useState<CommentAnchor | null>(null)\n const [isSubmitting, setIsSubmitting] = React.useState(false)\n const [resolvingCommentId, setResolvingCommentId] = React.useState<string | null>(null)\n const [grantAccessNames, setGrantAccessNames] = React.useState<string[] | null>(null)\n const grantResolver = React.useRef<((decision: GrantAccessDecision) => void) | null>(null)\n const submissionContextSequence = React.useRef(0)\n const reloadSequence = React.useRef(0)\n const activeReload = React.useRef<AbortController | null>(null)\n const activeDocumentId = React.useRef<string | null>(null)\n const mutationContextId = `documents-comments:${documentId}`\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n resourceKind: string\n resourceId: string\n retryLastMutation: () => Promise<boolean>\n }>({ contextId: mutationContextId, blockedMessage: t('ui.forms.flash.saveBlocked') })\n const activePendingMentions = React.useMemo(\n () => pendingMentions.filter((mention) => bodyContainsPendingMention(body, mention)),\n [body, pendingMentions],\n )\n\n const reload = React.useCallback(async () => {\n const reloadId = ++reloadSequence.current\n const controller = new AbortController()\n activeReload.current?.abort()\n activeReload.current = controller\n const isCurrent = () => reloadSequence.current === reloadId && !controller.signal.aborted\n const documentChanged = activeDocumentId.current !== documentId\n activeDocumentId.current = documentId\n setState((current) => !documentChanged && current.status === 'ready' ? current : { status: 'loading' })\n try {\n const maxPages = Math.ceil(DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT / DOCUMENTS_COMMENT_LIST_PAGE_SIZE)\n const pathForPage = (page: number) => (\n `/api/documents/${encodeURIComponent(documentId)}/comments?page=${page}&pageSize=${DOCUMENTS_COMMENT_LIST_PAGE_SIZE}`\n )\n const firstCall = await apiCall<unknown>(pathForPage(1), { signal: controller.signal })\n if (!isCurrent()) return\n if (!firstCall.ok) {\n setState({ status: 'error', message: t('documents.comments.error.load') })\n return\n }\n\n const firstRoot = readRecord(firstCall.result)\n const totalPages = Math.min(\n maxPages,\n Math.max(1, firstRoot ? readNumber(firstRoot, 'totalPages', 'total_pages') ?? 1 : 1),\n )\n const remainingCalls = totalPages > 1\n ? await Promise.all(Array.from({ length: totalPages - 1 }, (_, index) => (\n apiCall<unknown>(pathForPage(index + 2), { signal: controller.signal })\n )))\n : []\n if (!isCurrent()) return\n if (remainingCalls.some((call) => !call.ok)) {\n setState({ status: 'error', message: t('documents.comments.error.load') })\n return\n }\n\n const calls = [firstCall, ...remainingCalls]\n const comments = [...calls].reverse().flatMap((call) => readCommentItems(call.result))\n const userLabels = calls.reduce<UserLabels>((labels, call) => ({\n ...labels,\n ...readUserLabels(call.result, t('documents.users.unknown')),\n }), {})\n setState({ status: 'ready', comments, userLabels })\n } catch (error) {\n if (isCurrent()) {\n setState({ status: 'error', message: error instanceof Error ? error.message : t('documents.comments.error.load') })\n }\n } finally {\n if (activeReload.current === controller) activeReload.current = null\n }\n }, [documentId, t])\n\n React.useEffect(() => {\n void reload()\n return () => {\n reloadSequence.current += 1\n activeReload.current?.abort()\n activeReload.current = null\n }\n }, [reload])\n\n const cancelPendingGrantAccess = React.useCallback(() => {\n const resolve = grantResolver.current\n grantResolver.current = null\n resolve?.('cancel')\n }, [])\n\n React.useEffect(() => {\n setGrantAccessNames(null)\n setIsSubmitting(false)\n return () => {\n submissionContextSequence.current += 1\n cancelPendingGrantAccess()\n }\n }, [cancelPendingGrantAccess, documentId])\n\n const labelFor = React.useCallback((userId: string) => {\n const labels = state.status === 'ready' ? state.userLabels : {}\n return labels[userId.toLowerCase()]?.label ?? t('documents.users.unknown')\n }, [state, t])\n\n const resetComposer = React.useCallback(() => {\n setBody('')\n setPendingMentions([])\n setParentCommentId(null)\n setPendingAnchor(null)\n }, [])\n\n const chooseGrantAccess = React.useCallback((share: boolean) => {\n const resolve = grantResolver.current\n grantResolver.current = null\n setGrantAccessNames(null)\n resolve?.(share ? 'share' : 'skip')\n }, [])\n\n const requestGrantAccess = React.useCallback((names: string[]) => new Promise<GrantAccessDecision>((resolve) => {\n cancelPendingGrantAccess()\n grantResolver.current = resolve\n setGrantAccessNames(names)\n }), [cancelPendingGrantAccess])\n\n const resolveGrantAccessTo = React.useCallback(async (\n isCurrentSubmission: () => boolean,\n ): Promise<GrantAccessResolution> => {\n const userIds = Array.from(new Set(activePendingMentions.map((mention) => mention.userId.toLowerCase())))\n if (userIds.length === 0) return { cancelled: false }\n // Intentionally outside useGuardedMutation: access-check is read-shaped\n // (a POST only to carry the user-id list in the body) and mutates nothing.\n const call = await apiCall<unknown>(\n `/api/documents/${encodeURIComponent(documentId)}/comments/access-check`,\n { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ userIds }) },\n )\n if (!isCurrentSubmission()) return { cancelled: true }\n if (!call.ok) throw new Error(t('documents.comments.error.save'))\n const withoutAccess = readWithoutAccess(call.result).filter((user) => userIds.includes(user.userId))\n if (withoutAccess.length === 0) return { cancelled: false }\n const response = readRecord(call.result)\n const shareableUserIds = new Set(\n Array.isArray(response?.shareableUserIds)\n ? response.shareableUserIds.filter((value): value is string => typeof value === 'string').map((value) => value.toLowerCase())\n : [],\n )\n const shareableUsers = withoutAccess.filter((user) => shareableUserIds.has(user.userId))\n if (!canShare || shareableUsers.length === 0) {\n return { cancelled: false, grantAccessTo: [], hasUnnotifiedMentions: true }\n }\n const pendingMentionNames = new Map(\n activePendingMentions.map((mention) => [mention.userId.toLowerCase(), mention.name]),\n )\n const decision = await requestGrantAccess(shareableUsers.map((user) => (\n pendingMentionNames.get(user.userId) ?? user.label ?? labelFor(user.userId)\n )))\n if (decision === 'cancel' || !isCurrentSubmission()) return { cancelled: true }\n return {\n cancelled: false,\n grantAccessTo: decision === 'share' ? shareableUsers.map((user) => user.userId) : [],\n hasUnnotifiedMentions: decision === 'skip' || shareableUsers.length < withoutAccess.length,\n }\n }, [activePendingMentions, canShare, documentId, labelFor, requestGrantAccess, t])\n\n const submit = React.useCallback(async () => {\n const trimmedBody = body.trim()\n if (!trimmedBody || !canComment) return\n const submissionSequence = submissionContextSequence.current\n const isCurrentSubmission = () => submissionContextSequence.current === submissionSequence\n setIsSubmitting(true)\n try {\n const grantResolution = await resolveGrantAccessTo(isCurrentSubmission)\n if (grantResolution.cancelled || !isCurrentSubmission()) return\n const anchor = pendingAnchor ?? (editor\n ? (await import('./CommentAnchorNavigation')).captureCommentAnchor(editor)\n : null)\n if (!isCurrentSubmission()) return\n const mentions = activePendingMentions.map(({ userId }) => ({ userId }))\n await runMutation({\n operation: () => apiCallOrThrow(\n `/api/documents/${encodeURIComponent(documentId)}/comments`,\n {\n method: 'POST', headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n body: trimmedBody,\n anchor,\n parentCommentId,\n mentions,\n grantAccessTo: grantResolution.grantAccessTo,\n }),\n },\n { errorMessage: t('documents.comments.error.save') },\n ),\n context: { formId: mutationContextId, resourceKind: 'documents.document_comment', resourceId: documentId, retryLastMutation },\n mutationPayload: { body: trimmedBody, parentCommentId, mentions },\n })\n if (!isCurrentSubmission()) return\n if (grantResolution.hasUnnotifiedMentions) {\n flash(t('documents.comments.grant.noAccessInfo'), 'info')\n }\n resetComposer()\n await reload()\n } catch (error) {\n if (isCurrentSubmission()) {\n flash(error instanceof Error ? error.message : t('documents.comments.error.save'), 'error')\n }\n } finally {\n if (isCurrentSubmission()) setIsSubmitting(false)\n }\n }, [activePendingMentions, body, canComment, documentId, editor, mutationContextId, parentCommentId, pendingAnchor, reload, resetComposer, resolveGrantAccessTo, retryLastMutation, runMutation, t])\n\n const resolveComment = React.useCallback(async (comment: DocumentComment) => {\n if (!comment.canResolve) return\n setResolvingCommentId(comment.id)\n try {\n await runMutation({\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(comment.updatedAt),\n () => apiCallOrThrow(\n `/api/documents/${encodeURIComponent(documentId)}/comments`,\n { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: comment.id, resolved: comment.resolvedAt === null }) },\n { errorMessage: t('documents.comments.error.save') },\n ),\n ),\n context: { formId: mutationContextId, resourceKind: 'documents.document_comment', resourceId: comment.id, retryLastMutation },\n mutationPayload: { id: comment.id, resolved: comment.resolvedAt === null },\n })\n await reload()\n } catch (error) {\n if (!surfaceRecordConflict(error, t, { onRefresh: () => { void reload() } })) {\n flash(error instanceof Error ? error.message : t('documents.comments.error.save'), 'error')\n }\n } finally {\n setResolvingCommentId(null)\n }\n }, [documentId, mutationContextId, reload, retryLastMutation, runMutation, t])\n\n const comments = state.status === 'ready' ? state.comments : []\n const parentComment = parentCommentId ? findCommentById(comments, parentCommentId) : null\n return {\n state, comments, body, setBody, pendingMentions, setPendingMentions, parentCommentId,\n pendingAnchor, setPendingAnchor, isSubmitting, resolvingCommentId, grantAccessNames,\n chooseGrantAccess, labelFor, resetComposer, reload, submit, resolveComment,\n startReply: (comment: DocumentComment) => { setPendingAnchor(null); setParentCommentId(comment.id) },\n replyToName: parentComment ? labelFor(parentComment.authorUserId) : null,\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAEA,YAAY,WAAW;AAEvB,SAAS,SAAS,gBAAgB,mCAAmC;AACrE,SAAS,0BAA0B;AACnC,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rE;AAAA,IAAe;AAAA,IAAkB;AAAA,IAAc;AAAA,IAAoB;AAAA,IACnE;AAAA,IAAmB;AAAA,IAAU;AAAA,IAAe;AAAA,IAAQ;AAAA,IAAQ;AAAA,IAC5D,YAAY,CAAC,YAA6B;AAAE,uBAAiB,IAAI;AAAG,yBAAmB,QAAQ,EAAE;AAAA,IAAE;AAAA,IACnG,aAAa,gBAAgB,SAAS,cAAc,YAAY,IAAI;AAAA,EACtE;AACF;",
|
|
6
6
|
"names": ["comments"]
|
|
7
7
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
+
import { useContentSecurityPolicyNonce } from "@open-mercato/ui/theme/ContentSecurityPolicyProvider";
|
|
2
3
|
import * as React from "react";
|
|
3
4
|
import { useEditor } from "@tiptap/react";
|
|
4
5
|
import { useT } from "@open-mercato/shared/lib/i18n/context";
|
|
@@ -41,6 +42,7 @@ function documentCounts(editor) {
|
|
|
41
42
|
}
|
|
42
43
|
function useDocumentEditor(input) {
|
|
43
44
|
const t = useT();
|
|
45
|
+
const nonce = useContentSecurityPolicyNonce();
|
|
44
46
|
const editorRef = React.useRef(null);
|
|
45
47
|
const countTimerRef = React.useRef(null);
|
|
46
48
|
const readOnlyRef = React.useRef(input.readOnly);
|
|
@@ -82,6 +84,7 @@ function useDocumentEditor(input) {
|
|
|
82
84
|
}), ...getClientEditorExtras(), DocumentPagination, ...suggestions];
|
|
83
85
|
}, [input.collabResources, input.editorMode, t]);
|
|
84
86
|
const editor = useEditor({
|
|
87
|
+
injectNonce: nonce,
|
|
85
88
|
extensions,
|
|
86
89
|
content: input.editorMode === "fallback" ? input.initialContentHtml : void 0,
|
|
87
90
|
editable: !input.readOnly,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/documents/backend/documents/%5Bid%5D/useDocumentEditor.ts"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport type { Editor } from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { useEditor } from '@tiptap/react'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport {\n activateEntityRefFromKeyboardEvent,\n activateEntityRefFromPointerEvent,\n getClientEditorExtras,\n getCollaborativeEditorExtensions,\n getDocumentEditorExtensions,\n} from '../../../lib/editorConfig'\nimport { createEntitySuggestionExtension } from '../../../lib/entitySuggestion'\nimport { DocumentPagination } from './documentPagination'\nimport type { CollabResources, EditorSelectionRange, EditorWordCount } from './editorTypes'\n\ntype UseDocumentEditorInput = {\n documentId: string\n initialContentHtml: string\n editorMode: 'collab' | 'fallback'\n collabResources?: CollabResources\n readOnly: boolean\n onEditorReady?: (editor: Editor | null) => void\n onUpdate?: (editor: Editor) => void\n onEntitySuggestion: (range: EditorSelectionRange) => void\n onSuggestionClose: () => void\n}\n\nexport const DOCUMENT_COUNT_UPDATE_DELAY_MS = 150\n\nexport function countDocumentWordsAndCharacters(doc: ProseMirrorNode): EditorWordCount {\n let words = 0\n let characters = 0\n let firstBlock = true\n let insideWord = false\n\n doc.nodesBetween(0, doc.content.size, (node) => {\n const nodeText = node.isText ? node.text ?? '' : node.isLeaf ? ' ' : ''\n if (node.isBlock && ((node.isLeaf && nodeText.length > 0) || node.isTextblock)) {\n if (firstBlock) firstBlock = false\n else insideWord = false\n }\n characters += nodeText.length\n for (let index = 0; index < nodeText.length; index += 1) {\n if (nodeText[index] === ' ') {\n insideWord = false\n } else if (!insideWord) {\n words += 1\n insideWord = true\n }\n }\n })\n return { words, characters }\n}\n\nfunction documentCounts(editor: Editor | null): EditorWordCount {\n if (!editor) return { words: 0, characters: 0 }\n return countDocumentWordsAndCharacters(editor.state.doc)\n}\n\nexport function useDocumentEditor(input: UseDocumentEditorInput) {\n const t = useT()\n const editorRef = React.useRef<Editor | null>(null)\n const countTimerRef = React.useRef<number | null>(null)\n const readOnlyRef = React.useRef(input.readOnly)\n const onEntitySuggestionRef = React.useRef(input.onEntitySuggestion)\n const onSuggestionCloseRef = React.useRef(input.onSuggestionClose)\n const [counts, setCounts] = React.useState<EditorWordCount>({ words: 0, characters: 0 })\n readOnlyRef.current = input.readOnly\n onEntitySuggestionRef.current = input.onEntitySuggestion\n onSuggestionCloseRef.current = input.onSuggestionClose\n\n const applyCounts = React.useCallback((updated: Editor | null) => {\n const next = documentCounts(updated)\n React.startTransition(() => {\n setCounts((current) => current.words === next.words && current.characters === next.characters ? current : next)\n })\n }, [])\n const scheduleCounts = React.useCallback((updated: Editor) => {\n if (countTimerRef.current !== null) window.clearTimeout(countTimerRef.current)\n countTimerRef.current = window.setTimeout(() => {\n countTimerRef.current = null\n applyCounts(updated)\n }, DOCUMENT_COUNT_UPDATE_DELAY_MS)\n }, [applyCounts])\n\n const extensions = React.useMemo(() => {\n const suggestions = [createEntitySuggestionExtension({\n onTrigger: ({ range }) => {\n if (!readOnlyRef.current) onEntitySuggestionRef.current(range)\n },\n onClose: () => onSuggestionCloseRef.current(),\n })]\n return input.editorMode === 'collab' && input.collabResources\n ? [...getCollaborativeEditorExtensions({\n ydoc: input.collabResources.ydoc,\n provider: input.collabResources.provider,\n user: input.collabResources.user,\n placeholder: t('documents.editor.placeholder'),\n fallbackUserLabel: t('documents.users.unknown'),\n fallbackEntityRefLabel: t('documents.editor.entityRef.fallbackLabel'),\n }), ...getClientEditorExtras(), DocumentPagination, ...suggestions]\n : [...getDocumentEditorExtensions({\n entityRefFallbackLabel: t('documents.editor.entityRef.fallbackLabel'),\n }), ...getClientEditorExtras(), DocumentPagination, ...suggestions]\n }, [input.collabResources, input.editorMode, t])\n\n const editor = useEditor({\n extensions,\n content: input.editorMode === 'fallback' ? input.initialContentHtml : undefined,\n editable: !input.readOnly,\n editorProps: {\n attributes: {\n class: 'min-h-96 text-base leading-7 text-foreground focus-visible:outline-none',\n role: 'textbox',\n 'aria-label': t('documents.editor.content.ariaLabel'),\n 'aria-multiline': 'true',\n },\n handleClick(_view, _position, event) {\n return activateEntityRefFromPointerEvent(\n event,\n (href) => { window.open(href, '_blank', 'noopener') },\n )\n },\n handleKeyDown(_view, event) {\n return activateEntityRefFromKeyboardEvent(\n event,\n (href) => { window.open(href, '_blank', 'noopener') },\n )\n },\n },\n onCreate: ({ editor: created }) => { editorRef.current = created; applyCounts(created); input.onEditorReady?.(created) },\n onDestroy: () => {\n if (countTimerRef.current !== null) window.clearTimeout(countTimerRef.current)\n countTimerRef.current = null\n editorRef.current = null\n input.onEditorReady?.(null)\n },\n onUpdate: ({ editor: updated }) => {\n editorRef.current = updated\n scheduleCounts(updated)\n input.onUpdate?.(updated)\n },\n }, [input.documentId, input.editorMode, extensions])\n\n React.useEffect(() => { editorRef.current = editor; editor?.setEditable(!input.readOnly) }, [editor, input.readOnly])\n React.useEffect(() => {\n if (input.readOnly) onSuggestionCloseRef.current()\n }, [input.readOnly])\n React.useEffect(() => () => {\n if (countTimerRef.current !== null) window.clearTimeout(countTimerRef.current)\n }, [])\n React.useEffect(() => () => { input.onEditorReady?.(null) }, [input.onEditorReady])\n return { editor, editorRef, counts }\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\nimport { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'\n\nimport * as React from 'react'\nimport type { Editor } from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { useEditor } from '@tiptap/react'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport {\n activateEntityRefFromKeyboardEvent,\n activateEntityRefFromPointerEvent,\n getClientEditorExtras,\n getCollaborativeEditorExtensions,\n getDocumentEditorExtensions,\n} from '../../../lib/editorConfig'\nimport { createEntitySuggestionExtension } from '../../../lib/entitySuggestion'\nimport { DocumentPagination } from './documentPagination'\nimport type { CollabResources, EditorSelectionRange, EditorWordCount } from './editorTypes'\n\ntype UseDocumentEditorInput = {\n documentId: string\n initialContentHtml: string\n editorMode: 'collab' | 'fallback'\n collabResources?: CollabResources\n readOnly: boolean\n onEditorReady?: (editor: Editor | null) => void\n onUpdate?: (editor: Editor) => void\n onEntitySuggestion: (range: EditorSelectionRange) => void\n onSuggestionClose: () => void\n}\n\nexport const DOCUMENT_COUNT_UPDATE_DELAY_MS = 150\n\nexport function countDocumentWordsAndCharacters(doc: ProseMirrorNode): EditorWordCount {\n let words = 0\n let characters = 0\n let firstBlock = true\n let insideWord = false\n\n doc.nodesBetween(0, doc.content.size, (node) => {\n const nodeText = node.isText ? node.text ?? '' : node.isLeaf ? ' ' : ''\n if (node.isBlock && ((node.isLeaf && nodeText.length > 0) || node.isTextblock)) {\n if (firstBlock) firstBlock = false\n else insideWord = false\n }\n characters += nodeText.length\n for (let index = 0; index < nodeText.length; index += 1) {\n if (nodeText[index] === ' ') {\n insideWord = false\n } else if (!insideWord) {\n words += 1\n insideWord = true\n }\n }\n })\n return { words, characters }\n}\n\nfunction documentCounts(editor: Editor | null): EditorWordCount {\n if (!editor) return { words: 0, characters: 0 }\n return countDocumentWordsAndCharacters(editor.state.doc)\n}\n\nexport function useDocumentEditor(input: UseDocumentEditorInput) {\n const t = useT()\n const nonce = useContentSecurityPolicyNonce()\n const editorRef = React.useRef<Editor | null>(null)\n const countTimerRef = React.useRef<number | null>(null)\n const readOnlyRef = React.useRef(input.readOnly)\n const onEntitySuggestionRef = React.useRef(input.onEntitySuggestion)\n const onSuggestionCloseRef = React.useRef(input.onSuggestionClose)\n const [counts, setCounts] = React.useState<EditorWordCount>({ words: 0, characters: 0 })\n readOnlyRef.current = input.readOnly\n onEntitySuggestionRef.current = input.onEntitySuggestion\n onSuggestionCloseRef.current = input.onSuggestionClose\n\n const applyCounts = React.useCallback((updated: Editor | null) => {\n const next = documentCounts(updated)\n React.startTransition(() => {\n setCounts((current) => current.words === next.words && current.characters === next.characters ? current : next)\n })\n }, [])\n const scheduleCounts = React.useCallback((updated: Editor) => {\n if (countTimerRef.current !== null) window.clearTimeout(countTimerRef.current)\n countTimerRef.current = window.setTimeout(() => {\n countTimerRef.current = null\n applyCounts(updated)\n }, DOCUMENT_COUNT_UPDATE_DELAY_MS)\n }, [applyCounts])\n\n const extensions = React.useMemo(() => {\n const suggestions = [createEntitySuggestionExtension({\n onTrigger: ({ range }) => {\n if (!readOnlyRef.current) onEntitySuggestionRef.current(range)\n },\n onClose: () => onSuggestionCloseRef.current(),\n })]\n return input.editorMode === 'collab' && input.collabResources\n ? [...getCollaborativeEditorExtensions({\n ydoc: input.collabResources.ydoc,\n provider: input.collabResources.provider,\n user: input.collabResources.user,\n placeholder: t('documents.editor.placeholder'),\n fallbackUserLabel: t('documents.users.unknown'),\n fallbackEntityRefLabel: t('documents.editor.entityRef.fallbackLabel'),\n }), ...getClientEditorExtras(), DocumentPagination, ...suggestions]\n : [...getDocumentEditorExtensions({\n entityRefFallbackLabel: t('documents.editor.entityRef.fallbackLabel'),\n }), ...getClientEditorExtras(), DocumentPagination, ...suggestions]\n }, [input.collabResources, input.editorMode, t])\n\n const editor = useEditor({\n injectNonce: nonce,\n extensions,\n content: input.editorMode === 'fallback' ? input.initialContentHtml : undefined,\n editable: !input.readOnly,\n editorProps: {\n attributes: {\n class: 'min-h-96 text-base leading-7 text-foreground focus-visible:outline-none',\n role: 'textbox',\n 'aria-label': t('documents.editor.content.ariaLabel'),\n 'aria-multiline': 'true',\n },\n handleClick(_view, _position, event) {\n return activateEntityRefFromPointerEvent(\n event,\n (href) => { window.open(href, '_blank', 'noopener') },\n )\n },\n handleKeyDown(_view, event) {\n return activateEntityRefFromKeyboardEvent(\n event,\n (href) => { window.open(href, '_blank', 'noopener') },\n )\n },\n },\n onCreate: ({ editor: created }) => { editorRef.current = created; applyCounts(created); input.onEditorReady?.(created) },\n onDestroy: () => {\n if (countTimerRef.current !== null) window.clearTimeout(countTimerRef.current)\n countTimerRef.current = null\n editorRef.current = null\n input.onEditorReady?.(null)\n },\n onUpdate: ({ editor: updated }) => {\n editorRef.current = updated\n scheduleCounts(updated)\n input.onUpdate?.(updated)\n },\n }, [input.documentId, input.editorMode, extensions])\n\n React.useEffect(() => { editorRef.current = editor; editor?.setEditable(!input.readOnly) }, [editor, input.readOnly])\n React.useEffect(() => {\n if (input.readOnly) onSuggestionCloseRef.current()\n }, [input.readOnly])\n React.useEffect(() => () => {\n if (countTimerRef.current !== null) window.clearTimeout(countTimerRef.current)\n }, [])\n React.useEffect(() => () => { input.onEditorReady?.(null) }, [input.onEditorReady])\n return { editor, editorRef, counts }\n}\n"],
|
|
5
|
+
"mappings": ";AACA,SAAS,qCAAqC;AAE9C,YAAY,WAAW;AAGvB,SAAS,iBAAiB;AAC1B,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uCAAuC;AAChD,SAAS,0BAA0B;AAe5B,MAAM,iCAAiC;AAEvC,SAAS,gCAAgC,KAAuC;AACrF,MAAI,QAAQ;AACZ,MAAI,aAAa;AACjB,MAAI,aAAa;AACjB,MAAI,aAAa;AAEjB,MAAI,aAAa,GAAG,IAAI,QAAQ,MAAM,CAAC,SAAS;AAC9C,UAAM,WAAW,KAAK,SAAS,KAAK,QAAQ,KAAK,KAAK,SAAS,MAAM;AACrE,QAAI,KAAK,YAAa,KAAK,UAAU,SAAS,SAAS,KAAM,KAAK,cAAc;AAC9E,UAAI,WAAY,cAAa;AAAA,UACxB,cAAa;AAAA,IACpB;AACA,kBAAc,SAAS;AACvB,aAAS,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS,GAAG;AACvD,UAAI,SAAS,KAAK,MAAM,KAAK;AAC3B,qBAAa;AAAA,MACf,WAAW,CAAC,YAAY;AACtB,iBAAS;AACT,qBAAa;AAAA,MACf;AAAA,IACF;AAAA,EACF,CAAC;AACD,SAAO,EAAE,OAAO,WAAW;AAC7B;AAEA,SAAS,eAAe,QAAwC;AAC9D,MAAI,CAAC,OAAQ,QAAO,EAAE,OAAO,GAAG,YAAY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IACvH,WAAW,MAAM;AACf,UAAI,cAAc,YAAY,KAAM,QAAO,aAAa,cAAc,OAAO;AAC7E,oBAAc,UAAU;AACxB,gBAAU,UAAU;AACpB,YAAM,gBAAgB,IAAI;AAAA,IAC5B;AAAA,IACA,UAAU,CAAC,EAAE,QAAQ,QAAQ,MAAM;AACjC,gBAAU,UAAU;AACpB,qBAAe,OAAO;AACtB,YAAM,WAAW,OAAO;AAAA,IAC1B;AAAA,EACF,GAAG,CAAC,MAAM,YAAY,MAAM,YAAY,UAAU,CAAC;AAEnD,QAAM,UAAU,MAAM;AAAE,cAAU,UAAU;AAAQ,YAAQ,YAAY,CAAC,MAAM,QAAQ;AAAA,EAAE,GAAG,CAAC,QAAQ,MAAM,QAAQ,CAAC;AACpH,QAAM,UAAU,MAAM;AACpB,QAAI,MAAM,SAAU,sBAAqB,QAAQ;AAAA,EACnD,GAAG,CAAC,MAAM,QAAQ,CAAC;AACnB,QAAM,UAAU,MAAM,MAAM;AAC1B,QAAI,cAAc,YAAY,KAAM,QAAO,aAAa,cAAc,OAAO;AAAA,EAC/E,GAAG,CAAC,CAAC;AACL,QAAM,UAAU,MAAM,MAAM;AAAE,UAAM,gBAAgB,IAAI;AAAA,EAAE,GAAG,CAAC,MAAM,aAAa,CAAC;AAClF,SAAO,EAAE,QAAQ,WAAW,OAAO;AACrC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
3
3
|
import * as React from "react";
|
|
4
|
+
import { useContentSecurityPolicyNonce } from "@open-mercato/ui/theme/ContentSecurityPolicyProvider";
|
|
4
5
|
import { EditorContent, useEditor, useEditorState } from "@tiptap/react";
|
|
5
6
|
import { Bold, Heading1, Heading2, Italic, List, ListOrdered } from "lucide-react";
|
|
6
7
|
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
|
|
@@ -23,9 +24,11 @@ function EditorButton({ editor, label, active, children, onClick }) {
|
|
|
23
24
|
}
|
|
24
25
|
function TemplateBodyEditor({ bodyHtml, tokenOptions, onChange }) {
|
|
25
26
|
const t = useT();
|
|
27
|
+
const nonce = useContentSecurityPolicyNonce();
|
|
26
28
|
const editorLabelId = React.useId();
|
|
27
29
|
const [token, setToken] = React.useState();
|
|
28
30
|
const editor = useEditor({
|
|
31
|
+
injectNonce: nonce,
|
|
29
32
|
extensions: getDocumentEditorExtensions({
|
|
30
33
|
entityRefFallbackLabel: t("documents.editor.entityRef.fallbackLabel")
|
|
31
34
|
}),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/documents/backend/documents/components/TemplateBodyEditor.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport type { Editor } from '@tiptap/core'\nimport { EditorContent, useEditor, useEditorState } from '@tiptap/react'\nimport { Bold, Heading1, Heading2, Italic, List, ListOrdered } from 'lucide-react'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@open-mercato/ui/primitives/select'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { getDocumentEditorExtensions } from '../../../lib/editorConfig'\n\nconst EMPTY_TEMPLATE_EDITOR_STATE = {\n bold: false,\n italic: false,\n heading1: false,\n heading2: false,\n bulletList: false,\n orderedList: false,\n}\n\nfunction EditorButton({ editor, label, active, children, onClick }: {\n editor: Editor | null\n label: string\n active: boolean\n children: React.ReactNode\n onClick: (editor: Editor) => void\n}) {\n return <IconButton type=\"button\" variant={active ? 'outline' : 'ghost'} aria-label={label} aria-pressed={active} title={label} disabled={!editor} onMouseDown={(event) => event.preventDefault()} onClick={() => { if (editor) onClick(editor) }}>{children}</IconButton>\n}\n\nexport function TemplateBodyEditor({ bodyHtml, tokenOptions, onChange }: {\n bodyHtml: string\n tokenOptions: string[]\n onChange: (html: string) => void\n}) {\n const t = useT()\n const editorLabelId = React.useId()\n const [token, setToken] = React.useState<string | undefined>()\n const editor = useEditor({\n extensions: getDocumentEditorExtensions({\n entityRefFallbackLabel: t('documents.editor.entityRef.fallbackLabel'),\n }),\n content: bodyHtml,\n editable: true,\n editorProps: {\n attributes: {\n class: 'min-h-80 text-base leading-7 text-foreground focus-visible:outline-none',\n role: 'textbox',\n 'aria-labelledby': editorLabelId,\n 'aria-multiline': 'true',\n },\n },\n onUpdate: ({ editor: updated }) => onChange(updated.getHTML()),\n }, [])\n React.useEffect(() => {\n if (editor && editor.getHTML() !== bodyHtml) editor.commands.setContent(bodyHtml)\n }, [bodyHtml, editor])\n const editorState = useEditorState({\n editor,\n selector: ({ editor: current }) => current ? {\n bold: current.isActive('bold'),\n italic: current.isActive('italic'),\n heading1: current.isActive('heading', { level: 1 }),\n heading2: current.isActive('heading', { level: 2 }),\n bulletList: current.isActive('bulletList'),\n orderedList: current.isActive('orderedList'),\n } : EMPTY_TEMPLATE_EDITOR_STATE,\n }) ?? EMPTY_TEMPLATE_EDITOR_STATE\n return (\n <div className=\"space-y-3\">\n <Label id={editorLabelId}>{t('documents.templates.fields.body')}</Label>\n <div className=\"rounded-md border border-border bg-card\">\n <div className=\"flex flex-wrap items-center gap-1 border-b border-border p-2\">\n <EditorButton editor={editor} label={t('documents.editor.toolbar.bold')} active={editorState.bold} onClick={(current) => { current.chain().focus().toggleBold().run() }}><Bold /></EditorButton>\n <EditorButton editor={editor} label={t('documents.editor.toolbar.italic')} active={editorState.italic} onClick={(current) => { current.chain().focus().toggleItalic().run() }}><Italic /></EditorButton>\n <EditorButton editor={editor} label={t('documents.editor.toolbar.heading1')} active={editorState.heading1} onClick={(current) => { current.chain().focus().toggleHeading({ level: 1 }).run() }}><Heading1 /></EditorButton>\n <EditorButton editor={editor} label={t('documents.editor.toolbar.heading2')} active={editorState.heading2} onClick={(current) => { current.chain().focus().toggleHeading({ level: 2 }).run() }}><Heading2 /></EditorButton>\n <EditorButton editor={editor} label={t('documents.editor.toolbar.bulletList')} active={editorState.bulletList} onClick={(current) => { current.chain().focus().toggleBulletList().run() }}><List /></EditorButton>\n <EditorButton editor={editor} label={t('documents.editor.toolbar.orderedList')} active={editorState.orderedList} onClick={(current) => { current.chain().focus().toggleOrderedList().run() }}><ListOrdered /></EditorButton>\n <div className=\"min-w-52\">\n <Select value={token} onValueChange={(value) => {\n setToken(value)\n editor?.chain().focus().insertContent(value).run()\n window.setTimeout(() => setToken(undefined), 0)\n }}>\n <SelectTrigger aria-label={t('documents.templates.editor.insertField')}><SelectValue placeholder={t('documents.templates.editor.insertField')} /></SelectTrigger>\n <SelectContent>{tokenOptions.map((value) => <SelectItem key={value} value={value}>{value}</SelectItem>)}</SelectContent>\n </Select>\n </div>\n </div>\n <EditorContent editor={editor} className=\"max-w-none p-4 text-foreground [&_.ProseMirror]:min-h-80 [&_.ProseMirror]:focus-visible:outline-none\" />\n </div>\n </div>\n )\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'\nimport type { Editor } from '@tiptap/core'\nimport { EditorContent, useEditor, useEditorState } from '@tiptap/react'\nimport { Bold, Heading1, Heading2, Italic, List, ListOrdered } from 'lucide-react'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@open-mercato/ui/primitives/select'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { getDocumentEditorExtensions } from '../../../lib/editorConfig'\n\nconst EMPTY_TEMPLATE_EDITOR_STATE = {\n bold: false,\n italic: false,\n heading1: false,\n heading2: false,\n bulletList: false,\n orderedList: false,\n}\n\nfunction EditorButton({ editor, label, active, children, onClick }: {\n editor: Editor | null\n label: string\n active: boolean\n children: React.ReactNode\n onClick: (editor: Editor) => void\n}) {\n return <IconButton type=\"button\" variant={active ? 'outline' : 'ghost'} aria-label={label} aria-pressed={active} title={label} disabled={!editor} onMouseDown={(event) => event.preventDefault()} onClick={() => { if (editor) onClick(editor) }}>{children}</IconButton>\n}\n\nexport function TemplateBodyEditor({ bodyHtml, tokenOptions, onChange }: {\n bodyHtml: string\n tokenOptions: string[]\n onChange: (html: string) => void\n}) {\n const t = useT()\n const nonce = useContentSecurityPolicyNonce()\n const editorLabelId = React.useId()\n const [token, setToken] = React.useState<string | undefined>()\n const editor = useEditor({\n injectNonce: nonce,\n extensions: getDocumentEditorExtensions({\n entityRefFallbackLabel: t('documents.editor.entityRef.fallbackLabel'),\n }),\n content: bodyHtml,\n editable: true,\n editorProps: {\n attributes: {\n class: 'min-h-80 text-base leading-7 text-foreground focus-visible:outline-none',\n role: 'textbox',\n 'aria-labelledby': editorLabelId,\n 'aria-multiline': 'true',\n },\n },\n onUpdate: ({ editor: updated }) => onChange(updated.getHTML()),\n }, [])\n React.useEffect(() => {\n if (editor && editor.getHTML() !== bodyHtml) editor.commands.setContent(bodyHtml)\n }, [bodyHtml, editor])\n const editorState = useEditorState({\n editor,\n selector: ({ editor: current }) => current ? {\n bold: current.isActive('bold'),\n italic: current.isActive('italic'),\n heading1: current.isActive('heading', { level: 1 }),\n heading2: current.isActive('heading', { level: 2 }),\n bulletList: current.isActive('bulletList'),\n orderedList: current.isActive('orderedList'),\n } : EMPTY_TEMPLATE_EDITOR_STATE,\n }) ?? EMPTY_TEMPLATE_EDITOR_STATE\n return (\n <div className=\"space-y-3\">\n <Label id={editorLabelId}>{t('documents.templates.fields.body')}</Label>\n <div className=\"rounded-md border border-border bg-card\">\n <div className=\"flex flex-wrap items-center gap-1 border-b border-border p-2\">\n <EditorButton editor={editor} label={t('documents.editor.toolbar.bold')} active={editorState.bold} onClick={(current) => { current.chain().focus().toggleBold().run() }}><Bold /></EditorButton>\n <EditorButton editor={editor} label={t('documents.editor.toolbar.italic')} active={editorState.italic} onClick={(current) => { current.chain().focus().toggleItalic().run() }}><Italic /></EditorButton>\n <EditorButton editor={editor} label={t('documents.editor.toolbar.heading1')} active={editorState.heading1} onClick={(current) => { current.chain().focus().toggleHeading({ level: 1 }).run() }}><Heading1 /></EditorButton>\n <EditorButton editor={editor} label={t('documents.editor.toolbar.heading2')} active={editorState.heading2} onClick={(current) => { current.chain().focus().toggleHeading({ level: 2 }).run() }}><Heading2 /></EditorButton>\n <EditorButton editor={editor} label={t('documents.editor.toolbar.bulletList')} active={editorState.bulletList} onClick={(current) => { current.chain().focus().toggleBulletList().run() }}><List /></EditorButton>\n <EditorButton editor={editor} label={t('documents.editor.toolbar.orderedList')} active={editorState.orderedList} onClick={(current) => { current.chain().focus().toggleOrderedList().run() }}><ListOrdered /></EditorButton>\n <div className=\"min-w-52\">\n <Select value={token} onValueChange={(value) => {\n setToken(value)\n editor?.chain().focus().insertContent(value).run()\n window.setTimeout(() => setToken(undefined), 0)\n }}>\n <SelectTrigger aria-label={t('documents.templates.editor.insertField')}><SelectValue placeholder={t('documents.templates.editor.insertField')} /></SelectTrigger>\n <SelectContent>{tokenOptions.map((value) => <SelectItem key={value} value={value}>{value}</SelectItem>)}</SelectContent>\n </Select>\n </div>\n </div>\n <EditorContent editor={editor} className=\"max-w-none p-4 text-foreground [&_.ProseMirror]:min-h-80 [&_.ProseMirror]:focus-visible:outline-none\" />\n </div>\n </div>\n )\n}\n"],
|
|
5
|
+
"mappings": ";AA6BS,cAuDG,YAvDH;AA3BT,YAAY,WAAW;AACvB,SAAS,qCAAqC;AAE9C,SAAS,eAAe,WAAW,sBAAsB;AACzD,SAAS,MAAM,UAAU,UAAU,QAAQ,MAAM,mBAAmB;AACpE,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AACtB,SAAS,QAAQ,eAAe,YAAY,eAAe,mBAAmB;AAC9E,SAAS,YAAY;AACrB,SAAS,mCAAmC;AAE5C,MAAM,8BA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AAE,GAAG,8BAAC,YAAS,GAAE;AAAA,QAC5M,oBAAC,gBAAa,QAAgB,OAAO,EAAE,qCAAqC,GAAG,QAAQ,YAAY,YAAY,SAAS,CAAC,YAAY;AAAE,kBAAQ,MAAM,EAAE,MAAM,EAAE,iBAAiB,EAAE,IAAI;AAAA,QAAE,GAAG,8BAAC,QAAK,GAAE;AAAA,QACnM,oBAAC,gBAAa,QAAgB,OAAO,EAAE,sCAAsC,GAAG,QAAQ,YAAY,aAAa,SAAS,CAAC,YAAY;AAAE,kBAAQ,MAAM,EAAE,MAAM,EAAE,kBAAkB,EAAE,IAAI;AAAA,QAAE,GAAG,8BAAC,eAAY,GAAE;AAAA,QAC7M,oBAAC,SAAI,WAAU,YACb,+BAAC,UAAO,OAAO,OAAO,eAAe,CAAC,UAAU;AAC9C,mBAAS,KAAK;AACd,kBAAQ,MAAM,EAAE,MAAM,EAAE,cAAc,KAAK,EAAE,IAAI;AACjD,iBAAO,WAAW,MAAM,SAAS,MAAS,GAAG,CAAC;AAAA,QAChD,GACE;AAAA,8BAAC,iBAAc,cAAY,EAAE,wCAAwC,GAAG,8BAAC,eAAY,aAAa,EAAE,wCAAwC,GAAG,GAAE;AAAA,UACjJ,oBAAC,iBAAe,uBAAa,IAAI,CAAC,UAAU,oBAAC,cAAuB,OAAe,mBAAtB,KAA4B,CAAa,GAAE;AAAA,WAC1G,GACF;AAAA,SACF;AAAA,MACA,oBAAC,iBAAc,QAAgB,WAAU,wGAAuG;AAAA,OAClJ;AAAA,KACF;AAEJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
3
3
|
import * as React from "react";
|
|
4
|
+
import { useContentSecurityPolicyNonce } from "@open-mercato/ui/theme/ContentSecurityPolicyProvider";
|
|
4
5
|
import { EditorContent, useEditor } from "@tiptap/react";
|
|
5
6
|
import { Alert, AlertDescription, AlertTitle } from "@open-mercato/ui/primitives/alert";
|
|
6
7
|
import { LoadingMessage } from "@open-mercato/ui/backend/detail";
|
|
7
8
|
import { useT } from "@open-mercato/shared/lib/i18n/context";
|
|
8
9
|
import { getDocumentEditorExtensions } from "../../../lib/editorConfig.js";
|
|
9
10
|
function PreviewSurface({ html, fallbackLabel }) {
|
|
11
|
+
const nonce = useContentSecurityPolicyNonce();
|
|
10
12
|
const editor = useEditor({
|
|
13
|
+
injectNonce: nonce,
|
|
11
14
|
extensions: getDocumentEditorExtensions({ entityRefFallbackLabel: fallbackLabel }),
|
|
12
15
|
content: html,
|
|
13
16
|
editable: false,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/documents/backend/documents/components/TemplatePreview.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { EditorContent, useEditor } from '@tiptap/react'\nimport { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'\nimport { LoadingMessage } from '@open-mercato/ui/backend/detail'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { getDocumentEditorExtensions } from '../../../lib/editorConfig'\nimport type { TemplatePreviewResult } from './templateUi'\n\nfunction PreviewSurface({ html, fallbackLabel }: { html: string; fallbackLabel: string }) {\n const editor = useEditor({\n extensions: getDocumentEditorExtensions({ entityRefFallbackLabel: fallbackLabel }),\n content: html,\n editable: false,\n editorProps: { attributes: { class: 'min-h-48 text-base leading-7 text-foreground focus-visible:outline-none' } },\n }, [fallbackLabel])\n React.useEffect(() => { editor?.commands.setContent(html) }, [editor, html])\n return <EditorContent editor={editor} className=\"max-w-none rounded-md border border-border bg-card p-4\" />\n}\n\nexport function TemplatePreview({ preview, isLoading }: { preview: TemplatePreviewResult | null; isLoading: boolean }) {\n const t = useT()\n if (isLoading) return <LoadingMessage label={t('documents.templates.preview.loading')} />\n if (!preview) {\n return (\n <div className=\"rounded-md border border-dashed border-border p-4 text-sm text-muted-foreground\">\n {t('documents.templates.preview.empty')}\n </div>\n )\n }\n return (\n <div className=\"space-y-3\">\n {preview.unresolvedTokens.length > 0 ? (\n <Alert status=\"warning\">\n <AlertTitle>{t('documents.templates.preview.unresolvedTitle')}</AlertTitle>\n <AlertDescription>{t('documents.templates.preview.unresolvedBody', { tokens: preview.unresolvedTokens.join(', ') })}</AlertDescription>\n </Alert>\n ) : null}\n <PreviewSurface html={preview.contentHtml} fallbackLabel={t('documents.editor.entityRef.fallbackLabel')} />\n </div>\n )\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'\nimport { EditorContent, useEditor } from '@tiptap/react'\nimport { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'\nimport { LoadingMessage } from '@open-mercato/ui/backend/detail'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { getDocumentEditorExtensions } from '../../../lib/editorConfig'\nimport type { TemplatePreviewResult } from './templateUi'\n\nfunction PreviewSurface({ html, fallbackLabel }: { html: string; fallbackLabel: string }) {\n const nonce = useContentSecurityPolicyNonce()\n const editor = useEditor({\n injectNonce: nonce,\n extensions: getDocumentEditorExtensions({ entityRefFallbackLabel: fallbackLabel }),\n content: html,\n editable: false,\n editorProps: { attributes: { class: 'min-h-48 text-base leading-7 text-foreground focus-visible:outline-none' } },\n }, [fallbackLabel])\n React.useEffect(() => { editor?.commands.setContent(html) }, [editor, html])\n return <EditorContent editor={editor} className=\"max-w-none rounded-md border border-border bg-card p-4\" />\n}\n\nexport function TemplatePreview({ preview, isLoading }: { preview: TemplatePreviewResult | null; isLoading: boolean }) {\n const t = useT()\n if (isLoading) return <LoadingMessage label={t('documents.templates.preview.loading')} />\n if (!preview) {\n return (\n <div className=\"rounded-md border border-dashed border-border p-4 text-sm text-muted-foreground\">\n {t('documents.templates.preview.empty')}\n </div>\n )\n }\n return (\n <div className=\"space-y-3\">\n {preview.unresolvedTokens.length > 0 ? (\n <Alert status=\"warning\">\n <AlertTitle>{t('documents.templates.preview.unresolvedTitle')}</AlertTitle>\n <AlertDescription>{t('documents.templates.preview.unresolvedBody', { tokens: preview.unresolvedTokens.join(', ') })}</AlertDescription>\n </Alert>\n ) : null}\n <PreviewSurface html={preview.contentHtml} fallbackLabel={t('documents.editor.entityRef.fallbackLabel')} />\n </div>\n )\n}\n"],
|
|
5
|
+
"mappings": ";AAqBS,cAgBD,YAhBC;AAnBT,YAAY,WAAW;AACvB,SAAS,qCAAqC;AAC9C,SAAS,eAAe,iBAAiB;AACzC,SAAS,OAAO,kBAAkB,kBAAkB;AACpD,SAAS,sBAAsB;AAC/B,SAAS,YAAY;AACrB,SAAS,mCAAmC;AAG5C,SAAS,eAAe,EAAE,MAAM,cAAc,GAA4C;AACxF,QAAM,QAAQ,8BAA8B;AAC5C,QAAM,SAAS,UAAU;AAAA,IACvB,aAAa;AAAA,IACb,YAAY,4BAA4B,EAAE,wBAAwB,cAAc,CAAC;AAAA,IACjF,SAAS;AAAA,IACT,UAAU;AAAA,IACV,aAAa,EAAE,YAAY,EAAE,OAAO,0EAA0E,EAAE;AAAA,EAClH,GAAG,CAAC,aAAa,CAAC;AAClB,QAAM,UAAU,MAAM;AAAE,YAAQ,SAAS,WAAW,IAAI;AAAA,EAAE,GAAG,CAAC,QAAQ,IAAI,CAAC;AAC3E,SAAO,oBAAC,iBAAc,QAAgB,WAAU,0DAAyD;AAC3G;AAEO,SAAS,gBAAgB,EAAE,SAAS,UAAU,GAAkE;AACrH,QAAM,IAAI,KAAK;AACf,MAAI,UAAW,QAAO,oBAAC,kBAAe,OAAO,EAAE,qCAAqC,GAAG;AACvF,MAAI,CAAC,SAAS;AACZ,WACE,oBAAC,SAAI,WAAU,mFACZ,YAAE,mCAAmC,GACxC;AAAA,EAEJ;AACA,SACE,qBAAC,SAAI,WAAU,aACZ;AAAA,YAAQ,iBAAiB,SAAS,IACjC,qBAAC,SAAM,QAAO,WACZ;AAAA,0BAAC,cAAY,YAAE,6CAA6C,GAAE;AAAA,MAC9D,oBAAC,oBAAkB,YAAE,8CAA8C,EAAE,QAAQ,QAAQ,iBAAiB,KAAK,IAAI,EAAE,CAAC,GAAE;AAAA,OACtH,IACE;AAAA,IACJ,oBAAC,kBAAe,MAAM,QAAQ,aAAa,eAAe,EAAE,0CAA0C,GAAG;AAAA,KAC3G;AAEJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
} from "../data/validators.js";
|
|
21
21
|
import { DOCUMENTS_ENTITY_IDS } from "../lib/constants.js";
|
|
22
22
|
import { assertDocumentCommentCapacity } from "../lib/historyLimits.js";
|
|
23
|
-
import { resolveUserAccess } from "../lib/permissions.js";
|
|
23
|
+
import { resolveUserAccess, resolveUserDocumentTier } from "../lib/permissions.js";
|
|
24
24
|
import { resolveWatcherRecipients } from "../lib/watchers.js";
|
|
25
25
|
import {
|
|
26
26
|
assertDocumentCommandCapability,
|
|
@@ -462,7 +462,7 @@ const createCommentCommand = {
|
|
|
462
462
|
for (const mentionedUserId of mentionUserIds) {
|
|
463
463
|
const grantIdentity = grantIdentityByUserId.get(mentionedUserId);
|
|
464
464
|
if (!grantIdentity || !canShare) continue;
|
|
465
|
-
const tier = await
|
|
465
|
+
const tier = await resolveUserDocumentTier(em, input.documentId, input, mentionedUserId, ctx.container);
|
|
466
466
|
if (tier) continue;
|
|
467
467
|
await assertUserPrincipal(ctx.container, input, mentionedUserId);
|
|
468
468
|
let share = await loadMentionShare(em, input, mentionedUserId, true);
|