@pie-element/select-text 14.0.4-next.20261011174919 → 14.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -101,7 +101,7 @@ var f = {
101
101
  return r.length > 0 ? "partially-correct" : "incorrect";
102
102
  }, _ = (e, t) => (t || []).filter((t) => e.findIndex((e) => e.correct && m(e, t)) !== -1), v = (e, t, r) => {
103
103
  if (!t || n(t)) return 0;
104
- let i = _(e.tokens, t.selectedTokens).length, a = (e.tokens || []).filter((e) => e.correct === !0), o = i - (t.selectedTokens && t.selectedTokens.length > a.length ? t.selectedTokens && t.selectedTokens.length - i : 0), s = o < 0 ? 0 : o;
104
+ let i = _(e.tokens, t.selectedTokens).length, a = (e.tokens || []).filter((e) => e.correct === !0), o = i - (t.selectedTokens && t.selectedTokens.length > a.length && t.selectedTokens ? t.selectedTokens.length - i : 0), s = o < 0 ? 0 : o;
105
105
  return r.length ? parseFloat((s / r.length).toFixed(2)) : 0;
106
106
  }, y = (e, t, n) => {
107
107
  let r = [], i = t?.selectedTokens || [], a = e?.tokens || [];
@@ -194,7 +194,7 @@ var S = (e) => ({
194
194
  t[n]?.required && !E(e[n]) && (o[n] = "This field is required.");
195
195
  });
196
196
  let c = (n || []).reduce((e, t) => t.correct ? e + 1 : e, 0);
197
- return s < r ? o.tokensError = `There should be at least ${r} tokens defined.` : s > i && (o.tokensError = `No more than ${i} tokens should be defined.`), c < 1 ? o.selectionsError = "There should be at least 1 token selected." : c > a && (o.selectionsError = `No more than ${a} tokens should be selected.`), o;
197
+ return s < r ? o.tokensError = `There should be at least ${r} tokens defined.` : i !== void 0 && s > i && (o.tokensError = `No more than ${i} tokens should be defined.`), c < 1 ? o.selectionsError = "There should be at least 1 token selected." : a !== void 0 && c > a && (o.selectionsError = `No more than ${a} tokens should be selected.`), o;
198
198
  };
199
199
  //#endregion
200
200
  export { T as createCorrectResponseSession, x as createDefaultModel, g as getCorrectness, y as getLogTrace, v as getPartialScore, w as model, C as normalize, S as normalizeSession, b as outcome, D as validate };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../../../shared/feedback/dist/index.js","../../../../../../shared/controller-utils/dist/index.js","../../../../src/controller/defaults.ts","../../../../src/controller/index.ts"],"sourcesContent":["//#region src/defaults.ts\nvar e = {\n\tcorrect: {\n\t\ttype: \"default\",\n\t\tdefault: \"Correct\",\n\t\tcustom: \"Correct\"\n\t},\n\tincorrect: {\n\t\ttype: \"default\",\n\t\tdefault: \"Incorrect\",\n\t\tcustom: \"Incorrect\"\n\t},\n\tpartial: {\n\t\ttype: \"default\",\n\t\tdefault: \"Nearly\",\n\t\tcustom: \"Nearly\"\n\t},\n\tunanswered: {\n\t\ttype: \"default\",\n\t\tdefault: \"You have not entered a response\",\n\t\tcustom: \"You have not entered a response\"\n\t}\n};\n//#endregion\n//#region src/utils.ts\nfunction t(e) {\n\treturn e === \"partially-correct\" ? \"partial\" : e;\n}\n//#endregion\n//#region src/index.ts\nfunction n(n, r) {\n\tlet i = {\n\t\t...e,\n\t\t...r\n\t}, a = t(n), o = e[a] || {}, s = i[a] || o;\n\treturn {\n\t\tconfig: s,\n\t\tfallback: o[s.type || \"default\"]\n\t};\n}\nfunction r(e, t = {}) {\n\treturn new Promise((r) => {\n\t\tlet { config: a, fallback: o } = n(e, t);\n\t\ti(a, o).then(r);\n\t});\n}\nfunction i(e, t) {\n\treturn new Promise((n) => {\n\t\tif (!e || e.type === \"none\") {\n\t\t\tn(void 0);\n\t\t\treturn;\n\t\t}\n\t\tn(e[e.type] || t);\n\t});\n}\nfunction a(e, t = {}) {\n\tlet { config: r, fallback: i } = n(e, t);\n\treturn o(r, i);\n}\nfunction o(e, t) {\n\tif (!(!e || e.type === \"none\")) return e[e.type] || t;\n}\n//#endregion\nexport { e as defaultFeedback, o as getActualFeedback, a as getActualFeedbackForCorrectness, i as getFeedback, r as getFeedbackForCorrectness, t as normalizeCorrectness };\n","//#region \\0rolldown/runtime.js\nvar e = Object.defineProperty, t = (t, n) => {\n\tlet r = {};\n\tfor (var i in t) e(r, i, {\n\t\tget: t[i],\n\t\tenumerable: !0\n\t});\n\treturn n || e(r, Symbol.toStringTag, { value: \"Module\" }), r;\n};\n//#endregion\n//#region src/persistence.ts\nfunction n(e) {\n\treturn Array.isArray(e) ? e.filter((e) => e != null) : [];\n}\nfunction r(e) {\n\tlet t = [...e];\n\tfor (let e = t.length - 1; e > 0; e--) {\n\t\tlet n = Math.floor(Math.random() * (e + 1));\n\t\t[t[e], t[n]] = [t[n], t[e]];\n\t}\n\treturn t;\n}\nfunction i(e) {\n\treturn e == null ? !0 : Array.isArray(e) ? e.length === 0 : typeof e == \"object\" && Object.keys(e).length === 0;\n}\nasync function a(e, t, a, o = \"value\") {\n\tlet s = n(t?.data?.shuffledValues ?? t?.shuffledValues ?? []);\n\tif (!t) {\n\t\tconsole.warn(\"Unable to save shuffled choices because there's no session.\");\n\t\treturn;\n\t}\n\tif (!i(s)) return n(s.map((t) => e.find((e) => e[o] === t)));\n\tlet c = r(e);\n\tif (a && typeof a == \"function\") try {\n\t\tlet e = n(c.map((e) => e[o]));\n\t\ti(e) ? console.error(`shuffledValues is an empty array - refusing to call updateSession. shuffledChoices: ${JSON.stringify(c)}, key: ${o}`) : await a(t.id, t.element, { shuffledValues: e });\n\t} catch (e) {\n\t\tconsole.warn(\"Unable to save shuffled order for choices\"), console.error(e);\n\t}\n\telse console.warn(\"Unable to save shuffled choices, shuffle will happen every time.\");\n\treturn c;\n}\nfunction o(e, t, n) {\n\treturn !!(e.lockChoiceOrder || n?.[\"@pie-element\"]?.lockChoiceOrder);\n}\n//#endregion\n//#region src/partial-scoring.ts\nvar s = /* @__PURE__ */ t({ enabled: () => c });\nfunction c(e, t, n) {\n\treturn e?.partialScoring === !1 || t?.partialScoring === !1 ? !1 : typeof n != \"boolean\" || n;\n}\n//#endregion\nexport { a as getShuffledChoices, o as lockChoices, s as partialScoring };\n","// @ts-nocheck\n\nexport default {\n feedbackEnabled: false,\n highlightChoices: false,\n maxSelections: 0,\n mode: 'sentence',\n partialScoring: false,\n prompt: '',\n promptEnabled: true,\n rationale: '',\n rationaleEnabled: true,\n scoringType: 'auto',\n studentInstructionsEnabled: true,\n teacherInstructions: '',\n teacherInstructionsEnabled: true,\n text: '',\n tokens: [],\n toolbarEditorPosition: 'bottom',\n};\n","// @ts-nocheck\n\nimport debug from 'debug';\nimport { isEmpty } from '@pie-element/shared-lodash';\nimport { getFeedbackForCorrectness } from '@pie-element/shared-feedback';\nimport { partialScoring } from '@pie-element/shared-controller-utils';\nimport defaults from './defaults.js';\n\nconst log = debug('@pie-element:select-text:controller');\n\nconst equalTokens = (token1 = {}, token2 = {}) =>\n (token1?.start === token2?.start && token1?.end === token2?.end) ||\n // this case is used for the cases when the token's start & end were recalculated\n (token1?.start === token2?.oldStart && token1?.end === token2?.oldEnd);\n\nconst normalizeTokens = (tokens = [], selectedTokens = [], evaluateMode = false) =>\n (tokens || []).map((token) => {\n const isCorrect = !!token.correct;\n // search if correct token is missing from session\n const isMissing = isCorrect && !(selectedTokens || []).find((selectedToken) => equalTokens(token, selectedToken));\n\n return {\n ...token,\n correct: evaluateMode ? isCorrect : undefined,\n isMissing: evaluateMode ? isMissing : undefined,\n };\n });\n\nexport const getCorrectness = (tokens, selected) => {\n const correct = tokens.filter((t) => t.correct === true);\n\n if (correct.length === 0) {\n return 'unknown';\n }\n\n const correctSelected = getCorrectSelected(tokens, selected);\n\n if (correctSelected.length === selected.length) {\n if (correctSelected.length === correct.length) {\n return 'correct';\n } else if (correctSelected.length > 0) {\n return 'partially-correct';\n }\n }\n\n if (correctSelected.length > 0) {\n return 'partially-correct';\n }\n\n return 'incorrect';\n};\n\nconst getCorrectSelected = (tokens, selected) =>\n (selected || []).filter((s) => tokens.findIndex((token) => token.correct && equalTokens(token, s)) !== -1);\n\nexport const getPartialScore = (question, session, totalCorrect) => {\n if (!session || isEmpty(session)) {\n return 0;\n }\n\n const correctCount = getCorrectSelected(question.tokens, session.selectedTokens).length;\n const correctTokens = (question.tokens || []).filter((t) => t.correct === true);\n const extraSelected = session.selectedTokens ? session.selectedTokens.length > correctTokens.length : 0;\n const incorrectCount = extraSelected ? session.selectedTokens && session.selectedTokens.length - correctCount : 0;\n const count = correctCount - incorrectCount;\n const positiveCount = count < 0 ? 0 : count;\n\n return totalCorrect.length ? parseFloat((positiveCount / totalCorrect.length).toFixed(2)) : 0;\n};\n\n/**\n * Generates detailed trace log for select-text scoring evaluation\n * @param {Object} question - the question model\n * @param {Object} session - the student session\n * @param {Object} env - the environment\n * @returns {Array<string>} traceLog\n */\nexport const getLogTrace = (question, session, env) => {\n const traceLog = [];\n\n const selectedTokens = session?.selectedTokens || [];\n const tokens = question?.tokens || [];\n\n if (selectedTokens.length === 0) {\n traceLog.push('Student did not select any token.');\n return traceLog;\n }\n\n traceLog.push(`Student selected ${selectedTokens.length} token(s).`);\n\n let totalCorrectTokens = 0;\n let correctSelected = 0;\n let missingCount = 0;\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n if (token.correct) {\n totalCorrectTokens++;\n const matched = selectedTokens.some((s) => equalTokens(token, s));\n if (matched) {\n correctSelected++;\n } else {\n missingCount++;\n }\n }\n }\n\n const incorrectSelected = selectedTokens.length - correctSelected;\n\n if (correctSelected > 0) {\n traceLog.push(`${correctSelected} correct token(s) selected.`);\n }\n\n if (incorrectSelected > 0) {\n traceLog.push(`${incorrectSelected} incorrect token(s) selected.`);\n }\n\n if (missingCount > 0) {\n traceLog.push(`${missingCount} required correct token(s) were not selected.`);\n }\n\n const partialScoringEnabled = partialScoring.enabled(question, env, true);\n\n if (partialScoringEnabled) {\n traceLog.push('Score calculated using partial scoring.');\n traceLog.push(\n 'Score is based on the number of correct minus incorrect selections, divided by the total number of correct tokens.',\n );\n\n if (incorrectSelected > 0 && selectedTokens.length > totalCorrectTokens) {\n traceLog.push(\n 'Extra selected tokens beyond the correct set reduce the score.',\n );\n }\n } else {\n traceLog.push('Score calculated using all-or-nothing scoring.');\n traceLog.push(\n 'Student must select all correct tokens and no incorrect tokens to receive full credit.',\n );\n }\n\n const rawScore = getPartialScore(question, session, tokens.filter((t) => t.correct));\n const finalScore = partialScoringEnabled ? rawScore : rawScore === 1 ? 1 : 0;\n\n traceLog.push(`Final score: ${finalScore}.`);\n\n return traceLog;\n};\n\nexport const outcome = (question, session, env) =>\n new Promise((resolve) => {\n if (!session || isEmpty(session)) {\n resolve({ score: 0, empty: true, logTrace: ['Student did not select any token.'] });\n }\n\n session = normalizeSession(session);\n\n if (env.mode !== 'evaluate') {\n resolve({ score: undefined, completed: undefined, logTrace: [] });\n } else {\n const enabled = partialScoring.enabled(question, env, true);\n const totalCorrect = question.tokens.filter((t) => t.correct);\n const score = getPartialScore(question, session, totalCorrect);\n resolve({\n score: enabled ? score : score === 1 ? 1 : 0,\n logTrace: getLogTrace(question, session, env),\n });\n }\n });\n\nexport function createDefaultModel(model = {}) {\n return new Promise((resolve) => {\n resolve({ ...defaults, ...model });\n });\n}\n\nexport const normalizeSession = (session) => ({ selectedTokens: [], ...session });\n\nexport const normalize = (question) => ({ ...defaults, ...question });\n\nexport const model = (question, session, env) => {\n session = session || { selectedToken: [] };\n session.selectedTokens = session.selectedTokens || [];\n const normalizedQuestion = normalize(question);\n\n return new Promise((resolve) => {\n log('[model]', 'normalizedQuestion: ', normalizedQuestion);\n log('[model]', 'session: ', session);\n\n const tokens = normalizeTokens(normalizedQuestion.tokens, session.selectedTokens, env.mode === 'evaluate');\n log('[model] tokens:', tokens);\n\n const correctness =\n env.mode === 'evaluate' ? getCorrectness(normalizedQuestion.tokens, session.selectedTokens) : undefined;\n\n const fb =\n env.mode === 'evaluate' && normalizedQuestion.feedbackEnabled\n ? getFeedbackForCorrectness(correctness, normalizedQuestion.feedback)\n : Promise.resolve(undefined);\n\n fb.then((feedback) => {\n const out = {\n tokens,\n highlightChoices: normalizedQuestion.highlightChoices,\n prompt: normalizedQuestion.promptEnabled ? normalizedQuestion.prompt : null,\n text: normalizedQuestion.text,\n disabled: env.mode !== 'gather',\n maxSelections: normalizedQuestion.maxSelections,\n correctness,\n env,\n feedback,\n incorrect: env.mode === 'evaluate' ? correctness !== 'correct' : undefined,\n language: normalizedQuestion.language,\n extraCSSRules: normalizedQuestion.extraCSSRules,\n };\n\n if (env.role === 'instructor' && (env.mode === 'view' || env.mode === 'evaluate')) {\n out.rationale = normalizedQuestion.rationaleEnabled ? normalizedQuestion.rationale : null;\n out.teacherInstructions = normalizedQuestion.teacherInstructionsEnabled\n ? normalizedQuestion.teacherInstructions\n : null;\n } else {\n out.rationale = null;\n out.teacherInstructions = null;\n }\n\n resolve(out);\n });\n });\n};\n\nexport const createCorrectResponseSession = (question, env) => {\n return new Promise((resolve) => {\n if (env.mode !== 'evaluate' && env.role === 'instructor') {\n const { tokens } = question;\n const selectedTokens = tokens.filter((t) => t.correct);\n\n resolve({\n id: '1',\n selectedTokens,\n });\n } else {\n resolve(null);\n }\n });\n};\n\n// remove all html tags\nconst getInnerText = (html) => (html || '').replaceAll(/<[^>]*>/g, '');\n\n// remove all html tags except img, iframe and source tag for audio\nconst getContent = (html) => (html || '').replace(/(<(?!img|iframe|source)([^>]+)>)/gi, '');\n\nexport const validate = (model = {}, config = {}) => {\n const { tokens } = model;\n const { minTokens = 2, maxTokens, maxSelections } = config;\n const errors = {};\n const nbOfTokens = (tokens || []).length;\n\n ['teacherInstructions', 'prompt', 'rationale'].forEach((field) => {\n if (config[field]?.required && !getContent(model[field])) {\n errors[field] = 'This field is required.';\n }\n });\n\n const nbOfSelections = (tokens || []).reduce((acc, token) => (token.correct ? acc + 1 : acc), 0);\n\n if (nbOfTokens < minTokens) {\n errors.tokensError = `There should be at least ${minTokens} tokens defined.`;\n } else if (nbOfTokens > maxTokens) {\n errors.tokensError = `No more than ${maxTokens} tokens should be defined.`;\n }\n\n if (nbOfSelections < 1) {\n errors.selectionsError = 'There should be at least 1 token selected.';\n } else if (nbOfSelections > maxSelections) {\n errors.selectionsError = `No more than ${maxSelections} tokens should be selected.`;\n }\n\n return errors;\n};\n"],"mappings":";;;mCACI,IAAI;CACP,SAAS;EACR,MAAM;EACN,SAAS;EACT,QAAQ;CACT;CACA,WAAW;EACV,MAAM;EACN,SAAS;EACT,QAAQ;CACT;CACA,SAAS;EACR,MAAM;EACN,SAAS;EACT,QAAQ;CACT;CACA,YAAY;EACX,MAAM;EACN,SAAS;EACT,QAAQ;CACT;AACD;AAGA,SAAS,EAAE,GAAG;CACb,OAAO,MAAM,sBAAsB,YAAY;AAChD;AAGA,SAAS,EAAE,GAAG,GAAG;CAChB,IAAI,IAAI;EACP,GAAG;EACH,GAAG;CACJ,GAAG,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,GAAG,IAAI,EAAE,MAAM;CACzC,OAAO;EACN,QAAQ;EACR,UAAU,EAAE,EAAE,QAAQ;CACvB;AACD;AACA,SAAS,EAAE,GAAG,IAAI,CAAC,GAAG;CACrB,OAAO,IAAI,SAAS,MAAM;EACzB,IAAI,EAAE,QAAQ,GAAG,UAAU,MAAM,EAAE,GAAG,CAAC;EACvC,EAAE,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC;CACf,CAAC;AACF;AACA,SAAS,EAAE,GAAG,GAAG;CAChB,OAAO,IAAI,SAAS,MAAM;EACzB,IAAI,CAAC,KAAK,EAAE,SAAS,QAAQ;GAC5B,EAAE,KAAK,CAAC;GACR;EACD;EACA,EAAE,EAAE,EAAE,SAAS,CAAC;CACjB,CAAC;AACF;;;ACrDA,IAAI,IAAI,OAAO,gBA8CX,IAAoB,kBA9CY,GAAG,MAAM;CAC5C,IAAI,IAAI,CAAC;CACT,KAAK,IAAI,KAAK,GAAG,EAAE,GAAG,GAAG;EACxB,KAAK,EAAE;EACP,YAAY,CAAC;CACd,CAAC;CACD,OAAO,KAAK,EAAE,GAAG,OAAO,aAAa,EAAE,OAAO,SAAS,CAAC,GAAG;AAC5D,EAuCwB,CAAE,EAAE,eAAe,EAAE,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hB,CAAC,GAOG,KAAc,OAAU,KAAQ,GAAA,CAAI,QAAQ,sCAAsC,EAAE,GAE7E,KAAY,IAAQ,CAAC,GAAG,IAAS,CAAC,MAAM;CACnD,IAAM,EAAE,cAAW,GACb,EAAE,eAAY,GAAG,cAAW,qBAAkB,GAC9C,IAAS,CAAC,GACV,KAAc,KAAU,CAAC,EAAA,CAAG;CAElC;EAAC;EAAuB;EAAU;CAAW,CAAC,CAAC,SAAS,MAAU;EAChE,AAAI,EAAO,EAAM,EAAE,YAAY,CAAC,EAAW,EAAM,EAAM,MACrD,EAAO,KAAS;CAEpB,CAAC;CAED,IAAM,KAAkB,KAAU,CAAC,EAAA,CAAG,QAAQ,GAAK,MAAW,EAAM,UAAU,IAAM,IAAI,GAAM,CAAC;CAc/F,OAZI,IAAa,IACf,EAAO,cAAc,4BAA4B,EAAU,oBAClD,IAAa,MACtB,EAAO,cAAc,gBAAgB,EAAU,8BAG7C,IAAiB,IACnB,EAAO,kBAAkB,+CAChB,IAAiB,MAC1B,EAAO,kBAAkB,gBAAgB,EAAc,+BAGlD;AACT"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../../../shared/feedback/dist/index.js","../../../../../../shared/controller-utils/dist/index.js","../../../../src/controller/defaults.ts","../../../../src/controller/index.ts"],"sourcesContent":["//#region src/defaults.ts\nvar e = {\n\tcorrect: {\n\t\ttype: \"default\",\n\t\tdefault: \"Correct\",\n\t\tcustom: \"Correct\"\n\t},\n\tincorrect: {\n\t\ttype: \"default\",\n\t\tdefault: \"Incorrect\",\n\t\tcustom: \"Incorrect\"\n\t},\n\tpartial: {\n\t\ttype: \"default\",\n\t\tdefault: \"Nearly\",\n\t\tcustom: \"Nearly\"\n\t},\n\tunanswered: {\n\t\ttype: \"default\",\n\t\tdefault: \"You have not entered a response\",\n\t\tcustom: \"You have not entered a response\"\n\t}\n};\n//#endregion\n//#region src/utils.ts\nfunction t(e) {\n\treturn e === \"partially-correct\" ? \"partial\" : e;\n}\n//#endregion\n//#region src/index.ts\nfunction n(n, r) {\n\tlet i = {\n\t\t...e,\n\t\t...r\n\t}, a = t(n), o = e[a] || {}, s = i[a] || o;\n\treturn {\n\t\tconfig: s,\n\t\tfallback: o[s.type || \"default\"]\n\t};\n}\nfunction r(e, t = {}) {\n\treturn new Promise((r) => {\n\t\tlet { config: a, fallback: o } = n(e, t);\n\t\ti(a, o).then(r);\n\t});\n}\nfunction i(e, t) {\n\treturn new Promise((n) => {\n\t\tif (!e || e.type === \"none\") {\n\t\t\tn(void 0);\n\t\t\treturn;\n\t\t}\n\t\tn(e[e.type] || t);\n\t});\n}\nfunction a(e, t = {}) {\n\tlet { config: r, fallback: i } = n(e, t);\n\treturn o(r, i);\n}\nfunction o(e, t) {\n\tif (!(!e || e.type === \"none\")) return e[e.type] || t;\n}\n//#endregion\nexport { e as defaultFeedback, o as getActualFeedback, a as getActualFeedbackForCorrectness, i as getFeedback, r as getFeedbackForCorrectness, t as normalizeCorrectness };\n","//#region \\0rolldown/runtime.js\nvar e = Object.defineProperty, t = (t, n) => {\n\tlet r = {};\n\tfor (var i in t) e(r, i, {\n\t\tget: t[i],\n\t\tenumerable: !0\n\t});\n\treturn n || e(r, Symbol.toStringTag, { value: \"Module\" }), r;\n};\n//#endregion\n//#region src/persistence.ts\nfunction n(e) {\n\treturn Array.isArray(e) ? e.filter((e) => e != null) : [];\n}\nfunction r(e) {\n\tlet t = [...e];\n\tfor (let e = t.length - 1; e > 0; e--) {\n\t\tlet n = Math.floor(Math.random() * (e + 1));\n\t\t[t[e], t[n]] = [t[n], t[e]];\n\t}\n\treturn t;\n}\nfunction i(e) {\n\treturn e == null ? !0 : Array.isArray(e) ? e.length === 0 : typeof e == \"object\" && Object.keys(e).length === 0;\n}\nasync function a(e, t, a, o = \"value\") {\n\tlet s = n(t?.data?.shuffledValues ?? t?.shuffledValues ?? []);\n\tif (!t) {\n\t\tconsole.warn(\"Unable to save shuffled choices because there's no session.\");\n\t\treturn;\n\t}\n\tif (!i(s)) return n(s.map((t) => e.find((e) => e[o] === t)));\n\tlet c = r(e);\n\tif (a && typeof a == \"function\") try {\n\t\tlet e = n(c.map((e) => e[o]));\n\t\ti(e) ? console.error(`shuffledValues is an empty array - refusing to call updateSession. shuffledChoices: ${JSON.stringify(c)}, key: ${o}`) : await a(t.id, t.element, { shuffledValues: e });\n\t} catch (e) {\n\t\tconsole.warn(\"Unable to save shuffled order for choices\"), console.error(e);\n\t}\n\telse console.warn(\"Unable to save shuffled choices, shuffle will happen every time.\");\n\treturn c;\n}\nfunction o(e, t, n) {\n\treturn !!(e.lockChoiceOrder || n?.[\"@pie-element\"]?.lockChoiceOrder);\n}\n//#endregion\n//#region src/partial-scoring.ts\nvar s = /* @__PURE__ */ t({ enabled: () => c });\nfunction c(e, t, n) {\n\treturn e?.partialScoring === !1 || t?.partialScoring === !1 ? !1 : typeof n != \"boolean\" || n;\n}\n//#endregion\nexport { a as getShuffledChoices, o as lockChoices, s as partialScoring };\n","import type { SelectTextModel, TextToken } from '../types.js';\n\nexport default {\n feedbackEnabled: false,\n highlightChoices: false,\n maxSelections: 0,\n mode: 'sentence',\n partialScoring: false,\n prompt: '',\n promptEnabled: true,\n rationale: '',\n rationaleEnabled: true,\n scoringType: 'auto',\n studentInstructionsEnabled: true,\n teacherInstructions: '',\n teacherInstructionsEnabled: true,\n text: '',\n tokens: [] as TextToken[],\n toolbarEditorPosition: 'bottom',\n} satisfies Omit<SelectTextModel, 'id' | 'element'>;\n","import debug from 'debug';\nimport { isEmpty } from '@pie-element/shared-lodash';\nimport { getFeedbackForCorrectness, type Correctness, type Feedback } from '@pie-element/shared-feedback';\nimport { partialScoring } from '@pie-element/shared-controller-utils';\nimport type { ExtraCSSRules, PieEnvironment } from '@pie-element/shared-types';\nimport defaults from './defaults.js';\nimport type { SelectTextConfiguration, SelectTextModel, SelectTextSession, TextToken } from '../types.js';\n\nconst log = debug('@pie-element:select-text:controller');\n\ntype ResponseCorrectness = 'unknown' | 'correct' | 'partially-correct' | 'incorrect';\n\n/** A token as the delivery view receives it; `correct` and `isMissing` are set in evaluate mode only. */\ntype TokenView = Omit<TextToken, 'correct'> & { correct: boolean | undefined; isMissing: boolean | undefined };\n\n/** The model the delivery view receives. */\ntype ModelView = {\n tokens: TokenView[];\n highlightChoices?: boolean;\n prompt: string | null | undefined;\n text: string;\n disabled: boolean;\n maxSelections?: number;\n correctness: ResponseCorrectness | undefined;\n env: PieEnvironment;\n feedback: string | undefined;\n incorrect: boolean | undefined;\n language?: string;\n extraCSSRules?: ExtraCSSRules;\n rationale?: string | null;\n teacherInstructions?: string | null;\n};\n\ntype Outcome = { score: number | undefined; empty?: boolean; completed?: undefined; logTrace: string[] };\n\n/** Errors `validate()` reports, keyed by field. */\nexport type SelectTextValidationErrors = {\n teacherInstructions?: string;\n prompt?: string;\n rationale?: string;\n tokensError?: string;\n selectionsError?: string;\n};\n\n/** The session `model()` works on; without a session it starts from one carrying `selectedToken`. */\ntype ModelSession = SelectTextSession & { selectedToken?: TextToken[] };\n\nconst equalTokens = (token1: Partial<TextToken> = {}, token2: Partial<TextToken> = {}) =>\n (token1?.start === token2?.start && token1?.end === token2?.end) ||\n // this case is used for the cases when the token's start & end were recalculated\n (token1?.start === token2?.oldStart && token1?.end === token2?.oldEnd);\n\nconst normalizeTokens = (tokens: TextToken[] = [], selectedTokens: TextToken[] = [], evaluateMode = false): TokenView[] =>\n (tokens || []).map((token) => {\n const isCorrect = !!token.correct;\n // search if correct token is missing from session\n const isMissing = isCorrect && !(selectedTokens || []).find((selectedToken) => equalTokens(token, selectedToken));\n\n return {\n ...token,\n correct: evaluateMode ? isCorrect : undefined,\n isMissing: evaluateMode ? isMissing : undefined,\n };\n });\n\nexport const getCorrectness = (tokens: TextToken[], selected: TextToken[]): ResponseCorrectness => {\n const correct = tokens.filter((t) => t.correct === true);\n\n if (correct.length === 0) {\n return 'unknown';\n }\n\n const correctSelected = getCorrectSelected(tokens, selected);\n\n if (correctSelected.length === selected.length) {\n if (correctSelected.length === correct.length) {\n return 'correct';\n } else if (correctSelected.length > 0) {\n return 'partially-correct';\n }\n }\n\n if (correctSelected.length > 0) {\n return 'partially-correct';\n }\n\n return 'incorrect';\n};\n\nconst getCorrectSelected = (tokens: TextToken[], selected: TextToken[] | undefined) =>\n (selected || []).filter((s) => tokens.findIndex((token) => token.correct && equalTokens(token, s)) !== -1);\n\nexport const getPartialScore = (\n question: SelectTextModel,\n session: SelectTextSession | undefined,\n totalCorrect: TextToken[],\n) => {\n if (!session || isEmpty(session)) {\n return 0;\n }\n\n const correctCount = getCorrectSelected(question.tokens, session.selectedTokens).length;\n const correctTokens = (question.tokens || []).filter((t) => t.correct === true);\n const extraSelected = session.selectedTokens ? session.selectedTokens.length > correctTokens.length : 0;\n const incorrectCount = extraSelected && session.selectedTokens ? session.selectedTokens.length - correctCount : 0;\n const count = correctCount - incorrectCount;\n const positiveCount = count < 0 ? 0 : count;\n\n return totalCorrect.length ? parseFloat((positiveCount / totalCorrect.length).toFixed(2)) : 0;\n};\n\n/**\n * Generates detailed trace log for select-text scoring evaluation\n * @param {Object} question - the question model\n * @param {Object} session - the student session\n * @param {Object} env - the environment\n * @returns {Array<string>} traceLog\n */\nexport const getLogTrace = (question: SelectTextModel, session: SelectTextSession | undefined, env: PieEnvironment) => {\n const traceLog: string[] = [];\n\n const selectedTokens = session?.selectedTokens || [];\n const tokens = question?.tokens || [];\n\n if (selectedTokens.length === 0) {\n traceLog.push('Student did not select any token.');\n return traceLog;\n }\n\n traceLog.push(`Student selected ${selectedTokens.length} token(s).`);\n\n let totalCorrectTokens = 0;\n let correctSelected = 0;\n let missingCount = 0;\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n if (token.correct) {\n totalCorrectTokens++;\n const matched = selectedTokens.some((s) => equalTokens(token, s));\n if (matched) {\n correctSelected++;\n } else {\n missingCount++;\n }\n }\n }\n\n const incorrectSelected = selectedTokens.length - correctSelected;\n\n if (correctSelected > 0) {\n traceLog.push(`${correctSelected} correct token(s) selected.`);\n }\n\n if (incorrectSelected > 0) {\n traceLog.push(`${incorrectSelected} incorrect token(s) selected.`);\n }\n\n if (missingCount > 0) {\n traceLog.push(`${missingCount} required correct token(s) were not selected.`);\n }\n\n const partialScoringEnabled = partialScoring.enabled(question, env, true);\n\n if (partialScoringEnabled) {\n traceLog.push('Score calculated using partial scoring.');\n traceLog.push(\n 'Score is based on the number of correct minus incorrect selections, divided by the total number of correct tokens.',\n );\n\n if (incorrectSelected > 0 && selectedTokens.length > totalCorrectTokens) {\n traceLog.push(\n 'Extra selected tokens beyond the correct set reduce the score.',\n );\n }\n } else {\n traceLog.push('Score calculated using all-or-nothing scoring.');\n traceLog.push(\n 'Student must select all correct tokens and no incorrect tokens to receive full credit.',\n );\n }\n\n const rawScore = getPartialScore(question, session, tokens.filter((t) => t.correct));\n const finalScore = partialScoringEnabled ? rawScore : rawScore === 1 ? 1 : 0;\n\n traceLog.push(`Final score: ${finalScore}.`);\n\n return traceLog;\n};\n\nexport const outcome = (question: SelectTextModel, session: SelectTextSession | undefined, env: PieEnvironment) =>\n new Promise<Outcome>((resolve) => {\n if (!session || isEmpty(session)) {\n resolve({ score: 0, empty: true, logTrace: ['Student did not select any token.'] });\n }\n\n session = normalizeSession(session);\n\n if (env.mode !== 'evaluate') {\n resolve({ score: undefined, completed: undefined, logTrace: [] });\n } else {\n const enabled = partialScoring.enabled(question, env, true);\n const totalCorrect = question.tokens.filter((t) => t.correct);\n const score = getPartialScore(question, session, totalCorrect);\n resolve({\n score: enabled ? score : score === 1 ? 1 : 0,\n logTrace: getLogTrace(question, session, env),\n });\n }\n });\n\nexport function createDefaultModel(model: Partial<SelectTextModel> = {}) {\n return new Promise<Partial<SelectTextModel>>((resolve) => {\n resolve({ ...defaults, ...model });\n });\n}\n\nexport const normalizeSession = (session: SelectTextSession | undefined) => ({\n selectedTokens: [] as TextToken[],\n ...session,\n});\n\nexport const normalize = (question: SelectTextModel) => ({ ...defaults, ...question });\n\nexport const model = (question: SelectTextModel, session: ModelSession | null | undefined, env: PieEnvironment) => {\n session = session || { selectedToken: [] };\n session.selectedTokens = session.selectedTokens || [];\n const normalizedQuestion = normalize(question);\n\n return new Promise<ModelView>((resolve) => {\n log('[model]', 'normalizedQuestion: ', normalizedQuestion);\n log('[model]', 'session: ', session);\n\n const tokens = normalizeTokens(normalizedQuestion.tokens, session.selectedTokens, env.mode === 'evaluate');\n log('[model] tokens:', tokens);\n\n const correctness =\n env.mode === 'evaluate' ? getCorrectness(normalizedQuestion.tokens, session.selectedTokens as TextToken[]) : undefined;\n\n const fb =\n env.mode === 'evaluate' && normalizedQuestion.feedbackEnabled\n ? getFeedbackForCorrectness(correctness as Correctness, normalizedQuestion.feedback as Partial<Feedback>)\n : Promise.resolve(undefined);\n\n fb.then((feedback) => {\n const out: ModelView = {\n tokens,\n highlightChoices: normalizedQuestion.highlightChoices,\n prompt: normalizedQuestion.promptEnabled ? normalizedQuestion.prompt : null,\n text: normalizedQuestion.text,\n disabled: env.mode !== 'gather',\n maxSelections: normalizedQuestion.maxSelections,\n correctness,\n env,\n feedback,\n incorrect: env.mode === 'evaluate' ? correctness !== 'correct' : undefined,\n language: normalizedQuestion.language,\n extraCSSRules: normalizedQuestion.extraCSSRules,\n };\n\n if (env.role === 'instructor' && (env.mode === 'view' || env.mode === 'evaluate')) {\n out.rationale = normalizedQuestion.rationaleEnabled ? normalizedQuestion.rationale : null;\n out.teacherInstructions = normalizedQuestion.teacherInstructionsEnabled\n ? normalizedQuestion.teacherInstructions\n : null;\n } else {\n out.rationale = null;\n out.teacherInstructions = null;\n }\n\n resolve(out);\n });\n });\n};\n\nexport const createCorrectResponseSession = (question: SelectTextModel, env: PieEnvironment) => {\n return new Promise<SelectTextSession | null>((resolve) => {\n if (env.mode !== 'evaluate' && env.role === 'instructor') {\n const { tokens } = question;\n const selectedTokens = tokens.filter((t) => t.correct);\n\n resolve({\n id: '1',\n selectedTokens,\n });\n } else {\n resolve(null);\n }\n });\n};\n\n// remove all html tags except img, iframe and source tag for audio\nconst getContent = (html: string | undefined) => (html || '').replace(/(<(?!img|iframe|source)([^>]+)>)/gi, '');\n\nexport const validate = (\n model: Partial<SelectTextModel> = {},\n config: SelectTextConfiguration = {},\n): SelectTextValidationErrors => {\n const { tokens } = model;\n const { minTokens = 2, maxTokens, maxSelections } = config;\n const errors: SelectTextValidationErrors = {};\n const nbOfTokens = (tokens || []).length;\n\n (['teacherInstructions', 'prompt', 'rationale'] as const).forEach((field) => {\n if (config[field]?.required && !getContent(model[field])) {\n errors[field] = 'This field is required.';\n }\n });\n\n const nbOfSelections = (tokens || []).reduce((acc, token) => (token.correct ? acc + 1 : acc), 0);\n\n if (nbOfTokens < minTokens) {\n errors.tokensError = `There should be at least ${minTokens} tokens defined.`;\n } else if (maxTokens !== undefined && nbOfTokens > maxTokens) {\n errors.tokensError = `No more than ${maxTokens} tokens should be defined.`;\n }\n\n if (nbOfSelections < 1) {\n errors.selectionsError = 'There should be at least 1 token selected.';\n } else if (maxSelections !== undefined && nbOfSelections > maxSelections) {\n errors.selectionsError = `No more than ${maxSelections} tokens should be selected.`;\n }\n\n return errors;\n};\n"],"mappings":";;;mCACI,IAAI;CACP,SAAS;EACR,MAAM;EACN,SAAS;EACT,QAAQ;CACT;CACA,WAAW;EACV,MAAM;EACN,SAAS;EACT,QAAQ;CACT;CACA,SAAS;EACR,MAAM;EACN,SAAS;EACT,QAAQ;CACT;CACA,YAAY;EACX,MAAM;EACN,SAAS;EACT,QAAQ;CACT;AACD;AAGA,SAAS,EAAE,GAAG;CACb,OAAO,MAAM,sBAAsB,YAAY;AAChD;AAGA,SAAS,EAAE,GAAG,GAAG;CAChB,IAAI,IAAI;EACP,GAAG;EACH,GAAG;CACJ,GAAG,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,GAAG,IAAI,EAAE,MAAM;CACzC,OAAO;EACN,QAAQ;EACR,UAAU,EAAE,EAAE,QAAQ;CACvB;AACD;AACA,SAAS,EAAE,GAAG,IAAI,C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jD,EAAO,cAAc,gBAAgB,EAAU,8BAG7C,IAAiB,IACnB,EAAO,kBAAkB,+CAChB,MAAkB,KAAA,KAAa,IAAiB,MACzD,EAAO,kBAAkB,gBAAgB,EAAc,+BAGlD;AACT"}
@@ -1,19 +1,20 @@
1
+ import type { TextToken } from '../types.js';
1
2
  declare const _default: {
2
- feedbackEnabled: boolean;
3
- highlightChoices: boolean;
3
+ feedbackEnabled: false;
4
+ highlightChoices: false;
4
5
  maxSelections: number;
5
- mode: string;
6
- partialScoring: boolean;
6
+ mode: "sentence";
7
+ partialScoring: false;
7
8
  prompt: string;
8
- promptEnabled: boolean;
9
+ promptEnabled: true;
9
10
  rationale: string;
10
- rationaleEnabled: boolean;
11
- scoringType: string;
12
- studentInstructionsEnabled: boolean;
11
+ rationaleEnabled: true;
12
+ scoringType: "auto";
13
+ studentInstructionsEnabled: true;
13
14
  teacherInstructions: string;
14
- teacherInstructionsEnabled: boolean;
15
+ teacherInstructionsEnabled: true;
15
16
  text: string;
16
- tokens: never[];
17
- toolbarEditorPosition: string;
17
+ tokens: TextToken[];
18
+ toolbarEditorPosition: "bottom";
18
19
  };
19
20
  export default _default;
@@ -1,5 +1,48 @@
1
- export declare const getCorrectness: (tokens: any, selected: any) => "unknown" | "correct" | "partially-correct" | "incorrect";
2
- export declare const getPartialScore: (question: any, session: any, totalCorrect: any) => number;
1
+ import type { ExtraCSSRules, PieEnvironment } from '@pie-element/shared-types';
2
+ import type { SelectTextConfiguration, SelectTextModel, SelectTextSession, TextToken } from '../types.js';
3
+ type ResponseCorrectness = 'unknown' | 'correct' | 'partially-correct' | 'incorrect';
4
+ /** A token as the delivery view receives it; `correct` and `isMissing` are set in evaluate mode only. */
5
+ type TokenView = Omit<TextToken, 'correct'> & {
6
+ correct: boolean | undefined;
7
+ isMissing: boolean | undefined;
8
+ };
9
+ /** The model the delivery view receives. */
10
+ type ModelView = {
11
+ tokens: TokenView[];
12
+ highlightChoices?: boolean;
13
+ prompt: string | null | undefined;
14
+ text: string;
15
+ disabled: boolean;
16
+ maxSelections?: number;
17
+ correctness: ResponseCorrectness | undefined;
18
+ env: PieEnvironment;
19
+ feedback: string | undefined;
20
+ incorrect: boolean | undefined;
21
+ language?: string;
22
+ extraCSSRules?: ExtraCSSRules;
23
+ rationale?: string | null;
24
+ teacherInstructions?: string | null;
25
+ };
26
+ type Outcome = {
27
+ score: number | undefined;
28
+ empty?: boolean;
29
+ completed?: undefined;
30
+ logTrace: string[];
31
+ };
32
+ /** Errors `validate()` reports, keyed by field. */
33
+ export type SelectTextValidationErrors = {
34
+ teacherInstructions?: string;
35
+ prompt?: string;
36
+ rationale?: string;
37
+ tokensError?: string;
38
+ selectionsError?: string;
39
+ };
40
+ /** The session `model()` works on; without a session it starts from one carrying `selectedToken`. */
41
+ type ModelSession = SelectTextSession & {
42
+ selectedToken?: TextToken[];
43
+ };
44
+ export declare const getCorrectness: (tokens: TextToken[], selected: TextToken[]) => ResponseCorrectness;
45
+ export declare const getPartialScore: (question: SelectTextModel, session: SelectTextSession | undefined, totalCorrect: TextToken[]) => number;
3
46
  /**
4
47
  * Generates detailed trace log for select-text scoring evaluation
5
48
  * @param {Object} question - the question model
@@ -7,11 +50,42 @@ export declare const getPartialScore: (question: any, session: any, totalCorrect
7
50
  * @param {Object} env - the environment
8
51
  * @returns {Array<string>} traceLog
9
52
  */
10
- export declare const getLogTrace: (question: any, session: any, env: any) => string[];
11
- export declare const outcome: (question: any, session: any, env: any) => Promise<unknown>;
12
- export declare function createDefaultModel(model?: {}): Promise<unknown>;
13
- export declare const normalizeSession: (session: any) => any;
14
- export declare const normalize: (question: any) => any;
15
- export declare const model: (question: any, session: any, env: any) => Promise<unknown>;
16
- export declare const createCorrectResponseSession: (question: any, env: any) => Promise<unknown>;
17
- export declare const validate: (model?: {}, config?: {}) => {};
53
+ export declare const getLogTrace: (question: SelectTextModel, session: SelectTextSession | undefined, env: PieEnvironment) => string[];
54
+ export declare const outcome: (question: SelectTextModel, session: SelectTextSession | undefined, env: PieEnvironment) => Promise<Outcome>;
55
+ export declare function createDefaultModel(model?: Partial<SelectTextModel>): Promise<Partial<SelectTextModel>>;
56
+ export declare const normalizeSession: (session: SelectTextSession | undefined) => {
57
+ id?: string;
58
+ element?: string;
59
+ selectedTokens: TextToken[];
60
+ };
61
+ export declare const normalize: (question: SelectTextModel) => {
62
+ maxSelections: number;
63
+ mode: "sentence" | "words" | "paragraphs" | "word" | "paragraph" | "";
64
+ partialScoring: boolean;
65
+ feedback?: import("../types.js").ComplexFeedbackType;
66
+ tokens: TextToken[];
67
+ text: string;
68
+ prompt: string;
69
+ promptEnabled: boolean;
70
+ highlightChoices: boolean;
71
+ rationale: string;
72
+ scoringType: "auto" | "rubric";
73
+ studentInstructions?: string;
74
+ teacherInstructions: string;
75
+ feedbackEnabled: boolean;
76
+ rationaleEnabled: boolean;
77
+ studentInstructionsEnabled: boolean;
78
+ teacherInstructionsEnabled: boolean;
79
+ spellCheckEnabled?: boolean;
80
+ toolbarEditorPosition: "bottom" | "top";
81
+ rubricEnabled?: boolean;
82
+ language?: string;
83
+ extraCSSRules?: ExtraCSSRules;
84
+ id: string;
85
+ element: string;
86
+ accessibilityCatalogs?: import("@pie-element/shared-types").AccessibilityCatalog[];
87
+ };
88
+ export declare const model: (question: SelectTextModel, session: ModelSession | null | undefined, env: PieEnvironment) => Promise<ModelView>;
89
+ export declare const createCorrectResponseSession: (question: SelectTextModel, env: PieEnvironment) => Promise<SelectTextSession | null>;
90
+ export declare const validate: (model?: Partial<SelectTextModel>, config?: SelectTextConfiguration) => SelectTextValidationErrors;
91
+ export {};
@@ -22,7 +22,7 @@ var a = t("@pie-element:select-text:controller"), o = (e = {}, t = {}) => e?.sta
22
22
  return r.length > 0 ? "partially-correct" : "incorrect";
23
23
  }, l = (e, t) => (t || []).filter((t) => e.findIndex((e) => e.correct && o(e, t)) !== -1), u = (e, t, r) => {
24
24
  if (!t || n(t)) return 0;
25
- let i = l(e.tokens, t.selectedTokens).length, a = (e.tokens || []).filter((e) => e.correct === !0), o = i - (t.selectedTokens && t.selectedTokens.length > a.length ? t.selectedTokens && t.selectedTokens.length - i : 0), s = o < 0 ? 0 : o;
25
+ let i = l(e.tokens, t.selectedTokens).length, a = (e.tokens || []).filter((e) => e.correct === !0), o = i - (t.selectedTokens && t.selectedTokens.length > a.length && t.selectedTokens ? t.selectedTokens.length - i : 0), s = o < 0 ? 0 : o;
26
26
  return r.length ? parseFloat((s / r.length).toFixed(2)) : 0;
27
27
  }, d = (e, t, n) => {
28
28
  let r = [], a = t?.selectedTokens || [], s = e?.tokens || [];
@@ -115,7 +115,7 @@ var m = (e) => ({
115
115
  t[n]?.required && !v(e[n]) && (o[n] = "This field is required.");
116
116
  });
117
117
  let c = (n || []).reduce((e, t) => t.correct ? e + 1 : e, 0);
118
- return s < r ? o.tokensError = `There should be at least ${r} tokens defined.` : s > i && (o.tokensError = `No more than ${i} tokens should be defined.`), c < 1 ? o.selectionsError = "There should be at least 1 token selected." : c > a && (o.selectionsError = `No more than ${a} tokens should be selected.`), o;
118
+ return s < r ? o.tokensError = `There should be at least ${r} tokens defined.` : i !== void 0 && s > i && (o.tokensError = `No more than ${i} tokens should be defined.`), c < 1 ? o.selectionsError = "There should be at least 1 token selected." : a !== void 0 && c > a && (o.selectionsError = `No more than ${a} tokens should be selected.`), o;
119
119
  };
120
120
  //#endregion
121
121
  export { _ as createCorrectResponseSession, p as createDefaultModel, c as getCorrectness, d as getLogTrace, u as getPartialScore, g as model, h as normalize, m as normalizeSession, f as outcome, y as validate };
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export { default } from './delivery/index.js';
2
+ export type * from './types.js';