webapp/src/context/profile.tsx

85 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-11-28 13:18:25 +00:00
import type { ProfileInput } from '../graphql/schema/core.gen'
2023-12-26 10:05:15 +00:00
import { createContext, createEffect, JSX, useContext } from 'solid-js'
2022-12-01 17:16:14 +00:00
import { createStore } from 'solid-js/store'
2023-12-19 09:34:24 +00:00
import { apiClient } from '../graphql/client/core'
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-12-20 16:54:20 +00:00
const { author } = useSession()
const [form, setForm] = createStore<ProfileInput>({})
2022-12-07 08:37:40 +00:00
const submit = async (profile: ProfileInput) => {
2023-12-19 09:34:24 +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 () => {
2023-12-25 06:52:04 +00:00
if (author()) {
const currentAuthor = author()
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
}
})
2023-12-25 06:52:04 +00:00
2022-12-01 17:16:14 +00:00
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>
}