Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add duplicate document action #194

Merged
merged 10 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/07-duplicating-translated-documents.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Duplicating translated documents

This plugin includes a custom document action that will duplicate a localized document, its translations, and the metadata document that relates them.

![Duplicate document action](./img/duplicate-document-action.png)

Import the document action and configure which document types will use it:

```ts
import {
documentInternationalization,
DuplicateWithTranslationsAction,
} from '@sanity/document-internationalization'

export default defineConfig({
// ...all other config
document: {
actions(prev, {schemaType}) {
// these will be the schema types you're passing to the plugin configuration
return schemaTypes.includes(schemaType)
? prev.map((action) =>
action.action === 'duplicate'
? DuplicateWithTranslationsAction
: action
)
: prev
},
},
})
```
Binary file added docs/img/duplicate-document-action.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
252 changes: 252 additions & 0 deletions src/actions/DuplicateWithTranslationsAction.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
import {CopyIcon} from '@sanity/icons'
import {useToast} from '@sanity/ui'
import {uuid} from '@sanity/uuid'
import {useCallback, useMemo, useState} from 'react'
import {filter, firstValueFrom} from 'rxjs'
import {
DEFAULT_STUDIO_CLIENT_OPTIONS,
type DocumentActionComponent,
type Id,
InsufficientPermissionsMessage,
type PatchOperations,
useClient,
useCurrentUser,
useDocumentOperation,
useDocumentPairPermissions,
useDocumentStore,
useTranslation,
} from 'sanity'
import {useRouter} from 'sanity/router'
import {structureLocaleNamespace} from 'sanity/structure'

import {METADATA_SCHEMA_NAME, TRANSLATIONS_ARRAY_NAME} from '../constants'
import {useTranslationMetadata} from '../hooks/useLanguageMetadata'
import {documenti18nLocaleNamespace} from '../i18n'

const DISABLED_REASON_KEY = {
METADATA_NOT_FOUND: 'action.duplicate.disabled.missing-metadata',
MULTIPLE_METADATA: 'action.duplicate.disabled.multiple-metadata',
NOTHING_TO_DUPLICATE: 'action.duplicate.disabled.nothing-to-duplicate',
NOT_READY: 'action.duplicate.disabled.not-ready',
}

export const DuplicateWithTranslationsAction: DocumentActionComponent = ({
id,
type,
onComplete,
}) => {
const documentStore = useDocumentStore()
const {duplicate} = useDocumentOperation(id, type)
const {navigateIntent} = useRouter()
const [isDuplicating, setDuplicating] = useState(false)
const [permissions, isPermissionsLoading] = useDocumentPairPermissions({
id,
type,
permission: 'duplicate',
})
const {data, loading: isMetadataDocumentLoading} = useTranslationMetadata(id)
const hasOneMetadataDocument = useMemo(() => {
return Array.isArray(data) && data.length <= 1
}, [data])
const metadataDocument = Array.isArray(data) && data.length ? data[0] : null
const client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS)
const toast = useToast()
const {t: s} = useTranslation(structureLocaleNamespace)
const {t: d} = useTranslation(documenti18nLocaleNamespace)
const currentUser = useCurrentUser()

const handle = useCallback(async () => {
setDuplicating(true)

try {
if (!metadataDocument) {
throw new Error('Metadata document not found')
}

// 1. Duplicate the document and its localized versions
const translations = new Map<string, Id>()
await Promise.all(
metadataDocument[TRANSLATIONS_ARRAY_NAME].map(async (translation) => {
const dupeId = uuid()
const locale = translation._key
const docId = translation.value?._ref

if (!docId) {
throw new Error('Translation document not found')
}

const {duplicate: duplicateTranslation} = await firstValueFrom(
documentStore.pair
.editOperations(docId, type)
.pipe(filter((op) => op.duplicate.disabled !== 'NOT_READY'))
)

if (duplicateTranslation.disabled) {
throw new Error('Cannot duplicate document')
}

const duplicateTranslationSuccess = firstValueFrom(
documentStore.pair
.operationEvents(docId, type)
.pipe(filter((e) => e.op === 'duplicate' && e.type === 'success'))
)
duplicateTranslation.execute(dupeId)
await duplicateTranslationSuccess

translations.set(locale, dupeId)
})
)

// 2. Duplicate the metadata document
const {duplicate: duplicateMetadata} = await firstValueFrom(
documentStore.pair
.editOperations(metadataDocument._id, METADATA_SCHEMA_NAME)
.pipe(filter((op) => op.duplicate.disabled !== 'NOT_READY'))
)

if (duplicateMetadata.disabled) {
throw new Error('Cannot duplicate document')
}

const duplicateMetadataSuccess = firstValueFrom(
documentStore.pair
.operationEvents(metadataDocument._id, METADATA_SCHEMA_NAME)
.pipe(filter((e) => e.op === 'duplicate' && e.type === 'success'))
)
const dupeId = uuid()
duplicateMetadata.execute(dupeId)
await duplicateMetadataSuccess

// 3. Patch the duplicated metadata document to update the references
// TODO: use document store

Check warning on line 121 in src/actions/DuplicateWithTranslationsAction.tsx

View workflow job for this annotation

GitHub Actions / Lint & Build

Unexpected 'todo' comment: 'TODO: use document store'
// const {patch: patchMetadata} = await firstValueFrom(
// documentStore.pair
// .editOperations(dupeId, METADATA_SCHEMA_NAME)
// .pipe(filter((op) => op.patch.disabled !== 'NOT_READY'))
// )

// if (patchMetadata.disabled) {
// throw new Error('Cannot patch document')
// }

// await firstValueFrom(
// documentStore.pair
// .consistencyStatus(dupeId, METADATA_SCHEMA_NAME)
// .pipe(filter((isConsistant) => isConsistant))
// )

// const patchMetadataSuccess = firstValueFrom(
// documentStore.pair
// .operationEvents(dupeId, METADATA_SCHEMA_NAME)
// .pipe(filter((e) => e.op === 'patch' && e.type === 'success'))
// )

const patch: PatchOperations = {
set: Object.fromEntries(
Array.from(translations.entries()).map(([locale, documentId]) => [
`${TRANSLATIONS_ARRAY_NAME}[_key == "${locale}"].value._ref`,
documentId,
])
),
}

// patchMetadata.execute([patch])
// await patchMetadataSuccess
await client.transaction().patch(dupeId, patch).commit()

// 4. Navigate to the duplicated document
navigateIntent('edit', {
id: Array.from(translations.values()).at(0),
type,
})

onComplete()
} catch (error) {
console.error(error)
toast.push({
status: 'error',
title: 'Error duplicating document',
description:
error instanceof Error
? error.message
: 'Failed to duplicate document',
})
} finally {
setDuplicating(false)
}
}, [
client,
documentStore.pair,
metadataDocument,
navigateIntent,
onComplete,
toast,
type,
])

return useMemo(() => {
if (!isPermissionsLoading && !permissions?.granted) {
return {
icon: CopyIcon,
disabled: true,
label: d('action.duplicate.label'),
title: (
<InsufficientPermissionsMessage
context="duplicate-document"
currentUser={currentUser}
/>
),
}
}

if (!isMetadataDocumentLoading && !metadataDocument) {
return {
icon: CopyIcon,
disabled: true,
label: d('action.duplicate.label'),
title: d(DISABLED_REASON_KEY.METADATA_NOT_FOUND),
}
}

if (!hasOneMetadataDocument) {
return {
icon: CopyIcon,
disabled: true,
label: d('action.duplicate.label'),
title: d(DISABLED_REASON_KEY.MULTIPLE_METADATA),
}
}

return {
icon: CopyIcon,
disabled:
isDuplicating ||
Boolean(duplicate.disabled) ||
isPermissionsLoading ||
isMetadataDocumentLoading,
label: isDuplicating
? s('action.duplicate.running.label')
: d('action.duplicate.label'),
title: duplicate.disabled
? s(DISABLED_REASON_KEY[duplicate.disabled])
: '',
onHandle: handle,
}
}, [
currentUser,
duplicate.disabled,
handle,
hasOneMetadataDocument,
isDuplicating,
isMetadataDocumentLoading,
isPermissionsLoading,
metadataDocument,
permissions?.granted,
s,
d,
])
}

DuplicateWithTranslationsAction.action = 'duplicate'
// @ts-expect-error `displayName` is used by React DevTools
DuplicateWithTranslationsAction.displayName = 'DuplicateWithTranslationsAction'
21 changes: 21 additions & 0 deletions src/i18n/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {defineLocaleResourceBundle} from 'sanity'

/**
* The locale namespace for the document internationalization plugin.
*
* @public
*/
export const documenti18nLocaleNamespace =
'document-internationalization' as const

/**
* The default locale bundle for the document internationalization plugin, which is US English.
*
* @internal
*/
export const documentInternationalizationUsEnglishLocaleBundle =
defineLocaleResourceBundle({
locale: 'en-US',
namespace: documenti18nLocaleNamespace,
resources: () => import('./resources'),
})
7 changes: 7 additions & 0 deletions src/i18n/resources.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default {
'action.duplicate.label': 'Duplicate with translations',
'action.duplicate.disabled.missing-metadata':
'The document cannot be duplicated because the metadata document is missing',
'action.duplicate.disabled.multiple-metadata':
'The document cannot be duplicated because there are multiple metadata documents',
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export {DeleteTranslationAction} from './actions/DeleteTranslationAction'
export {DuplicateWithTranslationsAction} from './actions/DuplicateWithTranslationsAction'
export {useDocumentInternationalizationContext} from './components/DocumentInternationalizationContext'
export {DocumentInternationalizationMenu} from './components/DocumentInternationalizationMenu'
export {documentInternationalization} from './plugin'
Expand Down
5 changes: 5 additions & 0 deletions src/plugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {DocumentInternationalizationProvider} from './components/DocumentInterna
import {DocumentInternationalizationMenu} from './components/DocumentInternationalizationMenu'
import OptimisticallyStrengthen from './components/OptimisticallyStrengthen'
import {API_VERSION, DEFAULT_CONFIG, METADATA_SCHEMA_NAME} from './constants'
import {documentInternationalizationUsEnglishLocaleBundle} from './i18n'
import metadata from './schema/translation/metadata'
import type {PluginConfig, TranslationReference} from './types'

Expand Down Expand Up @@ -39,6 +40,10 @@ export const documentInternationalization = definePlugin<PluginConfig>(
},
},

i18n: {
bundles: [documentInternationalizationUsEnglishLocaleBundle],
},

// Adds:
// - A bulk-publishing UI component to the form
// - Will only work for projects on a compatible plan
Expand Down
Loading