File size: 14,173 Bytes
d1f47f9
378f397
 
 
d1f47f9
 
 
ca6e756
 
5b3cd1e
 
378f397
ca6e756
378f397
 
d1f47f9
378f397
 
d1f47f9
 
ca6e756
 
d1f47f9
 
 
 
 
 
 
 
 
 
 
 
ca6e756
d1f47f9
de7cd1e
d1f47f9
 
 
 
ca6e756
5b3cd1e
d1f47f9
 
 
 
 
 
 
 
 
 
ca6e756
5b3cd1e
378f397
d1f47f9
 
 
 
 
ca6e756
 
 
d1f47f9
 
 
 
 
 
 
 
 
 
 
ca6e756
5b3cd1e
d1f47f9
 
378f397
 
d1f47f9
 
378f397
 
 
d1f47f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a59c3c4
 
d1f47f9
 
de7cd1e
d1f47f9
a59c3c4
d1f47f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a59c3c4
 
d1f47f9
 
 
a59c3c4
d1f47f9
a59c3c4
 
d1f47f9
 
 
 
 
378f397
 
d1f47f9
 
 
 
 
 
 
a59c3c4
d1f47f9
 
 
 
 
 
a59c3c4
 
d1f47f9
 
 
a59c3c4
d1f47f9
 
a59c3c4
d1f47f9
a59c3c4
d1f47f9
 
 
 
 
 
 
 
 
 
 
378f397
d1f47f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// The plan on the page: the answer that leads "Your picture", the panel beside the bell, each row, the curve's tooltip
// and the announcement when a picture is read; the distance and width controls; what a phone sees (phone.js) and the
// working behind "+"; and a file's code as made (made.js). A change of distance, width or what the picture shows
// redraws only these, in place, with no server call (plan.js).
import { $, el, textEl } from './util.js';
import { t } from './copy.js';
import { panelVerdict, prefixText, rowVerdict } from './verdict.js';
import { pairLines, pairWith } from './pair.js';
import { madeHead, madeLines, refreshMade } from './made.js';
import { refreshTest, testHead } from './test_view.js';
import { kindChanged } from './test.js';
import { phoneField, refreshPhone } from './phone.js';
import { loadCapacity } from './capacity.js';
import { fail, hintEl, lengthOf, mark, parseNumber, say } from './fields.js';
import { shapeField } from './shape_view.js';
import {
  answerLines, answerText, distanceCm, distanceKey, distances, distText, fileFirst, howLines, inRange, lastPreset,
  loadPlan as loadSizes, looksLikeFile, looksLikePhoto, planFor, rangeIn, rowLines, setDistance, tableHeads, tableRows,
} from './plan.js';

/** app.js: the page data the plan reads (sizes.json), with the QR standard's capacities a file's lines use. */
export const loadPlan = (url) => Promise.all([loadSizes(url), loadCapacity('data/capacity.json')]);

let onChange = () => {}; // app.js: the rows and the panel follow a change
/** app.js: what to redraw after a change, and its list of pictures (for pairing pictures of one code). */
export function whenPlanChanges(fn, pictures) {
  onChange = fn;
  pairWith(pictures);
}

let before = ''; // the answer the section showed before its last redraw (refreshPlan)

/** After what the picture shows changed (yours.js, which has redrawn the section): the rows and the panel follow, and
 *  what changed is said: the new answer, or the context when the answer stays (or can't be planned), with the "looks
 *  like" suggestion, and a file's as-made lines (made.js). */
export function planChanged(p, fallback) {
  if (p.made) p.made.chosen = true; // the visitor chose: a file's own details no longer mark it (record.js)
  const plan = planFor(p);
  const planned = plan && plan.mode !== 'cant';
  const answer = planned && answerText(plan) !== before ? answerText(plan) : '';
  onChange();
  say([answer || fallback, suggestion(p), ...madeLines(p, plan)].filter(Boolean).join(' '));
  kindChanged(p); // a design test settles, stops, or shows again
}

// ---- "Your picture" -----------------------------------------------------------------------------------------------

/** The section's head for a planned picture: the answer as its heading, the lines under it, then the distance, the
 *  width (a file only) and how it is worked out, each one step away. */
export function planHead(p) {
  return [
    el('h2', { id: 'yoursTitle', class: 'plan-answer', tabindex: '-1' }),
    el('div', { class: 'plan-lines' }),
    madeHead(),
    testHead(p),
    el('div', { class: 'plan-tools' }, [distanceField(p), widthField(p), shapeField(p, { update, unchanged }), phoneField(p), el('details', { class: 'more plan-how' }, [
      el('summary', { text: t('plan.how.summary') }), el('div', { class: 'more-body method' }),
    ])]),
  ];
}

/** Everything the plan changes in the section, in place: the answer, its lines, a file's as-made lines, whether the
 *  width shows, the working, the score in the kicker, and whether the reading sits behind "+" (a file planned by its
 *  own width). */
export function refreshPlan(box, p) {
  const plan = planFor(p);
  const file = fileFirst(plan);
  wrapReading(box, file);
  for (const s of box.querySelectorAll('.kicker-score')) s.hidden = file; // the score is the reading's
  refreshPair(box, p);
  if (!plan || plan.mode === 'cant') return;
  const h = box.querySelector('.plan-answer');
  if (h) { before = h.textContent; h.textContent = answerText(plan); }
  const lines = answerLines(p, plan);
  box.querySelector('.plan-lines')?.replaceChildren(...lines.map((s, i) => el('p', { class: i === lines.length - 1 ? 'plan-assume' : '', text: s })));
  refreshMade(box, p, plan);
  refreshTest(box, p, plan);
  const width = box.querySelector('.plan-width');
  if (width) width.hidden = !(p.kind === 'graphic' && plan.share);
  refreshPhone(box, p, plan); // what a phone sees, drawn again only while its "+" is open
  box.querySelector('.plan-how .more-body')?.replaceChildren(...howLines(plan).map((s) => el('p', { text: s })), howTable(plan), sheetLink());
}

/** The test sheet, in a tab of its own so that it prints true to size (sheet.html): the camera, with your own phone. */
const sheetLink = () => el('p', {}, el('a', { href: 'sheet.html', target: '_blank', rel: 'noopener', text: t('plan.how.sheet') }));

/** Whom the picture matches among the others, and what changed (pair.js); redrawn as the list changes. */
export function refreshPair(box, p) {
  box.querySelector('.pair')?.replaceChildren(...pairLines(p).map((s, i) => el('p', { class: i ? 'pair-change' : 'pair-same', text: s })));
}

/** A file planned by its own width: its reading, labelled, behind "+"; any other picture: in the open. */
function wrapReading(box, file) {
  const inner = box.querySelector('.reading');
  if (!inner || inner.parentElement.matches('.reading-file') === file) return;
  if (!file) {
    inner.parentElement.replaceWith(inner);
    return;
  }
  const wrap = el('details', { class: 'more reading-file' }, el('summary', { text: t('plan.file_reading') }));
  inner.replaceWith(wrap);
  wrap.append(inner);
}

/** "Looks like a file", or else "if this is the file" for a picture that repeats its code, under Not sure; "looks like
 *  a photo" under The original graphic: suggestions, never switches. */
export function suggestion(p) {
  const r = p.result;
  if (p.kind === 'graphic' && p.made?.marked && !p.made.chosen) return t('made.record.marked'); // its own details marked it (record.js)
  if (p.kind === 'unsure' && planFor(p)?.mode === 'code' && looksLikeFile(r)) return t('plan.suggest_file');
  if (p.kind === 'unsure' && planFor(p)?.copies) return t('plan.suggest_repeat');
  if (p.kind === 'graphic' && looksLikePhoto(r)) return t('plan.suggest_photo');
  return '';
}

function update(p, announce) {
  const box = $('yourPicture');
  if (box) refreshPlan(box, p);
  onChange();
  if (announce) say(answerText(planFor(p)));
}

/** Leaving a box whose value the page already shows: say the answer, and redraw nothing, so a click that moved the
 *  focus away (onto a row, say) lands where it was aimed. */
const unchanged = (p, announce) => { if (announce) say(answerText(planFor(p))); };

/** "Scanning from closer or further?": the four distances as native radios, and an exact one behind "+". */
function distanceField(p) {
  const exact = el('input', { id: 'planExact', class: 'plan-input', type: 'text', inputmode: 'decimal', autocomplete: 'off', 'aria-describedby': 'planExactHint' });
  if (distanceKey() === 'exact') exact.value = String(distanceCm());
  const [lo, hi] = rangeIn('distance_cm');
  const hint = hintEl('planExactHint', t('plan.exact_hint', { lo, hi }));
  const radios = distances().map((d) => {
    const input = el('input', { type: 'radio', name: 'plan-at', value: d.key, ...(distanceKey() === d.key ? { checked: '' } : {}) });
    input.addEventListener('change', () => { setDistance(d.key); exact.value = ''; mark(exact, '', hint); update(p, true); });
    return el('label', { class: 'opt' }, [input, el('span', { text: t(`plan.distance.${d.key}.label`, { d: distText(d.cm) }) })]);
  });
  const typed = (announce) => {
    const cm = parseNumber(exact.value);
    if (cm === undefined) { // emptied: back to the last of the four chosen
      mark(exact, '', hint);
      if (distanceKey() !== 'exact') { unchanged(p, announce); return; }
      setDistance(lastPreset());
      for (const r of radios) { const input = r.querySelector('input'); input.checked = input.value === lastPreset(); }
      update(p, announce);
      return;
    }
    if (inRange('distance_cm', cm) == null) { fail(exact, t('plan.exact_invalid', { lo, hi }), hint, announce); return; }
    mark(exact, '', hint);
    if (distanceKey() === 'exact' && distanceCm() === cm) { unchanged(p, announce); return; }
    setDistance('exact', cm);
    for (const r of radios) r.querySelector('input').checked = false;
    update(p, announce);
  };
  exact.addEventListener('input', () => typed(false));
  exact.addEventListener('change', () => typed(true));
  return el('details', { class: 'more plan-distance' }, [
    el('summary', { text: t('plan.distance_summary') }),
    el('div', { class: 'more-body' }, [
      el('fieldset', { class: 'plan-at' }, [el('legend', { class: 'visually-hidden', text: t('plan.distance_legend') }), el('div', { class: 'opts' }, radios)]),
      el('details', { class: 'more plan-exact', ...(distanceKey() === 'exact' ? { open: '' } : {}) }, [
        el('summary', { text: t('plan.exact_summary') }),
        el('div', { class: 'more-body plan-field' }, [el('label', { for: 'planExact', text: t('plan.exact_label') }), exact, hint]),
      ]),
    ]),
  ]);
}

/** "Know how wide it'll be?": a file's printed width, in cm, mm or inches (as a number, or a fraction: parseInches,
 *  with or without a trailing in, " or ″); the answer becomes how far it scans from. */
function widthField(p) {
  const id = `planWidth${p.n}`;
  const input = el('input', { id, class: 'plan-input', type: 'text', inputmode: 'decimal', autocomplete: 'off', 'aria-describedby': `${id}Hint` });
  const unit = el('select', { class: 'plan-unit', 'aria-label': t('plan.width_unit') }, ['cm', 'mm', 'in'].map((u) => el('option', { value: u, text: u })));
  if (p.width) { input.value = p.width.value; unit.value = p.width.unit; }
  const keypad = () => input.setAttribute('inputmode', unit.value === 'in' ? 'text' : 'decimal'); // a fraction needs "/"
  keypad();
  const [lo0, hi0] = rangeIn('width_cm', unit.value);
  const hint = hintEl(`${id}Hint`, t('plan.width_hint', { lo: lo0, hi: hi0 }));
  const typed = (announce) => {
    const [lo, hi] = rangeIn('width_cm', unit.value); // the range in the unit chosen
    hint.dataset.text = t('plan.width_hint', { lo, hi });
    const next = lengthOf(input.value, unit.value, 'width_cm') ?? null; // as the page read it, which the answer repeats
    if (next?.error) { fail(input, t(next.error, { lo, hi }), hint, announce); return; } // not a form it takes, or out of range
    mark(input, '', hint);
    if (next?.text === p.width?.text) { unchanged(p, announce); return; }
    p.width = next;
    update(p, announce);
  };
  input.addEventListener('input', () => typed(false));
  input.addEventListener('change', () => typed(true));
  unit.addEventListener('change', () => { keypad(); typed(input.value.trim() !== ''); }); // with no width typed, nothing to say
  return el('details', { class: 'more plan-width', ...(p.width ? { open: '' } : {}) }, [
    el('summary', { text: t('plan.width_summary') }),
    el('div', { class: 'more-body plan-field' }, [el('label', { for: id, text: t('plan.width_label') }), el('span', { class: 'plan-pair' }, [input, unit]), hint]),
  ]);
}

/** The measured table, the picture's own version marked; each distance and width with its inch figure on a second
 *  line (after a space, so it is read apart). */
function howTable(plan) {
  const rows = tableRows();
  const caption = t('plan.how.table_caption');
  const two = ([metric, inches]) => [metric, ...(inches ? [' ', el('span', { class: 'in', text: inches })] : [])];
  return el('div', { class: 'plan-table-wrap', role: 'region', 'aria-label': caption, tabindex: '0' }, el('table', { class: 'plan-table' }, [
    textEl('caption', '', caption),
    el('thead', {}, el('tr', {}, [[t('plan.how.table_version')], [t('plan.how.table_need')], ...tableHeads()].map((h) => el('th', { scope: 'col' }, two(h))))),
    el('tbody', {}, rows.map((r) => el('tr', r.version === plan.need.version ? { class: 'on' } : {}, [
      el('th', { scope: 'row', text: r.label }), el('td', { text: r.need }), ...r.widths.map((w) => el('td', {}, two(w))),
    ]))),
  ]));
}

// ---- beside the bell, in the list, on the curve, when read -----------------------------------------------------------

/** The panel: the answer first; a file planned by its own width keeps its reading behind "+". */
export function panelPlan(p) {
  const plan = planFor(p);
  const verdict = panelVerdict(p.result);
  if (!plan) return [verdict];
  const answer = el('p', { class: `panel-plan${plan.mode === 'cant' || plan.shape?.cant ? ' cant' : ''}`, text: answerText(plan) });
  if (!fileFirst(plan)) return [answer, verdict];
  return [answer, el('details', { class: 'more panel-file' }, [el('summary', { text: t('plan.file_reading') }), verdict])];
}

/** A row's verdict column: the width and what it's for first, then the level; a file planned by its width, no level. */
export function rowPlan(p) {
  const span = rowVerdict(p);
  const plan = planFor(p);
  const [lead, why] = rowLines(plan);
  if (!lead) return span;
  const sep = () => el('span', { class: 'pv-sep', text: ', ' });
  if (!why) { // a width that can't be planned: a short line before the level
    span.prepend(el('span', { class: 'pv-for' }, [lead, sep()]));
    return span;
  }
  const head = [el('span', { class: 'pv-plan' }, [lead, sep()]), el('span', { class: 'pv-for' }, [why, fileFirst(plan) ? null : sep()])];
  if (fileFirst(plan)) span.replaceChildren(...head);
  else span.prepend(...head);
  return span;
}

/** The curve's tooltip lines after the picture's name. */
export function tipLines(p) {
  const plan = planFor(p);
  const verdict = prefixText(p.result);
  if (!plan) return [['k', verdict]];
  return [['k', answerText(plan)], ['k', fileFirst(plan) ? t('plan.file_tip', { verdict }) : verdict]];
}

/** What is said when a picture is read: the answer, then the level. */
export function announceText(p) {
  return tipLines(p).map(([, s]) => s).join(' ');
}