webapp/src/context/editor.tsx

264 lines
6.8 KiB
TypeScript
Raw Normal View History

import type { JSX } from 'solid-js'
import { Accessor, createContext, createSignal, useContext } from 'solid-js'
import { createStore, SetStoreFunction } from 'solid-js/store'
2023-05-11 11:06:29 +00:00
import { Topic, TopicInput } from '../graphql/types.gen'
2023-05-05 20:05:50 +00:00
import { apiClient } from '../utils/apiClient'
import { useLocalize } from './localize'
import { useSnackbar } from './snackbar'
2023-05-08 17:21:06 +00:00
import { openPage } from '@nanostores/router'
import { router, useRouter } from '../stores/router'
2023-05-10 20:20:53 +00:00
import { slugify } from '../utils/slugify'
import { Editor } from '@tiptap/core'
type WordCounter = {
characters: number
words: number
}
export type ShoutForm = {
layout?: string
shoutId: number
slug: string
title: string
subtitle: string
selectedTopics: Topic[]
2023-05-10 20:20:53 +00:00
mainTopic?: Topic
body: string
coverImageUrl: string
media?: string
}
type EditorContextType = {
isEditorPanelVisible: Accessor<boolean>
wordCounter: Accessor<WordCounter>
form: ShoutForm
2023-05-10 20:20:53 +00:00
formErrors: Record<keyof ShoutForm, string>
editorRef: { current: () => Editor }
actions: {
saveShout: (form: ShoutForm) => Promise<void>
saveDraft: (form: ShoutForm) => Promise<void>
saveDraftToLocalStorage: (form: ShoutForm) => void
getDraftFromLocalStorage: (shoutId: number) => ShoutForm
publishShout: (form: ShoutForm) => Promise<void>
2023-05-08 17:21:06 +00:00
publishShoutById: (shoutId: number) => Promise<void>
deleteShout: (shoutId: number) => Promise<boolean>
toggleEditorPanel: () => void
countWords: (value: WordCounter) => void
setForm: SetStoreFunction<ShoutForm>
2023-05-10 20:20:53 +00:00
setFormErrors: SetStoreFunction<Record<keyof ShoutForm, string>>
setEditor: (editor: () => Editor) => void
}
}
const EditorContext = createContext<EditorContextType>()
export function useEditorContext() {
return useContext(EditorContext)
}
2023-05-11 11:06:29 +00:00
const topic2topicInput = (topic: Topic): TopicInput => {
return {
id: topic.id,
slug: topic.slug,
title: topic.title
}
}
export const EditorProvider = (props: { children: JSX.Element }) => {
2023-05-05 20:05:50 +00:00
const { t } = useLocalize()
2023-05-08 17:21:06 +00:00
const { page } = useRouter()
2023-05-05 20:05:50 +00:00
const {
actions: { showSnackbar }
} = useSnackbar()
2023-05-03 16:13:48 +00:00
const [isEditorPanelVisible, setIsEditorPanelVisible] = createSignal<boolean>(false)
const editorRef: { current: () => Editor } = { current: null }
const [form, setForm] = createStore<ShoutForm>(null)
2023-05-10 20:20:53 +00:00
const [formErrors, setFormErrors] = createStore<Record<keyof ShoutForm, string>>(null)
const [wordCounter, setWordCounter] = createSignal<WordCounter>({
characters: 0,
words: 0
})
2023-05-05 20:05:50 +00:00
2023-05-03 16:13:48 +00:00
const toggleEditorPanel = () => setIsEditorPanelVisible((value) => !value)
const countWords = (value) => setWordCounter(value)
2023-05-05 20:05:50 +00:00
2023-05-08 17:21:06 +00:00
const validate = () => {
2023-05-05 20:05:50 +00:00
if (!form.title) {
setFormErrors('title', t('Required'))
return false
}
const parsedMedia = JSON.parse(form.media)
if (form.layout === 'video' && !parsedMedia[0]) {
showSnackbar({ type: 'error', body: t('Looks like you forgot to upload the video') })
return false
}
2023-05-08 17:21:06 +00:00
return true
}
2023-05-10 20:20:53 +00:00
const validateSettings = () => {
if (form.selectedTopics.length === 0) {
setFormErrors('selectedTopics', t('Required'))
return false
}
return true
}
const updateShout = async (formToUpdate: ShoutForm, { publish }: { publish: boolean }) => {
2023-05-10 20:20:53 +00:00
return apiClient.updateArticle({
shoutId: formToUpdate.shoutId,
2023-05-10 20:20:53 +00:00
shoutInput: {
body: formToUpdate.body,
topics: formToUpdate.selectedTopics.map((topic) => topic2topicInput(topic)),
2023-05-10 20:20:53 +00:00
// authors?: InputMaybe<Array<InputMaybe<Scalars['String']>>>
// community?: InputMaybe<Scalars['Int']>
mainTopic: topic2topicInput(formToUpdate.mainTopic),
slug: formToUpdate.slug,
subtitle: formToUpdate.subtitle,
title: formToUpdate.title,
cover: formToUpdate.coverImageUrl,
media: formToUpdate.media
2023-05-10 20:20:53 +00:00
},
publish
})
}
const saveShout = async (formToSave: ShoutForm) => {
if (isEditorPanelVisible()) {
toggleEditorPanel()
}
2023-05-10 20:20:53 +00:00
if (page().route === 'edit' && !validate()) {
return
}
if (page().route === 'editSettings' && !validateSettings()) {
2023-05-08 17:21:06 +00:00
return
}
2023-05-05 20:05:50 +00:00
try {
const shout = await updateShout(formToSave, { publish: false })
removeDraftFromLocalStorage(formToSave.shoutId)
2023-05-08 17:21:06 +00:00
if (shout.visibility === 'owner') {
openPage(router, 'drafts')
} else {
openPage(router, 'article', { slug: shout.slug })
}
2023-05-05 20:05:50 +00:00
} catch (error) {
2023-05-08 18:01:11 +00:00
console.error('[saveShout]', error)
2023-05-05 20:05:50 +00:00
showSnackbar({ type: 'error', body: t('Error') })
}
}
const saveDraft = async (draftForm: ShoutForm) => {
await updateShout(draftForm, { publish: false })
}
const saveDraftToLocalStorage = (formToSave: ShoutForm) => {
localStorage.setItem(`shout-${formToSave.shoutId}`, JSON.stringify(formToSave))
}
const getDraftFromLocalStorage = (shoutId: number) => {
return JSON.parse(localStorage.getItem(`shout-${shoutId}`))
}
const removeDraftFromLocalStorage = (shoutId: number) => {
localStorage.removeItem(`shout-${shoutId}`)
}
const publishShout = async (formToPublish: ShoutForm) => {
if (isEditorPanelVisible()) {
toggleEditorPanel()
}
2023-05-10 20:20:53 +00:00
2023-05-08 17:21:06 +00:00
if (page().route === 'edit') {
2023-05-11 11:06:29 +00:00
if (!validate()) {
return
}
await updateShout(formToPublish, { publish: false })
2023-05-11 11:06:29 +00:00
2023-05-10 20:20:53 +00:00
const slug = slugify(form.title)
2023-05-08 17:21:06 +00:00
setForm('slug', slug)
openPage(router, 'editSettings', { shoutId: form.shoutId.toString() })
return
}
2023-05-11 11:06:29 +00:00
if (!validateSettings()) {
return
}
2023-05-05 20:05:50 +00:00
try {
await updateShout(formToPublish, { publish: true })
2023-05-08 18:26:42 +00:00
openPage(router, 'feed')
2023-05-08 17:21:06 +00:00
} catch (error) {
2023-05-08 18:01:11 +00:00
console.error('[publishShout]', error)
2023-05-08 17:21:06 +00:00
showSnackbar({ type: 'error', body: t('Error') })
}
}
const publishShoutById = async (shoutId: number) => {
try {
await apiClient.updateArticle({
shoutId,
publish: true
})
openPage(router, 'feed')
} catch (error) {
2023-05-08 18:01:11 +00:00
console.error('[publishShoutById]', error)
2023-05-08 17:21:06 +00:00
showSnackbar({ type: 'error', body: t('Error') })
}
}
const deleteShout = async (shoutId: number) => {
try {
await apiClient.deleteShout({
shoutId
2023-05-05 20:05:50 +00:00
})
return true
} catch {
showSnackbar({ type: 'error', body: t('Error') })
return false
}
}
const setEditor = (editor: () => Editor) => {
editorRef.current = editor
}
const actions = {
2023-05-05 20:05:50 +00:00
saveShout,
saveDraft,
saveDraftToLocalStorage,
getDraftFromLocalStorage,
2023-05-05 20:05:50 +00:00
publishShout,
2023-05-08 17:21:06 +00:00
publishShoutById,
deleteShout,
toggleEditorPanel,
countWords,
2023-05-05 20:05:50 +00:00
setForm,
setFormErrors,
setEditor
}
const value: EditorContextType = {
actions,
form,
formErrors,
editorRef,
isEditorPanelVisible,
wordCounter
}
return <EditorContext.Provider value={value}>{props.children}</EditorContext.Provider>
}