Skip to content

Commit

Permalink
minor: projects blankslate and some other minor improvements (#130)
Browse files Browse the repository at this point in the history
Fixes env boolean value coercion. Fixes minor stuff from the dashboard
projects table.
  • Loading branch information
geclos authored Sep 2, 2024
1 parent 62d9024 commit 567e3bf
Show file tree
Hide file tree
Showing 18 changed files with 216 additions and 58 deletions.
19 changes: 19 additions & 0 deletions apps/web/src/actions/projects/update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use server'

import { ProjectsRepository } from '@latitude-data/core/repositories'
import { updateProject } from '@latitude-data/core/services/projects/update'
import { z } from 'zod'

import { authProcedure } from '../procedures'

export const updateProjectAction = authProcedure
.createServerAction()
.input(z.object({ id: z.number(), name: z.string() }))
.handler(async ({ input, ctx }) => {
const workspace = ctx.workspace
const scope = new ProjectsRepository(workspace.id)
const project = await scope.find(input.id).then((r) => r.unwrap())
const result = await updateProject(project, { name: input.name })

return result.unwrap()
})
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ export function ProjectsTable({
{relativeTime(
findDocuments(project.id).sort(
(a: DocumentVersion, b: DocumentVersion) =>
b.updatedAt.getTime() - a.updatedAt.getTime(),
)?.[0]?.updatedAt,
b.createdAt.getTime() - a.createdAt.getTime(),
)?.[0]?.createdAt,
)}
</Text.H4>
</TableCell>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use client'

import React from 'react'

import { Text } from '@latitude-data/web-ui'
import useProjects from '$/stores/projects'
import { EditableText } from 'node_modules/@latitude-data/web-ui/src/ds/molecules/EditableText'
import { useDebouncedCallback } from 'use-debounce'

export default function BreadcrumpInput({ projectId }: { projectId: number }) {
const { data, update } = useProjects()
const project = data.find((p) => p.id === projectId)
const handleChange = useDebouncedCallback(
(value?: string) => {
if (!value) return
if (!project) return

update({ id: project.id, name: value })
},
250,
{ trailing: true },
)

if (!project) return null

return (
<EditableText
value={project.name}
handleChange={handleChange}
fallback={(value) => <Text.H5M>{value}</Text.H5M>}
/>
)
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
import { Text } from '@latitude-data/web-ui'
import { getDocumentsAtCommitAction } from '$/actions/documents/getDocumentsAtCommitAction'
import {
findCommitCached,
findProjectCached,
} from '$/app/(private)/_data-access'
import { getCurrentUser } from '$/services/auth/getCurrentUser'
import { ROUTES } from '$/services/routes'
import { redirect } from 'next/navigation'

import DocumentsLayout from '../_components/DocumentsLayout'

export default async function DocumentsPage({
Expand All @@ -6,10 +16,41 @@ export default async function DocumentsPage({
params: { projectId: string; commitUuid: string }
}) {
const projectId = Number(params.projectId)
const commintUuid = params.commitUuid
const commitUuid = params.commitUuid
const session = await getCurrentUser()
const project = await findProjectCached({
projectId: Number(params.projectId),
workspaceId: session.workspace.id,
})
const commit = await findCommitCached({
project,
uuid: commitUuid,
})
const [documents, error] = await getDocumentsAtCommitAction({
projectId: project.id,
commitId: commit.id,
})
if (error) throw error
if (documents && documents.length > 0) {
return redirect(
ROUTES.projects
.detail({ id: project.id })
.commits.detail({ uuid: params.commitUuid })
.documents.detail({ uuid: documents[0]?.documentUuid! }).root,
)
}

return (
<DocumentsLayout projectId={projectId} commitUuid={commintUuid}>
<div>List of documents</div>
<DocumentsLayout projectId={projectId} commitUuid={commitUuid}>
<div className='flex-1 flex flex-row justify-center py-6 pr-4 h-full'>
<div className='rounded-lg flex flex-col flex-1 gap-4 p-4 items-center justify-center bg-secondary'>
<Text.H5M>
{commit.mergedAt
? '👈 There are no prompts in this version, to get started create a new version from the sidebar.'
: '👈 There are no prompts in this version, to get started create one from the sidebar.'}
</Text.H5M>
</div>
</div>
</DocumentsLayout>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import { getCurrentUser, SessionData } from '$/services/auth/getCurrentUser'
import { ROUTES } from '$/services/routes'
import { notFound } from 'next/navigation'

import BreadcrumpInput from './documents/_components/BreadcrumpInput'

export type CommitPageParams = {
children: ReactNode
params: ProjectPageParams['params'] & { commitUuid: string }
Expand Down Expand Up @@ -67,7 +69,7 @@ export default async function CommitLayout({
/>
),
},
{ name: project.name },
{ name: <BreadcrumpInput projectId={project.id} /> },
{
name: (
<BreadcrumpBadge
Expand Down
Original file line number Diff line number Diff line change
@@ -1,44 +1,14 @@
import { DocumentDetailWrapper } from '@latitude-data/web-ui'
import {
getResizablePanelGroupData,
MIN_SIDEBAR_WIDTH_PX,
ResizableGroups,
} from '$/app/_lib/getResizablePanelGroupData'
import {
findCommitCached,
findProjectCached,
} from '$/app/(private)/_data-access'
import { getCurrentUser } from '$/services/auth/getCurrentUser'

import Sidebar from './_components/Sidebar'

export const dynamic = 'force-dynamic'
import { ROUTES } from '$/services/routes'
import { redirect } from 'next/navigation'

export default async function CommitRoot({
params,
}: {
params: { projectId: string; commitUuid: string }
}) {
const session = await getCurrentUser()
const project = await findProjectCached({
projectId: Number(params.projectId),
workspaceId: session.workspace.id,
})
const commit = await findCommitCached({
project,
uuid: params.commitUuid,
})
const resizableId = ResizableGroups.DocumentSidebar
const sidebarWidth =
getResizablePanelGroupData({ group: resizableId }) ?? MIN_SIDEBAR_WIDTH_PX
return (
<DocumentDetailWrapper
resizableId={resizableId}
sidebarWidth={sidebarWidth}
minSidebarWidth={MIN_SIDEBAR_WIDTH_PX}
sidebar={<Sidebar project={project} commit={commit} />}
>
<div className='p-32'>Main content. Remove Tailwind Styles from here</div>
</DocumentDetailWrapper>
redirect(
ROUTES.projects
.detail({ id: Number(params.projectId) })
.commits.detail({ uuid: params.commitUuid }).documents.root,
)
}
6 changes: 5 additions & 1 deletion apps/web/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ export default createEnv({
REDIS_PASSWORD: z.string().optional(),
GATEWAY_HOSTNAME: z.string(),
GATEWAY_PORT: z.coerce.number().optional(),
GATEWAY_SSL: z.coerce.boolean().optional().default(true),
GATEWAY_SSL: z
.enum(['true', 'false'])
.transform((value) => value === 'true')
.optional()
.default('true'),
},
runtimeEnv: {
DATABASE_URL: process.env.DATABASE_URL,
Expand Down
13 changes: 12 additions & 1 deletion apps/web/src/stores/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useToast } from '@latitude-data/web-ui'
import { createProjectAction } from '$/actions/projects/create'
import { destroyProjectAction } from '$/actions/projects/destroy'
import { fetchProjectsAction } from '$/actions/projects/fetch'
import { updateProjectAction } from '$/actions/projects/update'
import useLatitudeAction from '$/hooks/useLatitudeAction'
import useSWR, { SWRConfiguration } from 'swr'

Expand Down Expand Up @@ -37,6 +38,16 @@ export default function useProjects(opts?: SWRConfiguration) {
mutate([...data, project])
},
})
const { execute: update } = useLatitudeAction(updateProjectAction, {
onSuccess: ({ data: project }) => {
toast({
title: 'Project updated',
description: `${project.name} has been updated successfully`,
})

mutate(data.map((p) => (p.id === project.id ? project : p)))
},
})
const { execute: destroy } = useLatitudeAction(destroyProjectAction, {
onSuccess: ({ data: project }) => {
toast({
Expand All @@ -48,5 +59,5 @@ export default function useProjects(opts?: SWRConfiguration) {
},
})

return { data, mutate, create, destroy, ...rest }
return { data, mutate, create, update, destroy, ...rest }
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ describe('getDocumentAtCommit', () => {

expect(omit(document, 'id', 'updatedAt')).toEqual({
...omit(doc, 'id', 'updatedAt'),
projectId: String(project.id),
projectId: project.id,
mergedAt: mergedCommit.mergedAt,
resolvedContent: 'VERSION_1',
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const tt = {
// drizzle-orm, which is hot garbage, but it works. We need it otherwise the
// resulting subquery returns two columns with the same name id and we can't
// use it in a join.
projectId: sql<number>`${projects.id}`.as('projectId'),
projectId: sql<number>`${projects.id}::int`.as('projectId'),
}

export class DocumentVersionsRepository extends Repository<typeof tt> {
Expand Down
19 changes: 11 additions & 8 deletions packages/core/src/repositories/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,26 @@ export default abstract class Repository<U extends ColumnsSelection> {

abstract get scope(): SubqueryWithSelection<U, string>

async findAll() {
const result = await this.db.select().from(this.scope)
return Result.ok(result)
}

async find(id: string | number) {
const result = await this.db
.select()
.from(this.scope)
// TODO: This is correct but I don't have time to fix the type
// TODO: This is correct but I don't have time to fix the types
// as it involves some generics with the return value of scope
// in the child classes
//
// @ts-expect-error
.where(eq(this.scope.id, id))
.limit(1)
if (!result[0])
if (!result[0]) {
return Result.error(new NotFoundError(`Record with id ${id} not found`))
}

return Result.ok(result[0])
}

async findAll() {
const result = await this.db.select().from(this.scope)
return Result.ok(result)
return Result.ok(result[0]!)
}
}
1 change: 1 addition & 0 deletions packages/core/src/services/projects/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './create'
export * from './destroy'
export * from './update'
22 changes: 22 additions & 0 deletions packages/core/src/services/projects/update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { eq } from 'drizzle-orm'

import { Project } from '../../browser'
import { database } from '../../client'
import { Result, Transaction } from '../../lib'
import { projects } from '../../schema'

export async function updateProject(
project: Project,
values: Partial<Project>,
db = database,
) {
return Transaction.call<Project>(async (tx) => {
const updates = await tx
.update(projects)
.set(values)
.where(eq(projects.id, project.id))
.returning()

return Result.ok(updates[0]!)
}, db)
}
4 changes: 3 additions & 1 deletion packages/sdks/typescript/src/env/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ export default createEnv({
server: {
GATEWAY_HOSTNAME: z.string(),
GATEWAY_PORT: z.coerce.number().optional(),
GATEWAY_SSL: z.coerce.boolean(),
GATEWAY_SSL: z
.enum(['true', 'false'])
.transform((value) => value === 'true'),
},
runtimeEnv: {
GATEWAY_HOSTNAME: process.env.GATEWAY_HOSTNAME ?? 'localhost',
Expand Down
6 changes: 6 additions & 0 deletions packages/web-ui/src/ds/atoms/Button/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const buttonContainerVariants = cva(
variants: {
variant: {
default: 'bg-accent-foreground hover:bg-accent-foreground/90',
nope: 'bg-transparent hover:bg-transparent',
destructive:
'bg-destructive-muted-foreground hover:bg-destructive-muted-foreground/90',
outline: 'hover:bg-accent/60',
Expand Down Expand Up @@ -56,6 +57,7 @@ const buttonVariants = cva(
variant: {
default:
'bg-primary text-primary-foreground group-hover:bg-primary/90 shadow-[inset_0px_2px_2px_rgba(255,255,255,0.25),inset_0px_-1px_4px_rgba(0,0,0,0.04)]',
nope: 'bg-transparent text-primary-foreground group-hover:bg-transparent',
destructive:
'bg-destructive text-destructive-foreground group-hover:bg-destructive/90 shadow-[inset_0px_2px_2px_rgba(255,255,255,0.25),inset_0px_-1px_4px_rgba(0,0,0,0.04)]',
outline:
Expand All @@ -79,6 +81,10 @@ const buttonVariants = cva(
},
},
compoundVariants: [
{
variant: 'nope',
className: 'p-0',
},
{
variant: 'outline',
fanciness: 'fancy',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ export function DocumentTextEditor({
readOnlyMessage,
isSaved,
}: DocumentTextEditorProps) {
console.log('wtf')

const [defaultValue, _] = useState(value)
const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null)
const monacoRef = useRef<Monaco | null>(null)
Expand Down
Loading

0 comments on commit 567e3bf

Please sign in to comment.