Skip to content
This repository has been archived by the owner on Jan 2, 2025. It is now read-only.

Commit

Permalink
WIP middle end drafts
Browse files Browse the repository at this point in the history
  • Loading branch information
ericvicenti committed Jun 27, 2024
1 parent 029fb6e commit 28ab5a7
Show file tree
Hide file tree
Showing 19 changed files with 251 additions and 219 deletions.
2 changes: 2 additions & 0 deletions frontend/apps/desktop/src/app-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import path from 'path'
import z from 'zod'
import {commentsApi} from './app-comments'
import {diagnosisApi} from './app-diagnosis'
import {draftsApi} from './app-drafts'
import {experimentsApi} from './app-experiments'
import {favoritesApi} from './app-favorites'
import {gatewaySettingsApi} from './app-gateway-settings'
Expand Down Expand Up @@ -148,6 +149,7 @@ function getRouteRefocusKey(route: NavRoute): string | null {
}

export const router = t.router({
drafts: draftsApi,
experiments: experimentsApi,
diagnosis: diagnosisApi,
welcoming: welcomingApi,
Expand Down
61 changes: 61 additions & 0 deletions frontend/apps/desktop/src/app-drafts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import fs from 'fs/promises'
import {join} from 'path'
import z from 'zod'
import {userDataPath} from './app-paths'
import {t} from './app-trpc'

const draftsDir = join(userDataPath, 'drafts')

let draftIdList: string[] | undefined = undefined

async function initDrafts() {
await fs.mkdir(draftsDir, {recursive: true})
await fs.readdir(draftsDir)
const allDraftFiles = await fs.readdir(draftsDir)
const allDraftIds = allDraftFiles.map((filename) => {
return filename.replace(/\.json$/, '')
})
draftIdList = allDraftIds
}

initDrafts()
.then(() => {
console.log('drafs ready')
})
.catch((e) => {
console.error('error preparing drafts', e)
})

export const draftsApi = t.router({
list: t.procedure.query(async () => {
return draftIdList
}),
get: t.procedure.input(z.string()).query(async ({input}) => {
const draftPath = join(draftsDir, `${input}.json`)
try {
const draft = JSON.parse(await fs.readFile(draftPath, 'utf-8'))
return draft
} catch (e) {
return null
}
}),
write: t.procedure
.input(
z.object({
draft: z.any(),
id: z.string(),
}),
)
.mutation(async ({input}) => {
const draftPath = join(draftsDir, `${input.id}.json`)
if (!draftIdList?.includes(input.id)) {
draftIdList?.push(input.id)
}
await fs.writeFile(draftPath, JSON.stringify(input.draft, null, 2))
}),
delete: t.procedure.input(z.string()).mutation(async ({input}) => {
const draftPath = join(draftsDir, `${input}.json`)
draftIdList = draftIdList?.filter((id) => id !== input)
await fs.unlink(draftPath)
}),
})
18 changes: 9 additions & 9 deletions frontend/apps/desktop/src/components/avatar-form.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {Avatar} from '@/components/avatar'
import {useMyAccount} from '@/models/accounts'
import {API_FILE_UPLOAD_URL} from '@shm/shared'
import {Stack, Tooltip} from '@shm/ui'
import {ChangeEvent} from 'react'
import { Avatar } from '@/components/avatar'
import { useMyAccount_deprecated } from '@/models/accounts'
import { API_FILE_UPLOAD_URL } from '@shm/shared'
import { Stack, Tooltip } from '@shm/ui'
import { ChangeEvent } from 'react'
import appError from '../errors'

export function AvatarForm({
Expand All @@ -14,15 +14,15 @@ export function AvatarForm({
url?: string
onAvatarUpload: (avatar: string) => Awaited<void>
}) {
const account = useMyAccount()
const account = useMyAccount_deprecated()
const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
const fileList = event.target.files
const file = fileList?.[0]
if (!file) return
handleUpload(file)
.then(() => {})
.then(() => { })
.catch((error) => {
appError(`Failed to upload avatar: ${e.message}`, {error})
appError(`Failed to upload avatar: ${e.message}`, { error })
})
.finally(() => {
event.target.value = ''
Expand Down Expand Up @@ -54,7 +54,7 @@ export function AvatarForm({
if (disabled) return avatarImage
return (
<Tooltip content="Click or Drag to Set Avatar Image">
<Stack hoverStyle={{opacity: 0.7}}>
<Stack hoverStyle={{ opacity: 0.7 }}>
<input
type="file"
onChange={handleFileChange}
Expand Down
4 changes: 2 additions & 2 deletions frontend/apps/desktop/src/components/commit-draft-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import { Check } from '@tamagui/lucide-icons'
import { PropsWithChildren } from 'react'
import { useGRPCClient } from '../app-context'
import { useMyAccount } from '../models/accounts'
import { useMyAccount_deprecated } from '../models/accounts'
import { usePublishDraft, usePushPublication } from '../models/documents'
import { DraftStatusContext } from '../models/draft-machine'
import { useGatewayHost, usePushOnPublish } from '../models/gateway-settings'
Expand All @@ -24,7 +24,7 @@ export default function CommitDraftButton() {
throw new Error('DraftPublicationButtons requires draft route')
const draftId = route.key == 'draft' ? route.draftId : null
const grpcClient = useGRPCClient()
const myAccount = useMyAccount()
const myAccount = useMyAccount_deprecated()
const mediaDialog = useMediaDialog()
const canPublish = DraftStatusContext.useSelector(
(s) => s.matches('idle') || s.matches('saved'),
Expand Down
26 changes: 13 additions & 13 deletions frontend/apps/desktop/src/components/contacts-prompt.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import {AccessURLRow} from '@/url'
import {HYPERMEDIA_PUBLIC_WEB_GATEWAY} from '@shm/shared'
import {Button, Spinner, TextArea, XStack, toast} from '@shm/ui'
import {UserPlus} from '@tamagui/lucide-icons'
import {compressToEncodedURIComponent} from 'lz-string'
import {ComponentProps, useMemo, useState} from 'react'
import { AccessURLRow } from '@/url'
import { HYPERMEDIA_PUBLIC_WEB_GATEWAY } from '@shm/shared'
import { Button, Spinner, TextArea, XStack, toast } from '@shm/ui'
import { UserPlus } from '@tamagui/lucide-icons'
import { compressToEncodedURIComponent } from 'lz-string'
import { ComponentProps, useMemo, useState } from 'react'
import appError from '../errors'
import {useMyAccount} from '../models/accounts'
import {useConnectPeer} from '../models/contacts'
import {useDaemonInfo} from '../models/daemon'
import {usePeerInfo} from '../models/networking'
import { useMyAccount_deprecated } from '../models/accounts'
import { useConnectPeer } from '../models/contacts'
import { useDaemonInfo } from '../models/daemon'
import { usePeerInfo } from '../models/networking'
import {
AppDialog,
DialogCloseButton,
Expand All @@ -29,11 +29,11 @@ function AddConnectionForm({
onClose,
}: {
onClose: () => void
input: true | {connectionString?: string; name?: string | undefined}
input: true | { connectionString?: string; name?: string | undefined }
}) {
const [peerText, setPeer] = useState('')
const daemonInfo = useDaemonInfo()
const account = useMyAccount()
const account = useMyAccount_deprecated()
const deviceId = daemonInfo.data?.peerId
const peerInfo = usePeerInfo(deviceId)

Expand All @@ -47,7 +47,7 @@ function AddConnectionForm({
toast.success('Connection Added')
},
onError: (error) => {
appError(`Connect to peer error: ${error?.rawMessage}`, {error})
appError(`Connect to peer error: ${error?.rawMessage}`, { error })
},
})

Expand Down
3 changes: 1 addition & 2 deletions frontend/apps/desktop/src/components/document-list.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useDocumentList, useDraftList } from '@/models/documents'
import { useDocumentList } from '@/models/documents'
import { Delete, List, Spinner } from '@shm/ui'

import { useAppContext } from '@/app-context'
Expand All @@ -18,7 +18,6 @@ export function DocumentsFullList({
header: ReactNode
}) {
const documents = useDocumentList({})
const drafts = useDraftList()
const { queryClient, grpcClient } = useAppContext()
const deleteDialog = useDeleteDialog()

Expand Down
4 changes: 2 additions & 2 deletions frontend/apps/desktop/src/components/edit-doc-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Button, Tooltip, toast } from '@shm/ui'
import { Pencil } from '@tamagui/lucide-icons'
import { useQueryInvalidator } from '../app-context'
import appError from '../errors'
import { useMyAccount } from '../models/accounts'
import { useMyAccount_deprecated } from '../models/accounts'
import { queryKeys } from '../models/query-keys'
import { generateBlockId } from '../utils/media-drag'
import { AccountRoute, DocumentRoute } from '../utils/routes'
Expand All @@ -27,7 +27,7 @@ export function useEditDraft(
},
) {
const draftList = useDraftList()
const myAccount = useMyAccount()
const myAccount = useMyAccount_deprecated()
const navigate = useNavigate(navMode)
const invalidate = useQueryInvalidator()

Expand Down
34 changes: 17 additions & 17 deletions frontend/apps/desktop/src/components/edit-profile-dialog.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {zodResolver} from '@hookform/resolvers/zod'
import {Profile} from '@shm/shared'
import { zodResolver } from '@hookform/resolvers/zod'
import { Profile } from '@shm/shared'
import {
Button,
DialogTitle,
Expand All @@ -9,23 +9,23 @@ import {
XStack,
YStack,
} from '@shm/ui'
import {useEffect} from 'react'
import {Control, useController, useForm} from 'react-hook-form'
import {z} from 'zod'
import {useMyAccount, useSetProfile} from '../models/accounts'
import {getAvatarUrl} from '../utils/account-url'
import {AvatarForm} from './avatar-form'
import {useAppDialog} from './dialog'
import {FormError, FormInput} from './form-input'
import { useEffect } from 'react'
import { Control, useController, useForm } from 'react-hook-form'
import { z } from 'zod'
import { useMyAccount_deprecated, useSetProfile } from '../models/accounts'
import { getAvatarUrl } from '../utils/account-url'
import { AvatarForm } from './avatar-form'
import { useAppDialog } from './dialog'
import { FormError, FormInput } from './form-input'

export function useEditProfileDialog() {
// for some reason the dialog doesn't work if the input is falsy
// input is not needed for this dialog, so we just use "true", lol
return useAppDialog<true>(EditProfileDialog)
}

function EditProfileDialog({onClose}: {onClose: () => void}) {
const myAccount = useMyAccount()
function EditProfileDialog({ onClose }: { onClose: () => void }) {
const myAccount = useMyAccount_deprecated()
const profile = myAccount.data?.profile
return (
<>
Expand All @@ -40,13 +40,13 @@ function EditProfileDialog({onClose}: {onClose: () => void}) {
}

const profileSchema = z.object({
alias: z.string().min(1, {message: 'Profile alias is required'}),
alias: z.string().min(1, { message: 'Profile alias is required' }),
avatar: z.string().optional(),
})
type ProfileFields = z.infer<typeof profileSchema>

function AvatarInput({control}: {control: Control<ProfileFields>}) {
const c = useController({control, name: 'avatar'})
function AvatarInput({ control }: { control: Control<ProfileFields> }) {
const c = useController({ control, name: 'avatar' })
return (
<AvatarForm
onAvatarUpload={c.field.onChange}
Expand All @@ -69,11 +69,11 @@ function ProfileForm({
control,
handleSubmit,
setFocus,
formState: {errors},
formState: { errors },
} = useForm<ProfileFields>({
resolver: zodResolver(profileSchema),
// OMG wow, this object gets mutated! bad things will happen if we don't spread the profile into a new object:
defaultValues: {...profile},
defaultValues: { ...profile },
})

useEffect(() => {
Expand Down
Loading

0 comments on commit 28ab5a7

Please sign in to comment.