webapp/src/context/profile.tsx

95 lines
2.5 KiB
TypeScript
Raw Normal View History

2023-11-28 13:18:25 +00:00
import type { ProfileInput } from '../graphql/schema/core.gen'
import { createContext, createEffect, createMemo, JSX, useContext } from 'solid-js'
2022-12-01 17:16:14 +00:00
import { createStore } from 'solid-js/store'
2023-12-03 10:22:42 +00:00
import { apiClient as coreClient } from '../graphql/client/core'
2023-11-28 18:04:51 +00:00
import { loadAuthor } from '../stores/zine/authors'
import { useSession } from './session'
2022-12-01 17:16:14 +00:00
type ProfileFormContextType = {
form: ProfileInput
actions: {
setForm: (profile: ProfileInput) => void
submit: (profile: ProfileInput) => Promise<void>
updateFormField: (fieldName: string, value: string, remove?: boolean) => void
}
}
const ProfileFormContext = createContext<ProfileFormContextType>()
export function useProfileForm() {
return useContext(ProfileFormContext)
}
const userpicUrl = (userpic: string) => {
2023-11-27 21:44:58 +00:00
if (userpic && userpic.includes('assets.discours.io')) {
return userpic.replace('100x', '500x500')
}
return userpic
}
export const ProfileFormProvider = (props: { children: JSX.Element }) => {
2023-11-28 18:04:51 +00:00
const { author: currentAuthor } = useSession()
const [form, setForm] = createStore<ProfileInput>({})
2022-12-01 17:16:14 +00:00
const currentSlug = createMemo(() => session()?.user?.slug)
2022-12-07 08:37:40 +00:00
2023-12-03 10:22:42 +00:00
const apiClient = createMemo(() => {
if (!coreClient.private) coreClient.connect()
return coreClient
})
2022-12-07 08:37:40 +00:00
const submit = async (profile: ProfileInput) => {
2023-12-03 10:22:42 +00:00
const response = await apiClient().updateProfile(profile)
2023-02-09 22:39:52 +00:00
if (response.error) {
console.error(response.error)
throw response.error
2022-12-07 08:37:40 +00:00
}
}
2022-12-01 17:16:14 +00:00
createEffect(async () => {
if (!currentSlug()) return
try {
const currentAuthor = await loadAuthor({ slug: currentSlug() })
setForm({
name: currentAuthor.name,
slug: currentAuthor.slug,
bio: currentAuthor.bio,
about: currentAuthor.about,
pic: userpicUrl(currentAuthor.pic),
links: currentAuthor.links,
})
2022-12-01 17:16:14 +00:00
} catch (error) {
console.error(error)
}
})
const updateFormField = (fieldName: string, value: string, remove?: boolean) => {
if (fieldName === 'links') {
if (remove) {
2022-12-01 19:28:43 +00:00
setForm(
'links',
form.links.filter((item) => item !== value),
2022-12-01 19:28:43 +00:00
)
2022-12-01 17:16:14 +00:00
} else {
2022-12-01 18:52:44 +00:00
setForm((prev) => ({ ...prev, links: [...prev.links, value] }))
2022-12-01 17:16:14 +00:00
}
} else {
setForm({
[fieldName]: value,
2022-12-01 17:16:14 +00:00
})
}
}
const value: ProfileFormContextType = {
form,
actions: {
submit,
updateFormField,
setForm,
},
}
2022-12-01 17:16:14 +00:00
return <ProfileFormContext.Provider value={value}>{props.children}</ProfileFormContext.Provider>
}