Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fix translations editor dirty-on-open and stale coverage grid (#14594)

Damian Legawiec4156d50a1424
diff --git a/.changeset/translations-dialog-dirty-and-cache.md b/.changeset/translations-dialog-dirty-and-cache.md
new file mode 100644
index 0000000000..d92f32493e
--- /dev/null
+++ b/.changeset/translations-dialog-dirty-and-cache.md
@@ -0,0 +1,9 @@
+---
+'@spree/dashboard': patch
+'@spree/dashboard-ui': patch
+'@spree/dashboard-core': patch
+---
+
+Stop the translations editor marking itself dirty on open, and refresh the translations page after a save or a catalog edit.
+
+The rich-text cell was treating TipTap's mount-time paragraph wrap as an unsaved change against descriptions stored as plain text. Translation queries now share one cache prefix so saving a translation, editing the source record, or importing a translations CSV invalidates the coverage grid instead of leaving it stale.
diff --git a/packages/dashboard-core/src/hooks/use-import.ts b/packages/dashboard-core/src/hooks/use-import.ts
index 955e64b119..bd8e59b229 100644
--- a/packages/dashboard-core/src/hooks/use-import.ts
+++ b/packages/dashboard-core/src/hooks/use-import.ts
@@ -26,7 +26,8 @@ const IMPORT_POLL_INTERVAL_MS = 2000
const ROWS_POLL_INTERVAL_MS = 5000
// Caches any import may have written to, plus `imports` itself (history table
-// status column). Deliberately not per-type — imports are rare, so a few
+// status column) and `translations` (product-translation CSV updates the
+// coverage grid). Deliberately not per-type — imports are rare, so a few
// extra refetches beat maintaining a type → resource map (product rows alone
// fan out to option types/values and categories created on the fly).
//
@@ -41,6 +42,7 @@ const IMPORT_TOUCHED_RESOURCES = [
'categories',
'customers',
'imports',
+ 'translations',
'prices',
'catalogs',
]
diff --git a/packages/dashboard-ui/src/index.ts b/packages/dashboard-ui/src/index.ts
index fe3f0e4d9e..a18d83b929 100644
--- a/packages/dashboard-ui/src/index.ts
+++ b/packages/dashboard-ui/src/index.ts
@@ -18,6 +18,7 @@ export * from './hooks/use-scrolled'
// ---------------------------------------------------------------------------
// Helpers + hooks
// ---------------------------------------------------------------------------
+export { sameRichText } from './lib/same-rich-text'
export { cn } from './lib/utils'
export { requiredMessage } from './lib/validation-messages'
// ---------------------------------------------------------------------------
diff --git a/packages/dashboard-ui/src/lib/same-rich-text.ts b/packages/dashboard-ui/src/lib/same-rich-text.ts
new file mode 100644
index 0000000000..5b78749f1c
--- /dev/null
+++ b/packages/dashboard-ui/src/lib/same-rich-text.ts
@@ -0,0 +1,107 @@
+/**
+ * Whether two rich-text strings are the same content after TipTap-style
+ * normalization. The editor wraps bare text in `<p>` and emits empty
+ * paragraphs (`<p></p>`, `<p><br></p>`) on mount — those must not count as
+ * an edit against a stored plain-text or empty baseline.
+ *
+ * Implemented with linear scans so a long string of empty paragraphs cannot
+ * trip a polynomial regular expression (CodeQL js/polynomial-redos).
+ */
+export function sameRichText(left: string, right: string): boolean {
+ return canonicalizeRichText(left) === canonicalizeRichText(right)
+}
+
+function canonicalizeRichText(html: string): string {
+ const withoutTrailingEmpty = stripTrailingEmptyParagraphs((html ?? '').trim())
+ if (!visibleText(withoutTrailingEmpty) && !hasImage(withoutTrailingEmpty)) return ''
+ if (!looksLikeHtml(withoutTrailingEmpty)) return `<p>${withoutTrailingEmpty}</p>`
+ return withoutTrailingEmpty
+}
+
+function stripTrailingEmptyParagraphs(html: string): string {
+ let end = html.length
+
+ while (end > 0) {
+ while (end > 0 && isAsciiWhitespace(html.charCodeAt(end - 1))) end -= 1
+ if (!html.slice(0, end).toLowerCase().endsWith('</p>')) break
+
+ const open = html.lastIndexOf('<p>', end - 4)
+ if (open === -1 || open > end - 4) break
+
+ const inner = html.slice(open + 3, end - 4).trim()
+ if (inner === '' || isBreakOnly(inner) || isNbspOnly(inner)) {
+ end = open
+ continue
+ }
+ break
+ }
+
+ return html.slice(0, end).trim()
+}
+
+function isBreakOnly(inner: string): boolean {
+ const lower = inner.toLowerCase()
+ return lower === '<br>' || lower === '<br/>' || lower === '<br />'
+}
+
+function isNbspOnly(inner: string): boolean {
+ return inner.replace(/&nbsp;/gi, '').trim() === ''
+}
+
+function isAsciiWhitespace(charCode: number): boolean {
+ return charCode === 32 || charCode === 9 || charCode === 10 || charCode === 13
+}
+
+function looksLikeHtml(value: string): boolean {
+ const start = value.search(/<\/?[a-z]/i)
+ if (start === -1) return false
+ return value.indexOf('>', start) !== -1
+}
+
+/** TipTap's image button can produce a paragraph that has no text. */
+function hasImage(html: string): boolean {
+ const lower = html.toLowerCase()
+ let index = 0
+ while (index < lower.length) {
+ const open = lower.indexOf('<img', index)
+ if (open === -1) return false
+ const after = lower.charCodeAt(open + 4)
+ if (
+ Number.isNaN(after) ||
+ after === 32 ||
+ after === 9 ||
+ after === 10 ||
+ after === 13 ||
+ after === 47 ||
+ after === 62
+ ) {
+ return true
+ }
+ index = open + 4
+ }
+ return false
+}
+
+function visibleText(html: string): string {
+ let text = ''
+ let index = 0
+ while (index < html.length) {
+ const open = html.indexOf('<', index)
+ if (open === -1) {
+ text += html.slice(index)
+ break
+ }
+ text += html.slice(index, open)
+ const close = html.indexOf('>', open + 1)
+ if (close === -1) {
+ text += html.slice(open)
+ break
+ }
+ text += ' '
+ index = close + 1
+ }
+ return text
+ .replace(/&nbsp;/gi, ' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+}
diff --git a/packages/dashboard-ui/src/ui/rich-text-editor.tsx b/packages/dashboard-ui/src/ui/rich-text-editor.tsx
index 41e9eeaf20..50b6d81937 100644
--- a/packages/dashboard-ui/src/ui/rich-text-editor.tsx
+++ b/packages/dashboard-ui/src/ui/rich-text-editor.tsx
@@ -6,6 +6,7 @@ import { EditorContent, useEditor, useEditorState } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import { useCallback, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { sameRichText } from '../lib/same-rich-text'
import { cn } from '../lib/utils'
import {
BoldIcon,
@@ -74,9 +75,11 @@ export function RichTextEditor({
// attempts another create instead of an update.
const onChangeRef = useRef(onChange)
const onBlurRef = useRef(onBlur)
+ const valueRef = useRef(value)
useEffect(() => {
onChangeRef.current = onChange
onBlurRef.current = onBlur
+ valueRef.current = value
})
const editor = useEditor({
@@ -97,7 +100,11 @@ export function RichTextEditor({
},
},
onUpdate: ({ editor }) => {
- onChangeRef.current?.(editor.getHTML())
+ const html = editor.getHTML()
+ // Mount and setContent re-parse the incoming value (bare text becomes
+ // `<p>…</p>`, empty becomes `<p></p>`). That is not a user edit.
+ if (sameRichText(html, valueRef.current)) return
+ onChangeRef.current?.(html)
},
onBlur: ({ event }) => {
// Tiptap fires `onBlur` whenever the contenteditable loses focus —
diff --git a/packages/dashboard/e2e/categories.spec.ts b/packages/dashboard/e2e/categories.spec.ts
index ea14804310..8bdbb918a1 100644
--- a/packages/dashboard/e2e/categories.spec.ts
+++ b/packages/dashboard/e2e/categories.spec.ts
@@ -20,7 +20,11 @@ async function createCategory(page: Page, name: string) {
await page.locator('#category-name').fill(name)
await page.getByRole('button', { name: /^save$/i }).click()
- // Create replaces the new-form route in history; back lands on the tree.
+ // The name input already holds this value on the new form, so it cannot
+ // prove save finished. Wait for create to replace `/new` with the edit
+ // route; only then does Back land on the tree instead of racing the
+ // replace onto the detail URL.
+ await expect(page).toHaveURL(/\/products\/categories\/(?!new(?:\?|$))/, { timeout: 15_000 })
await expect(page.locator('#category-name')).toHaveValue(name, { timeout: 15_000 })
await page.getByRole('button', { name: /^back$/i }).click()
await expect(page).toHaveURL(/\/products\/categories(?:\?|$)/, { timeout: 15_000 })
diff --git a/packages/dashboard/e2e/products-translations.spec.ts b/packages/dashboard/e2e/products-translations.spec.ts
index 4b2465a562..6b1623d5d2 100644
--- a/packages/dashboard/e2e/products-translations.spec.ts
+++ b/packages/dashboard/e2e/products-translations.spec.ts
@@ -1,7 +1,53 @@
import { expect, test } from '@playwright/test'
-import { login } from './helpers'
+import { gotoIndex, login } from './helpers'
import { createProduct } from './products-helpers'
+const TRANSLATIONS_PATH = (storeId: string) => `/${storeId}/products/translations`
+
+/** The records search — not the header "Search settings" command box. */
+function coverageSearch(page: import('@playwright/test').Page) {
+ return page.getByRole('searchbox', { name: 'Search…' })
+}
+
+async function seedProductWithPlainDescriptionTranslation(
+ page: import('@playwright/test').Page,
+ storeId: string,
+ accessToken: string,
+ name: string,
+ descriptionDe: string,
+): Promise<string> {
+ const headers = {
+ 'X-Spree-Store-Id': storeId,
+ Authorization: `Bearer ${accessToken}`,
+ }
+ const created = await page.request.post('/api/v3/admin/products', {
+ headers,
+ data: { name, status: 'active', price: 9.99 },
+ })
+ if (!created.ok()) {
+ throw new Error(`Failed to seed product: ${created.status()} ${await created.text()}`)
+ }
+ const { id } = (await created.json()) as { id: string }
+
+ const batched = await page.request.post('/api/v3/admin/translations/batch', {
+ headers,
+ data: {
+ translations: [
+ {
+ resource_type: 'product',
+ resource_id: id,
+ values: { de: { description: descriptionDe } },
+ },
+ ],
+ },
+ })
+ if (!batched.ok()) {
+ throw new Error(`Failed to seed translation: ${batched.status()} ${await batched.text()}`)
+ }
+
+ return id
+}
+
// The e2e store has a US/USD (default_locale en) market plus a Europe/EUR
// (default_locale de) market (see global-setup), so `de` is available as a
// non-default translation locale and the translations editor renders.
@@ -60,4 +106,80 @@ test.describe('product translations', () => {
await expect(save).toBeDisabled()
await expect(dialog.getByText(/unsaved change/i)).toHaveCount(0)
})
+
+ test('opening a record whose description is stored as plain text is not dirty', async ({
+ page,
+ }) => {
+ const creds = await login(page)
+ const suffix = Date.now()
+ const name = `E2E PlainDesc ${suffix}`
+ // Sample-data / CSV translations store description as bare text. TipTap
+ // wraps that in `<p>` on mount — that wrap must not count as an edit.
+ await seedProductWithPlainDescriptionTranslation(
+ page,
+ creds.store_id,
+ creds.accessToken,
+ name,
+ 'Höhenverstellbarer Standventilator mit 40cm Rotordurchmesser',
+ )
+
+ await gotoIndex(page, TRANSLATIONS_PATH(creds.store_id), /import/i)
+ await coverageSearch(page).fill(name)
+ await page.getByRole('button', { name }).click()
+
+ const dialog = page.getByRole('dialog')
+ await expect(dialog.getByText('Original', { exact: true })).toBeVisible({ timeout: 15_000 })
+ await expect(dialog.getByRole('button', { name: /^save translations$/i })).toBeDisabled()
+ await expect(dialog.getByText(/unsaved change/i)).toHaveCount(0)
+ })
+
+ test('renaming a product refreshes the translations coverage list', async ({ page }) => {
+ const creds = await login(page)
+ const suffix = Date.now()
+ const name = `E2E Rename ${suffix}`
+ const renamed = `E2E Renamed ${suffix}`
+ await createProduct(page, creds.store_id, name)
+ const productUrl = page.url()
+
+ await gotoIndex(page, TRANSLATIONS_PATH(creds.store_id), /import/i)
+ await coverageSearch(page).fill(name)
+ await expect(page.getByRole('row', { name: new RegExp(name) })).toBeVisible({ timeout: 15_000 })
+
+ await page.goto(productUrl)
+ await expect(page.getByLabel(/^name$/i)).toHaveValue(name, { timeout: 15_000 })
+ await page.getByLabel(/^name$/i).fill(renamed)
+ await page.getByRole('button', { name: /^save product$/i }).click()
+ await expect(page.getByText(/product saved/i)).toBeVisible({ timeout: 15_000 })
+
+ await gotoIndex(page, TRANSLATIONS_PATH(creds.store_id), /import/i)
+ await coverageSearch(page).fill(renamed)
+ await expect(page.getByRole('row', { name: new RegExp(renamed) })).toBeVisible({
+ timeout: 15_000,
+ })
+ })
+
+ test('saving a translation refreshes the coverage grid behind the editor', async ({ page }) => {
+ const creds = await login(page)
+ const suffix = Date.now()
+ const name = `E2E Coverage ${suffix}`
+ await createProduct(page, creds.store_id, name)
+
+ await gotoIndex(page, TRANSLATIONS_PATH(creds.store_id), /import/i)
+ await coverageSearch(page).fill(name)
+ const row = page.getByRole('row', { name: new RegExp(name) })
+ await expect(row).toBeVisible({ timeout: 15_000 })
+ await expect(row.getByText('—')).toBeVisible()
+
+ await row.getByRole('button', { name }).click()
+ const dialog = page.getByRole('dialog')
+ await expect(dialog.getByText('Original', { exact: true })).toBeVisible({ timeout: 15_000 })
+
+ await dialog.getByLabel('name de').fill(`Übersetzt ${suffix}`)
+ await dialog.getByRole('button', { name: /^save translations$/i }).click()
+ await expect(page.getByText(/translations saved/i)).toBeVisible({ timeout: 15_000 })
+ await dialog.getByRole('button', { name: /^close$/i }).click()
+
+ await expect(row.getByText('—')).toBeHidden({ timeout: 15_000 })
+ await expect(row.getByText(/\d+\/\d+/)).toBeVisible()
+ })
})
diff --git a/packages/dashboard/e2e/validation-messages.spec.ts b/packages/dashboard/e2e/validation-messages.spec.ts
index 6d025b8524..643f9dccbb 100644
--- a/packages/dashboard/e2e/validation-messages.spec.ts
+++ b/packages/dashboard/e2e/validation-messages.spec.ts
@@ -41,6 +41,10 @@ async function submitBlankProduct(page: Page, storeId: string, createButton: Reg
// blank one.
await name.fill('x')
await name.fill('')
+ // Create stays disabled while the form matches defaults. The description
+ // editor used to dirty it on mount by emitting `<p></p>`; that wrap is no
+ // longer treated as an edit, so leave an optional field changed instead.
+ await page.locator('#product-slug').fill('e2e-blank-submit')
const create = page.getByRole('button', { name: createButton }).first()
await expect(create).toBeEnabled()
await create.click()
diff --git a/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx b/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx
index dd8aae2313..5e28d49850 100644
--- a/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx
+++ b/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx
@@ -5,7 +5,7 @@ import {
type TranslatableField,
type TranslationBatchEntry,
} from '@spree/admin-sdk'
-import { adminClient, useResourceKey } from '@spree/dashboard-core'
+import { adminClient } from '@spree/dashboard-core'
import {
Button,
cn,
@@ -21,16 +21,17 @@ import {
SelectTrigger,
SelectValue,
Skeleton,
+ sameRichText,
Textarea,
toastManager,
useConfirm,
} from '@spree/dashboard-ui'
import { XIcon } from '@spree/dashboard-ui/icons'
-import { useQueryClient } from '@tanstack/react-query'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
type TranslatableResourceType,
+ useInvalidateTranslations,
useLocaleName,
useResourceTranslations,
} from '../../../hooks/use-translations'
@@ -98,8 +99,7 @@ export function ResourceTranslationsDialog({
const { t } = useTranslation()
const confirm = useConfirm()
const { data, isLoading, isError, refetch } = useResourceTranslations(resourceType, resourceId)
- const queryClient = useQueryClient()
- const coverageKey = useResourceKey('translations', 'coverage')
+ const invalidateTranslations = useInvalidateTranslations()
const rows = useMemo(() => (data ? flattenTree(data) : []), [data])
const targetLocales = useMemo(
@@ -165,11 +165,8 @@ export function ResourceTranslationsDialog({
await adminClient.translations.batch(Array.from(byResource.values()))
toastManager.add({ type: 'success', title: t('admin.translations.saved') })
setEdits(new Map())
- refetch()
- // A save changes how much of the catalog is translated, so the coverage
- // grid behind this dialog is now stale — it is what the merchant returns
- // to when they close.
- queryClient.invalidateQueries({ queryKey: coverageKey })
+ await refetch()
+ await invalidateTranslations()
} catch (err) {
// The grid has no form to render inline errors onto, so surface the
// server's validation message (if any) in the toast rather than the
@@ -312,9 +309,14 @@ function TranslationGrid({
const stored = row.translations[locale]?.[field.key]
const baseline = typeof stored === 'string' ? stored : ''
const unchanged = field.type === 'html' ? sameRichText(next, baseline) : next === baseline
+ if (unchanged) {
+ if (!prev.has(key)) return prev
+ const out = new Map(prev)
+ out.delete(key)
+ return out
+ }
const out = new Map(prev)
- if (unchanged) out.delete(key)
- else out.set(key, next)
+ out.set(key, next)
return out
})
},
@@ -421,10 +423,3 @@ function flattenTree(data: ResourceTranslations): TranslationRow[] {
function stripHtml(html: string): string {
return (new DOMParser().parseFromString(html, 'text/html').body.textContent ?? '').trim()
}
-
-// Equal markup, or both empty-equivalent (`""`, `<p></p>`, `<p><br></p>`) — the
-// latter prevents the rich-text editor's mount-time `<p></p>` emission from
-// registering as a change against an empty baseline.
-function sameRichText(a: string, b: string): boolean {
- return a === b || (!stripHtml(a) && !stripHtml(b))
-}
diff --git a/packages/dashboard/src/hooks/use-categories.ts b/packages/dashboard/src/hooks/use-categories.ts
index eaa16a72d1..3479bc4ff6 100644
--- a/packages/dashboard/src/hooks/use-categories.ts
+++ b/packages/dashboard/src/hooks/use-categories.ts
@@ -12,6 +12,7 @@ import {
} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import i18n from 'i18next'
+import { TRANSLATIONS_QUERY_RESOURCE, useInvalidateTranslations } from './use-translations'
export function useCategories() {
return useQuery({
@@ -42,25 +43,31 @@ export function useCategory(id: string | undefined) {
}
export function useCreateCategory() {
+ const invalidateTranslations = useInvalidateTranslations()
+
return useResourceMutation<Category, Error, CategoryCreateParams>({
mutationFn: (params) => adminClient.categories.create(params),
- invalidate: [['categories']],
+ invalidate: [['categories'], [TRANSLATIONS_QUERY_RESOURCE]],
successMessage: i18n.t('admin.categories.messages.created'),
errorMessage: i18n.t('admin.errors.failed_to_create'),
+ onSuccess: () => invalidateTranslations(),
})
}
export function useUpdateCategory(id: string) {
+ const invalidateTranslations = useInvalidateTranslations()
+
return useResourceMutation<Category, Error, CategoryUpdateParams>({
mutationFn: (params) => adminClient.categories.update(id, params),
// The nested products list is held back: it prefix-matches
// `['categories', id]`, and this update runs before the membership flush
// inside the page's Save — refreshing it there paints the pre-save rows
// for a frame. The flush refreshes it once, at the end.
- invalidate: [['categories'], ['categories', id]],
+ invalidate: [['categories'], ['categories', id], [TRANSLATIONS_QUERY_RESOURCE]],
doNotInvalidate: ['products'],
successMessage: i18n.t('admin.categories.messages.updated'),
errorMessage: i18n.t('admin.errors.failed_to_update'),
+ onSuccess: () => invalidateTranslations(),
})
}
@@ -75,14 +82,16 @@ export function useRepositionCategory() {
export function useDeleteCategory() {
const queryClient = useQueryClient()
const buildKey = useResourceKeyBuilder()
+ const invalidateTranslations = useInvalidateTranslations()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.categories.delete(id),
- invalidate: [['categories']],
+ invalidate: [['categories'], [TRANSLATIONS_QUERY_RESOURCE]],
successMessage: i18n.t('admin.categories.messages.deleted'),
errorMessage: i18n.t('admin.errors.failed_to_delete'),
onSuccess: (_data, id) => {
queryClient.removeQueries({ queryKey: buildKey('categories', id) })
+ invalidateTranslations()
},
})
}
diff --git a/packages/dashboard/src/hooks/use-collections.ts b/packages/dashboard/src/hooks/use-collections.ts
index c892b0fd7b..5613ad3fcd 100644
--- a/packages/dashboard/src/hooks/use-collections.ts
+++ b/packages/dashboard/src/hooks/use-collections.ts
@@ -7,6 +7,7 @@ import {
} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import i18n from 'i18next'
+import { TRANSLATIONS_QUERY_RESOURCE, useInvalidateTranslations } from './use-translations'
export function useCollections() {
return useQuery({
@@ -37,25 +38,31 @@ export function useCollection(id: string | undefined) {
}
export function useCreateCollection() {
+ const invalidateTranslations = useInvalidateTranslations()
+
return useResourceMutation<Collection, Error, CollectionCreateParams>({
mutationFn: (params) => adminClient.collections.create(params),
- invalidate: [['collections']],
+ invalidate: [['collections'], [TRANSLATIONS_QUERY_RESOURCE]],
successMessage: i18n.t('admin.collections.messages.created'),
errorMessage: i18n.t('admin.errors.failed_to_create'),
+ onSuccess: () => invalidateTranslations(),
})
}
export function useUpdateCollection(id: string) {
+ const invalidateTranslations = useInvalidateTranslations()
+
return useResourceMutation<Collection, Error, CollectionUpdateParams>({
mutationFn: (params) => adminClient.collections.update(id, params),
// The nested products list is held back: it prefix-matches
// `['collections', id]`, and this update runs before the membership flush
// inside the page's Save — refreshing it there paints the pre-save rows
// for a frame. The flush refreshes it once, at the end.
- invalidate: [['collections'], ['collections', id]],
+ invalidate: [['collections'], ['collections', id], [TRANSLATIONS_QUERY_RESOURCE]],
doNotInvalidate: ['products'],
successMessage: i18n.t('admin.collections.messages.updated'),
errorMessage: i18n.t('admin.errors.failed_to_update'),
+ onSuccess: () => invalidateTranslations(),
})
}
@@ -75,14 +82,16 @@ export function useRepositionCollection() {
export function useDeleteCollection() {
const queryClient = useQueryClient()
const buildKey = useResourceKeyBuilder()
+ const invalidateTranslations = useInvalidateTranslations()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.collections.delete(id),
- invalidate: [['collections']],
+ invalidate: [['collections'], [TRANSLATIONS_QUERY_RESOURCE]],
successMessage: i18n.t('admin.collections.messages.deleted'),
errorMessage: i18n.t('admin.errors.failed_to_delete'),
onSuccess: (_data, id) => {
queryClient.removeQueries({ queryKey: buildKey('collections', id) })
+ invalidateTranslations()
},
})
}
diff --git a/packages/dashboard/src/hooks/use-option-types.ts b/packages/dashboard/src/hooks/use-option-types.ts
index a5e5ad496e..6777edcb09 100644
--- a/packages/dashboard/src/hooks/use-option-types.ts
+++ b/packages/dashboard/src/hooks/use-option-types.ts
@@ -12,6 +12,7 @@ import {
} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import i18n from 'i18next'
+import { TRANSLATIONS_QUERY_RESOURCE, useInvalidateTranslations } from './use-translations'
/** Human-readable label for an option value, including its option type. */
export function optionValueLabel(optionValue: OptionValue): string {
@@ -102,34 +103,42 @@ export function useOptionType(id: string | undefined) {
}
export function useCreateOptionType() {
+ const invalidateTranslations = useInvalidateTranslations()
+
return useResourceMutation<OptionType, Error, OptionTypeCreateParams>({
mutationFn: (params) => adminClient.optionTypes.create(params),
- invalidate: [['option-types']],
+ invalidate: [['option-types'], [TRANSLATIONS_QUERY_RESOURCE]],
successMessage: i18n.t('admin.option_types.messages.created'),
errorMessage: i18n.t('admin.errors.failed_to_create'),
+ onSuccess: () => invalidateTranslations(),
})
}
export function useUpdateOptionType(id: string) {
+ const invalidateTranslations = useInvalidateTranslations()
+
return useResourceMutation<OptionType, Error, OptionTypeUpdateParams>({
mutationFn: (params) => adminClient.optionTypes.update(id, params),
- invalidate: [['option-types'], ['option-types', id]],
+ invalidate: [['option-types'], ['option-types', id], [TRANSLATIONS_QUERY_RESOURCE]],
successMessage: i18n.t('admin.option_types.messages.updated'),
errorMessage: i18n.t('admin.errors.failed_to_update'),
+ onSuccess: () => invalidateTranslations(),
})
}
export function useDeleteOptionType() {
const queryClient = useQueryClient()
const buildKey = useResourceKeyBuilder()
+ const invalidateTranslations = useInvalidateTranslations()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.optionTypes.delete(id),
- invalidate: [['option-types']],
+ invalidate: [['option-types'], [TRANSLATIONS_QUERY_RESOURCE]],
successMessage: i18n.t('admin.option_types.messages.deleted'),
errorMessage: i18n.t('admin.errors.failed_to_delete'),
onSuccess: (_data, id) => {
queryClient.removeQueries({ queryKey: buildKey('option-types', id) })
+ invalidateTranslations()
},
})
}
diff --git a/packages/dashboard/src/hooks/use-product.ts b/packages/dashboard/src/hooks/use-product.ts
index a79c3348bd..ccb35792de 100644
--- a/packages/dashboard/src/hooks/use-product.ts
+++ b/packages/dashboard/src/hooks/use-product.ts
@@ -7,6 +7,7 @@ import {
useResourceMutation,
} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { TRANSLATIONS_QUERY_RESOURCE, useInvalidateTranslations } from './use-translations'
export function useProduct(id: string) {
return useQuery({
@@ -43,26 +44,32 @@ export function useProduct(id: string) {
}
export function useCreateProduct() {
+ const invalidateTranslations = useInvalidateTranslations()
+
return useResourceMutation<Product, Error, ProductCreateParams>({
mutationFn: (params) => adminClient.products.create(params),
// STORE_QUERY_RESOURCE refreshes the setup-task state (Getting Started + nav badge).
- invalidate: [['products'], [STORE_QUERY_RESOURCE]],
+ // Translations coverage lists every product, so a create leaves it stale.
+ invalidate: [['products'], [TRANSLATIONS_QUERY_RESOURCE], [STORE_QUERY_RESOURCE]],
successMessage: false,
errorMessage: false,
+ onSuccess: () => invalidateTranslations(),
})
}
export function useUpdateProduct() {
const queryClient = useQueryClient()
const buildKey = useResourceKeyBuilder()
+ const invalidateTranslations = useInvalidateTranslations()
return useResourceMutation<Product, Error, { id: string } & ProductUpdateParams>({
mutationFn: ({ id, ...params }) => adminClient.products.update(id, params),
- invalidate: [['products']],
+ invalidate: [['products'], [TRANSLATIONS_QUERY_RESOURCE]],
successMessage: false,
errorMessage: false,
- onSuccess: (_data, variables) => {
+ onSuccess: async (_data, variables) => {
queryClient.invalidateQueries({ queryKey: buildKey('products', variables.id) })
+ await invalidateTranslations()
},
})
}
@@ -104,14 +111,16 @@ export function useRejectProduct() {
export function useDeleteProduct() {
const queryClient = useQueryClient()
const buildKey = useResourceKeyBuilder()
+ const invalidateTranslations = useInvalidateTranslations()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.products.delete(id),
- invalidate: [['products'], [STORE_QUERY_RESOURCE]],
+ invalidate: [['products'], [TRANSLATIONS_QUERY_RESOURCE], [STORE_QUERY_RESOURCE]],
successMessage: false,
errorMessage: false,
- onSuccess: (_data, id) => {
+ onSuccess: async (_data, id) => {
queryClient.removeQueries({ queryKey: buildKey('products', id) })
+ await invalidateTranslations()
},
})
}
diff --git a/packages/dashboard/src/hooks/use-translations.test.ts b/packages/dashboard/src/hooks/use-translations.test.ts
new file mode 100644
index 0000000000..d22e25f8a0
--- /dev/null
+++ b/packages/dashboard/src/hooks/use-translations.test.ts
@@ -0,0 +1,103 @@
+import { withStoreScope } from '@spree/dashboard-core'
+import { QueryClient } from '@tanstack/react-query'
+import { describe, expect, it } from 'vitest'
+import { TRANSLATIONS_QUERY_RESOURCE } from './use-translations'
+
+const STORE_ID = 'store_abc123'
+
+/**
+ * Replays a prefix invalidation of the translations resource and reports
+ * which of the seeded queries went stale. The coverage grid and each
+ * per-record matrix must share this prefix so one invalidate refreshes both.
+ */
+function staleAfterTranslationsInvalidation() {
+ const queryClient = new QueryClient()
+
+ try {
+ const seeded: Record<string, unknown[]> = {
+ coverage: [TRANSLATIONS_QUERY_RESOURCE, STORE_ID, 'coverage', 'product', { page: 1 }],
+ matrix: [TRANSLATIONS_QUERY_RESOURCE, STORE_ID, 'product', 'prod_1'],
+ legacyMatrix: ['product', STORE_ID, 'prod_1', 'translations'],
+ products: ['products', STORE_ID],
+ }
+
+ for (const key of Object.values(seeded)) {
+ queryClient.setQueryData(key, {})
+ }
+
+ queryClient.invalidateQueries({
+ queryKey: withStoreScope([TRANSLATIONS_QUERY_RESOURCE], STORE_ID),
+ refetchType: 'all',
+ })
+
+ return Object.entries(seeded)
+ .filter(([, key]) => queryClient.getQueryState(key)?.isInvalidated)
+ .map(([name]) => name)
+ } finally {
+ queryClient.clear()
+ }
+}
+
+describe('translations query invalidation', () => {
+ it('marks coverage and the per-record matrix stale', () => {
+ const stale = staleAfterTranslationsInvalidation()
+
+ expect(stale).toContain('coverage')
+ expect(stale).toContain('matrix')
+ })
+
+ it('does not match the old singular-resource matrix key', () => {
+ // The previous key was `['product', id, 'translations']`. Invalidating
+ // `['translations']` must not be assumed to reach it — that is why the
+ // matrix now lives under the translations prefix.
+ expect(staleAfterTranslationsInvalidation()).not.toContain('legacyMatrix')
+ })
+
+ it('leaves unrelated catalog lists cached', () => {
+ expect(staleAfterTranslationsInvalidation()).not.toContain('products')
+ })
+
+ it('matches the key product updates pass to invalidateQueries', () => {
+ // useUpdateProduct invalidates `buildKey('translations')` which is
+ // `withStoreScope(['translations'], storeId)` — the same prefix this
+ // helper uses. A key of `['products', id, 'translations']` would miss.
+ expect(staleAfterTranslationsInvalidation()).toEqual(
+ expect.arrayContaining(['coverage', 'matrix']),
+ )
+ })
+
+ it('refetches inactive coverage after refetchType all', async () => {
+ // Default invalidateQueries only refetches active observers. Coverage
+ // visited earlier has no observer, so `refetchType: 'all'` is what
+ // useInvalidateTranslations uses — this would stay at 1 without it.
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ const coverageKey = [TRANSLATIONS_QUERY_RESOURCE, STORE_ID, 'coverage', 'product', { page: 1 }]
+ let fetches = 0
+
+ try {
+ await queryClient.prefetchQuery({
+ queryKey: coverageKey,
+ queryFn: async () => {
+ fetches += 1
+ return {}
+ },
+ })
+ expect(fetches).toBe(1)
+
+ await queryClient.invalidateQueries({
+ queryKey: withStoreScope([TRANSLATIONS_QUERY_RESOURCE], STORE_ID),
+ })
+ expect(fetches).toBe(1)
+
+ await queryClient.invalidateQueries({
+ queryKey: withStoreScope([TRANSLATIONS_QUERY_RESOURCE], STORE_ID),
+ refetchType: 'all',
+ })
+ expect(fetches).toBe(2)
+ } finally {
+ queryClient.clear()
+ }
+ })
+})
diff --git a/packages/dashboard/src/hooks/use-translations.ts b/packages/dashboard/src/hooks/use-translations.ts
index b5a0dd025c..bdd8fc186c 100644
--- a/packages/dashboard/src/hooks/use-translations.ts
+++ b/packages/dashboard/src/hooks/use-translations.ts
@@ -4,8 +4,8 @@ import type {
TranslatableResource,
TranslationCoverage,
} from '@spree/admin-sdk'
-import { adminClient, useResourceKey } from '@spree/dashboard-core'
-import { useQuery } from '@tanstack/react-query'
+import { adminClient, useResourceKey, useResourceKeyBuilder } from '@spree/dashboard-core'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useCallback } from 'react'
/** The locales a merchant can translate content into (for nice display names). */
@@ -59,6 +59,35 @@ export function isTranslatableResourceType(
return Object.hasOwn(TRANSLATIONS_ACCESSORS, resourceType)
}
+/**
+ * Logical query-key prefix for every translations query — coverage grids and
+ * per-record matrices. Product (and other catalog) writes must invalidate
+ * this prefix: the matrix used to live under `['product', id, 'translations']`,
+ * which `['products']` never matches, so editing a record left the
+ * translations page serving a stale cache.
+ */
+export const TRANSLATIONS_QUERY_RESOURCE = 'translations'
+
+/**
+ * Marks every translations query stale and refetches observers — including
+ * ones that are not mounted. Prefix invalidation with the default
+ * `refetchType: 'active'` only refreshes the open page; a coverage grid
+ * visited earlier stayed on the pre-save payload until staleTime elapsed.
+ */
+export function useInvalidateTranslations() {
+ const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
+
+ return useCallback(
+ () =>
+ queryClient.invalidateQueries({
+ queryKey: buildKey(TRANSLATIONS_QUERY_RESOURCE),
+ refetchType: 'all',
+ }),
+ [queryClient, buildKey],
+ )
+}
+
/**
* Full translation matrix for any translatable resource: source values +
* content type per field, plus the translated value for every supported locale
@@ -70,9 +99,13 @@ export function useResourceTranslations(
resourceId: string,
) {
return useQuery<ResourceTranslations>({
- queryKey: useResourceKey(resourceType, resourceId, 'translations'),
+ queryKey: useResourceKey(TRANSLATIONS_QUERY_RESOURCE, resourceType, resourceId),
queryFn: () => TRANSLATIONS_ACCESSORS[resourceType].get(resourceId),
enabled: !!resourceId,
+ // Source values change when the catalog record is saved. The default
+ // 60s staleTime would otherwise keep the editor on the pre-save name
+ // after the merchant edits the product and reopens this dialog.
+ refetchOnMount: 'always',
})
}
@@ -97,13 +130,17 @@ export function useTranslationCoverage(
params: { page?: number; limit?: number } & Record<string, unknown>,
) {
return useQuery({
- queryKey: useResourceKey('translations', 'coverage', resourceType, params),
+ queryKey: useResourceKey(TRANSLATIONS_QUERY_RESOURCE, 'coverage', resourceType, params),
queryFn: () => adminClient.translations.coverage(resourceType, params),
enabled: !!resourceType,
// Hold the previous result while a new term or page loads. Without it
// every keystroke is a fresh query key with no data, so the page swaps to
// its loading state and unmounts the search box the merchant is typing in.
placeholderData: (previous) => previous,
+ // Always refetch when the merchant opens this page. Catalog edits and
+ // translation saves invalidate the shared prefix, but a missed key still
+ // left the 60s cache serving the previous name and coverage badges.
+ refetchOnMount: 'always',
})
}
diff --git a/packages/dashboard/src/lib/same-rich-text.test.ts b/packages/dashboard/src/lib/same-rich-text.test.ts
new file mode 100644
index 0000000000..2ba8bfd53c
--- /dev/null
+++ b/packages/dashboard/src/lib/same-rich-text.test.ts
@@ -0,0 +1,41 @@
+import { sameRichText } from '@spree/dashboard-ui'
+import { describe, expect, it } from 'vitest'
+
+describe('sameRichText', () => {
+ it('treats empty markup as equal to an empty string', () => {
+ expect(sameRichText('', '')).toBe(true)
+ expect(sameRichText('', '<p></p>')).toBe(true)
+ expect(sameRichText('', '<p><br></p>')).toBe(true)
+ expect(sameRichText('<p></p>', '<p><br></p>')).toBe(true)
+ })
+
+ it('treats bare text as equal to the same text wrapped in a paragraph', () => {
+ const plain = 'Höhenverstellbarer Standventilator mit 40cm Rotordurchmesser'
+ expect(sameRichText(plain, `<p>${plain}</p>`)).toBe(true)
+ expect(sameRichText(`<p>${plain}</p>`, `<p>${plain}</p><p></p>`)).toBe(true)
+ expect(sameRichText(`<p>${plain}</p>`, `<p>${plain}</p><p><br></p><p></p>`)).toBe(true)
+ })
+
+ it('does not treat a real wording change as equal', () => {
+ expect(sameRichText('<p>Standventilator</p>', '<p>Turmventilator</p>')).toBe(false)
+ expect(sameRichText('Standventilator', '<p>Turmventilator</p>')).toBe(false)
+ })
+
+ it('does not treat a formatting-only change as equal', () => {
+ expect(sameRichText('<p>Standventilator</p>', '<p><strong>Standventilator</strong></p>')).toBe(
+ false,
+ )
+ })
+
+ it('does not treat an image-only value as empty', () => {
+ const imageOnly = '<p><img src="https://cdn.example/fan.jpg" alt="Fan"></p>'
+ expect(sameRichText(imageOnly, '')).toBe(false)
+ expect(sameRichText(imageOnly, '<p></p>')).toBe(false)
+ expect(sameRichText(imageOnly, imageOnly)).toBe(true)
+ })
+
+ it('strips a long run of trailing empty paragraphs without hanging', () => {
+ const empty = '<p></p>'.repeat(200)
+ expect(sameRichText(`<p>Standventilator</p>${empty}`, '<p>Standventilator</p>')).toBe(true)
+ })
+})