Skip to content

Commit

Permalink
Fix never ending publish when news/localnews is published for the fir…
Browse files Browse the repository at this point in the history
…st time #2587 (#2606)

* 🐛 Fix never finishing publish action #2587

* 🚚 Rename #2587
  • Loading branch information
padms authored Nov 5, 2024
1 parent 0861454 commit b6fc9ff
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 79 deletions.
124 changes: 48 additions & 76 deletions sanityv3/actions/CustomPublishAction.ts
Original file line number Diff line number Diff line change
@@ -1,84 +1,56 @@
import { useState } from 'react'
import {
DocumentActionComponent,
DocumentActionConfirmDialogProps,
DocumentActionDescription,
DocumentActionProps,
DocumentActionsContext,
SanityClient,
} from 'sanity'
import { apiVersion } from '../sanity.client'
import { useToast } from '@sanity/ui'
import { useState, useEffect } from 'react'
import { DocumentActionConfirmDialogProps, DocumentActionProps, useDocumentOperation } from 'sanity'

const FIRST_PUBLISHED_AT_FIELD_NAME = 'firstPublishedAt'
const LAST_MODIFIED_AT_FIELD_NAME = 'lastModifiedAt'

const requiresConfirm = ['news', 'localNews']
const requiresFirstPublished = ['news', 'localNews']
export function SetAndPublishAction(props: DocumentActionProps) {
const { patch, publish } = useDocumentOperation(props.id, props.type)
const [isPublishing, setIsPublishing] = useState(false)
const [dialogOpen, setDialogOpen] = useState(false)

const updateCustomPublishFields = async (id: string, client: SanityClient, setFirstPublish: boolean) => {
const currentTimeStamp = new Date().toISOString()
const patch = client.patch(id).set({ [LAST_MODIFIED_AT_FIELD_NAME]: currentTimeStamp })
if (setFirstPublish) patch.set({ [FIRST_PUBLISHED_AT_FIELD_NAME]: currentTimeStamp })

await patch.commit().catch((e) => {
throw e
})
}

export function createCustomPublishAction(originalAction: DocumentActionComponent, context: DocumentActionsContext) {
const client = context.getClient({ apiVersion: apiVersion })
return (props: DocumentActionProps) => {
const [dialogOpen, setDialogOpen] = useState(false)
const originalResult = originalAction(props as DocumentActionProps) as DocumentActionDescription
const toast = useToast()

const handlePublish = async () => {
try {
if (requiresFirstPublished.includes(props.type)) {
await updateCustomPublishFields(
props.draft?._id || props.id,
client,
!props.published?.[FIRST_PUBLISHED_AT_FIELD_NAME],
)
}
originalResult.onHandle && originalResult.onHandle()
setDialogOpen(false)
} catch (e) {
console.error(e)
toast.push({
duration: 7000,
status: 'error',
title: 'Failed to publish, you probably miss the mutation token. Check console for details.',
})
setDialogOpen(false)
}
}

const confirmationBox = requiresConfirm.includes(props.type)
? {
onHandle: () => {
setDialogOpen(true)
},
dialog:
dialogOpen &&
props.draft &&
({
type: 'confirm',
onCancel: () => {
props.onComplete()
setDialogOpen(false)
},
onConfirm: handlePublish,
message: 'Are you sure you want to publish?',
} as DocumentActionConfirmDialogProps),
}
: {}

return {
...originalResult,
onHandle: handlePublish,
...confirmationBox,
useEffect(() => {
// if the isPublishing state was set to true and the draft has changed
// to become `null` the document has been published
if (isPublishing && !props.draft) {
setIsPublishing(false)
}
}, [props.draft])

return {
disabled: publish.disabled || dialogOpen,
label: isPublishing ? 'Publishing…' : `Publish`,
onHandle: () => {
// This will update the button text
setDialogOpen(true)
},
dialog:
dialogOpen &&
props.draft &&
({
type: 'confirm',
onCancel: () => {
props.onComplete()
setDialogOpen(false)
},
onConfirm: () => {
const currentTimeStamp = new Date().toISOString()
// set lastModifiedAt date.
patch.execute([{ set: { [LAST_MODIFIED_AT_FIELD_NAME]: currentTimeStamp } }])

//set firstPublishedAt date if not published.
if (!props.published?.[FIRST_PUBLISHED_AT_FIELD_NAME])
patch.execute([{ set: { [FIRST_PUBLISHED_AT_FIELD_NAME]: currentTimeStamp } }])

// Perform the publish
publish.execute()

// Signal that the action is completed
props.onComplete()

setDialogOpen(false)
},
message: 'Are you sure you want to publish?',
} as DocumentActionConfirmDialogProps),
}
}
7 changes: 4 additions & 3 deletions sanityv3/sanity.config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
PluginOptions,
SchemaTypeDefinition,
Template,
buildLegacyTheme } from 'sanity'
buildLegacyTheme,
} from 'sanity'

import type {
InputProps,
Expand All @@ -27,7 +28,7 @@ import { DeleteTranslationAction } from './actions/customDelete/DeleteTranslatio
import { documentInternationalization } from '@equinor/document-internationalization'
import { FotowareAssetSource } from './plugins/asset-source-fotoware'
import { BrandmasterAssetSource } from './plugins/asset-source-brandmaster'
import { createCustomPublishAction } from './actions/CustomPublishAction'
import { SetAndPublishAction } from './actions/CustomPublishAction'
import { dataset, projectId } from './sanity.client'
import { DatabaseIcon } from '@sanity/icons'
import { crossDatasetDuplicator } from '@sanity/cross-dataset-duplicator'
Expand Down Expand Up @@ -123,7 +124,7 @@ const getConfig = (datasetParam: string, projectIdParam: string, isSecret = fals
.map((originalAction) => {
switch (originalAction.action) {
case 'publish':
return createCustomPublishAction(originalAction, context)
return ['news', 'localNews'].includes(context.schemaType) ? SetAndPublishAction : originalAction
case 'duplicate':
return createCustomDuplicateAction(originalAction)
default:
Expand Down

0 comments on commit b6fc9ff

Please sign in to comment.