36 lines
1.2 KiB
TypeScript
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
|
|
}
|