personal-website/studio/documentActions/blogPostPublishAction.ts
Filipe Medeiros bfd7276e37
fix: some fixes and improvements in the studio
Signed-off-by: Filipe Medeiros <hello@filipesm.eu>
2023-12-03 12:26:10 +01:00

36 lines
1.2 KiB
TypeScript

import {useEffect, useState} from 'react'
import {DocumentActionComponent, PortableTextBlock, useDocumentOperation} from 'sanity'
import {toPlainText} from '@portabletext/toolkit'
export default function customPublishAction(originalPublishAction: DocumentActionComponent) {
const BetterAction: DocumentActionComponent = (props) => {
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
}