personal-website/studio/documentActions/blogPostPublishAction.ts
Filipe Medeiros 4a5a08906a
feat: article schema
Signed-off-by: Filipe Medeiros <hello@filipesm.eu>
2023-12-03 12:26:01 +01:00

41 lines
1.3 KiB
TypeScript

import {useEffect, useState} from 'react'
import {
DocumentActionComponent,
DocumentActionProps,
PortableTextBlock,
useDocumentOperation,
} from 'sanity'
import {toPlainText} from '@portabletext/toolkit'
export function blogPostPublishAction(originalPublishAction: DocumentActionComponent) {
const BetterAction = (props: DocumentActionProps) => {
const {patch, publish} = useDocumentOperation(props.id, props.type)
const [isPublishing, setIsPublishing] = useState(false)
useEffect(() => {
if (isPublishing && !props.draft) {
setIsPublishing(false)
}
}, [props.draft, isPublishing])
if (props.type !== 'blogPost') return originalPublishAction(props)
const content = (props.draft?.content ?? props.published?.content) as
| PortableTextBlock[]
| undefined
const readTimeInMinutes = content ? Math.ceil(toPlainText(content).length / 5 / 180) : 0
return {
disabled: publish.disabled,
label: isPublishing ? 'Publishing…' : 'Update & Publish',
onHandle: () => {
setIsPublishing(true)
props.type === 'blogPost' && patch.execute([{set: {readTime: `${readTimeInMinutes} min`}}])
publish.execute()
props.onComplete()
},
}
}
return BetterAction
}