egatari 0.6.20 → 0.6.21-rc.1
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.
- package/components2.lock.json +152 -1
- package/kit/core/llm-pack-assemble.mjs +13 -5
- package/kit/core/llm-pack-data.mjs +7 -7
- package/kit/core/llm-pack.mjs +4 -2
- package/kit/core/new-deck-pack.mjs +1 -1
- package/kit/core/new-deck.mjs +9 -4
- package/kit/instruction-version.json +1 -1
- package/kit/llm-pack.mjs +30 -10
- package/package.json +2 -1
- package/tools/narration-json.mjs +30 -0
- package/vendor/components/CATALOG.md +1 -1
- package/vendor/components/sha256/4e7384be4e55ae5fef362e776b52c9a20013a8d540a26cf9b4acded876c4d85b/README.en.md +35 -0
- package/vendor/components/sha256/4e7384be4e55ae5fef362e776b52c9a20013a8d540a26cf9b4acded876c4d85b/index.js +398 -0
- package/vendor/components-2/manifest-2.23.0.json +3229 -0
package/kit/llm-pack.mjs
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
// node kit/llm-pack.mjs --sets stats,math --lang ja 共通の本体(標準の部品)+ 束('all' で全部、指定なしで共通の本体だけ)
|
|
3
3
|
// node kit/llm-pack.mjs --plan paid [--sets …] 有料のプラン(どの部品も詳しく。--sets all --plan paid で指示の全体)
|
|
4
4
|
// node kit/llm-pack.mjs --no-fit [--sets …] 無料のプランで目安に収めない(下の fit をしない。比べる・調べる用)
|
|
5
|
+
// node kit/llm-pack.mjs --category teaching | --purposes predict [--sets …]
|
|
6
|
+
// 新規作成の ① の大分類・④ の伝えたいこと(無料のプランの詳しさだけに効く):授業・研修か「予想してから確かめる」なら
|
|
7
|
+
// m-predict も中核の 4 つと同じに詳しく書く(kit/core/llm-pack-assemble.mjs の freeFull。handoff #108。毎晩の評価が授業の題材で使う)
|
|
5
8
|
// node kit/llm-pack.mjs --from-sample <名前> [--request <文|ファイル>] [--plan …] [--lang …]
|
|
6
9
|
// 「このサンプルを参考に作る」で ② を書いて ④ で写す指示と同じバイト(backlog #130。kit/core/new-deck-pack.mjs の fromSamplePack):
|
|
7
10
|
// examples/<名前>/sample.json の場面・テーマ・ラベル(伝えたいこと・題材・読み手)と構成。--request の 1 行目は ② のタイトル、
|
|
@@ -17,13 +20,15 @@ import fs from 'node:fs';
|
|
|
17
20
|
import path from 'node:path';
|
|
18
21
|
import { fileURLToPath } from 'node:url';
|
|
19
22
|
import { fromSamplePack, sampleProblems } from './core/new-deck-pack.mjs';
|
|
23
|
+
import { CATEGORIES } from './core/new-deck.mjs';
|
|
20
24
|
import { readRegularText, READ_LIMITS } from './bounded-read.mjs';
|
|
21
|
-
import { buildPack, SETS, membersOfSet, packKb, kbOf, packSize, BRIEF, STANDARD, FREE_CORE, PACK_CAP_KB, FREE_PASTE_UNITS, pasteUnits, fitSize, loadedParts, partsPackOpts, fitPack, normalizeSets, SINGLE_SET_DROP_ORDER } from './core/llm-pack.mjs';
|
|
25
|
+
import { buildPack, SETS, membersOfSet, packKb, kbOf, packSize, BRIEF, STANDARD, FREE_CORE, TEACHING_FULL, freeFull, TIERS, PACK_CAP_KB, FREE_PASTE_UNITS, pasteUnits, fitSize, loadedParts, partsPackOpts, fitPack, normalizeSets, SINGLE_SET_DROP_ORDER } from './core/llm-pack.mjs';
|
|
22
26
|
|
|
23
27
|
// 前の系列 → 束
|
|
24
28
|
const SERIES_SETS = { academic: ['stats', 'math'], business: ['business'], kokugo: ['kokugo'], english: ['english'], info: [], social: ['maps'], music: ['music'] };
|
|
25
29
|
|
|
26
30
|
const USAGE = `usage: node kit/llm-pack.mjs [--sets <name,…|all>] [--lang en|ja] [--plan free|paid] [--no-fit]
|
|
31
|
+
[--category <id>] [--purposes <id,…>]
|
|
27
32
|
node kit/llm-pack.mjs --from-sample <name> [--request <text|file>] [--lang en|ja] [--plan free|paid]
|
|
28
33
|
node kit/llm-pack.mjs --list [--lang en|ja]
|
|
29
34
|
node kit/llm-pack.mjs --help
|
|
@@ -45,6 +50,10 @@ plus the packs of the chosen part sets (${SETS.join(', ')};
|
|
|
45
50
|
never the set's own parts; with two or more sets, specialized parts
|
|
46
51
|
are left out, largest first. stderr says what was shortened or left out
|
|
47
52
|
--no-fit the light instructions as assembled, without fitting it to the limit
|
|
53
|
+
--category, --purposes the answers to New… step 1 (${CATEGORIES.map((c) => c.id).join(', ')})
|
|
54
|
+
and step 4 (purposes, e.g. predict). They change only the light
|
|
55
|
+
instructions: with --category teaching or --purposes predict,
|
|
56
|
+
${TEACHING_FULL.join(', ')} is described in full like the core four
|
|
48
57
|
--from-sample exactly what the editor copies in New… after “Make one based on
|
|
49
58
|
this sample” (examples/<name>/sample.json): its setting, theme and parts (never
|
|
50
59
|
suggested for unticking, described in full), plus its structure; fitted to
|
|
@@ -73,16 +82,26 @@ const langArg = arg('--lang');
|
|
|
73
82
|
if (langArg !== undefined && !['en', 'ja'].includes(langArg)) { console.error(`--lang must be en or ja (got ${langArg})\n\n${USAGE}`); process.exit(2); }
|
|
74
83
|
const planArg = arg('--plan');
|
|
75
84
|
if (planArg !== undefined && !['free', 'paid'].includes(planArg)) { console.error(`--plan must be free or paid (got ${planArg})\n\n${USAGE}`); process.exit(2); }
|
|
76
|
-
const VALUED = ['--sets', '--series', '--tools', '--lang', '--plan', '--from-sample', '--request'];
|
|
85
|
+
const VALUED = ['--sets', '--series', '--tools', '--lang', '--plan', '--from-sample', '--request', '--category', '--purposes'];
|
|
77
86
|
const known = new Set([...VALUED, '--list', '--no-fit']);
|
|
78
87
|
const bad = argv.filter((a, i) => a.startsWith('-') && !known.has(a.split('=')[0]) && !(i > 0 && VALUED.includes(argv[i - 1])));
|
|
79
88
|
if (bad.length) { console.error(`unknown option ${bad[0]}\n\n${USAGE}`); process.exit(2); }
|
|
89
|
+
// 新規作成の ① の大分類と ④ の伝えたいこと(無料のプランの詳しく書く標準の部品だけに効く。handoff #108)
|
|
90
|
+
const categoryArg = arg('--category');
|
|
91
|
+
if (categoryArg !== undefined && !CATEGORIES.some((c) => c.id === categoryArg)) { console.error(`--category must be one of ${CATEGORIES.map((c) => c.id).join(', ')} (got ${categoryArg})\n\n${USAGE}`); process.exit(2); }
|
|
92
|
+
const purposesArg = arg('--purposes') === undefined ? [] : String(arg('--purposes')).split(',').map((x) => x.trim()).filter(Boolean);
|
|
93
|
+
const purposeIds = (TIERS.purposes || []).map((p) => p.id);
|
|
94
|
+
const badPurpose = purposesArg.find((x) => !purposeIds.includes(x));
|
|
95
|
+
if (badPurpose) { console.error(`--purposes: unknown purpose "${badPurpose}" (known: ${purposeIds.join(', ')})\n\n${USAGE}`); process.exit(2); }
|
|
96
|
+
const FULL = freeFull({ category: categoryArg || null, purposes: purposesArg });
|
|
80
97
|
|
|
81
|
-
// 無料のプランの指示を目安に収める(編集アプリと同じ fitPack。頼みたいことは記入欄のまま)→ {text, fit}
|
|
82
|
-
|
|
83
|
-
|
|
98
|
+
// 無料のプランの指示を目安に収める(編集アプリと同じ fitPack。頼みたいことは記入欄のまま)→ {text, fit}。
|
|
99
|
+
// full:詳しく書く標準の部品(既定は中核の 4 つ。授業なら m-predict も。short のときは中核の 4 つと一緒に短くする)
|
|
100
|
+
function fittedPack(sets, lang, full = null) {
|
|
101
|
+
const opts = (tags, short) => partsPackOpts(tags, 'free', short || !full ? { short } : { full });
|
|
102
|
+
const sizeOf = (tags, short) => fitSize(buildPack({ ...opts(tags, short), lang }), 'free');
|
|
84
103
|
const fit = fitPack(loadedParts(sets), 'free', { sizeOf, capBytes: PACK_CAP_KB.free * 1024 });
|
|
85
|
-
return { text: buildPack({ ...
|
|
104
|
+
return { text: buildPack({ ...opts(fit.tags, fit.short), lang }), fit };
|
|
86
105
|
}
|
|
87
106
|
|
|
88
107
|
// 「このサンプルを参考に作る」の指示(編集アプリの新規作成 ④ と同じ組み立て)
|
|
@@ -107,7 +126,7 @@ function samplePack(name, lang, plan) {
|
|
|
107
126
|
|
|
108
127
|
if (argv.includes('--from-sample')) {
|
|
109
128
|
try {
|
|
110
|
-
if (argv.includes('--no-fit') || arg('--sets') !== undefined || argv.includes('--list')) throw new Error('--from-sample cannot be used with --sets, --list
|
|
129
|
+
if (argv.includes('--no-fit') || arg('--sets') !== undefined || argv.includes('--list') || categoryArg !== undefined || purposesArg.length) throw new Error('--from-sample cannot be used with --sets, --list, --no-fit, --category or --purposes (the sample gives them)');
|
|
111
130
|
const lang = langArg || 'en', plan = planArg || 'free';
|
|
112
131
|
const r = samplePack(String(arg('--from-sample') || ''), lang, plan);
|
|
113
132
|
// 順位で組む(kit/core/new-deck-pack.mjs の newDeckPack):説明つきのパーツと名前だけのパーツの数を stderr に
|
|
@@ -145,11 +164,12 @@ if (argv.includes('--from-sample')) {
|
|
|
145
164
|
}
|
|
146
165
|
sets = sets === undefined ? [] : sets;
|
|
147
166
|
const lang = langArg || 'en', plan = planArg || 'free';
|
|
148
|
-
if (plan === 'paid'
|
|
167
|
+
if (plan === 'paid') process.stdout.write(buildPack({ sets, lang, plan }));
|
|
168
|
+
else if (argv.includes('--no-fit')) process.stdout.write(buildPack({ sets, lang, plan, full: FULL }));
|
|
149
169
|
else {
|
|
150
|
-
const { text, fit } = fittedPack(sets, lang);
|
|
170
|
+
const { text, fit } = fittedPack(sets, lang, FULL);
|
|
151
171
|
const limit = `${PACK_CAP_KB.free} KB or a paste length of ${FREE_PASTE_UNITS} (UTF-16 code units + line feeds)`;
|
|
152
|
-
if (fit.short) console.error(`note: light instructions: over ${limit}, so the core four (${FREE_CORE.join(', ')}) get only their catalogue line too (--no-fit for the pack as assembled)`);
|
|
172
|
+
if (fit.short) console.error(`note: light instructions: over ${limit}, so the core four (${FREE_CORE.join(', ')})${FULL.length > FREE_CORE.length ? ` and ${FULL.filter((t) => !FREE_CORE.includes(t)).join(', ')}` : ''} get only their catalogue line too (--no-fit for the pack as assembled)`);
|
|
153
173
|
// 束が 1 つなら中核の 4 つのほかの標準のパーツを決まった順に、2 つ以上なら専門のパーツを大きい順に(kit/core/llm-pack-assemble.mjs の fitPlan)
|
|
154
174
|
if (fit.dropped.length) console.error(normalizeSets(sets).length === 1
|
|
155
175
|
? `note: light instructions: still over ${limit}, so these standard parts were left out, in the fixed order: ${fit.dropped.join(', ')} (the ${normalizeSets(sets)[0]} parts and the core four are kept; --no-fit keeps them all)`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "egatari",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.21-rc.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"homepage": "https://studio.egatari.org/",
|
|
6
6
|
"repository": {
|
|
@@ -44,6 +44,7 @@
|
|
|
44
44
|
"tools/sheet.mjs",
|
|
45
45
|
"tools/comment-shots.mjs",
|
|
46
46
|
"tools/video.mjs",
|
|
47
|
+
"tools/narration-json.mjs",
|
|
47
48
|
"components.lock.json",
|
|
48
49
|
"components2.lock.json",
|
|
49
50
|
"themes.lock.json",
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// 口述原稿(narration.md)を JSON で出す。TTS(tts/synth.py)が parser を二重に持たないための口
|
|
2
|
+
//
|
|
3
|
+
// node tools/narration-json.mjs <narration.md> [--voice '<json>']
|
|
4
|
+
//
|
|
5
|
+
// 出力: {warnings: [文字列…(雛形の仮の行のままの段階も)], segments: [{key, slideKey, stepKey, line, digest, inputHash, bounds, turns:[{role, raw, display, tts, ttsParts, bounds}], ext:[{name, field, value, line}]}]}
|
|
6
|
+
// ext は拡張の行(@x-名前-欄 値)。発言にも digest にも入らない
|
|
7
|
+
// bounds は段階の区切り({cue} と {mark:…})の並び。synth.py が記録する cues と 1 対 1 に対応する(docs/contract.md §4)
|
|
8
|
+
// digest は kit/narration.mjs の segDigest(seg, voice)。voice には声の設定・正規化の目標値・
|
|
9
|
+
// 読み辞書の版など「音声を変えるものすべて」を入れる(呼び出し側が決める)
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import { readNarration, segDigest } from '../kit/narration.mjs';
|
|
12
|
+
import { inputCanonical } from '../kit/core/portable.mjs';
|
|
13
|
+
import { isPlaceholder } from '../kit/core/template-text.mjs';
|
|
14
|
+
|
|
15
|
+
const a = process.argv.slice(2);
|
|
16
|
+
let file = null, voice = {};
|
|
17
|
+
for (let i = 0; i < a.length; i++) {
|
|
18
|
+
if (a[i] === '--voice') voice = JSON.parse(a[++i]);
|
|
19
|
+
else file = a[i];
|
|
20
|
+
}
|
|
21
|
+
if (!file) { console.error('usage: node tools/narration-json.mjs <narration.md> [--voice json]'); process.exit(1); }
|
|
22
|
+
const segs = readNarration(file);
|
|
23
|
+
// inputHash:その段階の口述原稿の hash(format spec §5.4。音声が古いかを決める。synth.py が manifest に書く)
|
|
24
|
+
const out = segs.map((s) => ({ key: `${s.slideKey}:${s.stepKey}`, slideKey: s.slideKey, stepKey: s.stepKey, line: s.line, digest: segDigest(s, voice),
|
|
25
|
+
inputHash: crypto.createHash('sha256').update(inputCanonical(s)).digest('hex'), bounds: s.bounds, turns: s.turns, ext: s.ext || [] }));
|
|
26
|
+
// 雛形の仮の行(「✎ 」で始まる。kit/core/template-text.mjs)が残っている段階:TTS はそのまま読むので、合成の前に知らせる(止めない)
|
|
27
|
+
const warnings = [...(segs.warnings || [])];
|
|
28
|
+
for (const s of segs) if (s.turns.some((t) => isPlaceholder(t.raw))) warnings.push(`narration.md ${s.line} 行目: ステップ「${s.slideKey}:${s.stepKey}」の台本がテンプレートの仮の行(✎)のまま。AI 音声はこのまま読む / still the template placeholder (✎); the AI voice reads it as is`);
|
|
29
|
+
for (const w of warnings) console.error(`⚠ ${w}`);
|
|
30
|
+
process.stdout.write(JSON.stringify({ warnings, segments: out }));
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
| [`<m-tree>`](sha256/e0daed8338f51de7e86b5980a098394298455972218370ee65331ca48f7f9696/README.md) | 1.13.1 | 階層・分類の木(組織図、生物の分類など)を、根から 1 段ずつ組み立てる。座標は書かず、配置は部品が決める | 節の深さの数(by="level"、既定)か節の数(by="node")。節と edges の step があればその最大 | orient, by, link, size, fade, draw | [demo](sha256/e0daed8338f51de7e86b5980a098394298455972218370ee65331ca48f7f9696/demo.html) |
|
|
42
42
|
| [`<m-venn>`](sha256/82b2dbc925a4ae4511bb48ccb1777a3932313ac7e18cb91572371d272a930980/README.md) | 1.13.1 | 2 つか 3 つの集合の円(ベン図)。集合を 1 つずつ出し、最後に重なりを強めてその中の項目を出す | 集合の数 + 1(overlaps="each" なら 集合の数 + 項目のある重なりの数) | size, dur, spread, overlaps | [demo](sha256/82b2dbc925a4ae4511bb48ccb1777a3932313ac7e18cb91572371d272a930980/demo.html) |
|
|
43
43
|
|
|
44
|
-
## 2.x のパーツ(components2.lock.json の既定の版 2.
|
|
44
|
+
## 2.x のパーツ(components2.lock.json の既定の版 2.23.0)
|
|
45
45
|
|
|
46
46
|
1.x の目録にない、2.x 専用の要素パーツ(`kind: "element"`)。土台パーツ(`kind: "library"`:base・boxplot-core・codetree-core・
|
|
47
47
|
expr・heatmap-core・hist-core・icons・kanbun-core・markup-reader・plot・shape)は教材の作者が直接書かないので一覧には出さない。
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
---
|
|
2
|
+
summary: Predict, reveal; votes as bars, answer framed
|
|
3
|
+
steps: 0 question, 1 bars, answer-step (2)
|
|
4
|
+
props:
|
|
5
|
+
answer-step: 2 or more (default 2); after the step-1 count
|
|
6
|
+
unit: count unit
|
|
7
|
+
poll: live poll id
|
|
8
|
+
ticks: grid
|
|
9
|
+
example: {"question": "Which falls first?", "choices": [{"label": "Heavy"}, {"label": "Light"}, {"label": "Same"}], "answer": 2, "counts": [14, 3, 9], "note": "No air: same"}
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
Child JSON: `{"question", "choices": [{"label", "tone"?}], "answer": 0-based, "counts"?: [sample], "note"?: answer line, "labels"?: {"correct"?: mark (default "✓ Correct")}}`
|
|
13
|
+
|
|
14
|
+
- Only for a real vote or guess; not asides or answer-only
|
|
15
|
+
- 2–6 choices. Video/print/start show `counts` (or 0)
|
|
16
|
+
- Script uses `counts`; vote at `{note:hands up}` (parens get read)
|
|
17
|
+
- `poll="p1"`: live poll totals
|
|
18
|
+
|
|
19
|
+
<!-- llm: omit -->
|
|
20
|
+
Notes for authors of parts (check with dev)
|
|
21
|
+
|
|
22
|
+
- Steps: 0 question, choices, ticks (context first); 1 bars and controls; `answer-step` frame, "✓ correct", `note`, others faded, text `--muted` (≥ 4.5:1)
|
|
23
|
+
- Show later steps faintly: nothing ahead shown (`static preview = "none"`, manifest `preview: "none"`)
|
|
24
|
+
- Viewer state (spec §8.4): counts and guess survive step changes on the slide; reset to author values only on `ctx.entered` (since 2.0.0); `ctx.reset` only drops focus
|
|
25
|
+
- Answers (2.2.0, spec §8.4 `ctx.answer`): reaching the answer step with a guess calls `ctx.answer("q", correct, label)` once (again after going back); none without a guess, in video, or without `ctx.answer`. Since 2.3.0 the class declares `static questions = ["q"]`, so players count the question before its slide is shown
|
|
26
|
+
- Hands up; teacher counts ±1 or types. Alone: click = guess. Counts kept while on the slide
|
|
27
|
+
- Print: author values, no guess marks; screen counts restored after
|
|
28
|
+
- Methods: `input(choice, count)` (0–9999 integer, else console.warn; no-op in video); `counts()`
|
|
29
|
+
- On change: `CustomEvent("egatari-input", {bubbles: true, detail: {counts}})`
|
|
30
|
+
- live: `ctx.live?.poll(id)` → `number[] | null`; bars only for arrays, not in video/print
|
|
31
|
+
- `static interactive = true`, `static viewerInput = true` → manifest
|
|
32
|
+
- Keys: `+` `-` `↑` `↓` (buttons also `←` `→`); no digit keys; Esc/Enter leave the field
|
|
33
|
+
- No controls in video; hidden in print
|
|
34
|
+
- UI text (mark, labels, announcements) follows ctx.lang; `labels.correct` overrides the mark
|
|
35
|
+
<!-- llm: end -->
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
// m-predict:予想してから答えを開く。問いと選択肢、クラスの数(手を挙げた人数)を選択肢ごとの棒で見せ、作者の書いた段階で答えを開く
|
|
2
|
+
// <m-predict unit="人" style="height:440px"><script type="application/json">
|
|
3
|
+
// {"question": "重い球と軽い球、どちらが先に落ちる?",
|
|
4
|
+
// "choices": [{"label": "重い球"}, {"label": "軽い球"}, {"label": "同時"}],
|
|
5
|
+
// "answer": 2, "counts": [14, 3, 9], "note": "空気の抵抗を除けば、重さによらず同時に落ちる(ガリレオ)"}
|
|
6
|
+
// (JSON の終わり)</m-predict>
|
|
7
|
+
// 段階:0 = 問いと選択肢(と目盛り)。1 = 数の棒。answer-step(既定 2)= 答え(正しい選択肢に枠と ✓、ほかは薄く、note)
|
|
8
|
+
// 見る人の入力(仕様 §8.4「Viewer input」、Studio の約束事 §3):選択肢ごとの −1・+1 と数の欄(発表者が数える)、選択肢の名前を押すと「自分の予想」。
|
|
9
|
+
// 入力は (i, k, t) の外で、同じスライドにいるあいだは(段階を進めても戻っても)残る。ほかのスライドから入ったとき・飛んだとき(ctx.entered)だけ作者の counts に戻る。
|
|
10
|
+
// ctx.reset(触った部品を段階に入るときに戻す)では、触った跡(欄やボタンのフォーカス)だけを戻し、数と予想は残す(仕様 §8.4)
|
|
11
|
+
// 動画(?mode=video)では操作を作らず、input() も受け付けない。印刷では操作を隠し、作者の数を字で出す
|
|
12
|
+
// live(拡張 live §2.5):poll="p1" と書き、ctx.live があれば ctx.live.poll("p1") の数(number[] | null)を棒に出す。
|
|
13
|
+
// 見せてよいか(先生が見せると決めたか、3 人以上か)は実行系が決める。部品は配列が来たときだけ出し、動画・印刷では出さない
|
|
14
|
+
// 見せ方(docs/conventions.md §1):fade(0。棒と答えの印がフェードして現れる)・draw(棒が上の選択肢から順に現れ、答えの枠を線で引く。長さは同じ)
|
|
15
|
+
// 2.0(Egatari spec §6.1 の部品):base の MotionElement・el・mtext・prog・variant を使い、プレイヤーのグローバルは使わない。
|
|
16
|
+
// 見る人の入力を戻すのは ctx.entered だけ(1.x の deck:pos の代わりはない)。動画かどうかは mount の ctx.mode。
|
|
17
|
+
// 要素の大きさの問題は ctx.report("size", …)。印刷の前後は document.defaultView の beforeprint・afterprint
|
|
18
|
+
egatariParts.define({name: "predict", version: "2.3.0", requires: {base: "1.3.0"}, element: "m-predict"}, function(deps){
|
|
19
|
+
"use strict";
|
|
20
|
+
var base = deps.base;
|
|
21
|
+
// 表示の文字(ctx.lang、見る人の言語ではなく文書の言語)。correct は子の JSON の labels.correct で上書きできる
|
|
22
|
+
var TEXT = {
|
|
23
|
+
ja: {
|
|
24
|
+
correct: "✓ 正解",
|
|
25
|
+
noteWrong: "予想ははずれ。", noteRight: "予想は当たり。",
|
|
26
|
+
liveResults: "投票の結果",
|
|
27
|
+
guessLabel: function(label){ return "予想:" + label; },
|
|
28
|
+
countGroup: function(label){ return label + "の数"; },
|
|
29
|
+
countField: function(label, unit){ return label + "の数" + (unit ? "(" + unit + ")" : ""); },
|
|
30
|
+
decrease: function(label){ return label + ":1 減らす"; },
|
|
31
|
+
increase: function(label){ return label + ":1 増やす"; },
|
|
32
|
+
countAnnounce: function(label, v, unit){ return label + ":" + v + unit; },
|
|
33
|
+
unpicked: "予想を外しました",
|
|
34
|
+
pickedRight: function(label){ return "当たり:" + label; },
|
|
35
|
+
pickedWrong: function(label){ return "はずれ。答えは " + label; },
|
|
36
|
+
myGuess: function(label){ return "あなたの予想:" + label; },
|
|
37
|
+
answerAnnounce: function(label, note){ return "答え:" + label + (note ? "。" + note : ""); },
|
|
38
|
+
},
|
|
39
|
+
en: {
|
|
40
|
+
correct: "✓ Correct",
|
|
41
|
+
noteWrong: "Wrong. ", noteRight: "Right! ",
|
|
42
|
+
liveResults: "Poll results",
|
|
43
|
+
guessLabel: function(label){ return "Guess: " + label; },
|
|
44
|
+
countGroup: function(label){ return label + " count"; },
|
|
45
|
+
countField: function(label, unit){ return label + " count" + (unit ? " (" + unit + ")" : ""); },
|
|
46
|
+
decrease: function(label){ return label + ": decrease by 1"; },
|
|
47
|
+
increase: function(label){ return label + ": increase by 1"; },
|
|
48
|
+
countAnnounce: function(label, v, unit){ return label + ": " + v + (unit ? " " + unit : ""); },
|
|
49
|
+
unpicked: "Guess cleared",
|
|
50
|
+
pickedRight: function(label){ return "Correct: " + label; },
|
|
51
|
+
pickedWrong: function(label){ return "Wrong. The answer is " + label; },
|
|
52
|
+
myGuess: function(label){ return "My guess: " + label; },
|
|
53
|
+
answerAnnounce: function(label, note){ return "Answer: " + label + (note ? ". " + note : ""); },
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
var CSS_ID = "predict-2-1-1-css"; // the style element this part writes, named with its name and version (spec §6.1 Identifiers)
|
|
57
|
+
var CSS = [
|
|
58
|
+
"m-predict .pd-say{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}",
|
|
59
|
+
"m-predict .pd-pick{position:absolute;background:transparent;border:0;border-radius:10px;cursor:pointer;padding:0;margin:0}",
|
|
60
|
+
"m-predict .pd-pick:focus-visible,m-predict .pd-btn:focus-visible,m-predict .pd-num:focus-visible{outline:3px solid var(--emph);outline-offset:2px}",
|
|
61
|
+
"m-predict .pd-ctl{position:absolute;display:flex;gap:8px;align-items:center;height:48px}",
|
|
62
|
+
"m-predict .pd-btn{width:60px;height:48px;font:700 27px/1 var(--font-cap,var(--font-sans,sans-serif));color:var(--fg);background:var(--bg);border:2px solid var(--term);border-radius:8px;cursor:pointer;padding:0;touch-action:manipulation}",
|
|
63
|
+
"m-predict .pd-btn:active{background:var(--term-tint)}",
|
|
64
|
+
"m-predict .pd-num{width:80px;height:48px;box-sizing:border-box;font:700 27px/1 var(--font-cap,var(--font-sans,sans-serif));font-variant-numeric:tabular-nums;text-align:center;color:var(--fg);background:var(--bg);border:2px solid var(--muted);border-radius:8px;padding:0}",
|
|
65
|
+
"@media print{m-predict .pd-ctl,m-predict .pd-pick,m-predict .pd-mark,m-predict .pd-live{display:none!important}}",
|
|
66
|
+
].join("\n");
|
|
67
|
+
return class extends base.MotionElement {
|
|
68
|
+
static partName = "predict"; // the registry name (define meta name), for report prefixes
|
|
69
|
+
static variants = ["fade", "draw"];
|
|
70
|
+
static interactive = true; // 操作できるパーツ(docs/conventions.md §6)
|
|
71
|
+
static viewerInput = true; // 見る人の入力を受け付ける(仕様 §8.4)
|
|
72
|
+
static preview = "none"; // 先の段階は答えなので、授業の表示でも先を見せない(仕様 §8.4、docs/conventions.md §1.2)
|
|
73
|
+
static questions = ["q"]; // 問いの id(仕様 §8.4 questions):プレーヤーはファイルを開いた時点でこれを数え、完了の条件と SCORM の点数に使う(仕様 §9.2)
|
|
74
|
+
// データの形(kit/shape.js)
|
|
75
|
+
static shape = {
|
|
76
|
+
schema: {type: "object", additionalProperties: false, required: ["choices", "answer"], properties: {
|
|
77
|
+
question: {type: "string"},
|
|
78
|
+
choices: {type: "array", minItems: 2, maxItems: 6, items: {type: "object", additionalProperties: false, required: ["label"], properties: {
|
|
79
|
+
label: {type: "string"}, tone: {type: "string"}}}},
|
|
80
|
+
answer: {type: "integer"},
|
|
81
|
+
counts: {type: "array", items: {type: "integer"}},
|
|
82
|
+
note: {type: "string"},
|
|
83
|
+
labels: {type: "object", additionalProperties: false, properties: {correct: {type: "string"}}}}},
|
|
84
|
+
example: {question: "重い球と軽い球、どちらが先に落ちる?", choices: [{label: "重い球"}, {label: "軽い球"}, {label: "同時"}], answer: 2, counts: [14, 3, 9], note: "空気の抵抗を除けば同時に落ちる"},
|
|
85
|
+
note: {en: "choices are objects {\"label\": …} (not strings); answer is the 0-based index of the right choice; counts (optional) has one whole number ≥ 0 per choice",
|
|
86
|
+
ja: "choices は {\"label\": …} の並び(字の並びではない)。answer は正しい選択肢の番号(0 から数える)。counts(省略可)は選択肢ごとに 0 以上の整数を 1 つずつ"},
|
|
87
|
+
};
|
|
88
|
+
static props = {
|
|
89
|
+
"answer-step": {type: "number", default: 2, doc: "2 以上(既定 2)。人数を数えるステップ 1 のあとに答えを開く"},
|
|
90
|
+
unit: {type: "string", default: "", doc: "数の単位(人 など)"},
|
|
91
|
+
poll: {type: "string", default: "", doc: "live の投票の id(live 拡張のある再生で、見せてよいと決まった集計を棒に出す)"},
|
|
92
|
+
ticks: {type: "bool", default: true, doc: "数の軸の目盛りと格子"},
|
|
93
|
+
};
|
|
94
|
+
get aStep(){ return Math.max(1, Math.round(this.props["answer-step"]) || 2); }
|
|
95
|
+
get steps(){ return this.getAttribute("steps") !== null ? +this.getAttribute("steps") : this.aStep; }
|
|
96
|
+
// 作者の数(counts。書かなければ全部 0)
|
|
97
|
+
get author(){
|
|
98
|
+
var d = this.data || {}, n = (d.choices || []).length;
|
|
99
|
+
// 9999 まで(−1・+1 と数の欄が扱う数の上限。mount で知らせる)
|
|
100
|
+
return Array.from({length: n}, function(_, i){ var v = d.counts && d.counts[i]; return Number.isInteger(v) && v > 0 ? Math.min(9999, v) : 0; });
|
|
101
|
+
}
|
|
102
|
+
mount(ctx){
|
|
103
|
+
var self = this, d = this.data || {}, n = (d.choices || []).length;
|
|
104
|
+
this.T = /^ja\b/i.test(ctx.lang || "") ? TEXT.ja : TEXT.en;
|
|
105
|
+
if (!(d.answer >= 0 && d.answer < n)) throw new Error("answer " + d.answer + " is not a choice index (0–" + (n - 1) + ")");
|
|
106
|
+
if (d.counts && d.counts.length !== n) throw new Error("counts has " + d.counts.length + " numbers for " + n + " choices");
|
|
107
|
+
if (d.counts && d.counts.some(function(v){ return v < 0; })) throw new Error("counts must be 0 or more");
|
|
108
|
+
var big = (d.counts || []).filter(function(v){ return v > 9999; });
|
|
109
|
+
if (big.length) ctx.report("data", "[predict] counts " + big.join(", ") + " are more than 9999, the most the −1/+1 buttons and the field take; 9999 is shown");
|
|
110
|
+
this.variant = base.variant(this);
|
|
111
|
+
this.video = ctx.mode === "video";
|
|
112
|
+
// 答えの知らせ(2.2.0、仕様 §8.4 ctx.answer):答えのステップに予想を選んだ状態で着いたとき、そのときの予想の正誤と選択肢を渡す(render)。ctx.answer の無いプレーヤーでは何もしない
|
|
113
|
+
this._answer = typeof ctx.answer === "function" ? ctx.answer : null;
|
|
114
|
+
this.style.display = "block"; this.style.position = "relative";
|
|
115
|
+
if (!document.getElementById(CSS_ID)){ var st = document.createElement("style"); st.id = CSS_ID; st.textContent = CSS; document.head.appendChild(st); }
|
|
116
|
+
// 読み上げソフトへの知らせ
|
|
117
|
+
this.say = document.createElement("div"); this.say.className = "pd-say"; this.say.setAttribute("role", "status"); this.say.setAttribute("aria-live", "polite");
|
|
118
|
+
this.appendChild(this.say);
|
|
119
|
+
if (d.question) this.setAttribute("aria-label", d.question);
|
|
120
|
+
// 印刷は作者の値で描く(画面の数は消さない。afterprint で戻す)。beforeprint・afterprint は文書の窓(document.defaultView)に来る
|
|
121
|
+
var view = document.defaultView;
|
|
122
|
+
if (!this.video && view){
|
|
123
|
+
view.addEventListener("beforeprint", function(){ self._printing = true; self.redraw(); });
|
|
124
|
+
view.addEventListener("afterprint", function(){ self._printing = false; self.redraw(); });
|
|
125
|
+
}
|
|
126
|
+
this.place(ctx);
|
|
127
|
+
}
|
|
128
|
+
// 配置が変わった知らせ(仕様 §8.4 layout):要素の大きさが mount のときと変わったときだけ置き直す(変換で縮めるだけなら呼ばれない。
|
|
129
|
+
// 横に並んだ文の字が後から読み込まれて、段組みの中の幅が変わるときなど)。大きさ 0(隠れている)なら前の配置のまま
|
|
130
|
+
layout(ctx){
|
|
131
|
+
var W = this.clientWidth, H = this.clientHeight;
|
|
132
|
+
if (!W || !H || (W === this.g.W && H === this.g.H)) return;
|
|
133
|
+
// フォーカスが操作の中にあれば、作り直した同じ行・同じ場所の操作に戻す(字の読み込みや画面の切り替えで呼ばれても、キーボードや読み上げソフトで使う人に見えないように)
|
|
134
|
+
var a = document.activeElement, keep = null;
|
|
135
|
+
if (a && a !== this && this.contains(a)) this.rows.forEach(function(r, i){
|
|
136
|
+
if (a === r.pick) keep = {i: i, at: -1};
|
|
137
|
+
else if (r.ctl && r.ctl.contains(a)) keep = {i: i, at: Array.prototype.indexOf.call(r.ctl.children, a), sel: a === r.field ? [a.selectionStart, a.selectionEnd] : null};
|
|
138
|
+
});
|
|
139
|
+
this.place(ctx);
|
|
140
|
+
this.redraw();
|
|
141
|
+
var r = keep && this.rows[keep.i], e = r && (keep.at < 0 ? r.pick : r.ctl && r.ctl.children[keep.at]);
|
|
142
|
+
if (e){
|
|
143
|
+
e.focus({preventScroll: true});
|
|
144
|
+
if (keep.sel && keep.sel[0] != null) try { e.setSelectionRange(keep.sel[0], keep.sel[1]); } catch (x) {}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
// 大きさで決まる絵と操作を作る。数と予想(見る人の入力)・読み上げの知らせは残す(フォーカスは layout が戻す)
|
|
148
|
+
place(ctx){
|
|
149
|
+
var self = this, P = this.props, D = base, d = this.data || {}, ch = d.choices || [], n = ch.length, T = this.T;
|
|
150
|
+
var correctLabel = (d.labels && d.labels.correct) || T.correct;
|
|
151
|
+
var W = this.clientWidth, H = this.clientHeight, inter = !this.video;
|
|
152
|
+
if (this.svg){
|
|
153
|
+
this.svg.remove();
|
|
154
|
+
this.rows.forEach(function(r){ if (r.pick) r.pick.remove(); if (r.ctl) r.ctl.remove(); });
|
|
155
|
+
}
|
|
156
|
+
// 字の幅(base の textWidth:テーマの字で測った幅。mk:mtext で書く字で、*_^ は数えない)
|
|
157
|
+
var est = function(s, size, mk){ return D.textWidth(s, size, {font: self, mark: !!mk}); };
|
|
158
|
+
// 縦:問い・行・目盛り・注(と予想の当たり外れ)
|
|
159
|
+
var qh = d.question ? 54 : 0, nh = d.note || inter ? 50 : 0, tb = P.ticks ? 40 : 8;
|
|
160
|
+
var rh = Math.min(88, (H - qh - nh - tb) / n);
|
|
161
|
+
if (inter && rh < 54) ctx.report("size", "[predict] rows are " + rh.toFixed(0) + " px high; the −1/+1 buttons need 54 (make the element taller or use fewer choices)");
|
|
162
|
+
// 横:予想の印・選択肢の名前・棒・数と「正解」・操作
|
|
163
|
+
var mk = inter ? 40 : 0, LS = 26;
|
|
164
|
+
var lw = Math.min(W * 0.34, Math.max.apply(null, ch.map(function(c){ return est(c.label, LS, true); })) + 16);
|
|
165
|
+
var cw = inter ? 232 : 0;
|
|
166
|
+
var valW = est("9999" + P.unit, 26) + 12, okW = est(correctLabel, 26) + 16;
|
|
167
|
+
// 棒の軸の長さ:選択肢の名前・数・「正解」・操作の残り。BARMIN px より短ければ知らせ、その長さは残す(負の長さで棒が消え、目盛りが重ならないように)
|
|
168
|
+
var x0 = mk + lw + 8, x1 = W - cw - valW - okW - 8, BARMIN = 120;
|
|
169
|
+
if (x1 < x0 + BARMIN){ ctx.report("size", "[predict] the element is " + W + " px wide; the bars get " + Math.round(x1 - x0) + " px, less than " + BARMIN + " (make it about " + Math.ceil(W + x0 + BARMIN - x1) + " px wide or shorten the labels)"); x1 = x0 + BARMIN; }
|
|
170
|
+
this.g = {W: W, H: H, qh: qh, nh: nh, rh: rh, mk: mk, lw: lw, cw: cw,
|
|
171
|
+
x0: x0, x1: x1, y0: qh, y1: qh + rh * n};
|
|
172
|
+
var G = this.g;
|
|
173
|
+
var svg = this.svg = D.el("svg", {viewBox: "0 0 " + W + " " + H, width: W, height: H, style: "display:block;overflow:visible"});
|
|
174
|
+
this.insertBefore(svg, this.say);
|
|
175
|
+
var fitText = function(el, s, max, size, what, mk){
|
|
176
|
+
var z = size;
|
|
177
|
+
while (z > 24 && est(s, z, mk) > max) z--;
|
|
178
|
+
if (est(s, z, mk) > max) ctx.report("size", "[predict] the " + what + " does not fit (" + Math.ceil(est(s, z, mk) - max) + " px too wide at 24 px); shorten it");
|
|
179
|
+
el.setAttribute("font-size", z);
|
|
180
|
+
return el;
|
|
181
|
+
};
|
|
182
|
+
if (d.question) fitText(D.mtext(svg, 0, 36, d.question, {"font-size": 30, "font-weight": 700}), d.question, W - 8, 30, "question", true);
|
|
183
|
+
// 答えの枠(行の後ろ)
|
|
184
|
+
this.frame = D.el("rect", {x: 2, y: 0, width: Math.max(0, W - cw - 12), height: Math.max(0, rh - 8), rx: 10, fill: "none", stroke: "var(--emph)", "stroke-width": 3, opacity: 0}, svg);
|
|
185
|
+
this.frameLen = 2 * (W - cw - 12 + rh - 8);
|
|
186
|
+
// 目盛り(数の軸の上限は数で決まるので、render で置き直す。入れ物は先に作る)
|
|
187
|
+
var gT = D.el("g", {}, svg);
|
|
188
|
+
this.ticks = !P.ticks ? [] : Array.from({length: 8}, function(){
|
|
189
|
+
return {grid: D.el("line", {stroke: "var(--line)", "stroke-width": 1.2, y1: G.y0 + 4, y2: G.y1}, gT),
|
|
190
|
+
text: D.el("text", {"font-size": 24, "text-anchor": "middle", y: G.y1 + 30, style: "font-variant-numeric:tabular-nums"}, gT)};
|
|
191
|
+
});
|
|
192
|
+
if (P.ticks){ var z = D.el("text", {"font-size": 24, "text-anchor": "middle", x: G.x0, y: G.y1 + 30}, gT); z.textContent = "0"; }
|
|
193
|
+
D.el("line", {x1: G.x0, y1: G.y0 + 4, x2: G.x0, y2: G.y1, stroke: "var(--fg)", "stroke-width": 1.5}, svg);
|
|
194
|
+
var bw = Math.max(0, Math.min(46, rh * 0.56));
|
|
195
|
+
this.rows = ch.map(function(c, i){
|
|
196
|
+
var cy = G.y0 + rh * (i + 0.5), col = tone(c.tone);
|
|
197
|
+
var r = {cy: cy, col: col,
|
|
198
|
+
mark: inter ? D.el("circle", {cx: 16, cy: cy, r: 11, fill: "none", stroke: "var(--term)", "stroke-width": 2.5, "class": "pd-mark"}, svg) : null,
|
|
199
|
+
dot: inter ? D.el("circle", {cx: 16, cy: cy, r: 6, fill: "var(--term)", opacity: 0, "class": "pd-mark"}, svg) : null,
|
|
200
|
+
bar: D.el("rect", {x: G.x0, y: (cy - bw / 2).toFixed(1), height: bw.toFixed(1), rx: 3, fill: col, opacity: 0}, svg),
|
|
201
|
+
label: fitText(D.mtext(svg, mk + lw, cy + 9, c.label, {"text-anchor": "end", "font-size": LS}), c.label, lw - 8, LS, "label " + JSON.stringify(c.label), true),
|
|
202
|
+
val: D.el("text", {"font-size": 26, "font-weight": 700, y: (cy + 9).toFixed(1), opacity: 0, style: "font-variant-numeric:tabular-nums"}, svg)};
|
|
203
|
+
if (i === d.answer) r.ok = D.el("text", {"font-size": 26, "font-weight": 700, y: (cy + 9).toFixed(1), fill: "var(--emph)", opacity: 0}, svg);
|
|
204
|
+
if (r.ok) r.ok.textContent = correctLabel;
|
|
205
|
+
return r;
|
|
206
|
+
});
|
|
207
|
+
this.bw = bw;
|
|
208
|
+
// 注(答えと一緒に)と、予想の当たり外れ(見る人が予想したときだけ)
|
|
209
|
+
this.noteEl = D.el("text", {x: 0, y: H - 14, "font-size": 26, opacity: 0}, svg);
|
|
210
|
+
this.noteText = d.note || "";
|
|
211
|
+
if (d.note){ var notePrefix = est(T.noteWrong, 26) >= est(T.noteRight, 26) ? T.noteWrong : T.noteRight; fitText(this.noteEl, notePrefix + d.note, W - 8, 26, "note"); }
|
|
212
|
+
// live の集計の見出し(集計を出すときだけ)
|
|
213
|
+
this.liveEl = D.el("text", {x: W, y: G.y1 + 30, "font-size": 24, "text-anchor": "end", opacity: 0, "class": "pd-live"}, svg);
|
|
214
|
+
this.liveEl.textContent = T.liveResults;
|
|
215
|
+
// 操作:選択肢の名前(自分の予想)、−1・数の欄・+1。動画では作らない
|
|
216
|
+
if (inter){
|
|
217
|
+
var mkEl = function(tag, cls, attrs){ var e = document.createElement(tag); e.className = cls; for (var a in attrs) e.setAttribute(a, attrs[a]); self.appendChild(e); return e; };
|
|
218
|
+
var unit = P.unit;
|
|
219
|
+
this.rows.forEach(function(r, i){
|
|
220
|
+
var top = r.cy - 24;
|
|
221
|
+
r.pick = mkEl("button", "pd-pick", {type: "button", "aria-pressed": "false", "aria-label": T.guessLabel(ch[i].label)});
|
|
222
|
+
Object.assign(r.pick.style, {left: "0px", top: (r.cy - rh / 2 + 4) + "px", width: (mk + lw) + "px", height: (rh - 8) + "px"});
|
|
223
|
+
r.pick.addEventListener("click", function(e){ e.stopPropagation(); self.choose(i); });
|
|
224
|
+
var ctl = r.ctl = mkEl("div", "pd-ctl", {role: "group", "aria-label": T.countGroup(ch[i].label)});
|
|
225
|
+
Object.assign(ctl.style, {left: (W - cw + 16) + "px", top: top + "px"});
|
|
226
|
+
var bt = function(txt, dlt, ariaLabel){
|
|
227
|
+
var b = document.createElement("button"); b.type = "button"; b.className = "pd-btn"; b.textContent = txt; b.setAttribute("aria-label", ariaLabel);
|
|
228
|
+
b.addEventListener("click", function(e){ e.stopPropagation(); self.bump(i, dlt); });
|
|
229
|
+
b.addEventListener("keydown", function(e){ self.key(e, i, false); });
|
|
230
|
+
return b;
|
|
231
|
+
};
|
|
232
|
+
ctl.appendChild(bt("−1", -1, T.decrease(ch[i].label)));
|
|
233
|
+
var f = r.field = document.createElement("input");
|
|
234
|
+
f.type = "text"; f.className = "pd-num"; f.setAttribute("inputmode", "numeric"); f.setAttribute("autocomplete", "off");
|
|
235
|
+
f.setAttribute("aria-label", T.countField(ch[i].label, unit));
|
|
236
|
+
f.addEventListener("keydown", function(e){ self.key(e, i, true); });
|
|
237
|
+
f.addEventListener("input", function(){
|
|
238
|
+
var s = f.value.replace(/[^0-9]/g, "").slice(0, 4);
|
|
239
|
+
if (s !== f.value) f.value = s;
|
|
240
|
+
self.set(i, s === "" ? 0 : +s);
|
|
241
|
+
});
|
|
242
|
+
f.addEventListener("change", function(){ f.value = String(self.counts()[i]); });
|
|
243
|
+
ctl.appendChild(f);
|
|
244
|
+
ctl.appendChild(bt("+1", 1, T.increase(ch[i].label)));
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
function tone(t){ return /^(term|emph|muted|accent2|fg|series-[1-4])$/.test(t || "") ? "var(--" + t + ")" : "var(--term)"; }
|
|
248
|
+
}
|
|
249
|
+
// ---- 見る人の状態((i, k, t) の外)
|
|
250
|
+
// 今の数(見る人が変えていればその値、そうでなければ作者の値)。新しい配列を返す
|
|
251
|
+
counts(){ return (this._vc || this.author).slice(); }
|
|
252
|
+
// 発表者の画面から(Studio が呼ぶ):choice は 0 から数える選択肢の番号、count は新しい数(0 以上の整数)
|
|
253
|
+
input(choice, count){
|
|
254
|
+
if (this.video) return;
|
|
255
|
+
var n = this.author.length;
|
|
256
|
+
if (!Number.isInteger(choice) || choice < 0 || choice >= n || !Number.isInteger(count) || count < 0 || count > 9999){
|
|
257
|
+
console.warn("[predict] input(" + JSON.stringify(choice) + ", " + JSON.stringify(count) + ") ignored (choice 0–" + (n - 1) + ", count a whole number 0–9999)");
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
this.set(choice, count);
|
|
261
|
+
}
|
|
262
|
+
bump(i, dl){ this.set(i, this.counts()[i] + dl); }
|
|
263
|
+
set(i, v){
|
|
264
|
+
if (this.video || !this.rows) return;
|
|
265
|
+
v = Math.max(0, Math.min(9999, v));
|
|
266
|
+
var c = this.counts();
|
|
267
|
+
if (c[i] === v) return;
|
|
268
|
+
c[i] = v; this._vc = c;
|
|
269
|
+
this.redraw();
|
|
270
|
+
this.say.textContent = this.T.countAnnounce(this.data.choices[i].label, v, this.props.unit);
|
|
271
|
+
this.emit();
|
|
272
|
+
}
|
|
273
|
+
// 自分の予想(1 つ。もう一度押すと外す)
|
|
274
|
+
choose(i){
|
|
275
|
+
if (this.video) return;
|
|
276
|
+
var d = this.data, T = this.T;
|
|
277
|
+
this._pick = this._pick === i ? null : i;
|
|
278
|
+
this.redraw();
|
|
279
|
+
var lab = d.choices[i].label;
|
|
280
|
+
this.say.textContent = this._pick === null ? T.unpicked : this.revealed() ? (i === d.answer ? T.pickedRight(lab) : T.pickedWrong(d.choices[d.answer].label)) : T.myGuess(lab);
|
|
281
|
+
}
|
|
282
|
+
revealed(){ return this._k !== undefined && this._k >= this.aStep; }
|
|
283
|
+
key(e, i, field){
|
|
284
|
+
var k = e.key, up = k === "+" || k === "ArrowUp" || (!field && k === "ArrowRight"), dn = k === "-" || k === "−" || k === "ArrowDown" || (!field && k === "ArrowLeft");
|
|
285
|
+
if (up || dn){ e.preventDefault(); e.stopPropagation(); this.bump(i, up ? 1 : -1); return; }
|
|
286
|
+
if (field){
|
|
287
|
+
// 欄の中のキー(数字・矢印・Space など)はスライドを動かさない。Esc で欄を出る
|
|
288
|
+
e.stopPropagation();
|
|
289
|
+
if (k === "Escape" || k === "Enter") e.target.blur();
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
emit(){ this.dispatchEvent(new CustomEvent("egatari-input", {bubbles: true, detail: {counts: this.counts()}})); }
|
|
293
|
+
// 見る人の状態を捨てて作者の値に戻す。数を変えていたら知らせる
|
|
294
|
+
reset(){
|
|
295
|
+
var had = !!this._vc;
|
|
296
|
+
if (!had && this._pick == null) return false;
|
|
297
|
+
this._vc = null; this._pick = null;
|
|
298
|
+
if (had) this.emit();
|
|
299
|
+
return true;
|
|
300
|
+
}
|
|
301
|
+
// 触った跡だけを戻す(ctx.reset):部品の中のフォーカスを外す(欄は今の数を出し直す)。数と予想(見る人の入力)は残す
|
|
302
|
+
untouch(){
|
|
303
|
+
var a = document.activeElement;
|
|
304
|
+
if (a && a !== this && this.contains(a) && a.blur) a.blur();
|
|
305
|
+
}
|
|
306
|
+
// 入力のあとの描き直し:最後の (k, t) で paint だけを呼ぶ(render を通さないので、ctx.entered・ctx.reset を繰り返さない)
|
|
307
|
+
redraw(){ if (this._k !== undefined) this.paint(this._k, this._t, this._ctx); }
|
|
308
|
+
duration(k){
|
|
309
|
+
var a = this.aStep, d = 0;
|
|
310
|
+
if (k === 1) d = 0.6;
|
|
311
|
+
if (k === a) d += 0.6;
|
|
312
|
+
return d;
|
|
313
|
+
}
|
|
314
|
+
render(k, t, ctx){
|
|
315
|
+
// ほかのスライドから入ったとき・飛んだとき(ctx.entered)だけ、見る人の状態を捨てる。同じスライドの中の段階の移りでは残す。
|
|
316
|
+
// ctx.reset(触った部品が段階に入るとき)は触った跡だけを戻し、見る人の入力は消さない(仕様 §8.4)
|
|
317
|
+
if (ctx.entered === true) this.reset();
|
|
318
|
+
if (ctx.reset) this.untouch();
|
|
319
|
+
// 答えのステップに着いたとき(その前は答えより前のステップか、初めての描画)に予想があれば 1 回知らせる。同じステップの描き直しでは知らせない。
|
|
320
|
+
// 戻ってまた着けばもう 1 回。問いは部品に 1 つなので id は "q"。動画・印刷では知らせない
|
|
321
|
+
var a = this.aStep, was = this._k !== undefined && this._k >= a;
|
|
322
|
+
if (k >= a && !was && this._pick != null && this._answer && !this.video && !this._printing)
|
|
323
|
+
this._answer("q", this._pick === this.data.answer, String(this.data.choices[this._pick].label));
|
|
324
|
+
this._k = k; this._t = t; this._ctx = {mode: ctx.mode, preview: ctx.preview, live: ctx.live};
|
|
325
|
+
this.paint(k, t, this._ctx);
|
|
326
|
+
}
|
|
327
|
+
// (k, t) と見る人の状態の絵。ctx は {mode, preview, live}
|
|
328
|
+
paint(k, t, ctx){
|
|
329
|
+
var self = this, P = this.props, D = base, G = this.g, dd = this.data, n = this.rows.length, vr = this.variant, T = this.T;
|
|
330
|
+
var a = this.aStep;
|
|
331
|
+
// 数:live の集計(実行系が見せてよいと渡したときだけ)→ 見る人の数 → 作者の数
|
|
332
|
+
var live = null;
|
|
333
|
+
if (P.poll && ctx && ctx.live && typeof ctx.live.poll === "function" && !this.video && !this._printing){
|
|
334
|
+
var lv = ctx.live.poll(P.poll);
|
|
335
|
+
if (Array.isArray(lv)) live = Array.from({length: n}, function(_, i){ var v = +lv[i]; return isFinite(v) && v > 0 ? Math.round(v) : 0; });
|
|
336
|
+
}
|
|
337
|
+
var c = live || (this._printing ? this.author : this.counts()), pick = this._printing ? null : this._pick;
|
|
338
|
+
// 段階 1 の棒(draw は上から順に、同じ長さの中で)、答えの段階
|
|
339
|
+
// 先の段階は授業の表示(ctx.preview)でも見せない:予想する前に棒や答えが見えてはいけない(static preview = "none")
|
|
340
|
+
var e1 = k > 1 ? 1 : k < 1 ? 0 : null;
|
|
341
|
+
var at1 = 0, ea = k > a ? 1 : k < a ? 0 : D.prog(t, a === 1 ? 0.6 : 0, 0.6);
|
|
342
|
+
var rowE = function(j){
|
|
343
|
+
if (e1 !== null) return e1;
|
|
344
|
+
if (vr === "draw"){ var s = n > 1 ? 0.3 / (n - 1) : 0; return D.prog(t, at1 + j * s, 0.3); }
|
|
345
|
+
return D.prog(t, at1, 0.6);
|
|
346
|
+
};
|
|
347
|
+
// 数の軸
|
|
348
|
+
var M = nice(Math.max(4, Math.max.apply(null, c)) * 1.12), len = G.x1 - G.x0, X = function(v){ return G.x0 + Math.min(v, M) / M * len; };
|
|
349
|
+
var ts = Math.max(1, tickStep(M)), ti = 0;
|
|
350
|
+
// 短い軸では目盛りの数が重ならない間隔まで広げる(数の幅+16 px)
|
|
351
|
+
while (ts < M && len * ts / M < est(String(Math.ceil(M)), 24) + 16) ts = up(ts);
|
|
352
|
+
this.ticks.forEach(function(o, j){
|
|
353
|
+
var v = (j + 1) * ts, on = v <= M + 1e-9;
|
|
354
|
+
o.grid.setAttribute("x1", X(v).toFixed(1)); o.grid.setAttribute("x2", X(v).toFixed(1));
|
|
355
|
+
o.text.setAttribute("x", X(v).toFixed(1)); o.text.textContent = on ? String(v) : "";
|
|
356
|
+
o.grid.setAttribute("opacity", on ? 0.8 : 0); o.text.setAttribute("opacity", on ? 1 : 0);
|
|
357
|
+
});
|
|
358
|
+
var shown = ea > 0.5;
|
|
359
|
+
this.rows.forEach(function(r, j){
|
|
360
|
+
var e = rowE(j), isA = j === dd.answer, dim = isA ? 1 : 1 - 0.65 * ea;
|
|
361
|
+
r.bar.setAttribute("width", Math.max(0, X(c[j]) - G.x0).toFixed(1));
|
|
362
|
+
r.bar.setAttribute("opacity", (e * dim).toFixed(3));
|
|
363
|
+
r.val.textContent = self.fmt(c[j]);
|
|
364
|
+
r.val.setAttribute("x", (X(c[j]) + 10).toFixed(1));
|
|
365
|
+
r.val.setAttribute("opacity", e.toFixed(3));
|
|
366
|
+
// 答えを開いたら、ほかの選択肢の字は --muted(読める濃さのまま)
|
|
367
|
+
var txt = !isA && shown ? "var(--muted)" : "var(--fg)";
|
|
368
|
+
r.val.style.fill = txt; r.label.style.fill = txt;
|
|
369
|
+
r.label.setAttribute("font-weight", isA && shown ? 700 : 400);
|
|
370
|
+
if (r.ok){ r.ok.setAttribute("x", (X(c[j]) + 10 + est(self.fmt(c[j]), 26) + 14).toFixed(1)); r.ok.setAttribute("opacity", ea.toFixed(3)); }
|
|
371
|
+
if (r.dot){ r.dot.setAttribute("opacity", pick === j ? 1 : 0); r.pick.setAttribute("aria-pressed", pick === j ? "true" : "false"); }
|
|
372
|
+
if (r.ctl){
|
|
373
|
+
r.ctl.style.display = k >= 1 && !live ? "" : "none";
|
|
374
|
+
if (document.activeElement !== r.field) r.field.value = String(c[j]);
|
|
375
|
+
}
|
|
376
|
+
});
|
|
377
|
+
// 答えの枠:fade はフェード、draw は線を引く(同じ長さ)
|
|
378
|
+
var fy = G.y0 + G.rh * dd.answer + 4;
|
|
379
|
+
this.frame.setAttribute("y", fy.toFixed(1));
|
|
380
|
+
if (vr === "draw" && ea > 0 && ea < 1){ this.frame.setAttribute("stroke-dasharray", this.frameLen.toFixed(0)); this.frame.setAttribute("stroke-dashoffset", (this.frameLen * (1 - ea)).toFixed(1)); this.frame.setAttribute("opacity", 1); }
|
|
381
|
+
else { this.frame.removeAttribute("stroke-dasharray"); this.frame.removeAttribute("stroke-dashoffset"); this.frame.setAttribute("opacity", ea.toFixed(3)); }
|
|
382
|
+
// 注と、予想の当たり外れ
|
|
383
|
+
var pk = pick, st = pk != null && k >= a ? (pk === dd.answer ? T.noteRight : T.noteWrong) : "";
|
|
384
|
+
this.noteEl.textContent = (k >= a ? st : "") + this.noteText;
|
|
385
|
+
this.noteEl.setAttribute("opacity", ea.toFixed(3));
|
|
386
|
+
this.liveEl.setAttribute("opacity", live && k >= 1 ? 1 : 0);
|
|
387
|
+
// 答えを開いた段階に入ったら知らせる(入力の知らせは set・choose が後から書く)
|
|
388
|
+
if (this._sayK !== k && !this.video){ this._sayK = k; this.say.textContent = k >= a ? T.answerAnnounce(dd.choices[dd.answer].label, this.noteText) : ""; }
|
|
389
|
+
function est(s, size){ return D.textWidth(s, size, {font: self}); }
|
|
390
|
+
function nice(v){ var e = Math.pow(10, Math.floor(Math.log10(v))), x = v / e;
|
|
391
|
+
return [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10].filter(function(s){ return s >= x - 1e-9; })[0] * e; }
|
|
392
|
+
function up(v){ var e = Math.pow(10, Math.floor(Math.log10(v))); return Math.round([1, 2, 5, 10, 20].filter(function(s){ return s * e > v + 1e-9; })[0] * e); }
|
|
393
|
+
function tickStep(M){ var r = M / 4.5, e = Math.pow(10, Math.floor(Math.log10(r))), x = r / e;
|
|
394
|
+
return Math.round((x <= 1 ? 1 : x <= 2 ? 2 : x <= 2.5 ? 2.5 : x <= 5 ? 5 : 10) * e); }
|
|
395
|
+
}
|
|
396
|
+
fmt(v){ return String(v).replace(/\B(?=(\d{3})+(?!\d))/g, ",") + this.props.unit; }
|
|
397
|
+
};
|
|
398
|
+
});
|