diff --git a/README.md b/README.md index 277e6bc..7adfcd7 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ You can also override per-load via URL query params: `?contentId=do_123&lang=hi& | **Review workflow** | Send for review, reviewer request-changes (with reasons checklist), publish. | | **Locking** | Creates a content lock on upload / edit-open; retires it on close and on send-for-review. | | **Session guard** | 30-minute inactivity prompt (Continue / Close). | +| **Enrichments** | Ticking "Generate transcripts" when uploading a video saves `enrichmentTypes` on the content; the platform generates transcripts after publish. A published video's transcripts show in a read-only drawer and as preview captions, read via `POST /object/enrichment/v4/list` (served under `config.portalSlug`, default `/portal`). | | **Telemetry** | Emits Sunbird 3.0 telemetry (impression / interact / error / end) via `onTelemetryEvent`. | | **Preview** | Renders through the ekstep content renderer for every supported mimeType. | diff --git a/package-lock.json b/package-lock.json index 7f739d3..6594b75 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@project-sunbird/generic-editor-v2", - "version": "2.0.4", + "version": "2.0.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@project-sunbird/generic-editor-v2", - "version": "2.0.4", + "version": "2.0.8", "dependencies": { "jszip": "^3.10.1" }, @@ -95,6 +95,7 @@ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", @@ -444,6 +445,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" }, @@ -467,6 +469,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" } @@ -2245,8 +2248,7 @@ "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@types/babel__core": { "version": "7.20.5", @@ -2338,6 +2340,7 @@ "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@types/prop-types": "*", "csstype": "^3.2.2" @@ -2349,6 +2352,7 @@ "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", "dev": true, "license": "MIT", + "peer": true, "peerDependencies": { "@types/react": "^18.0.0" } @@ -2398,6 +2402,7 @@ "integrity": "sha512-sPhE4iHuJDSvoAiec+Ro8JyXw8f0ql13HFR82P99nCm9GwTEKG0KYLvDe6REk8BCXuit6vJAv/Yxg5ABaNS2rA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.62.1", "@typescript-eslint/types": "8.62.1", @@ -2891,6 +2896,7 @@ "integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -2981,7 +2987,6 @@ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } @@ -3095,6 +3100,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.10.38", "caniuse-lite": "^1.0.30001799", @@ -3463,8 +3469,7 @@ "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/dunder-proto": { "version": "1.0.1", @@ -3628,6 +3633,7 @@ "integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -4428,6 +4434,7 @@ "integrity": "sha512-8i7LzZj7BF8uplX+ZyOlIz86V6TAsSs+np6m1kpW9u0JWi4z/1t+FzcK1aek+ybTnAC4KhBL4uXCNT0wcUIeCw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "cssstyle": "^4.1.0", "data-urls": "^5.0.0", @@ -4652,7 +4659,6 @@ "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", "dev": true, "license": "MIT", - "peer": true, "bin": { "lz-string": "bin/bin.js" } @@ -5046,7 +5052,6 @@ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", @@ -5062,7 +5067,6 @@ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=10" }, @@ -5109,6 +5113,7 @@ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -5122,6 +5127,7 @@ "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" @@ -5135,8 +5141,7 @@ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/react-refresh": { "version": "0.17.0", @@ -5239,6 +5244,7 @@ "integrity": "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@types/estree": "1.0.9" }, @@ -5304,6 +5310,7 @@ "integrity": "sha512-OL3GoQyoUdDt843DpVmDO6y2k1sc5IhUDSpu8XucEI+35neq5QivZ1iuegnpraEVTJXlQGK1gl27zKcTLEPbQw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "chokidar": "^5.0.0", "immutable": "^5.1.5", @@ -5669,6 +5676,7 @@ "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -5771,6 +5779,7 @@ "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", diff --git a/package.json b/package.json index 550bc01..658b4c9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@project-sunbird/generic-editor-v2", - "version": "2.0.6", + "version": "2.0.8", "description": "Sunbird Generic Editor — React content upload/generic editor (theme-reactive, multilingual). Fork of @sunbird/content-editor that previews via the legacy ekstep content renderer.", "main": "dist/sunbird-generic-editor.umd.js", "module": "dist/sunbird-generic-editor.es.js", @@ -49,4 +49,4 @@ "vite-plugin-dts": "^4.5.4", "vitest": "^3.2.6" } -} \ No newline at end of file +} diff --git a/src/ContentEditor.test.tsx b/src/ContentEditor.test.tsx index cb9e165..023a7c6 100644 --- a/src/ContentEditor.test.tsx +++ b/src/ContentEditor.test.tsx @@ -1,4 +1,4 @@ -import { render, screen, waitFor } from '@testing-library/react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { describe, it, expect, vi } from 'vitest'; import ContentEditor from './ContentEditor'; import type { ContentEditorService } from './services/ContentEditorService'; @@ -11,6 +11,9 @@ function svc(over: Record = {}) { readContent: vi.fn().mockResolvedValue(mockContent), createLock: vi.fn().mockResolvedValue({}), retireLock: vi.fn().mockResolvedValue(undefined), + readFormFields: vi.fn().mockResolvedValue([]), + readFramework: vi.fn().mockResolvedValue([]), + searchFrameworks: vi.fn().mockResolvedValue([]), getBase: () => ({ baseUrl: '', apiSlug: '/action', headers: {}, fetchImpl: fetch }), getEndpoints: () => ({}), ...over, @@ -44,3 +47,114 @@ describe(' — existing content', () => { expect(await screen.findByText('Failed to load content.')).toBeInTheDocument(); }); }); + +describe(' — Dynamic Assess empty state', () => { + it('shows a placeholder instead of the legacy player when no body has been generated yet (positive)', async () => { + const service = svc({ + readContent: vi.fn().mockResolvedValue({ + ...mockContent, + primaryCategory: 'Dynamic Course Assessment', + totalQuestions: 0, + }), + }); + render(); + expect(await screen.findByText('No questions generated yet')).toBeInTheDocument(); + expect(screen.getByText(/save to generate the questions/)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Edit details' })).toBeInTheDocument(); + expect(screen.queryByText('PDF')).not.toBeInTheDocument(); + }); + + it('shows the normal preview once the job has written questions, even for a never-published Draft (negative)', async () => { + const service = svc({ + readContent: vi.fn().mockResolvedValue({ + ...mockContent, + primaryCategory: 'Dynamic Course Assessment', + status: 'Draft', + pkgVersion: 0, + totalQuestions: 3, + }), + }); + render(); + await waitFor(() => expect(screen.getAllByText('Sample content').length).toBeGreaterThan(0)); + expect(screen.queryByText('No questions generated yet')).not.toBeInTheDocument(); + }); + + it('does not point a reviewer at a Generate button they do not have (positive)', async () => { + const service = svc({ + readContent: vi.fn().mockResolvedValue({ + ...mockContent, + primaryCategory: 'Dynamic Course Assessment', + status: 'Review', + totalQuestions: 0, + }), + }); + const reviewerContext = { ...mockContext, user: { ...mockContext.user!, roles: ['CONTENT_REVIEWER'] } }; + render(); + expect(await screen.findByText('No questions have been generated for this content yet.')).toBeInTheDocument(); + expect(screen.queryByText(/save to generate the questions/)).not.toBeInTheDocument(); + }); +}); + +describe(' — Dynamic Assess generating overlay', () => { + const staleBody = JSON.stringify({ + theme: { stage: [{ 'org.ekstep.questionset': { config: { __cdata: JSON.stringify({ dynamic_assess: { skills: ['Physics'], target: { E: 2, M: 0, D: 0 } } }) } } }] }, + }); + const daContent = (over: Record = {}) => ({ + ...mockContent, + primaryCategory: 'Dynamic Course Assessment', + totalQuestions: 3, + lastUpdatedOn: 't0', + skill: ['Physics'], + difficultyTarget: '{"E":1,"M":1,"D":1}', + body: staleBody, + ...over, + }); + + it('shows a blocking loader while questions generate and removes it once the job writes (positive)', async () => { + let written = false; + const service = svc({ + readContent: vi.fn().mockImplementation(async () => daContent(written ? { lastUpdatedOn: 't1' } : {})), + refreshContentBody: vi.fn().mockResolvedValue({}), + }); + render(); + fireEvent.click(await screen.findByRole('button', { name: /Regenerate/ })); + expect(await screen.findByRole('status')).toHaveTextContent('Generating questions'); + // The settings banner stays hidden behind the loader while generating. + expect(screen.queryByText('Settings changed since the questions were generated')).not.toBeInTheDocument(); + written = true; + await waitFor(() => expect(screen.queryByText('Generating questions')).not.toBeInTheDocument(), { timeout: 8000 }); + expect(await screen.findByText('Questions generated')).toBeInTheDocument(); + }, 10000); + + it('never shows the loader or a Generate button for ordinary content (negative)', async () => { + render(); + await waitFor(() => expect(screen.getAllByText('Sample content').length).toBeGreaterThan(0)); + expect(screen.queryByRole('button', { name: /Regenerate/ })).not.toBeInTheDocument(); + expect(screen.queryByText('Generating questions')).not.toBeInTheDocument(); + }); +}); + +describe(' — Dynamic Assess stale settings banner', () => { + const generatedBody = JSON.stringify({ + theme: { stage: [{ 'org.ekstep.questionset': { config: { __cdata: JSON.stringify({ dynamic_assess: { skills: ['Physics'], target: { E: 3, M: 3, D: 3 } } }) } } }] }, + }); + const daContent = (over: Record = {}) => ({ + ...mockContent, primaryCategory: 'Dynamic Course Assessment', totalQuestions: 9, + skill: ['Physics'], difficultyTarget: '{"E":3,"M":3,"D":3}', body: generatedBody, ...over, + }); + + it('warns the creator and disables Send for Review when settings changed after generation (positive)', async () => { + const service = svc({ readContent: vi.fn().mockResolvedValue(daContent({ difficultyTarget: '{"E":3,"M":2,"D":3}' })) }); + render(); + expect(await screen.findByRole('alert')).toHaveTextContent('Settings changed since the questions were generated'); + expect(screen.getByText(/Click Regenerate to update them/)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Send for review/i })).toBeDisabled(); + }); + + it('shows no banner when the settings match the generated questions (negative)', async () => { + const service = svc({ readContent: vi.fn().mockResolvedValue(daContent()) }); + render(); + await waitFor(() => expect(screen.getAllByText('Sample content').length).toBeGreaterThan(0)); + expect(screen.queryByText('Settings changed since the questions were generated')).not.toBeInTheDocument(); + }); +}); diff --git a/src/ContentEditor.tsx b/src/ContentEditor.tsx index a55a9ec..624152c 100644 --- a/src/ContentEditor.tsx +++ b/src/ContentEditor.tsx @@ -10,11 +10,11 @@ import MetadataDrawer from './components/MetadataDrawer'; import CollaboratorDrawer from './components/CollaboratorDrawer'; import ReviewDrawer from './components/ReviewDrawer'; import ReviewCommentsDrawer from './components/ReviewCommentsDrawer'; -import TranscriptsDrawer from './components/TranscriptsDrawer'; +import EnrichmentsDrawer from './components/enrichment/EnrichmentsDrawer'; import AssetPickerModal from './components/AssetPickerModal'; import Toast from './components/Toast'; import { t } from './i18n/i18n'; -import { CheckIcon } from './icons'; +import { CheckIcon, InfoIcon, RefreshIcon } from './icons'; export type ContentEditorProps = UseEditorOptions; @@ -35,7 +35,32 @@ const ContentEditor: React.FC = (props) => { {(ed.view === 'upload' || ed.view === 'uploading') && (
)} - {ed.view === 'player' && } + {ed.view === 'player' && ed.isDynamicAssess && !ed.hasGeneratedBody && ( +
+ +

{t(ed.lang, 'DYNAMIC_ASSESS_EMPTY_TITLE')}

+ {/* Only an editor can save details (which generates); reviewers/readers just see it's empty. */} +

{t(ed.lang, ed.mode === 'edit' ? 'DYNAMIC_ASSESS_EMPTY_SUB' : 'DYNAMIC_ASSESS_EMPTY_SUB_READONLY')}

+ {ed.mode === 'edit' && ( + + )} +
+ )} + {/* Only when the saved settings don't match the questions and nothing is regenerating, e.g. a failed or older generation. */} + {ed.view === 'player' && ed.dynamicAssessStale && !ed.dynamicAssessRefreshing && ( +
+ +
+

{t(ed.lang, 'DYNAMIC_ASSESS_STALE_TITLE')}

+

{t(ed.lang, ed.mode === 'edit' ? 'DYNAMIC_ASSESS_STALE_SUB' : 'DYNAMIC_ASSESS_STALE_SUB_READONLY')}

+
+
+ )} + {ed.view === 'player' && !(ed.isDynamicAssess && !ed.hasGeneratedBody) && ( + + )}
ed.setDrawer(null)} /> @@ -44,7 +69,7 @@ const ContentEditor: React.FC = (props) => { - + @@ -67,6 +92,17 @@ const ContentEditor: React.FC = (props) => {
)} + {/* Blocks editing while the job writes the quiz, so a stale save can't race it. */} + {ed.isDynamicAssess && ed.dynamicAssessRefreshing && ( +
+
+
+

{t(ed.lang, 'DYNAMIC_ASSESS_GENERATING_TITLE')}

+

{t(ed.lang, 'DYNAMIC_ASSESS_GENERATING_SUB')}

+
+
+ )} + {/* Upload success overlay */} {ed.uploadSuccess && (
diff --git a/src/components/Drawer.tsx b/src/components/Drawer.tsx index db99ff6..650ab16 100644 --- a/src/components/Drawer.tsx +++ b/src/components/Drawer.tsx @@ -12,19 +12,24 @@ interface DrawerProps { closeLabel?: string; /** Extra class on the root, e.g. for a drawer-specific scoped theme override. */ className?: string; + /** Optional control shown in the header, left of the close button. */ + headerAction?: React.ReactNode; } /** Slide-in drawer (right in LTR, left in RTL). Always mounted so the transform transition runs. */ -const Drawer: React.FC = ({ open, onClose, titleIcon, title, footer, children, closeLabel = 'Close', className }) => ( +const Drawer: React.FC = ({ open, onClose, titleIcon, title, footer, children, closeLabel = 'Close', className, headerAction }) => (
{titleIcon}

{title}

- +
+ {headerAction} + +
{children}
{footer &&
{footer}
} diff --git a/src/components/EditorPreview.test.tsx b/src/components/EditorPreview.test.tsx index 25e27c2..4c2edba 100644 --- a/src/components/EditorPreview.test.tsx +++ b/src/components/EditorPreview.test.tsx @@ -1,7 +1,8 @@ -import { render, screen } from '@testing-library/react'; -import { describe, it, expect } from 'vitest'; -import EditorPreview from './EditorPreview'; +import { render, screen, fireEvent } from '@testing-library/react'; +import { describe, it, expect, vi } from 'vitest'; +import EditorPreview, { rendererData } from './EditorPreview'; import { makeEd, mockContext, mockContent } from '../test/mockEd'; +import type { EnrichmentObject } from '../types'; describe('', () => { it('renders nothing when there is no content (negative)', () => { @@ -32,65 +33,158 @@ describe('', () => { expect(container.querySelector('iframe')).toHaveAttribute('src', '/preview.html?foo=1&webview=true'); }); - it('renders the iframe immediately for non-video content regardless of transcriptsChecked', () => { - const ed = makeEd({ content: mockContent, transcriptsChecked: false }); // mockContent is application/pdf + it('renders the iframe immediately for non-video content regardless of enrichmentsChecked', () => { + const ed = makeEd({ content: mockContent, enrichmentsChecked: false }); // mockContent is application/pdf const { container } = render(); expect(container.querySelector('iframe')).toBeInTheDocument(); }); - it('shows a loading state instead of the iframe for video content until transcripts have been checked at least once (negative)', () => { + it('shows a loading state instead of the iframe for video content until enrichments have been checked at least once (negative)', () => { const videoContent = { ...mockContent, mimeType: 'video/mp4' }; - const ed = makeEd({ content: videoContent, transcriptsChecked: false, transcripts: [] }); + const ed = makeEd({ content: videoContent, enrichmentsChecked: false, enrichmentObjects: [] }); const { container } = render(); expect(container.querySelector('iframe')).not.toBeInTheDocument(); expect(container.querySelector('.ce-spinner')).toBeInTheDocument(); }); - it('renders the iframe for video content once transcriptsChecked is true, even with zero transcripts', () => { + it('renders the iframe for video content once enrichmentsChecked is true, even with zero objects', () => { const videoContent = { ...mockContent, mimeType: 'video/mp4' }; - const ed = makeEd({ content: videoContent, transcriptsChecked: true, transcripts: [] }); + const ed = makeEd({ content: videoContent, enrichmentsChecked: true, enrichmentObjects: [] }); const { container } = render(); expect(container.querySelector('iframe')).toBeInTheDocument(); }); it('does not treat a transcript with no status as Live (negative)', () => { const videoContent = { ...mockContent, mimeType: 'video/mp4' }; - const ed1 = makeEd({ - content: videoContent, - transcriptsChecked: true, - transcripts: [{ code: 'c_en', language: 'English', languageCode: 'en', captionsUrl: 'https://x/en.vtt' }], // no status - }); + const noStatus = { identifier: 't_en', enrichmentObjectType: 'Transcript', parentId: 'do_1', language: 'English', languageCode: 'en', captionsUrl: 'https://x/en.vtt' } as unknown as EnrichmentObject; + const ed1 = makeEd({ content: videoContent, enrichmentsChecked: true, enrichmentObjects: [noStatus] }); const { container, rerender } = render(); const withoutStatusIframe = container.querySelector('iframe'); - const ed2 = makeEd({ - content: videoContent, - transcriptsChecked: true, - transcripts: [], - }); + const ed2 = makeEd({ content: videoContent, enrichmentsChecked: true, enrichmentObjects: [] }); rerender(); - const emptyIframe = container.querySelector('iframe'); - // Same remount key either way, since a status-less entry must be excluded just like an empty list. - expect(emptyIframe).toBe(withoutStatusIframe); + // Same remount key either way, since a status-less object must be excluded just like an empty list. + expect(container.querySelector('iframe')).toBe(withoutStatusIframe); + }); + + it('does not remount when a Live object without a caption URL appears (negative)', () => { + const videoContent = { ...mockContent, mimeType: 'video/mp4' }; + const withUrl = { identifier: 't_en', enrichmentObjectType: 'Transcript', parentId: 'do_1', status: 'Live', captionsUrl: 'https://x/en.vtt' } as EnrichmentObject; + const noUrl = { identifier: 't_hi', enrichmentObjectType: 'Transcript', parentId: 'do_1', status: 'Live' } as EnrichmentObject; + const { container, rerender } = render( + , + ); + const first = container.querySelector('iframe'); + rerender(); + expect(container.querySelector('iframe')).toBe(first); }); - it('remounts the iframe (new DOM node) when the live-caption set changes at equal length', () => { + it('remounts the iframe (new DOM node) when the Live set changes at equal length', () => { const videoContent = { ...mockContent, mimeType: 'video/mp4' }; - const ed1 = makeEd({ - content: videoContent, - transcriptsChecked: true, - transcripts: [{ code: 'c_en', language: 'English', languageCode: 'en', captionsUrl: 'https://x/en.vtt', status: 'Live' }], + const live = (identifier: string, languageCode: string): EnrichmentObject => ({ + identifier, enrichmentObjectType: 'Transcript', parentId: 'do_1', status: 'Live', + language: languageCode, languageCode, captionsUrl: `https://x/${languageCode}.vtt`, }); + const ed1 = makeEd({ content: videoContent, enrichmentsChecked: true, enrichmentObjects: [live('c_en', 'en')] }); const { container, rerender } = render(); const firstIframe = container.querySelector('iframe'); - const ed2 = makeEd({ - content: videoContent, - transcriptsChecked: true, - transcripts: [{ code: 'c_fr', language: 'French', languageCode: 'fr', captionsUrl: 'https://x/fr.vtt', status: 'Live' }], - }); + const ed2 = makeEd({ content: videoContent, enrichmentsChecked: true, enrichmentObjects: [live('c_fr', 'fr')] }); rerender(); - const secondIframe = container.querySelector('iframe'); - expect(secondIframe).not.toBe(firstIframe); + expect(container.querySelector('iframe')).not.toBe(firstIframe); + }); + + it('does not remount the iframe when a non-Live object changes (negative)', () => { + const videoContent = { ...mockContent, mimeType: 'video/mp4' }; + const obj = (status: EnrichmentObject['status']): EnrichmentObject => ({ + identifier: 'c_hi', enrichmentObjectType: 'Transcript', parentId: 'do_1', status, + }); + const ed1 = makeEd({ content: videoContent, enrichmentsChecked: true, enrichmentObjects: [obj('Processing')] }); + const { container, rerender } = render(); + const firstIframe = container.querySelector('iframe'); + rerender(); + expect(container.querySelector('iframe')).toBe(firstIframe); + }); + + it('hands only the Live transcripts to the renderer as metadata.transcripts (VTT as artifactUrl)', () => { + const videoContent = { ...mockContent, mimeType: 'video/mp4' }; + const objects: EnrichmentObject[] = [ + { identifier: 't_en', enrichmentObjectType: 'Transcript', parentId: 'do_1', status: 'Live', language: 'English', languageCode: 'en', sourceLanguage: true, captionsUrl: 'https://x/en.vtt', artifactUrl: 'https://x/en.json' }, + { identifier: 't_hi', enrichmentObjectType: 'Transcript', parentId: 'do_1', status: 'Processing', language: 'Hindi', languageCode: 'hi' }, + ]; + const { container } = render(); + const iframe = container.querySelector('iframe')!; + const initializePreview = vi.fn(); + (iframe.contentWindow as unknown as { initializePreview: typeof initializePreview }).initializePreview = initializePreview; + fireEvent.load(iframe); + expect(initializePreview).toHaveBeenCalledTimes(1); + expect(initializePreview.mock.calls[0][0].metadata.transcripts).toEqual([ + { language: 'English', identifier: 't_en', languageCode: 'en', artifactUrl: 'https://x/en.vtt', wordByWordUrl: 'https://x/en.vtt', sourceLanguage: true }, + ]); + }); + + it('hands the ECML body to the renderer as data, so a generated Dynamic Assess lesson can play (positive)', () => { + const body = '{"theme":{"id":"theme","stage":[]}}'; + const ed = makeEd({ isDynamicAssess: true, content: { ...mockContent, mimeType: 'application/vnd.ekstep.ecml-archive', artifactUrl: undefined, body } }); + const { container } = render(); + const iframe = container.querySelector('iframe')!; + const initializePreview = vi.fn(); + (iframe.contentWindow as unknown as { initializePreview: typeof initializePreview }).initializePreview = initializePreview; + fireEvent.load(iframe); + expect(initializePreview).toHaveBeenCalledWith(expect.objectContaining({ data: { theme: { id: 'theme', stage: [] } } })); + }); + + it('gives the renderer the whole Dynamic Assess pool, in data and metadata.body, so the creator and reviewer see every question (positive)', () => { + const ids = ['a1', 'a2', 'a3']; + const body = JSON.stringify({ theme: { stage: [{ 'org.ekstep.questionset': [{ + config: { __cdata: JSON.stringify({ dynamic_assess: { target: { E: 1, M: 0, D: 0 }, levels: Object.fromEntries(ids.map((id) => [id, 'EASY'])) } }) }, + data: { __cdata: JSON.stringify(ids.map((id) => ({ identifier: id }))) }, + 'org.ekstep.question': ids.map((id) => ({ id })), + }] }] } }); + const ed = makeEd({ isDynamicAssess: true, content: { ...mockContent, mimeType: 'application/vnd.ekstep.ecml-archive', artifactUrl: undefined, body } }); + const { container } = render(); + const iframe = container.querySelector('iframe')!; + const initializePreview = vi.fn(); + (iframe.contentWindow as unknown as { initializePreview: typeof initializePreview }).initializePreview = initializePreview; + fireEvent.load(iframe); + const cfg = initializePreview.mock.calls[0]![0] as { metadata: { body: string }; data: unknown }; + const quiz = JSON.parse(cfg.metadata.body).theme.stage[0]['org.ekstep.questionset'][0]; + expect(quiz['org.ekstep.question']).toHaveLength(3); + expect(cfg.metadata.body).toBe(body); + expect(JSON.parse(cfg.metadata.body)).toEqual(cfg.data); + }); + + it('passes ordinary content metadata through untouched (negative)', () => { + const ed = makeEd({ isDynamicAssess: false, content: mockContent }); + const { container } = render(); + const iframe = container.querySelector('iframe')!; + const initializePreview = vi.fn(); + (iframe.contentWindow as unknown as { initializePreview: typeof initializePreview }).initializePreview = initializePreview; + fireEvent.load(iframe); + expect(initializePreview).toHaveBeenCalledWith(expect.objectContaining({ metadata: mockContent, data: {} })); + }); + + it('keeps passing empty data for regular ECML, so its preview loads exactly as before (negative)', () => { + const body = '{"theme":{"id":"theme","stage":[]}}'; + const ed = makeEd({ isDynamicAssess: false, content: { ...mockContent, mimeType: 'application/vnd.ekstep.ecml-archive', body } }); + const { container } = render(); + const iframe = container.querySelector('iframe')!; + const initializePreview = vi.fn(); + (iframe.contentWindow as unknown as { initializePreview: typeof initializePreview }).initializePreview = initializePreview; + fireEvent.load(iframe); + expect(initializePreview).toHaveBeenCalledWith(expect.objectContaining({ data: {} })); + }); +}); + +describe('rendererData', () => { + it('parses a JSON-string body and passes an object body through (positive)', () => { + expect(rendererData('{"theme":{}}')).toEqual({ theme: {} }); + expect(rendererData({ theme: {} })).toEqual({ theme: {} }); + }); + + it('falls back to {} with no body, and keeps a non-JSON (XML) body as-is (negative)', () => { + expect(rendererData(undefined)).toEqual({}); + expect(rendererData('')).toEqual({}); + expect(rendererData('')).toBe(''); }); }); diff --git a/src/components/EditorPreview.tsx b/src/components/EditorPreview.tsx index 5e48f3e..3a08555 100644 --- a/src/components/EditorPreview.tsx +++ b/src/components/EditorPreview.tsx @@ -1,41 +1,23 @@ import React, { useRef } from 'react'; import type { EditorController } from '../useEditor'; -import type { ContentData, EditorContext, RawTranscript } from '../types'; +import type { ContentData, EditorContext } from '../types'; import { getMimeTypeLabel, t } from '../i18n/i18n'; import { FileIcon } from '../icons'; -import { isVideoMimeType } from '../constants'; +import { applyEnrichments, enrichmentTypesForMime } from '../services/enrichment/registry'; -interface PlayerTranscript { - language: string; - identifier: string; - languageCode: string; - artifactUrl: string; - wordByWordUrl?: string; - sourceLanguage?: boolean; -} - -/** Maps raw enrichment.transcripts into the shape sunbird-video-player expects, mirroring - * the portal's ContentService mapping (artifactUrl here is the VTT, not transcript.json). - * Requires an explicit 'Live' status - a missing status is treated the same safe way - * TranscriptsDrawer.statusTone does (not-yet-approved), never served as a live caption. */ -function mapRawTranscripts(raw: RawTranscript[]): PlayerTranscript[] { - return raw - .filter((e): e is RawTranscript & { captionsUrl: string } => - !!e.captionsUrl && e.status === 'Live') - .map((e) => ({ - language: e.language || (e.languageCode || 'Unknown').toUpperCase(), - identifier: e.code ?? e.identifier ?? '', - languageCode: e.languageCode || '', - artifactUrl: e.captionsUrl, - wordByWordUrl: e.captionsUrl, - sourceLanguage: !!e.sourceLanguage, - })); +/** The ECML renderer reads the lesson from `data` (as the portal's EcmlPlayerService passes metadata.body); the API returns the body JSON-stringified. */ +export function rendererData(body: unknown): unknown { + if (body && typeof body === 'object') return body; + if (typeof body === 'string' && body.trim()) { + try { return JSON.parse(body); } catch { return body; } + } + return {}; } /** Preview via the legacy ekstep content renderer (all mimeTypes through its coreplugins), loaded in an iframe and driven via its global `initializePreview()`. */ const RendererPreview: React.FC<{ - content: ContentData; context: EditorContext; previewUrl: string; previewConfig: Record; -}> = ({ content, context, previewUrl, previewConfig }) => { + content: ContentData; context: EditorContext; previewUrl: string; previewConfig: Record; isDynamicAssess?: boolean; +}> = ({ content, context, previewUrl, previewConfig, isDynamicAssess = false }) => { const iframeRef = useRef(null); const src = `${previewUrl}${previewUrl.includes('?') ? '&' : '?'}webview=true`; @@ -44,6 +26,9 @@ const RendererPreview: React.FC<{ | (Window & { initializePreview?: (cfg: unknown) => void }) | null; if (!win || typeof win.initializePreview !== 'function') return; + // Only Dynamic Assess renders from its generated body: the whole pool, so the creator and reviewer see every question (learners get their own draw in the portal); other content keeps the renderer's own loading. + const data = isDynamicAssess ? rendererData((content as Record).body) : {}; + const metadata = content; win.initializePreview({ context: { mode: 'edit', @@ -57,8 +42,8 @@ const RendererPreview: React.FC<{ partner: [], }, config: previewConfig, - metadata: content, - data: {}, + metadata, + data, }); }; @@ -75,16 +60,16 @@ const RendererPreview: React.FC<{ }; const EditorPreview: React.FC<{ ed: EditorController; context: EditorContext }> = ({ ed, context }) => { - const { content, lang, previewUrl, previewConfig, transcripts: rawTranscripts, transcriptsChecked } = ed; + const { content, lang, previewUrl, previewConfig, enrichmentObjects, enrichmentsChecked } = ed; if (!content) return null; - const isVideo = isVideoMimeType(content.mimeType); - const transcripts = mapRawTranscripts(rawTranscripts); - // The iframe key changes only when the actual live-caption set changes (not just its - // count), so a same-count swap (one language leaves Live as another joins) still remounts. - const transcriptsKey = transcripts.map((tr) => tr.identifier).sort().join(','); - const previewMetadata = transcripts.length ? { ...content, transcripts } : content; + const hasEnrichments = enrichmentTypesForMime(content.mimeType).length > 0; + const previewMetadata = applyEnrichments(content, enrichmentObjects); + // Keyed on what the player actually receives (Live objects with a caption URL), so a change it can't show never restarts playback. + // A same-count swap (one object leaves as another joins) still changes the key and remounts. + const enrichmentsKey = ((previewMetadata.transcripts ?? []) as { identifier: string; artifactUrl: string }[]) + .map((tr) => `${tr.identifier}:${tr.artifactUrl}`).sort().join(','); return (
@@ -95,8 +80,8 @@ const EditorPreview: React.FC<{ ed: EditorController; context: EditorContext }> {t(lang, 'PREVIEW_MODE')}
- {isVideo && !transcriptsChecked ? ( - // Wait for the first transcripts check before ever mounting the renderer, so a + {hasEnrichments && !enrichmentsChecked ? ( + // Wait for the first enrichments check before ever mounting the renderer, so a // slow initial read can't yank the iframe out (and restart playback) right after // the user presses play - by the time it first mounts, this is already settled.
@@ -104,8 +89,10 @@ const EditorPreview: React.FC<{ ed: EditorController; context: EditorContext }>
) : ( ', () => { expect(publish).toHaveBeenCalled(); }); - it('shows "View transcript" for video content once transcripts exist, and opens the drawer', () => { - const setDrawer = vi.fn(); + it('shows "View transcript" once the content has Transcript objects, and opens the drawer for that type', () => { + const openEnrichmentDrawer = vi.fn(); const ed = makeEd({ - view: 'player', mode: 'edit', setDrawer, hasTranscripts: true, + view: 'player', mode: 'edit', openEnrichmentDrawer, presentEnrichmentTypes: ['Transcript'], content: { ...mockContent, mimeType: 'video/mp4' }, }); render(
); fireEvent.click(screen.getByRole('button', { name: 'View transcript' })); - expect(setDrawer).toHaveBeenCalledWith('transcripts'); + expect(openEnrichmentDrawer).toHaveBeenCalledWith('Transcript'); }); - it('hides "View transcript" for video content with no transcripts yet (negative)', () => { + it('hides "View transcript" when no enrichment type is present (negative)', () => { const ed = makeEd({ - view: 'player', mode: 'edit', hasTranscripts: false, + view: 'player', mode: 'edit', presentEnrichmentTypes: [], content: { ...mockContent, mimeType: 'video/mp4' }, }); render(
); expect(screen.queryByRole('button', { name: 'View transcript' })).not.toBeInTheDocument(); }); - it('hides "View transcript" for non-video content (negative)', () => { - const ed = makeEd({ view: 'player', mode: 'edit', content: { ...mockContent, mimeType: 'application/pdf' } }); + it('skips a present type that has no registry entry (negative)', () => { + const ed = makeEd({ view: 'player', mode: 'edit', presentEnrichmentTypes: ['Unknown'] }); render(
); expect(screen.queryByRole('button', { name: 'View transcript' })).not.toBeInTheDocument(); }); + + it('disables the enrichment button while busy (negative)', () => { + const ed = makeEd({ view: 'player', mode: 'edit', busy: true, presentEnrichmentTypes: ['Transcript'] }); + render(
); + expect(screen.getByRole('button', { name: 'View transcript' })).toBeDisabled(); + }); +}); + +describe('
— Regenerate (Dynamic Assess)', () => { + it('sits next to Save for the creator once questions exist and re-rolls on click (positive)', () => { + const refreshBody = vi.fn(); + const ed = makeEd({ view: 'player', content: mockContent, mode: 'edit', isDynamicAssess: true, hasGeneratedBody: true, refreshBody }); + render(
); + fireEvent.click(screen.getByRole('button', { name: /Regenerate/ })); + expect(refreshBody).toHaveBeenCalled(); + }); + + it('explains a disabled Send for review / Publish with a hover hint (positive)', () => { + const creator = makeEd({ view: 'player', content: mockContent, mode: 'edit', isDynamicAssess: true, hasGeneratedBody: false }); + const { container, unmount } = render(
); + expect(screen.getByRole('button', { name: /Send for review/i })).toBeDisabled(); + expect(container.querySelector('.ce-disabled-hint')).toHaveAttribute('data-tooltip', 'Generate questions before sending for review'); + unmount(); + const reviewer = makeEd({ view: 'player', content: mockContent, mode: 'review', isDynamicAssess: true, hasGeneratedBody: true, dynamicAssessStale: true }); + const { container: c2 } = render(
); + expect(screen.getByRole('button', { name: /Publish/ })).toBeDisabled(); + expect(c2.querySelector('.ce-disabled-hint')).toHaveAttribute('data-tooltip', 'Settings changed — generate questions again first'); + }); + + it('adds no hint wrapper for ordinary content (negative)', () => { + const { container } = render(
); + expect(container.querySelector('.ce-disabled-hint')).toBeNull(); + }); + + it('is hidden for reviewers, before any questions exist, and for ordinary content (negative)', () => { + const cases = [ + makeEd({ view: 'player', content: mockContent, mode: 'review', isDynamicAssess: true, hasGeneratedBody: true }), + makeEd({ view: 'player', content: mockContent, mode: 'edit', isDynamicAssess: true, hasGeneratedBody: false }), + makeEd({ view: 'player', content: mockContent, mode: 'edit', isDynamicAssess: false, hasGeneratedBody: true }), + ]; + for (const ed of cases) { + const { unmount } = render(
); + expect(screen.queryByRole('button', { name: /Regenerate/ })).not.toBeInTheDocument(); + unmount(); + } + }); }); diff --git a/src/components/Header.tsx b/src/components/Header.tsx index 85a1f40..0ba5a45 100644 --- a/src/components/Header.tsx +++ b/src/components/Header.tsx @@ -2,18 +2,31 @@ import React from 'react'; import type { EditorController } from '../useEditor'; import { t } from '../i18n/i18n'; import { - ImageIcon, PencilIcon, SaveIcon, CloseIcon, SendIcon, UserPlusIcon, CheckIcon, CommentIcon, CaptionsIcon, + ImageIcon, PencilIcon, SaveIcon, CloseIcon, SendIcon, UserPlusIcon, CheckIcon, CommentIcon, RefreshIcon, } from '../icons'; import { STATUS } from '../constants'; +import { enrichmentDefinition } from '../services/enrichment/registry'; +import { ENRICHMENT_UI } from './enrichment/enrichmentUi'; + +/** Hover hint for a disabled button: a disabled button is faded and gets no hover tooltip itself, so the hint sits on a wrapper. */ +const DisabledHint: React.FC<{ hint?: string; children: React.ReactNode }> = ({ hint, children }) => ( + hint ? {children} : <>{children} +); const Header: React.FC<{ ed: EditorController }> = ({ ed }) => { - const { content, lang, mode, setDrawer, saveDraft, close, busy, busyAction, setReviewErrors, setReviewSubmitMode, headerLogo, hasReviewComments, hasTranscripts } = ed; + const { + content, lang, mode, setDrawer, saveDraft, close, busy, busyAction, setReviewErrors, setReviewSubmitMode, + headerLogo, hasReviewComments, presentEnrichmentTypes, openEnrichmentDrawer, isDynamicAssess, hasGeneratedBody, dynamicAssessStale, + dynamicAssessRefreshing, refreshBody, + } = ed; const savingDraft = busyAction === 'save-draft'; const hasContent = !!content?.identifier && ed.view === 'player'; const isDraft = (content?.status ?? STATUS.DRAFT) === STATUS.DRAFT; const title = content?.name || t(lang, 'UNTITLED'); const canEdit = mode === 'edit'; const isReviewer = mode === 'review'; + const dynamicAssessBlocked = isDynamicAssess && (!hasGeneratedBody || dynamicAssessStale); + const dynamicAssessBlockedTip = dynamicAssessStale ? 'DYNAMIC_ASSESS_STALE_TIP' : 'DYNAMIC_ASSESS_GENERATE_FIRST'; return (
@@ -61,18 +74,24 @@ const Header: React.FC<{ ed: EditorController }> = ({ ed }) => { )} - {hasContent && hasTranscripts && ( - - )} + {hasContent && presentEnrichmentTypes.map((type) => { + const def = enrichmentDefinition(type); + const ui = ENRICHMENT_UI[type]; + if (!def || !ui) return null; + return ( + + ); + })} {canEdit && !isReviewer && hasReviewComments && ( )} - + + {/* Dynamic Assess re-roll with unchanged settings; a settings change already regenerates on Save. */} + {canEdit && !isReviewer && isDynamicAssess && hasGeneratedBody && ( + + )} +
{isReviewer ? ( @@ -107,27 +139,31 @@ const Header: React.FC<{ ed: EditorController }> = ({ ed }) => { - + + + ) : ( canEdit && ( - + + + ) )} diff --git a/src/components/MetadataDrawer.test.tsx b/src/components/MetadataDrawer.test.tsx index 5cd2eed..75f47a3 100644 --- a/src/components/MetadataDrawer.test.tsx +++ b/src/components/MetadataDrawer.test.tsx @@ -12,12 +12,12 @@ describe('', () => { expect(screen.getByText('Description')).toBeInTheDocument(); }); - it('saves metadata with the trimmed name (positive)', () => { + it('saves metadata with the trimmed name (positive)', async () => { const saveMetadata = vi.fn(); const ed = makeEd({ drawer: 'metadata', content: mockContent, saveMetadata }); render(); - fireEvent.click(screen.getByRole('button', { name: /Save changes/ })); - expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ name: 'Sample content' })); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ name: 'Sample content' }))); }); it('blocks save and toasts when the title is empty (negative)', () => { @@ -25,7 +25,7 @@ describe('', () => { const showToast = vi.fn(); const ed = makeEd({ drawer: 'metadata', content: { ...mockContent, name: '' }, saveMetadata, showToast }); render(); - fireEvent.click(screen.getByRole('button', { name: /Save changes/ })); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); expect(showToast).toHaveBeenCalledWith('Title is required.', 'error'); expect(saveMetadata).not.toHaveBeenCalled(); }); @@ -53,11 +53,598 @@ describe('', () => { expect(screen.getByRole('option', { name: 'Geometry' })).toBeInTheDocument(); }); - it('routes to save-and-submit in review-submit mode', () => { + it('routes to save-and-submit in review-submit mode', async () => { const saveMetadataAndSubmit = vi.fn(); const ed = makeEd({ drawer: 'metadata', content: mockContent, reviewSubmitMode: true, saveMetadataAndSubmit }); render(); fireEvent.click(screen.getByRole('button', { name: /Save & Submit/ })); - expect(saveMetadataAndSubmit).toHaveBeenCalledWith(expect.objectContaining({ name: 'Sample content' })); + await waitFor(() => expect(saveMetadataAndSubmit).toHaveBeenCalledWith(expect.objectContaining({ name: 'Sample content' }))); + }); + + it('keeps a skill field on a non-Dynamic form as an ordinary field (negative)', async () => { + const service = mockService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'skill', inputType: 'text', label: 'Skill', required: false, visible: true, editable: true }, + ]), + }); + render(); + expect(await screen.findByText('Skill')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Select Skill/ })).toBeNull(); + expect(screen.queryByText('Framework')).toBeNull(); + }); + + describe('difficultyTarget (Dynamic Assess)', () => { + const service = () => mockService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'difficultyTarget', label: 'Difficulty Target', required: true, visible: true, editable: true }, + ]), + }); + + it('renders three E/M/D number inputs and saves the entered counts as the API-expected JSON string', async () => { + const saveMetadata = vi.fn(); + // Seeded in the API's real wire format: a JSON string, not an object. + const ed = makeEd({ + drawer: 'metadata', service: service(), saveMetadata, + content: { ...mockContent, primaryCategory: 'Learning Resource', difficultyTarget: '{"E":1,"M":0,"D":0}' }, + }); + render(); + expect(await screen.findByText('Difficulty Target')).toBeInTheDocument(); + const easyInput = screen.getByDisplayValue('1'); + fireEvent.change(easyInput, { target: { value: '3' } }); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith( + expect.objectContaining({ difficultyTarget: '{"E":3,"M":0,"D":0}' }), + )); + }); + + it('gives each count input an accessible name inside a labelled group (positive)', async () => { + const ed = makeEd({ + drawer: 'metadata', service: service(), + content: { ...mockContent, primaryCategory: 'Learning Resource', difficultyTarget: '{"E":1,"M":2,"D":3}' }, + }); + render(); + expect(await screen.findByRole('group', { name: /Difficulty Target/ })).toBeInTheDocument(); + expect(screen.getByRole('spinbutton', { name: 'Easy' })).toHaveValue(1); + expect(screen.getByRole('spinbutton', { name: 'Medium' })).toHaveValue(2); + expect(screen.getByRole('spinbutton', { name: 'Difficult' })).toHaveValue(3); + }); + + it('blocks submit-for-review when every bucket is zero (negative)', async () => { + const saveMetadataAndSubmit = vi.fn(); + const setReviewErrors = vi.fn(); + const ed = makeEd({ + drawer: 'metadata', service: service(), reviewSubmitMode: true, saveMetadataAndSubmit, setReviewErrors, + content: { ...mockContent, primaryCategory: 'Learning Resource', difficultyTarget: { E: 0, M: 0, D: 0 } }, + }); + render(); + await screen.findByText('Difficulty Target'); + fireEvent.click(screen.getByRole('button', { name: /Save & Submit/ })); + expect(setReviewErrors).toHaveBeenCalledWith(['Difficulty Target']); + expect(saveMetadataAndSubmit).not.toHaveBeenCalled(); + }); + }); + + describe('pool sufficiency check (Dynamic Assess)', () => { + const serviceWithSkill = (over: Record = {}) => mockService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'skill', inputType: 'multiSelect', label: 'Skill', required: true, visible: true, editable: true }, + { code: 'difficultyTarget', label: 'Difficulty Target', required: true, visible: true, editable: true }, + ]), + readFramework: vi.fn().mockResolvedValue([ + { code: 'skill', name: 'Skill', index: 1, terms: [{ code: 'physics', name: 'physics' }] }, + ]), + ...over, + }); + const baseContent = { + ...mockContent, primaryCategory: 'Dynamic Course Assessment', + difficultyTarget: '{"E":2,"M":0,"D":0}', + }; + + /** Selects "physics" through the UI (baseContent has no saved skill). */ + async function selectPhysicsSkill() { + fireEvent.click(await screen.findByRole('button', { name: /Select Skill/ })); + fireEvent.click(await screen.findByText('physics')); + } + + it('blocks save and shows the per-level shortfall when the pool is insufficient (positive)', async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + const service = serviceWithSkill({ + searchAssessmentItemBucketCounts: vi.fn().mockResolvedValue({ physics: { E: 0, M: 0, D: 0 } }), + }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith( + expect.stringContaining('Easy: requested 2 needs 4, available 0'), 'error', + )); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('allows save when the pool covers the requested counts (negative)', async () => { + const saveMetadata = vi.fn(); + const service = serviceWithSkill({ + }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalled()); + }); + + it('blocks save when the pool has the requested count but not requested x multiplier (negative)', async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + const service = serviceWithSkill({ + // 3 Easy items exist but only floor(3/2)=1 can be drawn per the job's multiplier rule. + searchAssessmentItemBucketCounts: vi.fn().mockResolvedValue({ physics: { E: 3, M: 0, D: 0 } }), + }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith( + expect.stringContaining('Easy: requested 2 needs 4, available 2'), 'error', + )); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('blocks save, translated, when one skill has fewer than minCriteria x multiplier Live questions (positive)', async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + const service = serviceWithSkill({ + searchSkillPoolCounts: vi.fn().mockResolvedValue({ physics: 3 }), + }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith( + 'Each skill needs at least 4 Live questions. Too few for: physics', 'error', + )); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('shows and keeps the saved skill when the form loads after the drawer opens (positive)', async () => { + const saveMetadata = vi.fn(); + const service = serviceWithSkill({ + }); + // The editor holds the selection read from the framework's skill category as dynamicSkills. + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, content: { ...baseContent, dynamicSkills: ['physics'] } }); + render(); + await screen.findByText('Difficulty Target'); + expect(await screen.findByText('physics')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ skill: ['physics'] }), { skillField: 'skill' })); + }); + + it('blocks a skill the job could not give its own minimum at the chosen levels, which would otherwise stay stale forever (positive)', async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + // All of physics' questions are Difficult, but only Easy is requested. + const service = serviceWithSkill({ searchAssessmentItemBucketCounts: vi.fn().mockResolvedValue({ physics: { E: 0, M: 0, D: 30 } }) }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save & Generate/ })); + await waitFor(() => expect(showToast).toHaveBeenCalled()); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('blocks a target too small for the number of skills, like the job does (positive)', async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + const content = { ...baseContent, difficultyTarget: '{"E":1,"M":0,"D":0}' }; + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: serviceWithSkill(), saveMetadata, showToast, content }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save & Generate/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith(expect.stringContaining('must add up to at least 2'), 'error')); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it("checks the pool with the content's own multiplier, not the default (positive)", async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + // 9 Easy items cover 2 at the default x3, but not at this content's x5. + const service = serviceWithSkill({ searchAssessmentItemBucketCounts: vi.fn().mockResolvedValue({ physics: { E: 9, M: 0, D: 0 } }) }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: { ...baseContent, multiplier: 5 } }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save & Generate/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith(expect.stringContaining('Easy: requested 2 needs 10, available 5'), 'error')); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it("applies the content's own minCriteria to the target and the per-skill floor (positive)", async () => { + const showToast = vi.fn(); + const content = { ...baseContent, difficultyTarget: '{"E":4,"M":0,"D":0}', minCriteria: '4', multiplier: 2 }; + const service = serviceWithSkill({ searchSkillPoolCounts: vi.fn().mockResolvedValue({ physics: 7 }) }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, showToast, content }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save & Generate/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith('Each skill needs at least 8 Live questions. Too few for: physics', 'error')); + }); + + it('saves only once when Save & Generate is clicked twice during the pool check (negative)', async () => { + const saveMetadata = vi.fn(); + let release: () => void = () => {}; + const slow = vi.fn(() => new Promise((resolve) => { release = () => resolve({ physics: { E: 9, M: 9, D: 9 } }); })); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: serviceWithSkill({ searchAssessmentItemBucketCounts: slow }), saveMetadata, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + const button = screen.getByRole('button', { name: /Save & Generate/ }); + fireEvent.click(button); + fireEvent.click(button); + release(); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledTimes(1)); + expect(slow).toHaveBeenCalledTimes(1); + }); + + it('disables Save while questions are generating, so a save cannot skip its own generation (positive)', async () => { + const saveMetadata = vi.fn(); + const ed = makeEd({ isDynamicAssess: true, dynamicAssessRefreshing: true, drawer: 'metadata', service: serviceWithSkill(), saveMetadata, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + const button = screen.getByRole('button', { name: /Save/ }); + expect(button).toBeDisabled(); + fireEvent.click(button); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('refuses Save & Submit with changed settings instead of submitting stale questions (positive)', async () => { + const saveMetadataAndSubmit = vi.fn(); + const showToast = vi.fn(); + const searchAssessmentItemBucketCounts = vi.fn(); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', reviewSubmitMode: true, service: serviceWithSkill({ searchAssessmentItemBucketCounts }), saveMetadataAndSubmit, showToast, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith(expect.stringContaining('use Save & Generate'), 'error')); + expect(saveMetadataAndSubmit).not.toHaveBeenCalled(); + expect(searchAssessmentItemBucketCounts).not.toHaveBeenCalled(); + }); + + it('labels the button Save & Generate only when this save will generate (positive)', async () => { + const service = serviceWithSkill(); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + expect(screen.getByRole('button', { name: /Save changes/ })).toBeInTheDocument(); + await selectPhysicsSkill(); + expect(await screen.findByRole('button', { name: /Save & Generate/ })).toBeInTheDocument(); + }); + + it('skips the pool searches for a save that will not generate (negative)', async () => { + const searchAssessmentItemBucketCounts = vi.fn(); + const saveMetadata = vi.fn(); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: serviceWithSkill({ searchAssessmentItemBucketCounts }), saveMetadata, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + fireEvent.click(screen.getByRole('button', { name: /Save changes/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalled()); + expect(searchAssessmentItemBucketCounts).not.toHaveBeenCalled(); + }); + }); + + describe('minimum questions per skill panel (Dynamic Assess)', () => { + const service = () => mockService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'skill', inputType: 'multiSelect', label: 'Skill', required: true, visible: true, editable: true }, + { code: 'difficultyTarget', label: 'Difficulty Target', required: true, visible: true, editable: true }, + ]), + readFramework: vi.fn().mockResolvedValue([ + { code: 'skill', name: 'Skill', index: 1, terms: [{ code: 'physics', name: 'physics' }, { code: 'chemistry', name: 'chemistry' }] }, + ]), + }); + const dynamic = { ...mockContent, primaryCategory: 'Dynamic Course Assessment', difficultyTarget: '{"E":1,"M":1,"D":1}', dynamicSkills: ['physics'] }; + + it("shows the content's minimum against the live total and flags it when too low (positive)", async () => { + render(); + expect(await screen.findByText('Minimum questions per skill')).toBeInTheDocument(); + expect(screen.getByText('Total: 3 · Minimum: 4')).toBeInTheDocument(); + expect(screen.getByText('Each selected skill needs at least 4 questions; increase the total to at least 4.')).toBeInTheDocument(); + expect(screen.getByText('Needs adjustment')).toBeInTheDocument(); + fireEvent.change(screen.getByRole('spinbutton', { name: 'Easy' }), { target: { value: '2' } }); + expect(screen.getByText('Total: 4 · Minimum: 4')).toBeInTheDocument(); + expect(screen.queryByText('Needs adjustment')).toBeNull(); + expect(screen.getByText('Each selected skill needs at least 4 questions.')).toBeInTheDocument(); + }); + + it('multiplies the minimum by the number of selected skills, defaulting minCriteria to 2 (positive)', async () => { + render(); + expect(await screen.findByText('Total: 3 · Minimum: 4')).toBeInTheDocument(); + expect(screen.getByText('Needs adjustment')).toBeInTheDocument(); + }); + + it('is hidden until a skill is selected (negative)', async () => { + render(); + await screen.findByText('Difficulty Target'); + expect(screen.queryByText('Minimum questions per skill')).toBeNull(); + }); + + it('is never shown for non-Dynamic content (negative)', async () => { + const content = { ...mockContent, primaryCategory: 'Learning Resource', difficultyTarget: '{"E":1,"M":0,"D":0}', skill: ['physics'] }; + render(); + await screen.findByText('Difficulty Target'); + expect(screen.queryByText('Minimum questions per skill')).toBeNull(); + }); + + describe('"See an example"', () => { + const withCounts = () => { + const searchAssessmentItemBucketCounts = vi.fn().mockResolvedValue({}); + const searchSkillPoolCounts = vi.fn().mockResolvedValue({}); + return { svc: mockService({ ...service(), searchAssessmentItemBucketCounts, searchSkillPoolCounts }), searchAssessmentItemBucketCounts, searchSkillPoolCounts }; + }; + const open = async (content: Record, svc = withCounts().svc) => { + render(); + fireEvent.click(await screen.findByRole('button', { name: /See an example/ })); + }; + + it('is collapsed by default (negative)', async () => { + render(); + await screen.findByText('Minimum questions per skill'); + expect(screen.queryByText(/^Example: you pick 2 skills/)).toBeNull(); + }); + + it('explains the rule with a fixed example for minCriteria 2 (positive)', async () => { + await open(dynamic); + expect(screen.getByText('Example: you pick 2 skills and ask for 2 Easy, 2 Medium and 2 Difficult.')).toBeInTheDocument(); + expect(screen.getByText('Each learner gets 6 questions.')).toBeInTheDocument(); + expect(screen.getByText('Minimum 2 questions will come from each skill.')).toBeInTheDocument(); + }); + + it("follows the content's own minCriteria (3) (positive)", async () => { + await open({ ...dynamic, minCriteria: 3 }); + expect(screen.getByText('Example: you pick 2 skills and ask for 3 Easy, 3 Medium and 3 Difficult.')).toBeInTheDocument(); + expect(screen.getByText('Each learner gets 9 questions.')).toBeInTheDocument(); + expect(screen.getByText('Minimum 3 questions will come from each skill.')).toBeInTheDocument(); + }); + + it("doesn't change with the creator's skills or target (negative)", async () => { + await open({ ...dynamic, dynamicSkills: ['physics', 'chemistry'], difficultyTarget: '{"E":5,"M":0,"D":1}' }); + expect(screen.getByText('Example: you pick 2 skills and ask for 2 Easy, 2 Medium and 2 Difficult.')).toBeInTheDocument(); + expect(screen.getByText('Each learner gets 6 questions.')).toBeInTheDocument(); + }); + + it('runs no searches when opened (negative)', async () => { + const { svc, searchAssessmentItemBucketCounts, searchSkillPoolCounts } = withCounts(); + await open(dynamic, svc); + await new Promise((r) => setTimeout(r, 700)); + expect(searchAssessmentItemBucketCounts).not.toHaveBeenCalled(); + expect(searchSkillPoolCounts).not.toHaveBeenCalled(); + }); + + it('hides the example again (negative)', async () => { + await open(dynamic); + fireEvent.click(screen.getByRole('button', { name: /Hide/ })); + expect(screen.queryByText('Each learner gets 6 questions.')).toBeNull(); + }); + }); + }); + + describe('skills are selected in the framework\'s deepest category (Dynamic Assess)', () => { + // Deepest category is 'topic' and there is no category coded 'skill', like a non-USF framework. + const nonUsfService = (over: Record = {}) => mockService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'skill', inputType: 'multiSelect', label: 'Skill', required: true, visible: true, editable: true }, + { code: 'difficultyTarget', label: 'Difficulty Target', required: true, visible: true, editable: true }, + ]), + readFramework: vi.fn().mockResolvedValue([ + { code: 'topic', name: 'Topic', index: 2, terms: [{ code: 't1', name: 'Algebra' }, { code: 't2', name: 'Geometry' }] }, + { code: 'subject', name: 'Subject', index: 1, terms: [{ code: 's1', name: 'Maths' }] }, + ]), + ...over, + }); + const content = { ...mockContent, primaryCategory: 'Dynamic Course Assessment', difficultyTarget: '{"E":2,"M":0,"D":0}' }; + + it('offers the deepest category\'s terms under its own name, saves them in that category and checks the pool on it (positive)', async () => { + const saveMetadata = vi.fn(); + const pool = vi.fn().mockResolvedValue({ Algebra: { E: 9, M: 9, D: 9 } }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: nonUsfService({ searchAssessmentItemBucketCounts: pool }), saveMetadata, content }); + render(); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); + expect(await screen.findByText('Algebra')).toBeInTheDocument(); + expect(screen.getByText('Geometry')).toBeInTheDocument(); + expect(screen.queryByText('Maths')).not.toBeInTheDocument(); + fireEvent.click(screen.getByText('Algebra')); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ topic: ['Algebra'] }), { skillField: 'topic' })); + expect(saveMetadata.mock.calls[0][0]).not.toHaveProperty('skill'); + expect(pool).toHaveBeenCalledWith(['Algebra'], expect.anything(), 'topic'); + }); + + it('lets the author switch framework, reloading skill options from the new framework\'s deepest category (positive)', async () => { + const saveMetadata = vi.fn(); + const readFramework = vi.fn(async (fw: string) => (fw === 'USF' + ? [{ code: 'skill', name: 'Skill', index: 3, terms: [{ code: 'ph', name: 'Physics' }] }] + : [{ code: 'topic', name: 'Topic', index: 2, terms: [{ code: 't1', name: 'Algebra' }] }])); + const service = nonUsfService({ + readFramework, + searchFrameworks: vi.fn().mockResolvedValue([{ identifier: 'BMGS', name: 'BMGS' }, { identifier: 'USF', name: 'Universal Skills' }]), + }); + const ed = makeEd({ drawer: 'metadata', service, saveMetadata, isDynamicAssess: true, content: { ...content, framework: 'BMGS' } }); + render(); + + const picker = await screen.findByLabelText('Framework') as HTMLSelectElement; + await waitFor(() => expect(picker.value).toBe('BMGS')); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); + fireEvent.click(await screen.findByText('Algebra')); + fireEvent.mouseDown(document.body); // close the skill dropdown, as clicking elsewhere does + + fireEvent.change(picker, { target: { value: 'USF' } }); + await waitFor(() => expect(readFramework).toHaveBeenCalledWith('USF')); + fireEvent.click(await screen.findByRole('button', { name: /Select Skill/ })); // previous pick was cleared + fireEvent.click(await screen.findByText('Physics')); + expect(screen.queryByText('Algebra')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ framework: 'USF', skill: ['Physics'] }), { skillField: 'skill' })); + }); + + it('reloads the categories when the author picks the placeholder and then the same framework again (positive)', async () => { + const readFramework = vi.fn().mockResolvedValue([{ code: 'topic', name: 'Topic', index: 2, terms: [{ code: 't1', name: 'Algebra' }] }]); + const service = nonUsfService({ readFramework, searchFrameworks: vi.fn().mockResolvedValue([{ identifier: 'BMGS', name: 'BMGS' }]) }); + const ed = makeEd({ drawer: 'metadata', service, isDynamicAssess: true, content: { ...content, framework: 'BMGS' } }); + render(); + const picker = await screen.findByLabelText('Framework') as HTMLSelectElement; + await waitFor(() => expect(picker.value).toBe('BMGS')); + const callsBefore = readFramework.mock.calls.length; + fireEvent.change(picker, { target: { value: '' } }); + fireEvent.change(picker, { target: { value: 'BMGS' } }); + await waitFor(() => expect(readFramework.mock.calls.length).toBeGreaterThan(callsBefore)); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); + expect(await screen.findByText('Algebra')).toBeInTheDocument(); + }); + + it('keeps skill disabled until a framework is chosen (negative)', async () => { + const service = nonUsfService({ readFramework: vi.fn().mockResolvedValue([]) }); + const ed = makeEd({ drawer: 'metadata', service, isDynamicAssess: true, framework: '', content: { ...content, framework: undefined } }); + render(); + const skill = await screen.findByRole('button', { name: /Select a framework first/ }); + expect(skill).toBeDisabled(); + }); + + it('keeps the Save label in step with skill changes, and with other edits, after memoizing it (positive/negative)', async () => { + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: nonUsfService(), content }); + render(); + expect(await screen.findByRole('button', { name: 'Save changes' })).toBeInTheDocument(); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); + fireEvent.click(await screen.findByText('Algebra')); + expect(await screen.findByRole('button', { name: 'Save & Generate' })).toBeInTheDocument(); + fireEvent.change(screen.getByDisplayValue('Sample content'), { target: { value: 'Renamed' } }); + expect(screen.getByRole('button', { name: 'Save & Generate' })).toBeInTheDocument(); + }); + + it('keeps Skill disabled after the author picks the framework placeholder (positive)', async () => { + const service = nonUsfService({ searchFrameworks: vi.fn().mockResolvedValue([{ identifier: 'BMGS', name: 'BMGS' }]) }); + const ed = makeEd({ drawer: 'metadata', service, isDynamicAssess: true, framework: 'BMGS', content: { ...content, framework: 'BMGS' } }); + render(); + const picker = await screen.findByLabelText('Framework') as HTMLSelectElement; + await screen.findByRole('button', { name: /Select Topic/ }); + fireEvent.change(picker, { target: { value: '' } }); + await new Promise((r) => setTimeout(r, 20)); // let any fallback framework read resolve + expect(screen.getByRole('button', { name: /Select a framework first/ })).toBeDisabled(); + }); + + it('applies only the latest framework\'s categories when an earlier read resolves last (positive)', async () => { + let resolveBmgs: (v: unknown) => void = () => {}; + const readFramework = vi.fn((fw: string) => (fw === 'BMGS' + ? new Promise((r) => { resolveBmgs = r; }) + : Promise.resolve([{ code: 'skill', name: 'Skill', index: 3, terms: [{ code: 'ph', name: 'Physics' }] }]))); + const service = nonUsfService({ + readFramework, + searchFrameworks: vi.fn().mockResolvedValue([{ identifier: 'BMGS', name: 'BMGS' }, { identifier: 'USF', name: 'Universal Skills' }]), + }); + const ed = makeEd({ drawer: 'metadata', service, isDynamicAssess: true, content: { ...content, framework: 'BMGS' } }); + render(); + const picker = await screen.findByLabelText('Framework') as HTMLSelectElement; + await waitFor(() => expect(readFramework).toHaveBeenCalledWith('BMGS')); + fireEvent.change(picker, { target: { value: 'USF' } }); + await screen.findByRole('button', { name: /Select Skill/ }); + resolveBmgs([{ code: 'topic', name: 'Topic', index: 2, terms: [{ code: 't1', name: 'Algebra' }] }]); + await new Promise((r) => setTimeout(r, 20)); + expect(screen.getByRole('button', { name: /Select Skill/ })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Select Topic/ })).toBeNull(); + }); + + it('drops a generating save when the drawer closes during the pool check (positive)', async () => { + const saveMetadata = vi.fn(); + let resolvePool: (v: unknown) => void = () => {}; + const service = nonUsfService({ searchAssessmentItemBucketCounts: vi.fn(() => new Promise((r) => { resolvePool = r; })) }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, content }); + const { rerender } = render(); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); + fireEvent.click(await screen.findByText('Algebra')); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(service.searchAssessmentItemBucketCounts).toHaveBeenCalled()); + rerender(); + resolvePool({ Algebra: { E: 9, M: 9, D: 9 } }); + await new Promise((r) => setTimeout(r, 20)); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('sends an empty array when the author removes the last skill (positive)', async () => { + const saveMetadata = vi.fn(); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: nonUsfService(), saveMetadata, content: { ...content, dynamicSkills: ['Algebra'] } }); + render(); + fireEvent.click(await screen.findByRole('button', { name: /Algebra|Select Topic/ })); + fireEvent.click((await screen.findAllByText('Algebra')).at(-1) as HTMLElement); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalled()); + expect(saveMetadata.mock.calls[0][0]).toHaveProperty('topic', []); + }); + + describe('with a single-select parent category', () => { + const parentService = (over: Record = {}) => nonUsfService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'board', inputType: 'select', label: 'Board', visible: true, editable: true }, + { code: 'skill', inputType: 'multiSelect', label: 'Skill', required: true, visible: true, editable: true }, + { code: 'difficultyTarget', label: 'Difficulty Target', required: true, visible: true, editable: true }, + ]), + readFramework: vi.fn().mockResolvedValue([ + { code: 'board', name: 'Board', index: 1, terms: [ + { code: 's1', name: 'Maths', associations: [{ category: 'topic', name: 'Algebra' }] }, + { code: 's2', name: 'Science', associations: [{ category: 'topic', name: 'Optics' }] }, + ] }, + { code: 'topic', name: 'Topic', index: 2, terms: [{ code: 't1', name: 'Algebra' }, { code: 't2', name: 'Optics' }] }, + ]), + searchFrameworks: vi.fn().mockResolvedValue([{ identifier: 'BMGS', name: 'BMGS' }, { identifier: 'USF', name: 'Universal Skills' }]), + ...over, + }); + const parentSelect = async () => (await screen.findByRole('option', { name: 'Maths' })).closest('select') as HTMLSelectElement; + + it('lets a parent picked after a framework switch still narrow the skills (positive)', async () => { + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: parentService(), content: { ...content, framework: 'BMGS' } }); + render(); + const picker = await screen.findByLabelText('Framework') as HTMLSelectElement; + await waitFor(() => expect(picker.value).toBe('BMGS')); + fireEvent.change(picker, { target: { value: 'USF' } }); + fireEvent.change(await parentSelect(), { target: { value: 'Maths' } }); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); + expect(await screen.findByText('Algebra')).toBeInTheDocument(); + expect(screen.queryByText('Optics')).toBeNull(); + }); + + it('clears picked skills when their parent category changes (positive)', async () => { + const saveMetadata = vi.fn(); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: parentService(), saveMetadata, content: { ...content, framework: 'BMGS' } }); + render(); + fireEvent.change(await parentSelect(), { target: { value: 'Maths' } }); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); + fireEvent.click(await screen.findByText('Algebra')); + fireEvent.mouseDown(document.body); + fireEvent.change(await parentSelect(), { target: { value: 'Science' } }); + expect(await screen.findByRole('button', { name: /Select Topic/ })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalled()); + expect(saveMetadata.mock.calls[0][0]).toHaveProperty('topic', []); + }); + }); + + it('does not fall back to a free-text box when no category is literally named skill (negative)', async () => { + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: nonUsfService(), content }); + render(); + // The selection is a dropdown of the deepest category, never a plain text input. + expect(await screen.findByRole('button', { name: /Select Topic/ })).toBeInTheDocument(); + }); }); }); diff --git a/src/components/MetadataDrawer.tsx b/src/components/MetadataDrawer.tsx index 34453f5..49d6ef7 100644 --- a/src/components/MetadataDrawer.tsx +++ b/src/components/MetadataDrawer.tsx @@ -1,23 +1,137 @@ -import React, { useEffect, useMemo, useRef, useState } from 'react'; +import React, { useEffect, useId, useMemo, useRef, useState } from 'react'; import Drawer from './Drawer'; import type { EditorController } from '../useEditor'; import type { FormField, FrameworkCategory } from '../types'; -import { t } from '../i18n/i18n'; -import { cascadedOptions } from '../taxonomy'; +import { t, tf } from '../i18n/i18n'; +import { cascadedOptions, deepestCategoryCode } from '../taxonomy'; import { PencilIcon, ChevronDown, ImageIcon, CheckIcon } from '../icons'; +import { type DifficultyTarget, toDifficultyTarget, serializeDifficultyTarget } from '../difficultyTarget'; +import { dynamicAssessSettings, needsGeneration } from '../dynamicAssessDraw'; +import { planPool } from '../poolPlan'; /** * Multi-value field? Driven by the form definition, not a hardcoded list — a field * is an array if the form marks it multiselect (or dataType 'list'), so any custom * taxonomy category the framework returns is handled dynamically. */ -function isMultiField(f: FormField): boolean { +function isMultiField(f: FormField, dynamicAssess = false): boolean { + if (dynamicAssess && isSkillField(f)) return true; const it = (f.inputType ?? '').toLowerCase(); if (it.includes('multi')) return true; const dt = (f.dataType ?? '').toLowerCase(); return dt === 'list'; } +/** difficultyTarget is matched by code: the form definition has no inputType for three named number fields. */ +function isDifficultyTargetField(f: FormField): boolean { + return f.code?.toLowerCase() === 'difficultytarget'; +} + +/** Dynamic Assess skill is always a list bound to the framework's deepest category, matching question-set editor-v2's isSkillField. */ +function isSkillField(f: FormField): boolean { + return f.code?.toLowerCase() === 'skill'; +} + + +const DifficultyTargetInput: React.FC<{ + lang: string; label: string; required?: boolean; disabled?: boolean; + value: DifficultyTarget; onChange: (v: DifficultyTarget) => void; +}> = ({ lang, label, required, disabled, value, onChange }) => { + const rows: Array<{ key: keyof DifficultyTarget; text: string }> = [ + { key: 'E', text: t(lang, 'DIFFICULTY_EASY') }, + { key: 'M', text: t(lang, 'DIFFICULTY_MEDIUM') }, + { key: 'D', text: t(lang, 'DIFFICULTY_DIFFICULT') }, + ]; + const labelId = useId(); + return ( +
+ +
+ {rows.map(({ key, text }) => ( +
+ + { + const n = e.target.value === '' ? 0 : Math.max(0, Math.floor(Number(e.target.value)) || 0); + onChange({ ...value, [key]: n }); + }} + /> +
+ ))} +
+
+ ); +}; + +/** Live pool counts the job allocates from: per skill x level, and per skill overall (knowlg-service's floor). */ +export interface PoolCounts { buckets: Record>; skillCounts: Record } + +/** Why the job couldn't generate these settings (the first problem, in the order Save reports them), or null; shared by Save's check and the panel's example. */ +export function poolProblem( + lang: string, skills: string[], target: DifficultyTarget, counts: PoolCounts, minCriteria: number, multiplier: number, +): string | null { + const { buckets, skillCounts } = counts; + const plan = planPool(skills, target, (s, l) => buckets[s]?.[l] ?? 0, minCriteria, multiplier); + if (plan.infeasible) { + return tf(lang, 'ERROR_TOO_MANY_SKILLS', { count: skills.length, needed: skills.length * minCriteria, min: minCriteria }); + } + if (plan.uncovered.length) { + const levelKey = { E: 'DIFFICULTY_EASY', M: 'DIFFICULTY_MEDIUM', D: 'DIFFICULTY_DIFFICULT' } as const; + const lines = plan.uncovered.map(({ level, covered, target: requested }) => + tf(lang, 'ERROR_POOL_SHORTFALL', { level: t(lang, levelKey[level]), requested, needed: requested * multiplier, available: covered * multiplier })); + return `${t(lang, 'ERROR_POOL_INSUFFICIENT')}: ${lines.join('; ')}`; + } + // A skill that can't get its own minimum would be left out of the pool, and the settings would then never match the questions. + if (plan.shortSkills.length) return tf(lang, 'ERROR_SKILL_LEVELS_SHORT', { skills: plan.shortSkills.join(', ') }); + // Same per-skill floor knowlg-service enforces at Generate, so it fails here, translated, instead of after a successful save. + const perSkill = minCriteria * multiplier; + const shortSkills = skills.filter((s) => (skillCounts[s] ?? 0) < perSkill); + return shortSkills.length ? tf(lang, 'ERROR_SKILL_POOL_TOO_SMALL', { needed: perSkill, skills: shortSkills.join(', ') }) : null; +} + +/** Dynamic Assess: shows the per-skill minimum against the live Difficulty Target, so a too-small total is visible before Save rejects it; "See an example" explains the rule with a fixed example. */ +export const MinimumPerSkillPanel: React.FC<{ + lang: string; minCriteria: number; skillCount: number; target: DifficultyTarget; +}> = ({ lang, minCriteria, skillCount, target }) => { + const [expanded, setExpanded] = useState(false); + const total = (target.E ?? 0) + (target.M ?? 0) + (target.D ?? 0); + const minimum = minCriteria * skillCount; + const short = total < minimum; + // Fixed example (2 skills, n per level), independent of what the creator entered; only the system's minCriteria feeds it. + const n = Math.max(minCriteria, 1); + return ( +
+

{t(lang, 'MIN_PER_SKILL_TITLE')}

+

{tf(lang, short ? 'MIN_PER_SKILL_SHORT' : 'MIN_PER_SKILL_OK', { min: minCriteria, minimum })}

+ {expanded && ( +
+

{tf(lang, 'MIN_PER_SKILL_EX_INTRO', { n })}

+
    +
  • {tf(lang, 'MIN_PER_SKILL_EX_TOTAL', { total: 3 * n })}
  • +
  • {tf(lang, 'MIN_PER_SKILL_EX_EACH', { min: minCriteria })}
  • +
+
+ )} +
+ {tf(lang, 'MIN_PER_SKILL_TOTALS', { total, minimum })} + + {short && {t(lang, 'MIN_PER_SKILL_NEEDS_ADJUSTMENT')}} + + +
+
+ ); +}; + /** Fallback field set when form/read returns nothing (keeps the drawer usable). */ const FALLBACK_FIELDS: FormField[] = [ { code: 'appicon', inputType: 'file', label: 'Thumbnail', index: 1, visible: true, editable: true }, @@ -110,6 +224,8 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { const [values, setValues] = useState>({}); /* Multi-value taxonomy fields (medium, gradeLevel, subject) — real arrays. */ const [multiVals, setMultiVals] = useState>({}); + /* Dynamic Assess difficultyTarget fields — object-shaped {E,M,D}, keyed by code. */ + const [diffTargets, setDiffTargets] = useState>({}); const [appIcon, setAppIcon] = useState(); const [categories, setCategories] = useState([]); const [formFields, setFormFields] = useState([]); @@ -117,14 +233,39 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { const loadedFormKey = useRef(null); /** Content id already seeded this open-session — prevents an async form load re-seeding over edits. */ const seededRef = useRef(null); + /** Separate seed guard for difficultyTarget: it only appears once the async form loads, after seededRef has already fired. */ + const diffSeededRef = useRef(null); + /* Dynamic Assess: author-chosen framework; skill options come from its deepest category. */ + const [selectedFw, setSelectedFw] = useState(''); + // True while the pool searches run before a generating save, so a second click can't save twice. + const [checking, setChecking] = useState(false); + const [fwOptions, setFwOptions] = useState>([]); + const contentChannel = (content as Record | null)?.channel as string | undefined; + + // Bumped on every open/close, so a save still awaiting its pool check after the drawer closed is dropped. + const sessionRef = useRef(0); + useEffect(() => { + sessionRef.current += 1; + if (open) setSelectedFw(String(content?.framework || framework || '')); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open, content?.identifier]); + + useEffect(() => { + if (!open || !ed.isDynamicAssess) return; + service.searchFrameworks(contentChannel ?? ed.context.channel).then(setFwOptions).catch(() => setFwOptions([])); + }, [open, ed.isDynamicAssess, service, contentChannel, ed.context.channel]); /* Framework categories for taxonomy cascade. */ useEffect(() => { - const fw = content?.framework || framework; + // Dynamic Assess follows the picker alone, so choosing its placeholder leaves Skill without options. + const fw = ed.isDynamicAssess ? selectedFw : (content?.framework || framework); if (!open || !fw || loadedFw.current === fw) return; loadedFw.current = fw; - service.readFramework(fw).then(setCategories).catch(() => setCategories([])); - }, [open, content, framework, service]); + // Only the latest requested framework may apply, since a slower earlier read can resolve after it. + service.readFramework(fw) + .then((c) => { if (loadedFw.current === fw) setCategories(c); }) + .catch(() => { if (loadedFw.current === fw) setCategories([]); }); + }, [open, content, framework, service, selectedFw, ed.isDynamicAssess]); /* Form/read field definitions — save form for Edit Details, review form for * Submit-for-review. Keyed on subtype+action so switching mode refetches even @@ -157,6 +298,20 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { () => [...categories].sort((a, b) => (a.index ?? 0) - (b.index ?? 0)).map((c) => c.code), [categories], ); + const skillCategoryCode = useMemo(() => deepestCategoryCode(categories), [categories]); + // Dynamic Assess: the selection is the framework's deepest category, so the picker carries that category's name. + const skillCategoryLabel = ed.isDynamicAssess ? categories.find((c) => c.code === skillCategoryCode)?.name : undefined; + /** A form field for the deepest category itself, which the Dynamic skill picker already edits. */ + const isReplacedBySkillPicker = (f: FormField) => ed.isDynamicAssess && !!skillCategoryCode && f.code === skillCategoryCode && !isSkillField(f); + const skillPickerCode = ed.isDynamicAssess ? fields.find(isSkillField)?.code : undefined; + // This content's own rules (knowlg-service stores them at create), so the panel and pool check match what the job enforces. + const { minCriteria, multiplier } = dynamicAssessSettings(content as Record | null); + /** Content as this save would leave it, with the picker's terms as the in-memory selection. */ + const withSelection = (out: Record) => ({ + ...(content ?? {}), + ...out, + ...(skillPickerCode ? { dynamicSkills: multiVals[skillPickerCode] ?? [] } : {}), + }); const setVal = (code: string, v: string) => setValues((s) => ({ ...s, [code]: v })); const setMulti = (code: string, v: string[]) => setMultiVals((s) => ({ ...s, [code]: v })); @@ -177,8 +332,10 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { for (const f of fields) { if (f.code === 'name' || f.code === 'description') continue; if (f.code === 'appicon' || f.code === 'appIcon') continue; - const cv = (content as Record)[f.code]; - if (isMultiField(f)) { + if (isDifficultyTargetField(f)) continue; // seeded separately below — see diffSeededRef + // The Dynamic skill picker shows the selection read from the framework's skill field, not a field named "skill". + const cv = ed.isDynamicAssess && isSkillField(f) ? content.dynamicSkills : (content as Record)[f.code]; + if (isMultiField(f, ed.isDynamicAssess)) { multi[f.code] = Array.isArray(cv) ? cv.map(String) : cv != null && cv !== '' ? [String(cv)] : []; } else { vals[f.code] = cv != null ? String(cv) : ''; @@ -189,6 +346,26 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { setAppIcon(content.appIcon); }, [open, content, fields]); + /* Seeds difficultyTarget and skill once they appear (form-only fields, absent from FALLBACK_FIELDS); safe since neither is rendered before then. */ + useEffect(() => { + if (!open) { diffSeededRef.current = null; return; } + if (!content) return; + const dtFields = fields.filter(isDifficultyTargetField); + if (dtFields.length === 0) return; + if (diffSeededRef.current === content.identifier) return; + diffSeededRef.current = content.identifier; + const diff: Record = {}; + for (const f of dtFields) { + diff[f.code] = toDifficultyTarget((content as Record)[f.code]); + } + setDiffTargets((s) => ({ ...s, ...diff })); + const skill: Record = {}; + for (const f of ed.isDynamicAssess ? fields.filter(isSkillField) : []) { + skill[f.code] = content.dynamicSkills ?? []; + } + setMultiVals((s) => ({ ...s, ...skill })); + }, [open, content, fields]); + const appIconField = fields.find((f) => f.code === 'appicon' || f.code === 'appIcon'); const hasAppIcon = !!appIconField; const appIconLabel = appIconField?.label ?? appIconField?.name ?? t(lang, 'THUMBNAIL'); @@ -209,6 +386,19 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { setMulti(code, []); setVal(code, ''); } + // The Dynamic skill picker holds the deepest category's terms under its own code, so it resets with that category. + if (ed.isDynamicAssess && skillPickerCode && skillCategoryCode && orderedTaxoCodes.slice(idx + 1).includes(skillCategoryCode)) setMulti(skillPickerCode, []); + }; + + /** A new framework means different category terms, so clear skill and every category value picked under the old one. */ + const onFrameworkChange = (fw: string) => { + const codes = [...categories.map((c) => c.code), 'skill']; + setSelectedFw(fw); + setCategories([]); + loadedFw.current = null; // otherwise re-picking the original framework (or the placeholder) never reloads its categories + // Only fields already held as multiselects; an empty array for a single-select would mask its later value in selectedTaxo. + setMultiVals((s) => ({ ...s, ...Object.fromEntries(codes.filter((c) => c in s || c === skillPickerCode).map((c) => [c, []])) })); + setValues((s) => ({ ...s, ...Object.fromEntries(codes.filter((c) => c in s).map((c) => [c, ''])) })); }; /** Labels of required, editable, visible fields left empty (any inputType). */ @@ -216,33 +406,41 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { const miss: string[] = []; for (const f of fields) { if (!f.required || f.editable === false || f.visible === false) continue; + if (isReplacedBySkillPicker(f)) continue; const code = f.code; let empty: boolean; if (code === 'appicon' || code === 'appIcon') empty = !appIcon; - else if (isMultiField(f)) empty = (multiVals[code] ?? []).length === 0; + else if (isDifficultyTargetField(f)) { + const dt = diffTargets[code] ?? {}; + empty = (dt.E ?? 0) + (dt.M ?? 0) + (dt.D ?? 0) <= 0; + } + else if (isMultiField(f, ed.isDynamicAssess)) empty = (multiVals[code] ?? []).length === 0; else empty = !((values[code] ?? '').trim()); if (empty) miss.push(f.label ?? f.name ?? code); } return miss; }; - const onSave = () => { - const nameField = fields.find((f) => f.code === 'name'); - if (nameField?.required !== false && !(values.name ?? '').trim()) { - showToast(t(lang, 'ERROR_TITLE_REQUIRED'), 'error'); - return; - } - // On the submit-for-review path, enforce every required field the form marks (not just name). - if (reviewSubmitMode) { - const miss = missingRequired(); - if (miss.length) { setReviewErrors(miss); return; } - } + /** The fields this save would write; the Save label and onSave both read it, so they never disagree. */ + const buildOut = (): Record => { const out: Record = {}; for (const f of fields) { if (f.editable === false) continue; const code = f.code === 'appIcon' ? 'appIcon' : f.code; if (code === 'appicon' || code === 'appIcon') continue; // handled below - if (isMultiField(f)) { + if (isDifficultyTargetField(f)) { + out[f.code] = serializeDifficultyTarget(diffTargets[f.code] ?? { E: 0, M: 0, D: 0 }); + continue; + } + if (isReplacedBySkillPicker(f)) continue; + if (ed.isDynamicAssess && isSkillField(f)) { + // Saved in the framework's deepest category field, where the backend reads the selection; left out until that field is known. + const arr = multiVals[f.code]; + // An empty array, not undefined, so removing the last skill clears it on the server too; an unseeded picker writes nothing. + if (skillCategoryCode && arr) out[skillCategoryCode] = arr; + continue; + } + if (isMultiField(f, ed.isDynamicAssess)) { const arr = multiVals[f.code] ?? []; out[f.code] = arr.length ? arr : undefined; continue; @@ -252,10 +450,76 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { out[f.code] = raw || undefined; } if (appIcon) out.appIcon = appIcon; + if (ed.isDynamicAssess && selectedFw) out.framework = selectedFw; out.name = (values.name ?? '').trim(); + return out; + }; + + /** Blocks the save unless the job could generate these settings (its own allocation rules) and knowlg-service would accept every skill; returns true to proceed. */ + /** Live pool counts for these skills, from the same searches the job allocates from. */ + const loadPoolCounts = async (skills: string[]): Promise => { + const channel = (content as Record | null)?.channel as string | undefined; + const [buckets, skillCounts] = await Promise.all([ + service.searchAssessmentItemBucketCounts(skills, channel ?? ed.context.channel, skillCategoryCode ?? 'skill'), + service.searchSkillPoolCounts(skills, skillCategoryCode ?? 'skill'), + ]); + return { buckets, skillCounts }; + }; + + const checkPoolSufficiency = async (candidate: Record): Promise => { + const target = toDifficultyTarget(candidate.difficultyTarget); + const skillValues = Array.isArray(candidate.dynamicSkills) ? candidate.dynamicSkills.map(String) : []; + let counts: PoolCounts; + try { + counts = await loadPoolCounts(skillValues); + } catch { + showToast(t(lang, 'ERROR_POOL_CHECK_FAILED'), 'error'); + return false; + } + const problem = poolProblem(lang, skillValues, target, counts, minCriteria, multiplier); + if (problem) { + showToast(problem, 'error'); + return false; + } + return true; + }; + + const onSave = async () => { + if (checking || busy) return; // a second click during the pool searches would save and generate twice + if (ed.dynamicAssessRefreshing) return; // a save now would skip generating, since only one generation runs at a time + const nameField = fields.find((f) => f.code === 'name'); + if (nameField?.required !== false && !(values.name ?? '').trim()) { + showToast(t(lang, 'ERROR_TITLE_REQUIRED'), 'error'); + return; + } + // On the submit-for-review path, enforce every required field the form marks (not just name). + if (reviewSubmitMode) { + const miss = missingRequired(); + if (miss.length) { setReviewErrors(miss); return; } + } + const out = buildOut(); + const generates = needsGeneration(withSelection(out), content?.framework ?? ''); + // Submitting can't also generate, so changed settings must be saved (and generated) first. + if (reviewSubmitMode && generates) { + showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_SUBMIT_STALE'), 'error'); + return; + } + if (generates) { + const session = sessionRef.current; + setChecking(true); + try { + // The pool is only checked when this save will generate, so other edits cost no extra searches. + if (!(await checkPoolSufficiency(withSelection(out)))) return; + } finally { + setChecking(false); + } + if (sessionRef.current !== session) return; // the drawer closed or switched content during the check + } setReviewErrors([]); - if (reviewSubmitMode) saveMetadataAndSubmit(out); - else saveMetadata(out); + // Only a Dynamic save names the skill field it wrote; other content keeps the plain call. + const args: [Record, { skillField?: string }?] = ed.isDynamicAssess ? [out, { skillField: skillCategoryCode }] : [out]; + if (reviewSubmitMode) saveMetadataAndSubmit(...args); + else saveMetadata(...args); }; const onClose = () => { setReviewErrors([]); setReviewSubmitMode(false); setDrawer(null); }; @@ -270,10 +534,70 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { if (code === 'appicon' || code === 'appIcon') return null; // rendered in the top block + if (isDifficultyTargetField(f)) { + const target = diffTargets[code] ?? { E: 0, M: 0, D: 0 }; + const selectedSkills = skillPickerCode ? (multiVals[skillPickerCode] ?? []) : []; + return ( + + setDiffTargets((s) => ({ ...s, [code]: v }))} + /> + {ed.isDynamicAssess && selectedSkills.length > 0 && ( + + )} + + ); + } + + if (ed.isDynamicAssess && isSkillField(f)) { + // Current framework stays selectable even if it isn't in the system-default search results. + const fwList = selectedFw && !fwOptions.some((o) => o.identifier === selectedFw) + ? [{ identifier: selectedFw, name: selectedFw }, ...fwOptions] + : fwOptions; + return ( + + {ed.isDynamicAssess && ( +
+ +
+ + +
+
+ )} + setMulti(code, vals)} + /> +
+ ); + } + if (taxoCodes.has(code)) { const options = cascadedOptions(categories, code, selectedTaxo); // Multi vs single is decided by the form definition, not the field name. - if (isMultiField(f)) { + if (isMultiField(f, ed.isDynamicAssess)) { return ( = ({ ed }) => { ); }; - const taxoFields = fields.filter((f) => taxoCodes.has(f.code)); + // Live label: tells the author when Save will also generate questions. + // needsGeneration parses the ECML body, so it reruns only when skill, target, framework or content change, not on every keystroke in other fields. + const saveGenerates = useMemo( + () => ed.isDynamicAssess && open && needsGeneration(withSelection(buildOut()), content?.framework ?? ''), + // eslint-disable-next-line react-hooks/exhaustive-deps + [ed.isDynamicAssess, open, content, fields, multiVals, diffTargets, selectedFw, skillCategoryCode, skillPickerCode], + ); + + // Skill always renders with the other fields (under its framework picker), even when a framework names a category 'skill'. + const taxoFields = fields.filter((f) => taxoCodes.has(f.code) && !(ed.isDynamicAssess && isSkillField(f)) && !isReplacedBySkillPicker(f)); const nonTaxoFields = fields.filter( - (f) => !taxoCodes.has(f.code) && f.code !== 'appicon' && f.code !== 'appIcon', + (f) => (!taxoCodes.has(f.code) || (ed.isDynamicAssess && isSkillField(f))) && f.code !== 'appicon' && f.code !== 'appIcon', ); return ( @@ -354,10 +687,10 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { - } diff --git a/src/components/TranscriptsDrawer.test.tsx b/src/components/TranscriptsDrawer.test.tsx deleted file mode 100644 index 32e1ea5..0000000 --- a/src/components/TranscriptsDrawer.test.tsx +++ /dev/null @@ -1,766 +0,0 @@ -import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'; -import { describe, it, expect, vi, afterEach } from 'vitest'; -import TranscriptsDrawer from './TranscriptsDrawer'; -import { makeEd, mockService, mockContent } from '../test/mockEd'; - -const TRANSCRIPTS = [ - { identifier: 't_en', code: 'c_en', language: 'English', languageCode: 'en', status: 'Live', sourceLanguage: true, captionsUrl: 'https://x/en.vtt', artifactUrl: 'https://x/en.json', generatedOn: '2026-08-03T05:00:00Z' }, - { identifier: 't_hi', code: 'c_hi', language: 'Hindi', languageCode: 'hi', status: 'Review', sourceLanguage: false, artifactUrl: 'https://x/hi.json' }, - { identifier: 't_ta', code: 'c_ta', language: 'Tamil', languageCode: 'ta', status: 'Processing', sourceLanguage: false }, - { identifier: 't_te', code: 'c_te', language: 'Telugu', languageCode: 'te', status: 'Failed', sourceLanguage: false }, -]; - -describe('', () => { - it('loads and renders each language with its status when open', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service, content: { ...mockContent, mimeType: 'video/mp4' } }); - render(); - await waitFor(() => expect(service.readTranscripts).toHaveBeenCalledWith('do_1')); - expect(await screen.findByText('English')).toBeInTheDocument(); - expect(screen.getByText('Hindi')).toBeInTheDocument(); - expect(screen.getByText('Tamil')).toBeInTheDocument(); - expect(screen.getByText('Telugu')).toBeInTheDocument(); - expect(screen.getByText('Live')).toBeInTheDocument(); - expect(screen.getByText('Processing')).toBeInTheDocument(); - expect(screen.getByText('Failed')).toBeInTheDocument(); - expect(screen.getByText('SOURCE')).toBeInTheDocument(); - }); - - it('shows a placeholder icon and "Detecting language…" instead of blank/"??" when a Processing transcript has no language info yet', async () => { - const noLanguageYet = [{ identifier: 't_x', code: 'c_x', language: '', status: 'Processing', sourceLanguage: true }]; - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(noLanguageYet) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - expect(await screen.findByText('Detecting language…')).toBeInTheDocument(); - expect(screen.queryByText('??')).not.toBeInTheDocument(); - }); - - it('always lists the source language card first, regardless of its position in the backend response', async () => { - // TRANSCRIPTS has English (source) listed first already - reorder so it's last, - // to prove the UI is doing the sorting, not just reflecting response order. - const reordered = [...TRANSCRIPTS].reverse(); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(reordered) }); - const ed = makeEd({ drawer: 'transcripts', service }); - const { container } = render(); - await screen.findByText('English'); - const names = Array.from(container.querySelectorAll('.ce-transcript-name')).map((el) => el.textContent); - // Reversed input is [Telugu, Tamil, Hindi, English] - source moves to front, - // the rest keep their relative order: [English, Telugu, Tamil, Hindi]. - expect(names[0]).toContain('English'); - expect(names[names.length - 1]).toContain('Hindi'); - }); - - it('shows a note that other languages will appear once the source transcript is ready, when only the source exists so far', async () => { - const sourceOnly = [{ identifier: 't_en', code: 'c_en', language: 'English', status: 'Review', sourceLanguage: true }]; - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(sourceOnly) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - expect(await screen.findByText(/Translations for other languages will appear/)).toBeInTheDocument(); - }); - - it('does not show the translations-pending note once other languages already exist (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - expect(screen.queryByText(/Translations for other languages will appear/)).not.toBeInTheDocument(); - }); - - it('shows a note that status changes can take a few minutes to fully sync', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - expect(await screen.findByText(/take a few minutes to fully sync/)).toBeInTheDocument(); - }); - - it('does not show the sync note once every language is Live - nothing left to approve/reject (negative)', async () => { - const allLive = TRANSCRIPTS.map((tr) => ({ ...tr, status: 'Live' })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(allLive) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - expect(screen.queryByText(/take a few minutes to fully sync/)).not.toBeInTheDocument(); - }); - - it('does not show the sync note in the empty state - nothing has happened yet to sync (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue([]) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('No transcripts yet'); - expect(screen.queryByText(/take a few minutes to fully sync/)).not.toBeInTheDocument(); - }); - - it('shows an empty state when there are no transcripts yet (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue([]) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - expect(await screen.findByText('No transcripts yet')).toBeInTheDocument(); - }); - - it('does not fetch when the drawer is closed (negative)', () => { - const service = mockService(); - const ed = makeEd({ drawer: null, service }); - render(); - expect(service.readTranscripts).not.toHaveBeenCalled(); - }); - - it('shows a distinct load-error state (not "no transcripts yet") when the read fails (negative)', async () => { - const readTranscripts = vi.fn().mockRejectedValue(new Error('Unauthorized')); - const service = mockService({ readTranscripts }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - expect(await screen.findByText("Couldn't load transcripts")).toBeInTheDocument(); - expect(screen.getByText('Unauthorized')).toBeInTheDocument(); - expect(screen.queryByText('No transcripts yet')).not.toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Retry' })); - await waitFor(() => expect(readTranscripts).toHaveBeenCalledTimes(2)); - }); - - it('links a Live transcript\'s "Download captions" to its real captionsUrl', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - const link = await screen.findByRole('link', { name: 'Download captions' }); - expect(link).toHaveAttribute('href', 'https://x/en.vtt'); - expect(link).toHaveAttribute('download'); - }); - - it('shows only one download action for a Live transcript, not a duplicate (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - expect(screen.getAllByRole('link', { name: 'Download captions' })).toHaveLength(1); - }); - - it('disables the processing/failed action buttons as not-yet-implemented (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Tamil'); - const comingSoonButtons = screen.getAllByRole('button', { name: 'Coming soon' }); - expect(comingSoonButtons).toHaveLength(2); // Tamil (Processing) + Telugu (Failed) - comingSoonButtons.forEach((btn) => expect(btn).toBeDisabled()); - }); - - it('offers a "Review" action (not disabled) for a review-status language with a transcript file', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - const reviewBtn = screen.getByRole('button', { name: 'Review' }); - expect(reviewBtn).not.toBeDisabled(); - }); - - describe('segments view — status, approve and reject', () => { - it('shows the status and enabled Approve/Reject buttons for a review-status language', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - expect(screen.getByText('Needs review')).toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Approve Transcript' })).not.toBeDisabled(); - expect(screen.getByRole('button', { name: 'Reject' })).not.toBeDisabled(); - vi.unstubAllGlobals(); - }); - - it('does not show Approve/Reject buttons for a Live language (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); - await screen.findByText('Hello.'); - expect(screen.getByText('Live')).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Approve Transcript' })).not.toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Reject' })).not.toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - it('approves a Review transcript and only shows Live once the re-read confirms it', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS.map((tr) => (tr.language === 'Hindi' ? { ...tr, status: 'Live' } : tr))); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await waitFor(() => expect(approveTranscript).toHaveBeenCalledWith('do_1', 't_hi')); - await waitFor(() => expect(readTranscripts).toHaveBeenCalledTimes(2)); - await screen.findByText('Hindi'); - // Both English (already Live) and Hindi (just confirmed) now show Live. - await waitFor(() => expect(screen.getAllByText('Live')).toHaveLength(2)); - vi.unstubAllGlobals(); - }); - - it('rejects a Review transcript and only shows Draft once the re-read confirms it', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const rejectTranscript = vi.fn().mockResolvedValue({}); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS.map((tr) => (tr.language === 'Hindi' ? { ...tr, status: 'Draft' } : tr))); - const service = mockService({ readTranscripts, rejectTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Reject' })); - await waitFor(() => expect(rejectTranscript).toHaveBeenCalledWith('do_1', 't_hi')); - await screen.findByText('Hindi'); - expect(await screen.findByText('Draft')).toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - it('shows a "still processing" message (not Live) when approve succeeds but the re-read has not caught up yet (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - // Confirm re-read still reports Review - the approve hasn't landed server-side yet. - const readTranscripts = vi.fn().mockResolvedValue(TRANSCRIPTS); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - expect(await screen.findByText(/Almost there/)).toBeInTheDocument(); - expect(screen.getByText('Updating…')).toBeInTheDocument(); // not falsely shown as Live... - expect(screen.queryByText('Needs review')).not.toBeInTheDocument(); // ...nor left showing "Needs review" as if nothing happened - expect(screen.getByText('Namaste.')).toBeInTheDocument(); // stayed on the language, didn't close - vi.unstubAllGlobals(); - }); - - it('treats a failed confirmation re-read as "still processing", not as an approve failure', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - // The approve write itself succeeds; only the follow-up confirm re-read hits a network blip. - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) // initial load - .mockRejectedValueOnce(new Error('network blip')); // confirm re-read after approve - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await waitFor(() => expect(approveTranscript).toHaveBeenCalledWith('do_1', 't_hi')); - expect(await screen.findByText(/Almost there/)).toBeInTheDocument(); - expect(screen.queryByText("Couldn't complete this action. Please try again in a moment.")).not.toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Check again' })).toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - it('hides Approve/Reject while a just-submitted approve awaits confirmation - prevents a second, guaranteed-to-fail submit (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - // The approve itself succeeded server-side, but the confirm re-read hasn't caught up yet. - const readTranscripts = vi.fn().mockResolvedValue(TRANSCRIPTS); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await screen.findByText(/Almost there/); - // Re-clicking Approve now would fail with ERR_TRANSCRIPT_NOT_IN_REVIEW, so it must be gone. - expect(screen.queryByRole('button', { name: 'Approve Transcript' })).not.toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Reject' })).not.toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Check again' })).toBeInTheDocument(); - expect(approveTranscript).toHaveBeenCalledTimes(1); - vi.unstubAllGlobals(); - }); - - it('confirms and closes once the user clicks "Check again" after a pending approve', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS) // confirm right after approve: still Review - .mockResolvedValueOnce(TRANSCRIPTS.map((tr) => (tr.language === 'Hindi' ? { ...tr, status: 'Live' } : tr))); // Check again: now Live - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await screen.findByText(/Almost there/); - fireEvent.click(screen.getByRole('button', { name: 'Check again' })); - await waitFor(() => expect(readTranscripts).toHaveBeenCalledTimes(3)); - await screen.findByText('Hindi'); - await waitFor(() => expect(screen.getAllByText('Live')).toHaveLength(2)); - vi.unstubAllGlobals(); - }); - - it('surfaces an error (not an unhandled rejection) when "Check again" itself fails (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS) // confirm right after approve: still Review - .mockRejectedValueOnce(new Error('network blip')); // "Check again" click hits a network error - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await screen.findByText(/Almost there/); - fireEvent.click(screen.getByRole('button', { name: 'Check again' })); - expect(await screen.findByText("Couldn't complete this action. Please try again in a moment.")).toBeInTheDocument(); - // Still recoverable - the retry action itself must survive its own failure. - expect(screen.getByRole('button', { name: 'Check again' })).not.toBeDisabled(); - vi.unstubAllGlobals(); - }); - - it('shows a plain retry message (not the raw backend errmsg) and stays on the language when approve fails (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockRejectedValue(new Error('ERR_TRANSCRIPT_NOT_IN_REVIEW')); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS), approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - expect(await screen.findByText(/Couldn't complete this action/)).toBeInTheDocument(); - expect(screen.queryByText('ERR_TRANSCRIPT_NOT_IN_REVIEW')).not.toBeInTheDocument(); - expect(screen.getByText('Namaste.')).toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - it('treats "currently Live" as success (not failure) when approve fails because it already landed - closes without an error, straight from the error text', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockRejectedValue(new Error('Transcript must be in Review status to approve (currently Live).')); - const readTranscripts = vi.fn().mockResolvedValue(TRANSCRIPTS); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - // Closes back to the language list instead of showing an error - the error text - // itself already proved the approve's goal (Live) was reached by something else. - await waitFor(() => expect(screen.queryByText('Namaste.')).not.toBeInTheDocument()); - await screen.findByText('Hindi'); - expect(screen.queryByText('Needs review')).not.toBeInTheDocument(); - expect(screen.queryByText(/Couldn't complete this action/)).not.toBeInTheDocument(); - await waitFor(() => expect(screen.getAllByText('Live')).toHaveLength(2)); // English (already) + Hindi (just synced) - // No extra network round-trip needed - the true status came straight from the error text. - expect(readTranscripts).toHaveBeenCalledTimes(1); - vi.unstubAllGlobals(); - }); - - it('treats "currently Draft" as success (not failure) when reject fails because it already landed', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const rejectTranscript = vi.fn().mockRejectedValue(new Error('Transcript must be in Review status to reject (currently Draft).')); - const readTranscripts = vi.fn().mockResolvedValue(TRANSCRIPTS); - const service = mockService({ readTranscripts, rejectTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Reject' })); - await waitFor(() => expect(screen.queryByText('Namaste.')).not.toBeInTheDocument()); - await screen.findByText('Hindi'); - expect(screen.queryByText(/Couldn't complete this action/)).not.toBeInTheDocument(); - expect(await screen.findByText('Draft')).toBeInTheDocument(); - expect(readTranscripts).toHaveBeenCalledTimes(1); - vi.unstubAllGlobals(); - }); - - it('still shows the retry error but syncs the badge from the error text when the real status is neither Live nor Draft (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockRejectedValue(new Error('Transcript must be in Review status to approve (currently Failed).')); - const readTranscripts = vi.fn().mockResolvedValue(TRANSCRIPTS); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - expect(await screen.findByText(/Couldn't complete this action/)).toBeInTheDocument(); - expect(screen.queryByText(/currently Failed/)).not.toBeInTheDocument(); - // Badge/buttons reflect the parsed status without any extra network call. - await waitFor(() => expect(screen.getByText('Failed')).toBeInTheDocument()); - expect(screen.queryByRole('button', { name: 'Approve Transcript' })).not.toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Reject' })).not.toBeInTheDocument(); - expect(readTranscripts).toHaveBeenCalledTimes(1); - vi.unstubAllGlobals(); - }); - - it('falls back to a fresh re-read when the error text has no parseable status (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockRejectedValue(new Error('ERR_TRANSCRIPT_NOT_IN_REVIEW')); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS.map((tr) => (tr.language === 'Hindi' ? { ...tr, status: 'Live' } : tr))); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - expect(await screen.findByText(/Couldn't complete this action/)).toBeInTheDocument(); - await waitFor(() => expect(readTranscripts).toHaveBeenCalledTimes(2)); - await waitFor(() => expect(screen.getByText('Live')).toBeInTheDocument()); - expect(screen.queryByText('Needs review')).not.toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - }); - - it('does not offer a "Generate transcript" action - only the checkbox-driven flow triggers it (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue([]) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('No transcripts yet'); - expect(screen.queryByRole('button', { name: 'Generate transcript' })).not.toBeInTheDocument(); - expect(service.createTranscript).not.toHaveBeenCalled(); - }); - - describe('segments view', () => { - afterEach(() => { vi.unstubAllGlobals(); }); - - it('fetches artifactUrl and renders timestamped segments on "View segments"', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ - json: async () => ({ segments: [{ start: 0, end: 2.5, text: 'Hello there.' }, { start: 2.5, end: 5, text: 'Welcome.' }] }), - })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); - expect(await screen.findByText('Hello there.')).toBeInTheDocument(); - expect(screen.getByText('Welcome.')).toBeInTheDocument(); - expect(screen.getByText('0:00–0:02')).toBeInTheDocument(); - expect(fetch).toHaveBeenCalledWith('https://x/en.json'); - }); - - it('shows a load-error state when the JSON shape is unrecognized (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ unexpected: true }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); - expect(await screen.findByText("Couldn't load segments for this language.")).toBeInTheDocument(); - }); - - it('shows a load-error state when the fetch itself fails (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down'))); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); - expect(await screen.findByText("Couldn't load segments for this language.")).toBeInTheDocument(); - }); - - it('returns to the language list via "Back to languages"', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hi.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); - await screen.findByText('Hi.'); - fireEvent.click(screen.getByRole('button', { name: /Back to languages/ })); - expect(await screen.findByText('English')).toBeInTheDocument(); - expect(screen.queryByText('Hi.')).not.toBeInTheDocument(); - }); - - it('re-fetches the list when navigating back, so a status that changed while viewing segments isn\'t left stale', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hi.' }] }) })); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS.map((tr) => (tr.language === 'Hindi' ? { ...tr, status: 'Live' } : tr))); - const service = mockService({ readTranscripts }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); - await screen.findByText('Hi.'); - fireEvent.click(screen.getByRole('button', { name: /Back to languages/ })); - await waitFor(() => expect(readTranscripts).toHaveBeenCalledTimes(2)); - // Hindi (Review in the first fetch) now reflects the second fetch's Live status. - await screen.findByText('English'); - expect(await waitFor(() => screen.getAllByText('Live'))).toHaveLength(2); - }); - - it('does not offer "View segments" for a language with no artifactUrl (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - // Only English has artifactUrl in the fixture - exactly one "View segments" button. - expect(screen.getAllByRole('button', { name: 'View segments' })).toHaveLength(1); - }); - - describe('editing (source language, review status only)', () => { - // English is Live in the base fixture, so use a copy with its status set to Review. - const SOURCE_IN_REVIEW = TRANSCRIPTS.map((tr) => (tr.language === 'English' ? { ...tr, status: 'Review' } : tr)); - - it('shows a Modify button on the source-language card when it is in review, that opens segments straight into edit mode', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - expect(screen.queryByRole('button', { name: 'Modify' })).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Modify' })); - await screen.findByText('Hello there.'); - expect(screen.getByRole('textbox')).toHaveValue('Hello there.'); - }); - - it('does not show a Modify button for a non-source-language card (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - expect(screen.getAllByRole('button', { name: 'Modify' })).toHaveLength(1); - }); - - it('does not show a Modify button for a Live source-language card (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - expect(screen.queryByRole('button', { name: 'Modify' })).not.toBeInTheDocument(); - }); - - it('shows an Edit button for a source-language transcript in review', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - expect(await screen.findByRole('button', { name: 'Edit' })).toBeInTheDocument(); - }); - - it('does not show an Edit button for a non-source-language transcript (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[1]); - await screen.findByText('Namaste.'); - expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument(); - }); - - it('does not show an Edit button for a Live source-language transcript (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); - await screen.findByText('Hello there.'); - expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument(); - }); - - it('hides Edit while an approve is pending confirmation, even though activeLang.status is still stale "Review" (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const SOURCE_IN_REVIEW = TRANSCRIPTS.map((tr) => (tr.language === 'English' ? { ...tr, status: 'Review' } : tr)); - const approveTranscript = vi.fn().mockResolvedValue({}); - // Confirm re-read still reports Review - approve hasn't landed server-side yet. - const readTranscripts = vi.fn().mockResolvedValue(SOURCE_IN_REVIEW); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - expect(screen.getByRole('button', { name: 'Edit' })).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await screen.findByText(/Almost there/); - // Edit must disappear here - clicking it now would let the user start editing - // a transcript that's actually already Live, and Save would fail server-side. - expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument(); - }); - - it('turns segment text into an editable, pre-filled textarea after clicking Edit', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - const textbox = screen.getByRole('textbox') as HTMLTextAreaElement; - expect(textbox.value).toBe('Hello there.'); - fireEvent.change(textbox, { target: { value: 'Hello world.' } }); - expect(textbox.value).toBe('Hello world.'); - }); - - it('saves the full edited segment list via updateTranscript(contentId, transcriptId, segments)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ - json: async () => ({ segments: [{ id: 0, start: 0, end: 2.5, text: 'Hello there.' }, { id: 1, text: 'Bye.' }] }), - })); - const updateTranscript = vi.fn().mockResolvedValue({}); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW), updateTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - fireEvent.change(screen.getAllByRole('textbox')[0], { target: { value: 'Corrected text here' } }); - fireEvent.click(screen.getByRole('button', { name: 'Save' })); - await waitFor(() => expect(updateTranscript).toHaveBeenCalledWith('do_1', 't_en', [ - { id: 0, start: 0, end: 2.5, text: 'Corrected text here' }, - { id: 1, text: 'Bye.', start: undefined, end: undefined }, - ])); - }); - - it('preserves fields the parser does not model (e.g. Whisper seek/tokens) through an edit and save, changing only the edited text', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ - json: async () => ({ - segments: [{ id: 0, start: 0, end: 2.5, text: 'Hello there.', seek: 400, tokens: [1, 2, 3], avg_logprob: -0.2 }], - }), - })); - const updateTranscript = vi.fn().mockResolvedValue({}); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW), updateTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Corrected text here' } }); - fireEvent.click(screen.getByRole('button', { name: 'Save' })); - await waitFor(() => expect(updateTranscript).toHaveBeenCalledWith('do_1', 't_en', [ - { id: 0, start: 0, end: 2.5, text: 'Corrected text here', seek: 400, tokens: [1, 2, 3], avg_logprob: -0.2 }, - ])); - }); - - it('a slow fetch for a language the user has since left cannot land its segments onto the one now open (openSegments race guard)', async () => { - let resolveEnglish: (v: unknown) => void = () => {}; - const englishPromise = new Promise((resolve) => { resolveEnglish = resolve; }); - const fetchMock = vi.fn((url: string) => { - if (url === 'https://x/en.json') return englishPromise; - if (url === 'https://x/hi.json') return Promise.resolve({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) }); - return Promise.reject(new Error(`unexpected url: ${url}`)); - }); - vi.stubGlobal('fetch', fetchMock); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - - // Start English's (slow) fetch, then leave before it resolves. - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('English', { selector: '.ce-transcript-segments-title' }); - fireEvent.click(screen.getByRole('button', { name: /Back to languages/ })); - // Back to languages now re-fetches the list - wait for it to land before continuing. - await screen.findAllByRole('button', { name: 'Review' }); - - // Open Hindi - its (fast) fetch resolves first. - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[1]); - await screen.findByText('Namaste.'); - - // English's slow fetch finally resolves - it must not overwrite Hindi's segments. - await act(async () => { - resolveEnglish({ json: async () => ({ segments: [{ text: 'English text that must not appear.' }] }) }); - await new Promise((r) => setTimeout(r, 0)); - await new Promise((r) => setTimeout(r, 0)); - }); - expect(screen.queryByText('English text that must not appear.')).not.toBeInTheDocument(); - expect(screen.getByText('Namaste.')).toBeInTheDocument(); - expect(screen.getByText('Hindi', { selector: '.ce-transcript-segments-title' })).toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - it('exits edit mode and shows the saved text after a successful save', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ id: 0, text: 'Hello there.' }] }) })); - const service = mockService({ - readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW), - updateTranscript: vi.fn().mockResolvedValue({}), - }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Corrected text here' } }); - fireEvent.click(screen.getByRole('button', { name: 'Save' })); - await waitFor(() => expect(screen.getByText('Corrected text here')).toBeInTheDocument()); - expect(screen.queryByRole('textbox')).not.toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Edit' })).toBeInTheDocument(); - }); - - it('shows an error and stays in edit mode when the save fails (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ id: 0, text: 'Hello there.' }] }) })); - const service = mockService({ - readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW), - updateTranscript: vi.fn().mockRejectedValue(new Error('Save failed')), - }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Corrected text here' } }); - fireEvent.click(screen.getByRole('button', { name: 'Save' })); - expect(await screen.findByText('Save failed')).toBeInTheDocument(); - expect(screen.getByRole('textbox')).toBeInTheDocument(); - }); - - it('discards edits and returns to read-only text on Cancel', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Edited text.' } }); - fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); - expect(screen.getByText('Hello there.')).toBeInTheDocument(); - expect(screen.queryByText('Edited text.')).not.toBeInTheDocument(); - expect(screen.queryByRole('textbox')).not.toBeInTheDocument(); - }); - - it('does not leak edit mode when re-opening segments after Back to languages (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - expect(screen.getByRole('textbox')).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: /Back to languages/ })); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - expect(screen.queryByRole('textbox')).not.toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Edit' })).toBeInTheDocument(); - }); - }); - }); -}); diff --git a/src/components/TranscriptsDrawer.tsx b/src/components/TranscriptsDrawer.tsx deleted file mode 100644 index be463a0..0000000 --- a/src/components/TranscriptsDrawer.tsx +++ /dev/null @@ -1,585 +0,0 @@ -import React, { useEffect, useRef, useState } from 'react'; -import Drawer from './Drawer'; -import type { EditorController } from '../useEditor'; -import type { RawTranscript, TranscriptSegment } from '../types'; -import { t, tf } from '../i18n/i18n'; -import { CaptionsIcon } from '../icons'; - -interface ParsedSegments { - /** Display/editing view - only the fields the UI needs. */ - segments: TranscriptSegment[]; - /** The original segment objects, index-aligned with `segments`, kept around so a save - * can merge just the edited text back in rather than reconstructing (and thereby losing - * any field the parser doesn't know about, e.g. Whisper's seek/tokens/avg_logprob/...). */ - rawSegments: Record[]; -} - -/** Parses the artifactUrl transcript.json (Whisper-style `{segments:[...]}` or a bare array), returning null on any other shape. `rawSegments[i]` corresponds to `segments[i]` (a segment dropped for a non-string `text` is dropped from both, in lockstep). */ -function parseSegments(raw: unknown): ParsedSegments | null { - const obj = raw as Record | null; - const list = Array.isArray(raw) ? raw : Array.isArray(obj?.segments) ? (obj!.segments as unknown[]) : null; - if (!list) return null; - const segments: TranscriptSegment[] = []; - const rawSegments: Record[] = []; - list.forEach((item, index) => { - const o = item as Record; - const text = o.text ?? o.transcript ?? o.content; - if (typeof text !== 'string') return; - const start = o.start ?? o.startTime ?? o.start_time; - const end = o.end ?? o.endTime ?? o.end_time; - segments.push({ - id: typeof o.id === 'number' ? o.id : index, - text, - start: typeof start === 'number' ? start : undefined, - end: typeof end === 'number' ? end : undefined, - }); - rawSegments.push(o); - }); - return segments.length ? { segments, rawSegments } : null; -} - -function formatTimestamp(seconds?: number): string { - if (seconds == null || Number.isNaN(seconds)) return ''; - const m = Math.floor(seconds / 60); - const s = Math.floor(seconds % 60); - return `${m}:${String(s).padStart(2, '0')}`; -} - -/** The five backend-confirmed transcript statuses: Draft, Processing, Review, Live, Failed. */ -const KNOWN_STATUSES = ['Draft', 'Processing', 'Review', 'Live', 'Failed']; - -/** Extracts the real status from the approve/reject error text (e.g. "currently Live"), which is more reliable than a follow-up re-read that can come back stale. */ -function parseCurrentStatusFromError(message: string): string | null { - const found = /currently\s+(\w+)/i.exec(message)?.[1]; - return found ? KNOWN_STATUSES.find((s) => s.toLowerCase() === found.toLowerCase()) ?? null : null; -} - -type StatusTone = 'draft' | 'review' | 'processing' | 'live' | 'failed'; - -function statusTone(status?: string): StatusTone { - switch (status) { - case 'Draft': return 'draft'; - case 'Review': return 'review'; - case 'Processing': return 'processing'; - case 'Live': return 'live'; - case 'Failed': return 'failed'; - default: return 'draft'; // unrecognized - safest neutral treatment - } -} - -function statusLabel(lang: string, status?: string): string { - // Switches on the raw status (not statusTone, which already collapses anything - // unrecognized to 'draft') so a genuinely unexpected status still reaches the - // fallback instead of always being silently mislabeled "Draft". - switch (status) { - case 'Draft': return t(lang, 'STATUS_DRAFT'); - case 'Review': return t(lang, 'STATUS_NEEDS_REVIEW'); - case 'Processing': return t(lang, 'STATUS_PROCESSING'); - case 'Live': return t(lang, 'STATUS_LIVE'); - case 'Failed': return t(lang, 'STATUS_FAILED'); - default: return status || t(lang, 'STATUS_NEEDS_REVIEW'); - } -} - -/** Coarse "x min/hr/day ago", falling back to '' for a missing/invalid timestamp. */ -function relativeTime(lang: string, iso?: string): string { - if (!iso) return ''; - const then = new Date(iso).getTime(); - if (Number.isNaN(then)) return ''; - const mins = Math.round((Date.now() - then) / 60000); - if (mins < 1) return t(lang, 'TIME_JUST_NOW'); - if (mins < 60) return tf(lang, 'TIME_MINUTES_AGO', { n: mins }); - const hrs = Math.round(mins / 60); - if (hrs < 24) return tf(lang, 'TIME_HOURS_AGO', { n: hrs }); - const days = Math.round(hrs / 24); - return tf(lang, days === 1 ? 'TIME_DAY_AGO' : 'TIME_DAYS_AGO', { n: days }); -} - -/** TranscriptsDrawer — views/approves/rejects/edits content.enrichment.transcripts, fetched on open via a dedicated ?enrich=all read to avoid that cost elsewhere. */ -const TranscriptsDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { - const { lang, drawer, setDrawer, content, service, showToast } = ed; - const open = drawer === 'transcripts'; - - const [transcripts, setTranscripts] = useState([]); - const [loading, setLoading] = useState(false); - const [loadError, setLoadError] = useState(null); - - /* Segments sub-view for one language. */ - const [activeLang, setActiveLang] = useState(null); - const [segments, setSegments] = useState(null); - const [rawSegments, setRawSegments] = useState[] | null>(null); - const [segmentsLoading, setSegmentsLoading] = useState(false); - const [segmentsError, setSegmentsError] = useState(false); - /** Bumped by openSegments/closeSegments so a slow fetch for a language the user has - * already navigated away from can't land its result onto the wrong (now-active) one. */ - const segmentsRequestRef = useRef(0); - - /* Source-language segments can be edited (text only). */ - const [isEditingSegments, setIsEditingSegments] = useState(false); - const [draftSegments, setDraftSegments] = useState(null); - const [isSaving, setIsSaving] = useState(false); - const [saveError, setSaveError] = useState(null); - - /* Approve/reject applies asynchronously server-side, so we re-read and only show the new status once confirmed. */ - const [isApproving, setIsApproving] = useState(false); - const [isRejecting, setIsRejecting] = useState(false); - const [isCheckingStatus, setIsCheckingStatus] = useState(false); - const [actionError, setActionError] = useState(null); - const [pendingExpectedStatus, setPendingExpectedStatus] = useState(null); - - const load = () => { - if (!content?.identifier) return; - setLoading(true); - setLoadError(null); - service - .readTranscripts(content.identifier) - .then(setTranscripts) - .catch((err) => { - setTranscripts([]); - // Distinct from a genuinely-empty result - don't let a failed read masquerade as "no transcripts yet". - setLoadError(String((err as Error)?.message ?? t(lang, 'ERROR_GENERIC'))); - }) - .finally(() => setLoading(false)); - }; - - const closeSegments = () => { - segmentsRequestRef.current += 1; // discard any in-flight fetch for the language we're leaving - setActiveLang(null); - setSegments(null); - setRawSegments(null); - setSegmentsError(false); - setIsEditingSegments(false); - setDraftSegments(null); - setSaveError(null); - setActionError(null); - setPendingExpectedStatus(null); - }; - - /** "Back to languages" click handler - unlike closeSegments() alone (also used right after - * an already-fresh confirmed approve/reject), this re-fetches so manually navigating back - * without a confirmed action doesn't leave the list showing a stale, out-of-date status. */ - const backToLanguages = () => { - closeSegments(); - load(); - }; - - /** Single re-read to check whether an approve/reject has actually landed - - * updates the loaded list only when it truly matches, never assumes it. */ - const confirmTranscriptStatus = (transcriptId: string, expectedStatus: string): Promise => { - if (!content?.identifier) return Promise.resolve(false); - return service.readTranscripts(content.identifier).then((list) => { - const match = list.find((tr) => (tr.identifier ?? tr.code) === transcriptId); - if (match?.status === expectedStatus) { - setTranscripts(list); - return true; - } - return false; - }); - }; - - /** Re-syncs activeLang from the server when approve/reject itself fails, so the badge reflects the real status instead of contradicting the error below it. */ - const refreshActiveLangFromServer = (transcriptId: string): Promise => { - if (!content?.identifier) return Promise.resolve(); - return service.readTranscripts(content.identifier).then((list) => { - setTranscripts(list); - const fresh = list.find((tr) => (tr.identifier ?? tr.code) === transcriptId); - if (fresh) setActiveLang(fresh); - }); - }; - - /** Apply a status we already know for certain (parsed from an error, not a re-read) - * to both the list and the open segments view, without waiting on the network. */ - const applyKnownStatus = (transcriptId: string, status: string) => { - setTranscripts((list) => list.map((tr) => ((tr.identifier ?? tr.code) === transcriptId ? { ...tr, status } : tr))); - setActiveLang((prev) => (prev && (prev.identifier ?? prev.code) === transcriptId ? { ...prev, status } : prev)); - }; - - const startEditingSegments = () => { - if (!segments || !activeLang) return; - // Editing is only allowed while a transcript is genuinely in Review - a Live - // transcript is the published caption, so surface why instead of silently no-oping. - if (activeLang.status === 'Live') { - showToast(t(lang, 'ERROR_TRANSCRIPT_LIVE'), 'error'); - return; - } - if (activeLang.status !== 'Review') return; - setDraftSegments(segments.map((s) => ({ ...s }))); - setIsEditingSegments(true); - setSaveError(null); - }; - - const cancelEditingSegments = () => { - setIsEditingSegments(false); - setDraftSegments(null); - setSaveError(null); - }; - - const updateDraftSegmentText = (index: number, text: string) => { - setDraftSegments((prev) => (prev ? prev.map((s, i) => (i === index ? { ...s, text } : s)) : prev)); - }; - - const saveSegments = () => { - const transcriptId = activeLang?.identifier ?? activeLang?.code; - if (!draftSegments || !rawSegments || !content?.identifier || !transcriptId) return; - setIsSaving(true); - setSaveError(null); - // Merge only the edited text back into the original segment objects (index-aligned - // with draftSegments) instead of sending the reconstructed {id,text,start,end} view - - // any field the parser doesn't surface (Whisper's seek/tokens/avg_logprob/...) survives. - const merged = rawSegments.map((raw, i) => ({ ...raw, text: draftSegments[i]?.text ?? raw.text })); - service - .updateTranscript(content.identifier, transcriptId, merged) - .then(() => { - setSegments(draftSegments); - setRawSegments(merged); - setIsEditingSegments(false); - setDraftSegments(null); - }) - .catch((err) => { - setSaveError(String((err as Error)?.message ?? t(lang, 'ERROR_GENERIC'))); - }) - .finally(() => setIsSaving(false)); - }; - - const handleApprove = () => { - const transcriptId = activeLang?.identifier ?? activeLang?.code; - if (!activeLang || !content?.identifier || !transcriptId) return; - setIsApproving(true); - setActionError(null); - setPendingExpectedStatus(null); - service - .approveTranscript(content.identifier, transcriptId) - // A failed confirm re-read must not be reported as an approve failure - the - // approve itself already landed, so treat it the same as "not confirmed yet". - .then(() => confirmTranscriptStatus(transcriptId, 'Live').catch(() => false)) - .then((confirmed) => { - if (confirmed) closeSegments(); - else { - setActionError(t(lang, 'STATUS_UPDATE_PENDING')); - setPendingExpectedStatus('Live'); - } - }) - .catch((err) => { - const realStatus = parseCurrentStatusFromError(String((err as Error)?.message ?? '')); - if (realStatus) { - // Trust the error's own status over a re-read that may come back stale. - applyKnownStatus(transcriptId, realStatus); - if (realStatus === 'Live') { closeSegments(); return; } - setActionError(t(lang, 'ERROR_TRANSCRIPT_ACTION_FAILED')); - return; - } - // Unparseable error - re-sync from the server instead of surfacing a raw errmsg that could contradict the badge. - setActionError(t(lang, 'ERROR_TRANSCRIPT_ACTION_FAILED')); - return refreshActiveLangFromServer(transcriptId).catch(() => {}); - }) - .finally(() => setIsApproving(false)); - }; - - const handleReject = () => { - const transcriptId = activeLang?.identifier ?? activeLang?.code; - if (!activeLang || !content?.identifier || !transcriptId) return; - setIsRejecting(true); - setActionError(null); - setPendingExpectedStatus(null); - service - .rejectTranscript(content.identifier, transcriptId) - // Same reasoning as handleApprove: a failed confirm re-read isn't a reject failure. - .then(() => confirmTranscriptStatus(transcriptId, 'Draft').catch(() => false)) - .then((confirmed) => { - if (confirmed) closeSegments(); - else { - setActionError(t(lang, 'STATUS_UPDATE_PENDING')); - setPendingExpectedStatus('Draft'); - } - }) - .catch((err) => { - const realStatus = parseCurrentStatusFromError(String((err as Error)?.message ?? '')); - if (realStatus) { - applyKnownStatus(transcriptId, realStatus); - if (realStatus === 'Draft') { closeSegments(); return; } - setActionError(t(lang, 'ERROR_TRANSCRIPT_ACTION_FAILED')); - return; - } - setActionError(t(lang, 'ERROR_TRANSCRIPT_ACTION_FAILED')); - return refreshActiveLangFromServer(transcriptId).catch(() => {}); - }) - .finally(() => setIsRejecting(false)); - }; - - const handleRecheckStatus = () => { - const transcriptId = activeLang?.identifier ?? activeLang?.code; - if (!activeLang || !transcriptId || !pendingExpectedStatus) return; - setIsCheckingStatus(true); - confirmTranscriptStatus(transcriptId, pendingExpectedStatus) - .then((confirmed) => { - if (confirmed) closeSegments(); - else setActionError(t(lang, 'STATUS_UPDATE_PENDING')); - }) - .catch(() => setActionError(t(lang, 'ERROR_TRANSCRIPT_ACTION_FAILED'))) - .finally(() => setIsCheckingStatus(false)); - }; - - useEffect(() => { - if (!open) { closeSegments(); return; } - load(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [open, content?.identifier]); - - const openSegments = (tr: RawTranscript, startInEditMode = false) => { - if (!tr.artifactUrl) return; - const requestToken = ++segmentsRequestRef.current; - setActiveLang(tr); - setSegments(null); - setRawSegments(null); - setSegmentsError(false); - setIsEditingSegments(false); - setDraftSegments(null); - setSaveError(null); - setSegmentsLoading(true); - fetch(tr.artifactUrl) - .then((r) => r.json()) - .then((json) => { - // A slower fetch for a language the user has since navigated away from (Back, - // or straight to another language) must not clobber whatever's active now. - if (segmentsRequestRef.current !== requestToken) return; - const parsed = parseSegments(json); - if (!parsed) { setSegmentsError(true); return; } - setSegments(parsed.segments); - setRawSegments(parsed.rawSegments); - if (startInEditMode) { - setDraftSegments(parsed.segments.map((s) => ({ ...s }))); - setIsEditingSegments(true); - } - }) - .catch(() => { if (segmentsRequestRef.current === requestToken) setSegmentsError(true); }) - .finally(() => { if (segmentsRequestRef.current === requestToken) setSegmentsLoading(false); }); - }; - - const handleModifyClick = (tr: RawTranscript) => { - // Editing is only allowed while a transcript is genuinely in Review - a Live - // transcript is the published caption, so surface why instead of silently no-oping. - if (tr.status === 'Live') { - showToast(t(lang, 'ERROR_TRANSCRIPT_LIVE'), 'error'); - return; - } - if (tr.status !== 'Review') return; - openSegments(tr, true); - }; - - const renderSegmentsView = () => { - const tone = statusTone(activeLang!.status); - // Editable only for a source-language transcript still in Review, and not while - // pendingExpectedStatus is set (activeLang.status is stale until the confirm re-read lands). - const canShowEditControls = - activeLang!.sourceLanguage && activeLang!.status === 'Review' && !pendingExpectedStatus && - !segmentsLoading && !segmentsError && !!segments; - const displaySegments = isEditingSegments ? draftSegments : segments; - return ( -
- -
-
{activeLang!.language}
- {pendingExpectedStatus ? ( - // Once the user has acted, don't keep showing "Needs review" (as if nothing - // happened) while we wait for the server to catch up - show a neutral pending state instead. - - {t(lang, 'STATUS_UPDATING')} - - ) : ( - - {statusLabel(lang, activeLang!.status)} - - )} -
- {tone === 'review' && !isEditingSegments && !pendingExpectedStatus && ( -
- - -
- )} - {actionError && ( -
-

{actionError}

- {pendingExpectedStatus && ( - - )} -
- )} - {canShowEditControls && ( -
- {isEditingSegments ? ( - <> - - - - ) : ( - - )} -
- )} - {saveError &&

{saveError}

} - {segmentsLoading ? ( -
-
-
- ) : segmentsError || !displaySegments ? ( -

{t(lang, 'SEGMENTS_LOAD_ERROR')}

- ) : ( -
- {displaySegments.map((seg, i) => ( -
- {(seg.start != null || seg.end != null) && ( - - {formatTimestamp(seg.start)}{seg.end != null ? `–${formatTimestamp(seg.end)}` : ''} - - )} - {isEditingSegments ? ( -