fix(cms): robust prompt copy and a readable legal approval rule (MITHOME-113)

Found during the live check on a staging copy: the embedded browser
denied the async Clipboard API, so "copy prompt" failed silently. The
panel now falls back to a selection copy and finally leaves the prompt
selected with a Ctrl/Cmd+C hint; covered by component tests.

Payload only shows a generic "field is invalid" toast for the rejected
approval, so the legal pages' status field description now states the
two-model rule next to the field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Do Siki
2026-09-29 11:58:59 +02:00
co-authored by Claude Opus 5.5
parent bff08edafe
commit 98ac9859c7
5 changed files with 105 additions and 14 deletions
+4 -1
View File
@@ -60,7 +60,10 @@ export const LegalPages: CollectionConfig = {
},
// MITHOME-113: legal translations need a recorded multi-model review
// before they can be approved (src/lib/legal-validation.ts).
translationStatusField(validateLegalApproval),
translationStatusField(
validateLegalApproval,
' Jogi oldalon a „Jóváhagyva” állapothoz legalább két különböző modell el nem utasító validálása kell (lásd: Jogi validáció).',
),
legalValidationGroup,
],
}
@@ -0,0 +1,57 @@
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import '@testing-library/jest-dom'
import { LegalValidationPrompt } from './LegalValidationPrompt'
const docs = {
hu: { title: 'Adatvédelmi Tájékoztató', sections: [{ id: 's1', title: '1. Bevezetés', content: 'Szöveg' }] },
en: { title: 'Privacy Notice', sections: [{ id: 's1', title: '1. Introduction', content: 'Text' }] },
}
function mockFetch(en: object = docs.en) {
global.fetch = jest.fn(async (url: string) => ({
ok: true,
json: async () => (url.includes('locale=en') ? en : docs.hu),
})) as never
}
beforeEach(() => {
window.history.pushState({}, '', '/admin/collections/legal-pages/abc123')
mockFetch()
})
describe('LegalValidationPrompt (MITHOME-113)', () => {
it('should build the prompt from hu + en read without locale fallback', async () => {
render(<LegalValidationPrompt />)
const textarea = await screen.findByLabelText('Validációs prompt')
expect((textarea as HTMLTextAreaElement).value).toContain('[EN] 1. Introduction')
expect(global.fetch).toHaveBeenCalledWith(expect.stringContaining('/api/legal-pages/abc123?locale=en&fallback-locale=none&draft=true'), expect.anything())
})
it('should confirm a successful copy', async () => {
Object.assign(navigator, { clipboard: { writeText: jest.fn(async () => undefined) } })
render(<LegalValidationPrompt />)
await userEvent.click(await screen.findByRole('button', { name: 'Prompt másolása' }))
expect(await screen.findByRole('button', { name: 'Másolva ✓' })).toBeInTheDocument()
})
it('should fall back to selecting the prompt when the clipboard is denied', async () => {
Object.assign(navigator, { clipboard: { writeText: jest.fn(async () => Promise.reject(new Error('denied'))) } })
document.execCommand = jest.fn(() => false)
render(<LegalValidationPrompt />)
await userEvent.click(await screen.findByRole('button', { name: 'Prompt másolása' }))
expect(await screen.findByRole('status')).toHaveTextContent('Ctrl/Cmd+C')
})
it('should say there is nothing to validate without English text', async () => {
mockFetch({ title: '', sections: [] })
render(<LegalValidationPrompt />)
expect(await screen.findByText(/nincs mit validálni/)).toBeInTheDocument()
})
it('should ask to save a new document first', async () => {
window.history.pushState({}, '', '/admin/collections/legal-pages/create')
render(<LegalValidationPrompt />)
await waitFor(() => expect(screen.getByText(/Előbb mentsd el/)).toBeInTheDocument())
})
})
@@ -1,6 +1,6 @@
'use client'
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { buildLegalValidationPrompt, type LegalText } from '@/lib/legal-validation-prompt'
/**
@@ -37,6 +37,28 @@ async function readLocale(id: string, locale: 'hu' | 'en'): Promise<LegalText> {
return res.json()
}
type CopyResult = 'copied' | 'selected'
/**
* WHY a fallback chain: the async Clipboard API can be denied (permissions
* policy, embedded browsers) — then try the legacy selection copy, and as a
* last resort leave the whole prompt selected for a manual Ctrl/Cmd+C.
*/
async function copyPrompt(textarea: HTMLTextAreaElement): Promise<CopyResult> {
try {
await navigator.clipboard.writeText(textarea.value)
return 'copied'
} catch {
textarea.focus()
textarea.select()
try {
return document.execCommand('copy') ? 'copied' : 'selected'
} catch {
return 'selected'
}
}
}
async function fetchPromptState(): Promise<State> {
const id = docIdFromPath(window.location.pathname)
if (!id) return { kind: 'unsaved' }
@@ -51,7 +73,8 @@ async function fetchPromptState(): Promise<State> {
export function LegalValidationPrompt() {
const [state, setState] = useState<State>({ kind: 'loading' })
const [copied, setCopied] = useState(false)
const [copyResult, setCopyResult] = useState<CopyResult>()
const textareaRef = useRef<HTMLTextAreaElement>(null)
useEffect(() => {
let active = true
@@ -66,10 +89,11 @@ export function LegalValidationPrompt() {
void fetchPromptState().then(setState)
}
const copy = async (prompt: string) => {
await navigator.clipboard.writeText(prompt)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
const copy = async () => {
if (!textareaRef.current) return
const result = await copyPrompt(textareaRef.current)
setCopyResult(result)
if (result === 'copied') setTimeout(() => setCopyResult(undefined), 2000)
}
return (
@@ -86,15 +110,19 @@ export function LegalValidationPrompt() {
{state.kind === 'ready' && (
<>
<textarea
ref={textareaRef}
readOnly
value={state.prompt}
rows={8}
aria-label="Validációs prompt"
style={{ width: '100%', fontFamily: 'monospace', fontSize: '0.75rem' }}
/>
<button type="button" className="btn btn--style-primary btn--size-small" onClick={() => void copy(state.prompt)}>
{copied ? 'Másolva ✓' : 'Prompt másolása'}
<button type="button" className="btn btn--style-primary btn--size-small" onClick={() => void copy()}>
{copyResult === 'copied' ? 'Másolva ✓' : 'Prompt másolása'}
</button>
{copyResult === 'selected' && (
<p role="status">A böngésző nem engedte az automatikus másolást — a prompt ki van jelölve, másold Ctrl/Cmd+C-vel.</p>
)}
</>
)}
<button type="button" className="btn btn--style-secondary btn--size-small" onClick={reload}>
@@ -15,9 +15,11 @@ const LABELS: Record<EnTranslationStatus, string> = {
*
* WHY not localized: only English has a translation status — a localized
* field would show a meaningless value in the Hungarian (source) view.
* `validate` lets LegalPages add its multi-model validation rule.
* `validate` + `extraDescription` let LegalPages add (and explain) its
* multi-model validation rule — Payload only shows a generic "field is
* invalid" toast, so the rule must be readable next to the field.
*/
export function translationStatusField(validate?: SelectFieldSingleValidation): SelectField {
export function translationStatusField(validate?: SelectFieldSingleValidation, extraDescription = ''): SelectField {
return {
name: 'enTranslationStatus',
label: 'Angol fordítás állapota',
@@ -29,7 +31,8 @@ export function translationStatusField(validate?: SelectFieldSingleValidation):
position: 'sidebar',
description:
'Az angol oldal csak „Jóváhagyva” állapotban jelenik meg; addig a látogatók a magyar szöveget látják. ' +
'Az AI-draft gépi fordítás: jóváhagyás előtt ellenőrizni és szükség szerint javítani kell.',
'Az AI-draft gépi fordítás: jóváhagyás előtt ellenőrizni és szükség szerint javítani kell.' +
extraDescription,
},
}
}