Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@project-sunbird/generic-editor-v2",
"version": "2.0.6",
"version": "2.0.7",
"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",
Expand Down
116 changes: 115 additions & 1 deletion src/ContentEditor.test.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -11,6 +11,9 @@ function svc(over: Record<string, unknown> = {}) {
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,
Expand Down Expand Up @@ -44,3 +47,114 @@ describe('<ContentEditor /> — existing content', () => {
expect(await screen.findByText('Failed to load content.')).toBeInTheDocument();
});
});

describe('<ContentEditor /> — 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(<ContentEditor context={mockContext} contentId="do_da_1" service={service} onClose={vi.fn()} />);
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(<ContentEditor context={mockContext} contentId="do_da_2" service={service} onClose={vi.fn()} />);
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(<ContentEditor context={reviewerContext} contentId="do_da_3" service={service} onClose={vi.fn()} />);
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('<ContentEditor /> — 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<string, unknown> = {}) => ({
...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(<ContentEditor context={mockContext} contentId="do_da_4" service={service} onClose={vi.fn()} />);
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(<ContentEditor context={mockContext} contentId="do_1" service={svc()} onClose={vi.fn()} />);
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('<ContentEditor /> — 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<string, unknown> = {}) => ({
...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(<ContentEditor context={mockContext} contentId="do_da_6" service={service} onClose={vi.fn()} />);
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(<ContentEditor context={mockContext} contentId="do_da_7" service={service} onClose={vi.fn()} />);
await waitFor(() => expect(screen.getAllByText('Sample content').length).toBeGreaterThan(0));
expect(screen.queryByText('Settings changed since the questions were generated')).not.toBeInTheDocument();
});
});
40 changes: 38 additions & 2 deletions src/ContentEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import TranscriptsDrawer from './components/TranscriptsDrawer';
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;

Expand All @@ -35,7 +35,32 @@ const ContentEditor: React.FC<ContentEditorProps> = (props) => {
{(ed.view === 'upload' || ed.view === 'uploading') && (
<div className="ce-upload-overlay"><UploadCanvas ed={ed} /></div>
)}
{ed.view === 'player' && <EditorPreview ed={ed} context={props.context} />}
{ed.view === 'player' && ed.isDynamicAssess && !ed.hasGeneratedBody && (
<div className="ce-center">
<RefreshIcon size={32} />
<p>{t(ed.lang, 'DYNAMIC_ASSESS_EMPTY_TITLE')}</p>
{/* Only an editor can save details (which generates); reviewers/readers just see it's empty. */}
<p>{t(ed.lang, ed.mode === 'edit' ? 'DYNAMIC_ASSESS_EMPTY_SUB' : 'DYNAMIC_ASSESS_EMPTY_SUB_READONLY')}</p>
{ed.mode === 'edit' && (
<button type="button" className="ce-btn ce-btn--primary" onClick={() => ed.setDrawer('metadata')}>
{t(ed.lang, 'EDIT_DETAILS')}
</button>
)}
</div>
)}
{/* 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 && (
<div className="ce-stale-banner" role="alert">
<span className="ce-stale-banner-ic" aria-hidden="true"><InfoIcon size={17} /></span>
<div className="ce-stale-banner-tx">
<p className="ce-stale-banner-title">{t(ed.lang, 'DYNAMIC_ASSESS_STALE_TITLE')}</p>
<p className="ce-stale-banner-sub">{t(ed.lang, ed.mode === 'edit' ? 'DYNAMIC_ASSESS_STALE_SUB' : 'DYNAMIC_ASSESS_STALE_SUB_READONLY')}</p>
</div>
</div>
)}
{ed.view === 'player' && !(ed.isDynamicAssess && !ed.hasGeneratedBody) && (
<EditorPreview ed={ed} context={props.context} />
)}
</main>

<div className="ce-backdrop" data-open={ed.drawer !== null} onClick={() => ed.setDrawer(null)} />
Expand Down Expand Up @@ -67,6 +92,17 @@ const ContentEditor: React.FC<ContentEditorProps> = (props) => {
</div>
)}

{/* Blocks editing while the job writes the quiz, so a stale save can't race it. */}
{ed.isDynamicAssess && ed.dynamicAssessRefreshing && (
<div className="ce-generating-overlay" role="status" aria-live="polite">
Comment thread
Deeksha1502 marked this conversation as resolved.
Resolved
<div className="ce-generating-card">
<div className="ce-spinner ce-spinner--sm" />
<p className="ce-generating-title">{t(ed.lang, 'DYNAMIC_ASSESS_GENERATING_TITLE')}</p>
<p className="ce-generating-sub">{t(ed.lang, 'DYNAMIC_ASSESS_GENERATING_SUB')}</p>
</div>
</div>
)}

{/* Upload success overlay */}
{ed.uploadSuccess && (
<div className="ce-upload-success-overlay">
Expand Down
70 changes: 67 additions & 3 deletions src/components/EditorPreview.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
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';

describe('<EditorPreview />', () => {
Expand Down Expand Up @@ -93,4 +93,68 @@ describe('<EditorPreview />', () => {
const secondIframe = container.querySelector('iframe');
expect(secondIframe).not.toBe(firstIframe);
});

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(<EditorPreview ed={ed} context={mockContext} />);
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 only the draw in metadata.body too, never the full pool (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(<EditorPreview ed={ed} context={mockContext} />);
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(1);
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(<EditorPreview ed={ed} context={mockContext} />);
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(<EditorPreview ed={ed} context={mockContext} />);
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('<theme></theme>')).toBe('<theme></theme>');
});
});
29 changes: 24 additions & 5 deletions src/components/EditorPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { ContentData, EditorContext, RawTranscript } from '../types';
import { getMimeTypeLabel, t } from '../i18n/i18n';
import { FileIcon } from '../icons';
import { isVideoMimeType } from '../constants';
import { ecmlBodyForUser } from '../dynamicAssessDraw';

interface PlayerTranscript {
language: string;
Expand Down Expand Up @@ -32,10 +33,19 @@ function mapRawTranscripts(raw: RawTranscript[]): PlayerTranscript[] {
}));
}

/** 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<string, unknown>;
}> = ({ content, context, previewUrl, previewConfig }) => {
content: ContentData; context: EditorContext; previewUrl: string; previewConfig: Record<string, unknown>; isDynamicAssess?: boolean;
}> = ({ content, context, previewUrl, previewConfig, isDynamicAssess = false }) => {
const iframeRef = useRef<HTMLIFrameElement>(null);
const src = `${previewUrl}${previewUrl.includes('?') ? '&' : '?'}webview=true`;

Expand All @@ -44,6 +54,13 @@ const RendererPreview: React.FC<{
| (Window & { initializePreview?: (cfg: unknown) => void })
| null;
if (!win || typeof win.initializePreview !== 'function') return;
const rawBody = (content as Record<string, unknown>).body;
// Only Dynamic Assess renders from its generated body (the user's own draw, never the whole pool); other content keeps the renderer's own loading.
const data = isDynamicAssess ? ecmlBodyForUser(rendererData(rawBody), content.identifier, context.user?.id) : {};
// metadata.body carries the same draw, like the portal's ecmlForLearner, so the full pool never reaches the renderer.
const metadata = isDynamicAssess && rawBody
? { ...content, body: typeof rawBody === 'string' && data && typeof data === 'object' ? JSON.stringify(data) : data }
: content;
win.initializePreview({
context: {
mode: 'edit',
Expand All @@ -57,8 +74,8 @@ const RendererPreview: React.FC<{
partner: [],
},
config: previewConfig,
metadata: content,
data: {},
metadata,
data,
});
};

Expand Down Expand Up @@ -104,8 +121,10 @@ const EditorPreview: React.FC<{ ed: EditorController; context: EditorContext }>
</div>
) : (
<RendererPreview
key={`${content.identifier}-${content.artifactUrl ?? ''}-${transcriptsKey}`}
// A regenerated ECML body has no new artifactUrl, so lastUpdatedOn (set by the job) is what remounts the player onto it.
key={`${content.identifier}-${content.artifactUrl ?? ''}-${transcriptsKey}${ed.isDynamicAssess ? `-${String(content.lastUpdatedOn ?? '')}` : ''}`}
content={previewMetadata}
isDynamicAssess={ed.isDynamicAssess}
context={context}
previewUrl={previewUrl}
previewConfig={previewConfig}
Expand Down
Loading
Loading