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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/components/EditorPreview.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ describe('<EditorPreview />', () => {
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)', () => {
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'])) } }) },
Expand All @@ -120,7 +120,8 @@ describe('<EditorPreview />', () => {
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(quiz['org.ekstep.question']).toHaveLength(3);
expect(cfg.metadata.body).toBe(body);
expect(JSON.parse(cfg.metadata.body)).toEqual(cfg.data);
});

Expand Down
11 changes: 3 additions & 8 deletions src/components/EditorPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import type { ContentData, EditorContext, RawTranscript } from '../types';
import { getMimeTypeLabel, t } from '../i18n/i18n';
import { FileIcon } from '../icons';
import { isVideoMimeType } from '../constants';
import { dynamicAssessSettings, ecmlBodyForUser } from '../dynamicAssessDraw';

interface PlayerTranscript {
language: string;
Expand Down Expand Up @@ -54,13 +53,9 @@ 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, dynamicAssessSettings(content as Record<string, unknown>).multiplier) : {};
// 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;
// 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<string, unknown>).body) : {};
const metadata = content;
win.initializePreview({
context: {
mode: 'edit',
Expand Down
57 changes: 1 addition & 56 deletions src/dynamicAssessDraw.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { ecmlBodyForUser, pickForLearner, isGenerationStale, needsGeneration, selectedSkills, dynamicAssessSettings } from './dynamicAssessDraw';
import { isGenerationStale, needsGeneration, selectedSkills, dynamicAssessSettings } from './dynamicAssessDraw';
import { DYNAMIC_ASSESS_MIN_CRITERIA, DYNAMIC_ASSESS_POOL_MULTIPLIER } from './constants';

const levels: Record<string, string> = { a1: 'EASY', a2: 'EASY', a3: 'EASY', b1: 'MEDIUM', b2: 'MEDIUM', b3: 'MEDIUM' };
Expand All @@ -10,28 +10,6 @@ const body = (dynamic: boolean) => ({
'org.ekstep.question': Object.keys(levels).map((id) => ({ id })),
}] }] },
});
const quizOf = (b: any) => b.theme.stage[0]['org.ekstep.questionset'][0];

describe('ecmlBodyForUser', () => {
it("previews only the user's draw per level, matching the portal's seed (positive)", () => {
const out = ecmlBodyForUser(body(true), 'do_c', 'u1') as any;
const kept = quizOf(out)['org.ekstep.question'].map((q: any) => q.id);
expect(kept).toEqual(['a2', 'b3']); // literal ids, so a change to the draw or its count fails here
expect(JSON.parse(quizOf(out).config.__cdata).total_items).toBe(2);
});

it('does not mutate the original body', () => {
const original = body(true);
ecmlBodyForUser(original, 'do_c', 'u1');
expect(quizOf(original)['org.ekstep.question']).toHaveLength(6);
});

it('returns bodies without the dynamic block, and non-objects, unchanged (negative)', () => {
const plain = body(false);
expect(ecmlBodyForUser(plain, 'do_c', 'u1')).toBe(plain);
expect(ecmlBodyForUser({}, 'do_c', 'u1')).toEqual({});
});
});

describe('isGenerationStale', () => {
const generated = (block: Record<string, unknown>) => JSON.stringify({
Expand Down Expand Up @@ -70,39 +48,6 @@ describe('isGenerationStale', () => {
});
});

describe('ecmlBodyForUser — fail closed and parity', () => {
const withTarget = (target: unknown) => ({
theme: { stage: [{ 'org.ekstep.questionset': [{
config: { __cdata: JSON.stringify({ dynamic_assess: { target, levels } }) },
data: { __cdata: JSON.stringify(Object.keys(levels).map((id) => ({ identifier: id, max_score: 1 }))) },
'org.ekstep.question': Object.keys(levels).map((id) => ({ id })),
}] }] },
});

it('draws nothing, never the pool, for a zero or unparseable target (positive)', () => {
expect(quizOf(ecmlBodyForUser(withTarget({ E: 0, M: 0, D: 0 }), 'do_c', 'u1'))['org.ekstep.question']).toEqual([]);
expect(quizOf(ecmlBodyForUser(withTarget('nope'), 'do_c', 'u1'))['org.ekstep.question']).toEqual([]);
});

it('caps each level at its generated size ÷ multiplier, so an undersized pool is never shown whole (positive)', () => {
// 3 per level with target 3: uncapped this returned all 6 unshuffled; at ×2 only floor(3/2) = 1 per level is drawn.
expect(quizOf(ecmlBodyForUser(withTarget({ E: 3, M: 3, D: 0 }), 'do_c', 'u1', 2))['org.ekstep.question'].map((q: any) => q.id)).toEqual(['a2', 'b3']);
expect(quizOf(ecmlBodyForUser(withTarget({ E: 3, M: 3, D: 0 }), 'do_c', 'u1', 3))['org.ekstep.question'].map((q: any) => q.id)).toEqual(['a2', 'b3']);
});

it('draws the full target when the pool holds target × multiplier (negative)', () => {
expect(quizOf(ecmlBodyForUser(withTarget({ E: 2, M: 0, D: 0 }), 'do_c', 'u1', 1))['org.ekstep.question'].map((q: any) => q.id)).toEqual(['a1', 'a2']);
});

it('accepts a JSON-string target like the portal does (positive)', () => {
expect(quizOf(ecmlBodyForUser(withTarget('{"E":1,"M":1,"D":0}'), 'do_c', 'u1'))['org.ekstep.question']).toHaveLength(2);
});

it('matches the golden vector shared with the portal and the QuestionSet editor', () => {
expect(pickForLearner(['q1', 'q2', 'q3', 'q4', 'q5', 'q6'], 2, 'user-1:do_123:EASY')).toEqual(['q6', 'q3']);
});
});

describe('selectedSkills and needsGeneration (the selection lives in the framework\'s deepest category field)', () => {
it('reads the selection from the named field, deduped (positive)', () => {
expect(selectedSkills({ topic: ['Algebra', 'Algebra', 'Geometry'], skill: ['Ignored'] }, 'topic')).toEqual(['Algebra', 'Geometry']);
Expand Down
77 changes: 1 addition & 76 deletions src/dynamicAssessDraw.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// Same seeded draw as the portal's dynamicAssessSubset, so the preview shows the user the exact set they'd play; the full pool is never displayed.
// Dynamic Assess pool settings and generation checks; the editor previews the whole pool, and learners get their own draw in the portal.

import { DYNAMIC_ASSESS_MIN_CRITERIA, DYNAMIC_ASSESS_POOL_MULTIPLIER } from './constants';

const LEVELS = [['E', 'EASY'], ['M', 'MEDIUM'], ['D', 'DIFFICULT']] as const;
type Rec = Record<string, unknown>;

/** The value as a plain object, or undefined; narrows parsed ECML before it is indexed. */
Expand All @@ -14,38 +13,6 @@ function quizConfig(quiz: Rec | undefined): Rec | undefined {
try { return asRec(JSON.parse(String(asRec(quiz?.config)?.__cdata ?? ''))); } catch { return undefined; }
}

function hashSeed(seed: string): number {
let h = 0x811c9dc5;
for (let i = 0; i < seed.length; i++) {
h ^= seed.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return h >>> 0;
}

function seededRandom(seed: string): () => number {
let a = hashSeed(seed);
return () => {
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}

export function pickForLearner(ids: string[], count: number, seed: string): string[] {
const pool = [...new Set(ids)].sort();
if (count >= pool.length) return pool;
const rand = seededRandom(seed);
for (let i = pool.length - 1; i > 0; i--) {
const j = Math.floor(rand() * (i + 1));
const swap = pool[i] as string;
pool[i] = pool[j] as string;
pool[j] = swap;
}
return pool.slice(0, Math.max(0, count));
}

function parseBody(body: unknown): Rec | null {
if (body && typeof body === 'object') return body as Rec;
if (typeof body !== 'string' || !body.trim()) return null;
Expand Down Expand Up @@ -106,45 +73,3 @@ export function needsGeneration(c: { primaryCategory?: string; dynamicSkills?: u
if (savedFramework && String(c.framework ?? '') !== String(savedFramework)) return true;
return !(Number(c.totalQuestions ?? 0) > 0) || isGenerationStale(c.body, savedTarget, skills);
}

/** Trims each generated quiz in a parsed ECML body to this user's draw; bodies without the job's dynamic_assess block are returned unchanged. `multiplier` is the content's own (dynamicAssessSettings). */
export function ecmlBodyForUser(body: unknown, contentId: string, userId: string | undefined, multiplier = DYNAMIC_ASSESS_POOL_MULTIPLIER): unknown {
if (!body || typeof body !== 'object') return body;
const theme = asRec((body as Rec).theme);
const stages = Array.isArray(theme?.stage) ? theme.stage : [];
if (!stages.some((s) => asRec(s)?.['org.ekstep.questionset'])) return body;
const copy = structuredClone(body) as Rec;
const perLevel = Math.max(1, Math.trunc(multiplier) || 1);
let changed = false;
for (const stage of (asRec(copy.theme)?.stage ?? []) as unknown[]) {
for (const quiz of asList(asRec(stage)?.['org.ekstep.questionset']).map(asRec)) {
const config = quizConfig(quiz);
const block = asRec(config?.dynamic_assess);
const questions = asList(quiz?.['org.ekstep.question']).map((q) => asRec(q) ?? {});
if (!quiz || !config || !block || questions.length === 0) continue;
// Fails closed like the portal: a missing, zero or unparseable target draws nothing rather than revealing the pool.
const target = parseTarget(block.target);
const levels = asRec(block.levels) ?? {};
const picked = new Set<string>();
for (const [key, level] of LEVELS) {
const atLevel = questions.map((q) => String(q.id)).filter((id) => String(levels[id] ?? '').toUpperCase() === level);
// Capped at what the job generated for this level, like the QuestionSet editor, so an undersized pool is never shown whole.
const count = Math.min(Number(target[key]) || 0, Math.floor(atLevel.length / perLevel));
pickForLearner(atLevel, count, `${userId || 'anonymous'}:${contentId}:${level}`).forEach((id) => picked.add(id));
}
const kept = questions.filter((q) => picked.has(String(q.id)));
if (kept.length === questions.length) continue;
let items: Rec[] = [];
const data = asRec(quiz.data);
try { items = asList(JSON.parse(String(data?.__cdata ?? '[]'))).map((i) => asRec(i) ?? {}); } catch { items = []; }
const keptItems = items.filter((item) => picked.has(String(item.identifier)));
quiz['org.ekstep.question'] = kept;
if (data) data.__cdata = JSON.stringify(keptItems);
config.total_items = kept.length;
config.max_score = keptItems.length ? keptItems.reduce((sum, item) => sum + (Number(item.max_score) || 1), 0) : kept.length;
(quiz.config as Rec).__cdata = JSON.stringify(config);
changed = true;
}
}
return changed ? copy : body;
}
Loading