From 48667a7259fa12999df28fa823208923dd3927e1 Mon Sep 17 00:00:00 2001 From: Manasa Nandini Date: Wed, 21 Oct 2026 10:59:18 -0700 Subject: [PATCH] refactor(artifacts): simplify artifact file handling and remove unused comment features - Updated build command in CONTRIBUTING.md to increase memory limit. - Refactored artifact file handling by removing unnecessary checks for artifact paths in delete operations across multiple files. - Introduced new tests for diagram image handling in diagram-images.test.ts. - Removed deprecated comment-related components and functionality from the viewer, including virtual cursor and comments context. - Adjusted diagram node handling to exclude comments from search indexing. --- CONTRIBUTING.md | 2 +- src/artifacts/databases.ts | 8 +- src/artifacts/diagram-images.test.ts | 31 ++ src/artifacts/diagram-images.ts | 2 +- src/artifacts/docs.ts | 8 +- src/artifacts/maps.ts | 8 +- src/artifacts/queries.ts | 13 +- src/artifacts/write.test.ts | 46 +- src/artifacts/write.ts | 38 +- viewer/src/components/virtual-cursor.tsx | 39 -- viewer/src/features/comments/api/comments.ts | 52 -- .../comments/components/input-editor.tsx | 75 --- .../comments/contexts/comments-context.tsx | 117 ---- .../comments/hooks/use-tiptap-editor.ts | 252 --------- .../diagram-portal/helpers/search-index.ts | 2 +- .../left-sidebar/left-sidebar.tsx | 20 - .../left-sidebar/panel-comments.tsx | 505 ------------------ .../diagram-portal/nodes/comment-node.tsx | 247 --------- .../nodes/components/comment-item.tsx | 215 -------- .../nodes/components/comment-panel.tsx | 191 ------- .../nodes/components/comment-preview.tsx | 81 --- .../nodes/helpers/comment-helpers.ts | 71 --- .../features/diagram-portal/nodes/index.ts | 3 - .../diagram-portal/properties/index.tsx | 2 +- .../diagram-portal/react-flow-wrapper.tsx | 49 +- 25 files changed, 108 insertions(+), 1969 deletions(-) create mode 100644 src/artifacts/diagram-images.test.ts delete mode 100644 viewer/src/components/virtual-cursor.tsx delete mode 100644 viewer/src/features/comments/api/comments.ts delete mode 100644 viewer/src/features/comments/components/input-editor.tsx delete mode 100644 viewer/src/features/comments/contexts/comments-context.tsx delete mode 100644 viewer/src/features/comments/hooks/use-tiptap-editor.ts delete mode 100644 viewer/src/features/diagram-portal/left-sidebar/panel-comments.tsx delete mode 100644 viewer/src/features/diagram-portal/nodes/comment-node.tsx delete mode 100644 viewer/src/features/diagram-portal/nodes/components/comment-item.tsx delete mode 100644 viewer/src/features/diagram-portal/nodes/components/comment-panel.tsx delete mode 100644 viewer/src/features/diagram-portal/nodes/components/comment-preview.tsx delete mode 100644 viewer/src/features/diagram-portal/nodes/helpers/comment-helpers.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 49b3e0e..45ebab6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,7 +26,7 @@ UIGraph currently links a sibling `uigraph-lens` package (`link:../uigraph-lens` ```sh cd uigraph-lens && pnpm install && pnpm build -cd ../uigraph && pnpm install && pnpm build +cd ../uigraph && pnpm install && NODE_OPTIONS=--max-old-space-size=8192 pnpm build node dist/bin.mjs ``` diff --git a/src/artifacts/databases.ts b/src/artifacts/databases.ts index 721bc9e..e38d1c9 100644 --- a/src/artifacts/databases.ts +++ b/src/artifacts/databases.ts @@ -1,11 +1,7 @@ import path from 'node:path' import { exists, loadValid } from './docs.js' import { DATABASE_DIALECTS, parseDatabaseSchema, slugify } from './load.js' -import { - deleteArtifactFile, - isArtifactPath, - writeArtifactFile, -} from './write.js' +import { deleteArtifactFile, writeArtifactFile } from './write.js' import { appendItem, applyEdits, @@ -103,7 +99,7 @@ export async function deleteDatabase( const stillUsed = db.databases.some( (d) => d !== database && d.entry.schemaPath === database.entry.schemaPath ) - if (isArtifactPath(database.entry.schemaPath) && !stillUsed) { + if (!stillUsed) { await deleteArtifactFile(root, database.entry.schemaPath) } } diff --git a/src/artifacts/diagram-images.test.ts b/src/artifacts/diagram-images.test.ts new file mode 100644 index 0000000..a8593f8 --- /dev/null +++ b/src/artifacts/diagram-images.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { createRepo } from '../test-repo.js' +import { listDiagramImages, writeDiagramImage } from './diagram-images.js' + +describe('listDiagramImages', () => { + it.each(['./diagram/a.mmd', 'diagram/a.mmd'])( + 'returns a clean path for %s', + async (diagramPath) => { + const root = await createRepo({ 'diagram/images/shot.png': 'png' }) + const images = await listDiagramImages(root, diagramPath) + expect(images.map((image) => image.imagePath)).toEqual([ + 'diagram/images/shot.png', + ]) + } + ) +}) + +describe('writeDiagramImage', () => { + it('saves an upload next to a diagram outside .uigraph', async () => { + const root = await createRepo({ 'diagram/a.mmd': 'flowchart LR\n' }) + const imagePath = await writeDiagramImage( + root, + './diagram/a.mmd', + 'My Shot.png', + { data: Buffer.from('png'), contentType: 'image/png' } + ) + expect(imagePath).toBe('diagram/images/my-shot.png') + const images = await listDiagramImages(root, './diagram/a.mmd') + expect(images.map((image) => image.imagePath)).toEqual([imagePath]) + }) +}) diff --git a/src/artifacts/diagram-images.ts b/src/artifacts/diagram-images.ts index 79fe9b4..d8acddc 100644 --- a/src/artifacts/diagram-images.ts +++ b/src/artifacts/diagram-images.ts @@ -11,7 +11,7 @@ const DIAGRAM_IMAGE_EXTENSIONS: Record = { } function imageDirectory(diagramPath: string) { - return `${path.posix.dirname(diagramPath)}/images` + return path.posix.join(path.posix.dirname(diagramPath), 'images') } export async function listDiagramImages(root: string, diagramPath: string) { diff --git a/src/artifacts/docs.ts b/src/artifacts/docs.ts index cdb115b..ff0f74b 100644 --- a/src/artifacts/docs.ts +++ b/src/artifacts/docs.ts @@ -1,11 +1,7 @@ import fs from 'node:fs/promises' import path from 'node:path' import { loadArtifacts, slugify } from './load.js' -import { - deleteArtifactFile, - isArtifactPath, - writeArtifactFile, -} from './write.js' +import { deleteArtifactFile, writeArtifactFile } from './write.js' import { appendItem, applyEdits, @@ -107,7 +103,7 @@ export async function deleteDoc( const stillUsed = allDocs.some( (d) => d !== doc && d.entry.path === doc.entry.path ) - if (isArtifactPath(doc.entry.path) && !stillUsed) { + if (!stillUsed) { await deleteArtifactFile(root, doc.entry.path) } } diff --git a/src/artifacts/maps.ts b/src/artifacts/maps.ts index ddad567..bccf222 100644 --- a/src/artifacts/maps.ts +++ b/src/artifacts/maps.ts @@ -10,11 +10,7 @@ import { type CanvasFile, type MapEntry, } from './load.js' -import { - deleteArtifactFile, - isArtifactPath, - writeArtifactFile, -} from './write.js' +import { deleteArtifactFile, writeArtifactFile } from './write.js' import { appendItem, applyEdits, @@ -168,7 +164,7 @@ export async function deleteUnusedImages( ) ) for (const imagePath of imagePaths) { - if (isArtifactPath(imagePath) && !used.has(imagePath)) { + if (!used.has(imagePath)) { await deleteArtifactFile(root, imagePath) } } diff --git a/src/artifacts/queries.ts b/src/artifacts/queries.ts index fc4c884..d0f9e3d 100644 --- a/src/artifacts/queries.ts +++ b/src/artifacts/queries.ts @@ -1,10 +1,6 @@ import { loadValid } from './docs.js' import { slugify } from './load.js' -import { - deleteArtifactFile, - isArtifactPath, - writeArtifactFile, -} from './write.js' +import { deleteArtifactFile, writeArtifactFile } from './write.js' import { appendItem, applyEdits, @@ -100,11 +96,6 @@ export async function updateQuery( ) const { description, tags, queryText, path, ...rest } = query.entry if (path !== undefined) { - if (!isArtifactPath(path)) { - throw new Error( - `The query file ${path} is outside .uigraph and cannot be edited` - ) - } await writeArtifactFile(root, path, input.queryText) } const { source, document } = await readYaml(root, query.file) @@ -141,7 +132,7 @@ export async function deleteQuery( ) const path = query.entry.path const stillUsed = db.queries.some((q) => q !== query && q.entry.path === path) - if (path !== undefined && isArtifactPath(path) && !stillUsed) { + if (path !== undefined && !stillUsed) { await deleteArtifactFile(root, path) } } diff --git a/src/artifacts/write.test.ts b/src/artifacts/write.test.ts index 199b7c8..e9ef530 100644 --- a/src/artifacts/write.test.ts +++ b/src/artifacts/write.test.ts @@ -24,12 +24,8 @@ describe('writeArtifactFile', () => { it.each([ ['../outside.txt', 'Path must be relative to the repository'], ['/etc/passwd', 'Path must be relative to the repository'], - [ - '.uigraph/../src/index.ts', - 'Only .uigraph.yaml and files under .uigraph/', - ], - ['src/index.ts', 'Only .uigraph.yaml and files under .uigraph/'], - ['.uigraph/', 'Only .uigraph.yaml and files under .uigraph/'], + ['.uigraph/', 'Not a writable file path'], + ['.git/config', 'Not a writable file path'], ])('refuses %s', async (requested, message) => { const root = await createRepo({}) await expect(writeArtifactFile(root, requested, 'x')).rejects.toThrow( @@ -37,6 +33,14 @@ describe('writeArtifactFile', () => { ) }) + it('writes files outside .uigraph', async () => { + const root = await createRepo({}) + expect(await writeArtifactFile(root, './diagram/a.mmd', 'hi')).toBe( + 'diagram/a.mmd' + ) + expect(await readRepoFile(root, 'diagram/a.mmd')).toBe('hi') + }) + it('refuses to write through a symbolic link', async () => { const root = await createRepo({}) const outside = await createRepo({}) @@ -63,6 +67,15 @@ describe('deleteArtifactFile', () => { }) }) +describe('deleteArtifactFile outside .uigraph', () => { + it('removes the file and its empty folders', async () => { + const root = await createRepo({ 'diagram/a/b.mmd': 'x', 'keep.txt': 'y' }) + await deleteArtifactFile(root, 'diagram/a/b.mmd') + await expect(fs.readdir(root)).resolves.not.toContain('diagram') + expect(await readRepoFile(root, 'keep.txt')).toBe('y') + }) +}) + describe('diagrams', () => { it('creates a diagram with its own folder', async () => { const root = await createRepo({ @@ -160,6 +173,27 @@ describe('diagrams', () => { ).rejects.toThrow('ENOENT') }) + it("keeps a shared folder's images when deleting one diagram", async () => { + const root = await createRepo({ + '.uigraph.yaml': `version: 1 +architectureDiagrams: + - name: A + path: diagram/a.mmd + - name: B + path: diagram/b.mmd +`, + 'diagram/a.mmd': 'flowchart LR\n X --> Y\n', + 'diagram/b.mmd': 'flowchart LR\n X --> Y\n', + 'diagram/images/shot.png': 'png', + }) + await deleteDiagram(root, '.uigraph.yaml', 'diagram-a-mmd') + await expect( + fs.readFile(path.join(root, 'diagram/a.mmd')) + ).rejects.toThrow() + expect(await readRepoFile(root, 'diagram/images/shot.png')).toBe('png') + expect(await readRepoFile(root, 'diagram/b.mmd')).toContain('X') + }) + it('renames references to a diagram in maps', async () => { const root = await createRepo({ '.uigraph.yaml': `version: 1 diff --git a/src/artifacts/write.ts b/src/artifacts/write.ts index df4c080..0b96255 100644 --- a/src/artifacts/write.ts +++ b/src/artifacts/write.ts @@ -11,7 +11,7 @@ import fs from 'node:fs/promises' import path from 'node:path' import { isMap, isScalar, stringify, visit, type Node as YamlNode } from 'yaml' import { listDiagramImages } from './diagram-images.js' -import { contentHash, loadArtifacts, ROOT_CONFIG, slugify } from './load.js' +import { contentHash, loadArtifacts, slugify } from './load.js' import { appendItem, applyEdits, @@ -24,11 +24,7 @@ import { const MAX_WRITE_BYTES = 2_000_000 export const MAX_UPLOAD_BYTES = 50_000_000 -export function isArtifactPath(relativePath: string) { - return relativePath === ROOT_CONFIG || relativePath.startsWith('.uigraph/') -} - -function toArtifactPath(requested: string) { +function toRepoPath(requested: string) { const relativePath = path.posix .normalize(requested.replaceAll('\\', '/')) .replace(/^\.\//, '') @@ -38,16 +34,19 @@ function toArtifactPath(requested: string) { ) { throw new Error(`Path must be relative to the repository: ${requested}`) } - if (!isArtifactPath(relativePath) || relativePath.endsWith('/')) { - throw new Error( - `Only ${ROOT_CONFIG} and files under .uigraph/ can be written: ${requested}` - ) + if ( + relativePath === '' || + relativePath === '.' || + relativePath.endsWith('/') || + relativePath.split('/')[0] === '.git' + ) { + throw new Error(`Not a writable file path: ${requested}`) } return relativePath } export async function deleteArtifactFile(root: string, requested: string) { - const relativePath = toArtifactPath(requested) + const relativePath = toRepoPath(requested) let current = root for (const segment of relativePath.split('/')) { current = path.join(current, segment) @@ -59,10 +58,9 @@ export async function deleteArtifactFile(root: string, requested: string) { } } await fs.rm(current) - const artifactRoot = path.join(root, '.uigraph') for ( let directory = path.dirname(current); - directory.startsWith(`${artifactRoot}${path.sep}`); + directory !== root && directory !== path.join(root, '.uigraph'); directory = path.dirname(directory) ) { if ((await fs.readdir(directory)).length > 0) { @@ -77,7 +75,7 @@ export async function writeArtifactFile( requested: string, content: string | Buffer ) { - const relativePath = toArtifactPath(requested) + const relativePath = toRepoPath(requested) const limit = typeof content === 'string' ? MAX_WRITE_BYTES : MAX_UPLOAD_BYTES if (Buffer.byteLength(content) > limit) { throw new Error(`Content is larger than ${limit} bytes`) @@ -311,7 +309,15 @@ export async function deleteDiagram( if (diagram === undefined) { throw new Error(`Diagram ${diagramId} not found`) } - const images = await listDiagramImages(root, diagram.entry.path) + const sharesFolder = db.diagrams.some( + (d) => + d !== diagram && + path.posix.dirname(d.entry.path) === + path.posix.dirname(diagram.entry.path) + ) + const images = sharesFolder + ? [] + : await listDiagramImages(root, diagram.entry.path) const { source, document } = await readYaml(root, diagram.file) await writeArtifactFile( root, @@ -325,7 +331,7 @@ export async function deleteDiagram( diagram.entry.contextPath, ...images.map((image) => image.imagePath), ]) { - if (file !== undefined && isArtifactPath(file)) { + if (file !== undefined) { await deleteArtifactFile(root, file) } } diff --git a/viewer/src/components/virtual-cursor.tsx b/viewer/src/components/virtual-cursor.tsx deleted file mode 100644 index 8f1c9fa..0000000 --- a/viewer/src/components/virtual-cursor.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { useEffect, useState } from 'react' -import { GoComment } from 'react-icons/go' - -export function VirtualCursor() { - const [position, setPosition] = useState({ x: 0, y: 0 }) - const [isOverPane, setIsOverPane] = useState(false) - - useEffect(() => { - function handleMouseMove(event: MouseEvent) { - const target = event.target as HTMLElement | null - setIsOverPane(!!target?.closest('.react-flow__pane')) - setPosition({ x: event.clientX, y: event.clientY }) - } - - window.addEventListener('mousemove', handleMouseMove) - - return () => { - window.removeEventListener('mousemove', handleMouseMove) - } - }, []) - - if (!isOverPane) return null - - return ( -
-
- -
-
- ) -} diff --git a/viewer/src/features/comments/api/comments.ts b/viewer/src/features/comments/api/comments.ts deleted file mode 100644 index 160ec48..0000000 --- a/viewer/src/features/comments/api/comments.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { graphql } from '@/api' - -export type UIComment = { - commentId: string - resourceId: string - parentCommentId?: string | null - text: string - createdBy: string - createdAt: string - authorName?: string | null - authorAvatarUrl?: string | null -} - -export const COMMENTS = graphql(` - query Comments($orgId: ID!, $resourceId: ID!) { - comments(orgId: $orgId, resourceId: $resourceId) { - id - resourceId - parentCommentId - text - createdBy - createdAt - createdByActor { - id - name - avatarUrl - } - } - } -`) - -export const CREATE_COMMENT = graphql(` - mutation CreateComment($orgId: ID!, $input: CreateCommentInput!) { - createComment(orgId: $orgId, input: $input) { - id - } - } -`) - -export const UPDATE_COMMENT = graphql(` - mutation UpdateComment($orgId: ID!, $id: ID!, $input: UpdateCommentInput!) { - updateComment(orgId: $orgId, id: $id, input: $input) { - id - } - } -`) - -export const DELETE_COMMENT = graphql(` - mutation DeleteComment($orgId: ID!, $id: ID!) { - deleteComment(orgId: $orgId, id: $id) - } -`) diff --git a/viewer/src/features/comments/components/input-editor.tsx b/viewer/src/features/comments/components/input-editor.tsx deleted file mode 100644 index 70b8cc6..0000000 --- a/viewer/src/features/comments/components/input-editor.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import { cn } from '@/lib/utils' -import { EditorContent } from '@tiptap/react' -import { useTiptapEditor } from '../hooks/use-tiptap-editor' - -const darkEditorClassName = - 'border-[#2A3242] bg-[#1E2533] text-[#F4F7FC] shadow-none ring-0 focus-within:ring-0 [&_.ProseMirror]:text-[#F4F7FC] [&_.ProseMirror_p.is-editor-empty:first-child::before]:text-[#828DA3] [&_.mention]:bg-[#3B6BFF]/20 [&_.mention]:text-[#93B4FF]' - -export function InputEditor({ - value, - setValue, - className, - forceFocus = false, - theme = 'default', -}: { - value: string - setValue: (value: string) => void - className?: string - forceFocus?: boolean - theme?: 'default' | 'dark' -}) { - const editor = useTiptapEditor({ value, setValue, theme }) - - return ( -
{ - if (forceFocus) { - e.stopPropagation() - e.nativeEvent.stopImmediatePropagation() - } - }} - onDrop={(e) => { - if (forceFocus) { - e.stopPropagation() - e.nativeEvent.stopImmediatePropagation() - } - }} - > - -
- ) -} - -export function InputRenderer({ - value, - theme = 'default', -}: { - value: string - theme?: 'default' | 'dark' -}) { - const editor = useTiptapEditor({ - value, - setValue: () => {}, - editable: false, - theme, - }) - return ( - - ) -} diff --git a/viewer/src/features/comments/contexts/comments-context.tsx b/viewer/src/features/comments/contexts/comments-context.tsx deleted file mode 100644 index 302084e..0000000 --- a/viewer/src/features/comments/contexts/comments-context.tsx +++ /dev/null @@ -1,117 +0,0 @@ -import { useCurrentOrganization } from '@/store/auth-store' -import { useMutation, useQuery } from '@apollo/client' -import { arrayNonNullable } from 'daily-code' -import { createContext } from 'daily-code/react' -import { useCallback, useMemo, useState } from 'react' -import { - COMMENTS, - CREATE_COMMENT, - DELETE_COMMENT, - UPDATE_COMMENT, - type UIComment, -} from '../api/comments' - -export const [CommentsContextProvider, useCommentsContext] = createContext( - ({ resourceId }: { resourceId: string }) => { - const orgId = useCurrentOrganization()?.id - const [replyToCommentId, setReplyToCommentId] = useState( - null - ) - - const { data, loading } = useQuery(COMMENTS, { - fetchPolicy: 'cache-first', - variables: { orgId: orgId!, resourceId }, - skip: !orgId, - }) - - const refetchQueries = [ - { query: COMMENTS, variables: { orgId: orgId!, resourceId } }, - ] - - const [createCommentMutation] = useMutation(CREATE_COMMENT, { - awaitRefetchQueries: true, - refetchQueries, - }) - - const [updateCommentMutation] = useMutation(UPDATE_COMMENT, { - awaitRefetchQueries: true, - refetchQueries, - }) - - const [deleteCommentMutation] = useMutation(DELETE_COMMENT, { - awaitRefetchQueries: true, - refetchQueries, - }) - - const comments = useMemo(() => { - return arrayNonNullable(data?.comments) - .map((c) => ({ - commentId: c.id, - resourceId: c.resourceId, - parentCommentId: c.parentCommentId, - text: c.text, - createdBy: c.createdBy, - createdAt: c.createdAt, - authorName: c.createdByActor?.name, - authorAvatarUrl: c.createdByActor?.avatarUrl, - })) - .sort( - (a, b) => - new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime() - ) - }, [data]) - - const createComment = useCallback( - async (input: { text: string; parentCommentId?: string | null }) => { - if (!orgId) return - await createCommentMutation({ - variables: { - orgId, - input: { - resourceId, - text: input.text, - ...(input.parentCommentId - ? { parentCommentId: input.parentCommentId } - : {}), - }, - }, - }) - }, - [orgId, resourceId, createCommentMutation] - ) - - const updateComment = useCallback( - async (commentId: string, text: string) => { - if (!orgId) return - await updateCommentMutation({ - variables: { orgId, id: commentId, input: { text } }, - }) - }, - [orgId, updateCommentMutation] - ) - - const deleteComment = useCallback( - async (commentId: string) => { - if (!orgId) return - await deleteCommentMutation({ - variables: { orgId, id: commentId }, - }) - }, - [orgId, deleteCommentMutation] - ) - - return { - resourceId, - - comments, - isLoading: loading && !data?.comments, - - createComment, - updateComment, - deleteComment, - - replyToCommentId, - setReplyToCommentId, - } - } -) diff --git a/viewer/src/features/comments/hooks/use-tiptap-editor.ts b/viewer/src/features/comments/hooks/use-tiptap-editor.ts deleted file mode 100644 index f6bb525..0000000 --- a/viewer/src/features/comments/hooks/use-tiptap-editor.ts +++ /dev/null @@ -1,252 +0,0 @@ -import { MEMBERS } from '@/features/dashboard-settings/api/members' -import { useCurrentOrganization } from '@/store/auth-store' -import { useQuery } from '@apollo/client' -import Mention, { - MentionNodeAttrs, - MentionOptions, -} from '@tiptap/extension-mention' -import Placeholder from '@tiptap/extension-placeholder' -import { useEditor } from '@tiptap/react' -import StarterKit from '@tiptap/starter-kit' -import { arrayNonNullable } from 'daily-code' -import { useEffect, useMemo } from 'react' - -type MentionItem = { id: string; label: string } -type TiptapMentionOptions = Partial< - MentionOptions -> - -type UseTiptapEditorProps = { - value: string - setValue: (value: string) => void - editable?: boolean - theme?: 'default' | 'dark' -} - -function getMentionPopupClasses(theme: 'default' | 'dark') { - if (theme === 'dark') { - return { - list: 'w-[260px] overflow-hidden rounded-md border border-[#2A3242] bg-[#141925] shadow-lg', - itemBase: - 'flex w-full items-center px-3 py-2 text-left text-sm text-[#F4F7FC]', - itemSelected: 'bg-[#1E2533]', - itemDefault: 'bg-[#141925] hover:bg-[#1E2533]', - mentionClass: - 'rounded bg-[#3B6BFF]/20 px-1 py-0.5 font-medium text-[#93B4FF]', - } - } - - return { - list: 'w-[260px] overflow-hidden rounded-md border border-gray-200 bg-white shadow-md', - itemBase: - 'flex w-full items-center px-3 py-2 text-left text-sm text-gray-900', - itemSelected: 'bg-gray-100', - itemDefault: 'bg-white hover:bg-gray-100', - mentionClass: 'rounded bg-blue-50 px-1 py-0.5 font-medium text-blue-700', - } -} - -function safeParse(value: string) { - try { - return JSON.parse(value) - } catch { - return '' - } -} - -export function useTiptapEditor({ - value, - setValue, - editable = true, - theme = 'default', -}: UseTiptapEditorProps) { - const organizationId = useCurrentOrganization()?.id - const mentionPopupClasses = getMentionPopupClasses(theme) - - const { data } = useQuery(MEMBERS, { - fetchPolicy: 'cache-first', - variables: { orgId: organizationId! }, - skip: !organizationId, - }) - - const users = useMemo(() => { - const organizationUsers = arrayNonNullable(data?.members) - return organizationUsers.map((user) => ({ - id: user.email, - label: user.email, - })) as MentionItem[] - }, [data?.members]) - - const editor = useEditor( - { - editable, - immediatelyRender: false, - extensions: [ - StarterKit.configure({ - heading: false, - blockquote: false, - code: false, - codeBlock: false, - bulletList: false, - orderedList: false, - listItem: false, - horizontalRule: false, - }), - - ...(!editable - ? [] - : [ - Placeholder.configure({ - placeholder: 'Add a comment...', - }), - ]), - - Mention.configure({ - HTMLAttributes: { - class: mentionPopupClasses.mentionClass, - }, - suggestion: { - items({ query }) { - const q = query.trim().toLowerCase() - return q - ? users.filter((user) => user.label.toLowerCase().includes(q)) - : users - }, - - render() { - let popup: HTMLDivElement | null = null - let selectedIndex = 0 - let currentItems: MentionItem[] = [] - let currentCommand: ((item: MentionItem) => void) | null = null - let currentClientRect: (() => DOMRect | null) | null = null - - function update(props: { - items: MentionItem[] - command: (item: MentionItem) => void - clientRect?: (() => DOMRect | null) | null - }) { - if (!popup) return - - currentItems = props.items - currentCommand = props.command - currentClientRect = props.clientRect ?? null - - const rect = currentClientRect?.() - if (rect) { - popup.style.left = `${rect.left}px` - popup.style.top = `${rect.bottom + 6}px` - } - - popup.textContent = '' - if (!currentItems.length) return - - const list = document.createElement('div') - list.className = mentionPopupClasses.list - - if (selectedIndex >= currentItems.length) selectedIndex = 0 - - for (let index = 0; index < currentItems.length; index++) { - const item = currentItems[index] - const button = document.createElement('button') - button.type = 'button' - button.className = - mentionPopupClasses.itemBase + - ' ' + - (index === selectedIndex - ? mentionPopupClasses.itemSelected - : mentionPopupClasses.itemDefault) - button.textContent = item.label - button.onmousedown = (event) => { - event.preventDefault() - currentCommand?.(item) - } - list.appendChild(button) - } - - popup.appendChild(list) - } - - return { - onStart: (props) => { - selectedIndex = 0 - popup = document.createElement('div') - popup.className = 'fixed z-50' - document.body.appendChild(popup) - update(props) - }, - onUpdate: (props) => { - update(props) - }, - onKeyDown: (props) => { - if (props.event.key === 'Escape') { - popup?.remove() - popup = null - return true - } - - if (props.event.key === 'ArrowDown') { - if (!currentItems.length) return true - selectedIndex = (selectedIndex + 1) % currentItems.length - update({ - items: currentItems, - command: currentCommand || (() => {}), - clientRect: currentClientRect, - }) - return true - } - - if (props.event.key === 'ArrowUp') { - if (!currentItems.length) return true - selectedIndex = - (selectedIndex - 1 + currentItems.length) % - currentItems.length - update({ - items: currentItems, - command: currentCommand || (() => {}), - clientRect: currentClientRect, - }) - return true - } - - if (props.event.key === 'Enter') { - const item = currentItems[selectedIndex] - if (!item) return true - currentCommand?.(item) - return true - } - - return false - }, - onExit: () => { - popup?.remove() - popup = null - }, - } - }, - }, - } satisfies TiptapMentionOptions), - ], - content: safeParse(value), - onUpdate: ({ editor }) => { - const json = JSON.stringify(editor.getJSON(), null, 2) - setValue(json) - }, - }, - [theme, users, editable] - ) - - useEffect(() => { - if (!editor) return - - const prevValue = editor.getJSON() - const nextValue = safeParse(value) - - const isJSONEqual = JSON.stringify(prevValue) === JSON.stringify(nextValue) - - if (!isJSONEqual) { - editor.commands.setContent(nextValue) - } - }, [value, editor]) - - return editor -} diff --git a/viewer/src/features/diagram-portal/helpers/search-index.ts b/viewer/src/features/diagram-portal/helpers/search-index.ts index c4aa7fc..6420069 100644 --- a/viewer/src/features/diagram-portal/helpers/search-index.ts +++ b/viewer/src/features/diagram-portal/helpers/search-index.ts @@ -179,7 +179,7 @@ function buildEntry(node: Node): Omit | null { } } - if (node.type === 'image' || node.type === 'gif' || node.type === 'comment') { + if (node.type === 'image' || node.type === 'gif') { return null } diff --git a/viewer/src/features/diagram-portal/left-sidebar/left-sidebar.tsx b/viewer/src/features/diagram-portal/left-sidebar/left-sidebar.tsx index 5b4b684..4f85001 100644 --- a/viewer/src/features/diagram-portal/left-sidebar/left-sidebar.tsx +++ b/viewer/src/features/diagram-portal/left-sidebar/left-sidebar.tsx @@ -6,13 +6,11 @@ import { } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' import { BsDatabase } from 'react-icons/bs' -import { GoComment } from 'react-icons/go' import { LuCloudy, LuImage, LuShapes, LuWorkflow } from 'react-icons/lu' import { MdAnimation } from 'react-icons/md' import { RxText } from 'react-icons/rx' import { useFlowDiagramContext } from '../context/flow-diagram-context' import { SidebarAnimatedNodes } from './panel-animated-nodes' -import { SidebarComments } from './panel-comments' import { PanelDataSourcesUnified } from './panel-data-sources-unified' import { SidebarIcons } from './panel-icons' import { SidebarImages } from './panel-images' @@ -98,22 +96,6 @@ export function FloatingLeftSidebar() { } /> - } - isActive={ - sidebarActiveTool === 'comments' || - sidebarActiveTool === 'add-comment' - } - onClick={() => - setSidebarActiveTool((prev) => - prev === 'comments' || prev === 'add-comment' - ? null - : 'comments' - ) - } - /> - } @@ -134,8 +116,6 @@ export function FloatingLeftSidebar() { {sidebarActiveTool === 'animated' && } {sidebarActiveTool === 'text' && } {sidebarActiveTool === 'data-sources' && } - {(sidebarActiveTool === 'comments' || - sidebarActiveTool === 'add-comment') && } ) } diff --git a/viewer/src/features/diagram-portal/left-sidebar/panel-comments.tsx b/viewer/src/features/diagram-portal/left-sidebar/panel-comments.tsx deleted file mode 100644 index 0bbe033..0000000 --- a/viewer/src/features/diagram-portal/left-sidebar/panel-comments.tsx +++ /dev/null @@ -1,505 +0,0 @@ -import { BetterDeleteConfirmationModal } from '@/components/better-delete-confirmation-modal' -import { SuperCircleLoader } from '@/components/loader' -import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar' -import { Button } from '@/components/ui/button' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from '@/components/ui/dropdown-menu' -import { - COMMENTS, - CREATE_COMMENT, - DELETE_COMMENT, - UPDATE_COMMENT, - type UIComment, -} from '@/features/comments/api/comments' -import { - InputEditor, - InputRenderer, -} from '@/features/comments/components/input-editor' -import { cn } from '@/lib/utils' -import { useAuthStore, useCurrentOrganization } from '@/store/auth-store' -import { useMutation, useQuery } from '@apollo/client' -import { useNodes, useReactFlow } from '@xyflow/react' -import { arrayNonNullable } from 'daily-code' -import { - CrosshairIcon, - EditIcon, - MoreHorizontalIcon, - PlusIcon, - ReplyIcon, - SendIcon, - TrashIcon, -} from 'lucide-react' -import { useCallback, useEffect, useMemo, useState } from 'react' -import { useFlowDiagramContext } from '../context/flow-diagram-context' -import { formatTimeAgo } from '../nodes/helpers/comment-helpers' -import { SidebarLayout } from './sidebar-layout' - -export function SidebarComments() { - const { sidebarActiveTool, setSidebarActiveTool } = useFlowDiagramContext() - const { getNode, setCenter, setNodes } = useReactFlow() - const isAddingComment = sidebarActiveTool === 'add-comment' - - function focusComment(nodeId: string) { - const node = getNode(nodeId) - if (!node) return - - const width = node.measured?.width ?? node.width ?? 0 - const height = node.measured?.height ?? node.height ?? 0 - void setCenter(node.position.x + width / 2, node.position.y + height / 2, { - zoom: 1.5, - duration: 600, - }) - setNodes((nds) => nds.map((n) => ({ ...n, selected: n.id === nodeId }))) - } - const orgId = useCurrentOrganization()?.id - const storeUser = useAuthStore((state) => state.user) - const user = storeUser - ? { - userId: storeUser.userId, - name: storeUser.name, - avatarUrl: storeUser.avatarUrl ?? undefined, - } - : null - - const nodes = useNodes() - const commentNodeIds = nodes - .filter((node) => node.type === 'comment') - .map((node) => node.id) - const commentNodeIdsKey = commentNodeIds.join(',') - - const [byResource, setByResource] = useState>({}) - - const handleLoaded = useCallback( - (resourceId: string, comments: UIComment[]) => { - setByResource((prev) => ({ ...prev, [resourceId]: comments })) - }, - [] - ) - - const comments = useMemo(() => { - return commentNodeIdsKey - .split(',') - .filter(Boolean) - .flatMap((id) => byResource[id] ?? []) - .sort( - (a, b) => - new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime() - ) - }, [commentNodeIdsKey, byResource]) - - const resourceIdByComment = useMemo(() => { - const map: Record = {} - commentNodeIdsKey - .split(',') - .filter(Boolean) - .forEach((id) => { - ;(byResource[id] ?? []).forEach((comment) => { - map[comment.commentId] = id - }) - }) - return map - }, [commentNodeIdsKey, byResource]) - - const [createCommentMutation] = useMutation(CREATE_COMMENT) - const [updateCommentMutation] = useMutation(UPDATE_COMMENT) - const [deleteCommentMutation] = useMutation(DELETE_COMMENT) - - function refetchFor(resourceId: string) { - return { - awaitRefetchQueries: true, - refetchQueries: [ - { query: COMMENTS, variables: { orgId: orgId!, resourceId } }, - ], - } - } - - const [replyText, setReplyText] = useState('') - const [replyTo, setReplyTo] = useState<{ - commentId: string - name: string - } | null>(null) - const [isCreating, setIsCreating] = useState(false) - const [editingCommentId, setEditingCommentId] = useState(null) - const [editText, setEditText] = useState('') - const [updatingCommentId, setUpdatingCommentId] = useState( - null - ) - const [deletingCommentId, setDeletingCommentId] = useState( - null - ) - const [deleteTarget, setDeleteTarget] = useState(null) - - const lastCommentNodeId = commentNodeIds[commentNodeIds.length - 1] - - async function handleSend() { - const normalized = replyText.trim() - if (!normalized || isCreating || !user?.userId || !orgId) return - - const resourceId = replyTo - ? resourceIdByComment[replyTo.commentId] - : lastCommentNodeId - if (!resourceId) return - - setIsCreating(true) - try { - await createCommentMutation({ - variables: { - orgId, - input: { - resourceId, - text: normalized, - ...(replyTo ? { parentCommentId: replyTo.commentId } : {}), - }, - }, - ...refetchFor(resourceId), - }) - setReplyText('') - setReplyTo(null) - } finally { - setIsCreating(false) - } - } - - async function handleSaveEdit() { - const normalized = editText.trim() - if (!editingCommentId || !normalized || updatingCommentId || !orgId) return - const resourceId = resourceIdByComment[editingCommentId] - if (!resourceId) return - - setUpdatingCommentId(editingCommentId) - try { - await updateCommentMutation({ - variables: { orgId, id: editingCommentId, input: { text: normalized } }, - ...refetchFor(resourceId), - }) - setEditingCommentId(null) - setEditText('') - } finally { - setUpdatingCommentId(null) - } - } - - async function handleDelete(commentId: string) { - if (deletingCommentId || !orgId) return - const resourceId = resourceIdByComment[commentId] - if (!resourceId) return - - setDeletingCommentId(commentId) - try { - await deleteCommentMutation({ - variables: { orgId, id: commentId }, - ...refetchFor(resourceId), - }) - } finally { - setDeletingCommentId(null) - } - } - - return ( - - {commentNodeIds.map((id) => ( - - ))} - -
-
-

Comments

- -
- -
-
- {comments.length === 0 ? ( -
- No comments yet. Start the conversation! -
- ) : ( - comments.map((comment) => { - const isEditing = editingCommentId === comment.commentId - const isAuthor = user?.userId === comment.createdBy - const displayName = comment.authorName || 'User' - const parentName = comment.parentCommentId - ? comments.find( - (c) => c.commentId === comment.parentCommentId - )?.authorName - : null - const isUpdating = updatingCommentId === comment.commentId - const isDeleting = deletingCommentId === comment.commentId - - return ( -
-
- - - - {(displayName.charAt(0) || 'U').toUpperCase()} - - - -
-
- - {displayName} - - - {comment.createdAt - ? formatTimeAgo(comment.createdAt) - : ''} - -
- - {isEditing ? ( -
- -
- - -
-
- ) : ( - <> - {!!comment.parentCommentId && ( -
- Replying to{' '} - - {parentName || 'a comment'} - -
- )} -
- -
- -
- - - - - - - - - focusComment( - resourceIdByComment[comment.commentId] - ) - } - className="cursor-pointer gap-2 rounded-md px-2.5 py-2 text-sm text-[#F4F7FC] focus:bg-[#1E2533] focus:text-[#F4F7FC]" - > - - Focus Comment - - {isAuthor && ( - <> - { - setEditingCommentId(comment.commentId) - setEditText(comment.text ?? '') - }} - className="cursor-pointer gap-2 rounded-md px-2.5 py-2 text-sm text-[#F4F7FC] focus:bg-[#1E2533] focus:text-[#F4F7FC]" - > - - Edit - - - setDeleteTarget(comment.commentId) - } - className="text-destructive focus:text-destructive cursor-pointer gap-2 rounded-md px-2.5 py-2 text-sm focus:bg-[#1E2533]" - disabled={isDeleting} - > - - Delete - - - )} - - -
- - )} -
-
-
- ) - }) - )} -
-
- -
-
- {!!replyTo && ( -
-
- Replying to{' '} - - {replyTo.name} - -
- -
- )} - -
-
- -
- - -
-
-
-
- - { - if (!open) setDeleteTarget(null) - }} - title="Delete comment?" - description="This action cannot be undone." - onConfirm={async () => { - if (!deleteTarget) return - await handleDelete(deleteTarget) - setDeleteTarget(null) - }} - /> -
- ) -} - -function CommentCollector({ - orgId, - resourceId, - onLoaded, -}: { - orgId: string | undefined - resourceId: string - onLoaded: (resourceId: string, comments: UIComment[]) => void -}) { - const { data } = useQuery(COMMENTS, { - fetchPolicy: 'cache-first', - variables: { orgId: orgId!, resourceId }, - skip: !orgId, - }) - - const comments = useMemo(() => { - return arrayNonNullable(data?.comments).map((c) => ({ - commentId: c.id, - resourceId: c.resourceId, - parentCommentId: c.parentCommentId, - text: c.text, - createdBy: c.createdBy, - createdAt: c.createdAt, - authorName: c.createdByActor?.name, - authorAvatarUrl: c.createdByActor?.avatarUrl, - })) - }, [data]) - - useEffect(() => { - onLoaded(resourceId, comments) - }, [resourceId, comments, onLoaded]) - - return null -} diff --git a/viewer/src/features/diagram-portal/nodes/comment-node.tsx b/viewer/src/features/diagram-portal/nodes/comment-node.tsx deleted file mode 100644 index 5b4b2c2..0000000 --- a/viewer/src/features/diagram-portal/nodes/comment-node.tsx +++ /dev/null @@ -1,247 +0,0 @@ -import { - CommentsContextProvider, - useCommentsContext, -} from '@/features/comments/contexts/comments-context' -import { cn } from '@/lib/utils' -import { useAuthStore, useCurrentOrganization } from '@/store/auth-store' -import { Node, NodeProps, useReactFlow } from '@xyflow/react' -import { AnimatePresence, motion } from 'framer-motion' -import { useEffect, useState } from 'react' -import { CommentPanel } from './components/comment-panel' -import { CommentPreview } from './components/comment-preview' -import { NodeDataGenerator } from './types/node.types' - -export type CommentNodeData = NodeDataGenerator<{ - isResolved?: boolean -}> - -export type TCommentNode = Node - -export function CommentNode({ ...props }: NodeProps) { - return ( - - - - ) -} - -function CommentNodeContent({ ...props }: NodeProps) { - const { id, data, selected, dragging } = props - const { updateNodeData, setNodes } = useReactFlow() - const storeUser = useAuthStore((state) => state.user) - const user = storeUser - ? { - userId: storeUser.userId, - name: storeUser.name, - pic: storeUser.avatarUrl ?? undefined, - } - : null - const organizationId = useCurrentOrganization()?.id - const { comments, createComment, updateComment, deleteComment } = - useCommentsContext() - - const [isResolved, setIsResolved] = useState(data?.isResolved || false) - const [showPanel, setShowPanel] = useState(selected) - const [isHovered, setIsHovered] = useState(false) - const [replyText, setReplyText] = useState('') - const [replyToName, setReplyToName] = useState(null) - const [replyToCommentId, setReplyToCommentId] = useState(null) - const [editingCommentId, setEditingCommentId] = useState(null) - const [editText, setEditText] = useState('') - const [isCreating, setIsCreating] = useState(false) - const [updatingCommentId, setUpdatingCommentId] = useState( - null - ) - const [deletingCommentId, setDeletingCommentId] = useState( - null - ) - - function updateData(newData: Partial) { - updateNodeData(id, newData) - } - - async function addComment(content: string) { - const normalized = content.trim() - if (!normalized || !user?.userId || !organizationId) return - - await createComment({ - text: normalized, - parentCommentId: replyToCommentId ?? undefined, - }) - - setReplyText('') - } - - async function editComment(commentId: string, newContent: string) { - const normalized = newContent.trim() - if (!normalized) return - - await updateComment(commentId, normalized) - - setEditingCommentId(null) - setEditText('') - } - - async function deleteCommentById(commentId: string) { - await deleteComment(commentId) - } - - function toggleResolved() { - const newResolved = !isResolved - setIsResolved(newResolved) - updateData({ isResolved: newResolved }) - } - - async function handleReply() { - if (!replyText.trim() || isCreating) return - setIsCreating(true) - try { - await addComment(replyText) - } finally { - setIsCreating(false) - setReplyToName(null) - setReplyToCommentId(null) - } - } - - function handleReplyToAuthor(commentId: string, authorName: string) { - setReplyToName(authorName) - setReplyToCommentId(commentId) - setReplyText(`@${authorName} `) - } - - function handleCancelReply() { - setReplyToName(null) - setReplyToCommentId(null) - setReplyText('') - } - - function handleEdit(commentId: string, currentContent: string) { - setEditingCommentId(commentId) - setEditText(currentContent) - } - - async function handleSaveEdit() { - if (!editingCommentId || !editText.trim() || updatingCommentId) return - setUpdatingCommentId(editingCommentId) - try { - await editComment(editingCommentId, editText) - } finally { - setUpdatingCommentId(null) - } - } - - function handleCancelEdit() { - setEditingCommentId(null) - setEditText('') - } - - function handleEditTextChange(text: string) { - setEditText(text) - } - - async function handleDelete(commentId: string) { - if (deletingCommentId) return - setDeletingCommentId(commentId) - try { - await deleteCommentById(commentId) - } finally { - setDeletingCommentId(null) - } - } - - useEffect(() => { - setShowPanel(selected) - }, [selected]) - - return ( -
- setShowPanel(!showPanel)} - onMouseEnter={() => setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - whileHover={{ scale: 1.1 }} - whileTap={{ scale: 0.95 }} - transition={{ type: 'spring', stiffness: 400, damping: 17 }} - > - - - - - {comments.length > 0 && ( - - {comments.length} - - )} - - - - {isHovered && !selected && !dragging && ( - setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - /> - )} - - - - {selected && !dragging && ( - { - setShowPanel(false) - setNodes((nodes) => - nodes.map((n) => (n.id === id ? { ...n, selected: false } : n)) - ) - }} - onReplyTextChange={setReplyText} - onReply={handleReply} - onCancelReply={handleCancelReply} - onEdit={handleEdit} - onSaveEdit={handleSaveEdit} - onCancelEdit={handleCancelEdit} - onDelete={handleDelete} - onReplyToAuthor={handleReplyToAuthor} - onEditTextChange={handleEditTextChange} - /> - )} - -
- ) -} diff --git a/viewer/src/features/diagram-portal/nodes/components/comment-item.tsx b/viewer/src/features/diagram-portal/nodes/components/comment-item.tsx deleted file mode 100644 index 4de7607..0000000 --- a/viewer/src/features/diagram-portal/nodes/components/comment-item.tsx +++ /dev/null @@ -1,215 +0,0 @@ -import { BetterDeleteConfirmationModal } from '@/components/better-delete-confirmation-modal' -import { SuperCircleLoader } from '@/components/loader' -import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar' -import { Button } from '@/components/ui/button' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from '@/components/ui/dropdown-menu' -import type { UIComment } from '@/features/comments/api/comments' -import { - InputEditor, - InputRenderer, -} from '@/features/comments/components/input-editor' -import { cn } from '@/lib/utils' -import { motion } from 'framer-motion' -import { - EditIcon, - MoreHorizontalIcon, - ReplyIcon, - TrashIcon, -} from 'lucide-react' -import { useState } from 'react' -import { formatTimeAgo } from '../helpers/comment-helpers' - -type CommentItemProps = { - comment: UIComment - allComments: UIComment[] - editingCommentId: string | null - editText: string - user: { - userId: string - name?: string - pic?: string - } | null - updatingCommentId: string | null - deletingCommentId: string | null - onEdit: (commentId: string, currentContent: string) => void - onSaveEdit: () => void - onCancelEdit: () => void - onDelete: (commentId: string) => Promise - onReply: (commentId: string, authorName: string) => void - onEditTextChange: (text: string) => void -} - -export function CommentItem({ - comment, - allComments, - editingCommentId, - editText, - user, - updatingCommentId, - deletingCommentId, - onEdit, - onSaveEdit, - onCancelEdit, - onDelete, - onReply, - onEditTextChange, -}: CommentItemProps) { - const isEditing = editingCommentId === comment.commentId - const isAuthor = user?.userId === comment.createdBy - const avatarSrc = comment.authorAvatarUrl ?? '' - const displayName = comment.authorName || 'User' - const parentComment = allComments.find( - (c) => c.commentId && c.commentId === comment.parentCommentId - ) - const parentName = parentComment?.authorName - const isUpdating = - !!comment.commentId && updatingCommentId === comment.commentId - const isDeleting = - !!comment.commentId && deletingCommentId === comment.commentId - const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false) - - return ( - -
- - - - {(displayName.charAt(0) || 'U').toUpperCase()} - - - -
-
- - {displayName} - - - {comment.createdAt ? formatTimeAgo(comment.createdAt) : ''} - -
- - {isEditing ? ( -
- -
- - -
-
- ) : ( - <> - {!!comment.parentCommentId && ( -
- Replying to{' '} - - {parentName || 'a comment'} - -
- )} -
- -
- -
- - - {isAuthor && ( - - - - - - { - if (!comment.commentId) return - onEdit(comment.commentId, comment.text ?? '') - }} - className="cursor-pointer gap-2 rounded-md px-2.5 py-2 text-sm text-[#F4F7FC] focus:bg-[#1E2533] focus:text-[#F4F7FC]" - > - - Edit - - { - if (!comment.commentId) return - setIsDeleteModalOpen(true) - }} - className="text-destructive focus:text-destructive cursor-pointer gap-2 rounded-md px-2.5 py-2 text-sm focus:bg-[#1E2533]" - disabled={isDeleting} - > - - Delete - - - - )} -
- - )} -
-
- - setIsDeleteModalOpen(open)} - title="Delete comment?" - description="This action cannot be undone." - onConfirm={async () => { - if (!comment.commentId) return - await onDelete(comment.commentId) - }} - /> -
- ) -} diff --git a/viewer/src/features/diagram-portal/nodes/components/comment-panel.tsx b/viewer/src/features/diagram-portal/nodes/components/comment-panel.tsx deleted file mode 100644 index 36ba140..0000000 --- a/viewer/src/features/diagram-portal/nodes/components/comment-panel.tsx +++ /dev/null @@ -1,191 +0,0 @@ -import { SuperCircleLoader } from '@/components/loader' -import { Button } from '@/components/ui/button' -import type { UIComment } from '@/features/comments/api/comments' -import { InputEditor } from '@/features/comments/components/input-editor' -import { cn } from '@/lib/utils' -import { motion } from 'framer-motion' -import { CheckIcon, SendIcon, XIcon } from 'lucide-react' -import { CommentItem } from './comment-item' - -type CommentPanelProps = { - comments: UIComment[] - isResolved: boolean - user: { - userId: string - name?: string - pic?: string - } | null - replyText: string - replyToName: string | null - editingCommentId: string | null - editText: string - isCreating: boolean - updatingCommentId: string | null - deletingCommentId: string | null - onToggleResolved: () => void - onClose: () => void - onReplyTextChange: (text: string) => void - onReply: () => void - onCancelReply: () => void - onEdit: (commentId: string, currentContent: string) => void - onSaveEdit: () => void - onCancelEdit: () => void - onDelete: (commentId: string) => Promise - onReplyToAuthor: (commentId: string, authorName: string) => void - onEditTextChange: (text: string) => void -} - -export function CommentPanel({ - comments, - isResolved, - user, - replyText, - replyToName, - editingCommentId, - editText, - isCreating, - updatingCommentId, - deletingCommentId, - onToggleResolved, - onClose, - onReplyTextChange, - onReply, - onCancelReply, - onEdit, - onSaveEdit, - onCancelEdit, - onDelete, - onReplyToAuthor, - onEditTextChange, -}: CommentPanelProps) { - return ( - -
-
-

Comment

-
- - -
-
-
- -
e.stopPropagation()} - className="max-h-96 overflow-x-hidden overflow-y-auto" - > -
- {comments.length === 0 ? ( -
- No comments yet. Start the conversation! -
- ) : ( - comments.map((comment) => ( -
- -
- )) - )} -
-
- -
-
- {!!replyToName && ( -
-
- Replying to{' '} - - {replyToName} - -
- -
- )} - -
-
- -
- - -
-
-
-
- ) -} diff --git a/viewer/src/features/diagram-portal/nodes/components/comment-preview.tsx b/viewer/src/features/diagram-portal/nodes/components/comment-preview.tsx deleted file mode 100644 index 91526c6..0000000 --- a/viewer/src/features/diagram-portal/nodes/components/comment-preview.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar' -import type { UIComment } from '@/features/comments/api/comments' -import { InputRenderer } from '@/features/comments/components/input-editor' -import { motion } from 'framer-motion' -import { formatTimeAgo } from '../helpers/comment-helpers' - -type CommentPreviewProps = { - comments: UIComment[] - totalComments: number - onMouseEnter: () => void - onMouseLeave: () => void -} - -export function CommentPreview({ - comments, - totalComments, - onMouseEnter, - onMouseLeave, -}: CommentPreviewProps) { - return ( - - {comments.length > 0 ? ( - - ) : ( -
No comments yet
- )} -
- ) -} - -function CommentContent({ - comments, - totalComments, -}: { - comments: UIComment[] - totalComments: number -}) { - const avatarSrc = comments[0]?.authorAvatarUrl ?? '' - const displayName = comments[0]?.authorName || 'Anonymous' - - return ( -
-
- - - - {(displayName.charAt(0) || 'A').toUpperCase()} - - - - {displayName} - - - {comments[0]?.createdAt ? formatTimeAgo(comments[0].createdAt) : ''} - -
-
- -
- {totalComments > 1 && ( -
+{totalComments - 1} more
- )} -
- ) -} diff --git a/viewer/src/features/diagram-portal/nodes/helpers/comment-helpers.ts b/viewer/src/features/diagram-portal/nodes/helpers/comment-helpers.ts deleted file mode 100644 index b1e64c0..0000000 --- a/viewer/src/features/diagram-portal/nodes/helpers/comment-helpers.ts +++ /dev/null @@ -1,71 +0,0 @@ -export function generateCommentId(): string { - return Math.random().toString(36).substr(2, 9) -} - -export function formatTimeAgo(dateString: string): string { - const now = new Date() - const date = new Date(dateString) - const diffInMinutes = Math.floor( - (now.getTime() - date.getTime()) / (1000 * 60) - ) - - if (diffInMinutes < 1) return 'Just now' - if (diffInMinutes < 60) return `${diffInMinutes} min ago` - if (diffInMinutes < 1440) - return `${Math.floor(diffInMinutes / 60)} hour${ - Math.floor(diffInMinutes / 60) > 1 ? 's' : '' - } ago` - return `${Math.floor(diffInMinutes / 1440)} day${ - Math.floor(diffInMinutes / 1440) > 1 ? 's' : '' - } ago` -} - -export function calculateTotalComments(comments: Comment[]): number { - return comments.reduce((acc, comment) => { - return acc + 1 + (comment.replies?.length || 0) - }, 0) -} - -export function updateCommentInTree( - comments: Comment[], - commentId: string, - updater: (comment: Comment) => Comment -): Comment[] { - return comments.map((comment) => { - if (comment.id === commentId) { - return updater(comment) - } - if (comment.replies) { - return { - ...comment, - replies: updateCommentInTree(comment.replies, commentId, updater), - } - } - return comment - }) -} - -export function deleteCommentFromTree( - comments: Comment[], - commentId: string -): Comment[] { - return comments.filter((comment) => { - if (comment.id === commentId) return false - if (comment.replies) { - comment.replies = deleteCommentFromTree(comment.replies, commentId) - } - return true - }) -} - -export type Comment = { - id: string - content: string - author: { - name: string - avatar: string - userId: string - } - createdAt: string - replies?: Comment[] -} diff --git a/viewer/src/features/diagram-portal/nodes/index.ts b/viewer/src/features/diagram-portal/nodes/index.ts index 12b4c93..3d8ceb4 100644 --- a/viewer/src/features/diagram-portal/nodes/index.ts +++ b/viewer/src/features/diagram-portal/nodes/index.ts @@ -4,7 +4,6 @@ import { C4BoundaryNode } from './c4-boundary-node' import { C4Node } from './c4-node' import { CloudNode } from './cloud-node' import { CodeNode } from './code-node' -import { CommentNode } from './comment-node' import { DataTableInterfaceNode } from './data-table-node' import { DatabaseTableSQLNode } from './database-table-node-sql' import { GroupNode } from './group-node' @@ -24,7 +23,6 @@ export type * from './c4-boundary-node' export type * from './c4-node' export type * from './cloud-node' export type * from './code-node' -export type * from './comment-node' export type * from './database-table-node-sql' export type * from './group-node' export type * from './image-node' @@ -39,7 +37,6 @@ export type TNodeTypes = keyof typeof CUSTOM_NODE_TYPES export const CUSTOM_NODE_TYPES = { default: ShapeNode, builder: BuilderNode, - comment: CommentNode, gif: AnimatedNode, group: GroupNode, shape: ShapeNode, diff --git a/viewer/src/features/diagram-portal/properties/index.tsx b/viewer/src/features/diagram-portal/properties/index.tsx index d8b30f4..2d4d1da 100644 --- a/viewer/src/features/diagram-portal/properties/index.tsx +++ b/viewer/src/features/diagram-portal/properties/index.tsx @@ -124,7 +124,7 @@ export function FloatingProperties() { return ( <> - {node && node.type !== 'comment' ? ( + {node ? ( { - if (!reactFlowInstance) return - if (isPreviewing) return - if (sidebarActiveTool !== 'add-comment') return - - const id = generateUUID() - const position = reactFlowInstance.screenToFlowPosition({ - x: event.clientX, - y: event.clientY, - }) - - setNodes((nds: Node[]) => [ - ...nds, - { - id, - type: 'comment', - data: { message: '' }, - position, - } as Node, - ]) - - setSidebarActiveTool(null) - }, - [ - reactFlowInstance, - isPreviewing, - sidebarActiveTool, - setNodes, - setSidebarActiveTool, - ] - ) - const onDrawComplete = useCallback( (bounds: { x: number; y: number; width: number; height: number }) => { if (!reactFlowInstance) return @@ -398,7 +363,7 @@ export function ReactFlowWrapper({ } const nodesInBounds = nodes.filter((node: Node) => { - if (isFrameNode(node) || node.type === 'comment' || node.parentId) { + if (isFrameNode(node) || node.parentId) { return false } @@ -514,9 +479,7 @@ export function ReactFlowWrapper({ const isCtrlOrCmd = event.ctrlKey || event.metaKey const isEditingNodeLabel = - isTyping && - target.closest('.react-flow__node') !== null && - target.closest('.react-flow__node-comment') === null + isTyping && target.closest('.react-flow__node') !== null const canUndoRedo = !isTyping || isEditingNodeLabel if (isCtrlOrCmd && !event.shiftKey && event.key === 'z' && canUndoRedo) { @@ -582,8 +545,6 @@ export function ReactFlowWrapper({ return ( <> - {sidebarActiveTool === 'add-comment' && } - {isPreviewing && (