Skip to content

Commit

Permalink
Fix sidebar document creation by not importing server modules in client
Browse files Browse the repository at this point in the history
and by returning an object in the server action
  • Loading branch information
andresgutgon committed Jul 16, 2024
1 parent fe7fea7 commit fddba02
Show file tree
Hide file tree
Showing 36 changed files with 2,115 additions and 1,465 deletions.
18 changes: 8 additions & 10 deletions apps/web/src/actions/documents/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,20 @@
import { createDocumentVersion, DocumentType } from '@latitude-data/core'
import { z } from 'zod'

import { authProcedure } from '../procedures'
import { withProject } from '../procedures'

export const createDocumentVersionAction = authProcedure
export const createDocumentVersionAction = withProject
.createServerAction()
.input(
z.object({
commitUuid: z.string(),
documentType: z
.enum([
'folder' as DocumentType.Folder,
'document' as DocumentType.Document,
])
.optional(),
name: z.string(),
commitUuid: z.string(),
parentId: z.number().optional(),
documentType: z.nativeEnum(DocumentType).optional(),
}),
{ type: 'json' },
)
.handler(async ({ input }) => createDocumentVersion(input))
.handler(async ({ input }) => {
const result = await createDocumentVersion(input)
return result.unwrap()
})
14 changes: 14 additions & 0 deletions apps/web/src/actions/procedures/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { getCurrentUser } from '$/services/auth/getCurrentUser'
import { findProject } from '@latitude-data/core'
import { z } from 'zod'
import { createServerActionProcedure } from 'zsa'

/**
Expand All @@ -10,3 +12,15 @@ export const authProcedure = createServerActionProcedure().handler(async () => {
const data = (await getCurrentUser()).unwrap()
return { session: data.session!, workspace: data.workspace, user: data.user }
})

export const withProject = createServerActionProcedure(authProcedure)
.input(z.object({ projectId: z.number() }))
.handler(async ({ input, ctx }) => {
const project = (
await findProject({
projectId: input.projectId,
workspaceId: ctx.workspace.id,
})
).unwrap()
return { ...ctx, project }
})
4 changes: 2 additions & 2 deletions apps/web/src/app/api/commits/[commitUuid]/documents/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ export async function GET(
) {
try {
const staged = Boolean(req.nextUrl.searchParams.get('staged') || false)
const nodes = await materializeDocumentsAtCommit({ commitUuid, staged })
const documents = await materializeDocumentsAtCommit({ commitUuid, staged })

return NextResponse.json(nodes)
return NextResponse.json(documents)
} catch (err: unknown) {
const error = err as Error
return NextResponse.json({ error: error.message }, { status: 500 })
Expand Down
7 changes: 0 additions & 7 deletions apps/web/src/app/page.tsx

This file was deleted.

18 changes: 11 additions & 7 deletions apps/web/src/components/Sidebar/DocumentTree/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { faker } from '@faker-js/faker'
import type { DocumentType, DocumentVersion } from '@latitude-data/core'
import useDocumentVersions from '$/stores/documentVersions'

import toTree, { Node } from '../toTree'
import { Node, useTree } from '../toTree'

function generateName() {
return faker.science.chemicalElement().name
Expand Down Expand Up @@ -61,20 +61,24 @@ function TreeNode({ node, level = 0 }: { node: Node; level?: number }) {
)}
</div>
)}
{node.children.map((node) => (
<TreeNode node={node} level={level + 1} />
{node.children.map((node, idx) => (
<TreeNode key={idx} node={node} level={level + 1} />
))}
</div>
</div>
)
}

export default function DocumentTree({ nodes }: { nodes: DocumentVersion[] }) {
const { data } = useDocumentVersions(
export default function DocumentTree({
documents: serverDocuments,
}: {
documents: DocumentVersion[]
}) {
const { documents } = useDocumentVersions(
{ staged: true },
{ fallbackData: nodes },
{ fallbackData: serverDocuments },
)
const rootNode = toTree(data)
const rootNode = useTree({ documents })

return <TreeNode node={rootNode} />
}
4 changes: 2 additions & 2 deletions apps/web/src/components/Sidebar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { HEAD_COMMIT, materializeDocumentsAtCommit } from '@latitude-data/core'
import DocumentTree, { CreateNode } from './DocumentTree'

export default async function Sidebar() {
const nodes = await materializeDocumentsAtCommit({
const documents = await materializeDocumentsAtCommit({
commitUuid: HEAD_COMMIT,
staged: true,
})
Expand All @@ -16,7 +16,7 @@ export default async function Sidebar() {
<CreateNode />
</div>
</div>
<DocumentTree nodes={nodes} />
<DocumentTree documents={documents} />
</div>
)
}
38 changes: 21 additions & 17 deletions apps/web/src/components/Sidebar/toTree.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { useMemo } from 'react'

import { DocumentVersion } from '@latitude-data/core'

export class Node {
Expand All @@ -16,24 +18,26 @@ export class Node {
}
}

export default function toTree(docs: DocumentVersion[]) {
function iterate(node: Node) {
let children
if (node.isRoot) {
children = Object.values(docs)
.filter((doc) => !doc.parentId)
.map((doc) => new Node(doc))
} else {
children = docs
.filter((doc) => doc.parentId === node.doc!.id)
.map((doc) => new Node(doc))
}
export function useTree({ documents }: { documents: DocumentVersion[] }) {
return useMemo(() => {
function iterate(node: Node) {
let children
if (node.isRoot) {
children = Object.values(documents)
.filter((doc) => !doc.parentId)
.map((doc) => new Node(doc))
} else {
children = documents
.filter((doc) => doc.parentId === node.doc!.id)
.map((doc) => new Node(doc))
}

node.children = children
node.children.forEach(iterate)
node.children = children
node.children.forEach(iterate)

return node
}
return node
}

return iterate(new Node(undefined, [], true))
return iterate(new Node(undefined, [], true))
}, [documents])
}
46 changes: 29 additions & 17 deletions apps/web/src/stores/documentVersions.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
'use client'

import { DocumentVersion, HEAD_COMMIT } from '@latitude-data/core'
import { useCallback } from 'react'

import { DocumentVersion } from '@latitude-data/core'
import { HEAD_COMMIT, type DocumentType } from '@latitude-data/core/browser'
import { createDocumentVersionAction } from '$/actions/documents/create'
import useSWR, { SWRConfiguration } from 'swr'
import { useServerAction } from 'zsa-react'

const FIXME_HARDCODED_PROJECT_ID = 1
export default function useDocumentVersions(
{
commitUuid = HEAD_COMMIT,
Expand All @@ -19,30 +24,37 @@ export default function useDocumentVersions(
new URLSearchParams({
staged: String(staged),
}).toString()
const { mutate, data, ...rest } = useSWR(

const { mutate, data, ...rest } = useSWR<DocumentVersion[]>(
key,
(url: string) => fetch(url).then((res) => res.json()),
opts,
)
const create = async (payload: {
commitUuid?: string
name: string
documentType?: DocumentVersion['documentType']
parentId?: number
}) => {
try {
const doc = await createDocumentVersionAction({
const documents = data ?? []
const { execute } = useServerAction(createDocumentVersionAction)
const create = useCallback(
async (payload: {
commitUuid?: string
name: string
documentType?: DocumentType
parentId?: number
}) => {
const [document] = await execute({
...payload,
projectId: FIXME_HARDCODED_PROJECT_ID,
name: payload.name!,
commitUuid: payload.commitUuid || HEAD_COMMIT,
})
mutate([...data, doc])
const prev = documents ?? []

return doc
} catch (err) {
console.error(err)
}
}
if (document) {
mutate([...prev, document])
}

return document
},
[execute, mutate, documents],
)

return { ...rest, key, data, create, mutate }
return { ...rest, key, documents, create, mutate }
}
3 changes: 3 additions & 0 deletions apps/web/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
"baseUrl": ".",
"paths": {
"$/*": ["./src/*"],
"@latitude-data/core": ["../../packages/core/src/*"],
"@latitude-data/jobs": ["../../packages/jobs/src/*"],
"@latitude-data/web-ui": ["../../packages/web-ui/src/*"],
"$core/*": ["../../packages/core/src/*"],
"$jobs/*": ["../../packages/jobs/src/*"],
"$ui/*": ["../../packages/web-ui/src/*"],
Expand Down
10 changes: 10 additions & 0 deletions packages/core/drizzle/0000_nice_daimon_hellstrom.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE SCHEMA "latitude";
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "latitude"."document_hierarchies" (
"id" bigserial PRIMARY KEY NOT NULL,
"parent_id" bigint,
"depth" integer NOT NULL,
"child_id" bigint NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL
);
82 changes: 0 additions & 82 deletions packages/core/drizzle/0001_ambitious_mesmero.sql

This file was deleted.

Loading

0 comments on commit fddba02

Please sign in to comment.