File size: 13,828 Bytes
5b3cd1e
 
 
 
 
 
 
378f397
5b3cd1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378f397
5b3cd1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
811f3a9
 
 
 
 
 
 
 
5b3cd1e
 
811f3a9
5b3cd1e
 
811f3a9
 
5b3cd1e
 
 
 
 
 
811f3a9
5b3cd1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de7cd1e
 
 
 
 
 
5b3cd1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// The design test's block in "Your picture", under a file's as-made lines (plan_view.js mounts it): while the test
// waits or runs, how far it has got, what it does and what this browser downloads for it; then its answer, why a
// phone's scanner wasn't in it, and behind "+", how it was tested. The test's state is test.js's; the words come from
// copy.json, every number from test.json or sizes.json. testNote says what changed once, and never the counter.
import { $, WORDS, count, el, join } from './util.js';
import { t } from './copy.js';
import { needFor, planFor } from './plan.js';
import { shaped } from './shape.js';
import { platformKind } from './scanner.js';

const SERVER = ['zxing-cpp', 'wechat']; // the server's scanners, in the order the lines name them
const WAITING = ['queued', 'slot', 'busy', 'upload', 'running'];
let S = null; // web/data/test.json
let act = null; // test.js: { again(p), add(p), leave(p) }

/** test.js, once test.json is in. */
export function useView(settings, actions) {
  S = settings;
  act = actions;
}

/** test.js: the "How your pictures are placed" lines that say a test sends the picture again, only while tests run
 *  (on); otherwise the choice's sentence as before. */
export function howTest(on) {
  const fill = (id, text) => { const node = document.getElementById(id); if (node) node.textContent = text; };
  fill('howTestScanners', on ? t('test.how_scanners') : '');
  fill('howTestPrivacy', on ? t('test.privacy') : '');
  const s = t(on ? 'how.index_html.selector_test' : 'how.index_html.selector');
  if (s) fill('howSelector', s);
}

/** plan_view.js planHead: the block, hidden until the test has something to show, made once per section so that an
 *  open "+" stays open. Try again, Add and Leave it out are real buttons; each moves focus to the line that takes its
 *  place, which has tabindex -1, and the size line's two are described by its text. */
export function testHead(p) {
  if (!S?.page) return null;
  const size = `testSize-${p.n}`;
  const button = (cls, what, about) => {
    const b = el('button', { type: 'button', class: `linklike ${cls}`, hidden: '' });
    if (about) b.setAttribute('aria-describedby', about);
    b.addEventListener('click', () => { act[what](p); focusState(p); });
    return b;
  };
  return el('div', { class: 'test', 'data-n': String(p.n), hidden: '' }, [
    el('p', { class: 'test-state', id: `testState-${p.n}`, tabindex: '-1' }),
    el('p', { class: 'test-hint', hidden: '' }),
    el('p', { class: 'test-size', hidden: '' }, [
      el('span', { class: 'test-size-text', id: size }), ' ', button('test-offer', 'add', size), ' ',
      button('test-leave', 'leave', size),
    ]),
    el('p', { class: 'test-line2', id: `testLine2-${p.n}`, hidden: '' }),
    el('p', { class: 'test-acts', hidden: '' }, [button('test-again', 'again'), ' ', button('test-add', 'add')]),
    el('details', { class: 'more test-more', hidden: '' }, [
      el('summary', { text: t('test.more_summary') }), el('div', { class: 'more-body method' }),
    ]),
  ]);
}

/** test.js: the picture's block, when "Your picture" shows it. */
export function paintTest(p) {
  const node = $('yourPicture')?.querySelector(`.test[data-n="${p.n}"]`);
  if (node) render(node, p, planFor(p));
}

/** plan_view.js refreshPlan: the block in place, its {at} following a typed width. */
export function refreshTest(box, p, plan) {
  const node = box.querySelector('.test');
  if (node) render(node, p, plan);
}

const set = (node, text) => {
  node.textContent = text;
  node.hidden = !text;
};

function render(node, p, plan) {
  const rec = p.test;
  node.hidden = !(rec && rec.state !== 'settling' && p.kind === 'graphic' && plan && plan.mode !== 'cant');
  if (node.hidden) return;
  const q = (sel) => node.querySelector(sel);
  const had = [...node.querySelectorAll('.linklike')].find((b) => b === document.activeElement); // a button with focus
  const waiting = WAITING.includes(rec.state);
  const one = rec.state === 'done' ? lineOne(rec, plan) : null;
  const two = one && one.kind !== 'worse' ? lineTwo(rec) : null; // after "worse" the answer already warns
  const size = waiting ? sizeLine(rec, plan) : null;
  const name = rec.part?.name ? t(`test.name.${rec.part.name}`) : '';
  const state = q('.test-state');
  state.textContent = one ? one.text : stateLine(rec, plan);
  state.classList.toggle('running', waiting); // not printed: only lines 1 and 2 are
  set(q('.test-hint'), waiting ? t('test.hint', { s: S.scenes.s, at: t(`test.at.${at(plan)}_lower`) }) : '');
  set(q('.test-size-text'), size?.text || '');
  q('.test-size').hidden = !size;
  set(q('.test-offer'), size?.offer ? t('test.add', { name }) : '');
  set(q('.test-leave'), size?.leave ? t('test.leave') : '');
  const line2 = q('.test-line2');
  set(line2, two ? t(two.key, { name }) : '');
  const again = rec.state === 'failed' ? rec.retry : two?.act === 'again';
  set(q('.test-again'), again ? t('rows.again') : '');
  q('.test-again').setAttribute('aria-describedby', two ? line2.id : state.id); // heard as retrying the test
  set(q('.test-add'), two?.act === 'add' ? t('test.add', { name }) : '');
  q('.test-add').setAttribute('aria-describedby', line2.id);
  q('.test-acts').hidden = q('.test-again').hidden && q('.test-add').hidden;
  const more = one ? moreLines(rec, plan, one.kind) : [];
  q('.test-more').hidden = !more.length;
  q('.test-more .more-body').replaceChildren(...more.map((s) => el('p', { text: s })));
  if (had?.hidden) state.focus(); // it hid by itself (the browser's part ended, or the answer came): focus isn't lost
}

const at = (plan) => (shaped(plan) ? 'flat' : plan.mode === 'width' ? 'distance' : 'width'); // the test is at the flat need

/** The block's first line while the test waits or runs, or its can't line or failure (an answer is lineOne's). The
 *  counter follows whichever is slower, the server or this browser's scanner while its part runs. */
function stateLine(rec, plan) {
  const L = S.limits;
  if (rec.state === 'queued') return t('test.queued');
  if (rec.state === 'busy') return t('test.busy', { n: rec.n });
  if (rec.state === 'failed') return rec.line;
  if (rec.state === 'cant') {
    const min = plan.v === 1 ? L.min_ppm_v1 : L.min_ppm;
    return t(`test.cant.${rec.why}`, { min, mp: L.max_pixels / 1e6, max: L.max_version });
  }
  const part = rec.part;
  return t('test.running', { k: part?.running ? Math.min(rec.done || 0, part.k) : rec.done || 0, s: S.scenes.s });
}

/** Whether this browser's scanner took part: its part ended with an answer (all its scenes, or the early stop). */
const took = (part) => Boolean(part?.answer) && (part.end === 'settled' || part.end === 'complete');

/** The scanners that ran, with their answers: this browser's first (when it took part), then the server's two. */
function ran(rec) {
  const own = took(rec.part) ? [{ key: rec.part.name, answer: rec.part.answer }] : [];
  return [...own, ...SERVER.map((key) => ({ key, answer: rec.answers[key] }))];
}

const names = (list) => join(list.map((x) => t(`test.name.${x.key}`)));

/** Line 1: worse if any scanner read it worse, naming those that did; as well as a plain code only if every scanner
 *  did, naming them all; otherwise the test couldn't tell, naming those that couldn't. */
function lineOne(rec, plan) {
  const all = ran(rec);
  const of = (...answers) => all.filter((x) => answers.includes(x.answer));
  const kind = of('worse').length ? 'worse' : of('like').length === all.length ? 'like' : 'unsure';
  const who = names(kind === 'worse' ? of('worse') : kind === 'like' ? all : of('close', 'few'));
  return { kind, text: t(`test.${kind}`, { at: t(`test.at.${at(plan)}`), who }) };
}

/** The line 2s that send the visitor to Chrome on Android, and the ones that don't, for a code whose two truths differ
 *  (test_turn.js started), which Chrome on Android keeps its scanner out of. */
const NO_ANDROID = {
  'test.missing.google': 'test.missing.google_no_android',
  'test.missing.mac_none': 'test.missing.mac_none_no_android',
  'test.missing.other': 'test.missing.other_no_android',
};

/** Line 2, after "as well as" or "can't tell", the first that applies: the phone's scanner that wasn't in the test
 *  and where to get its answer; why this browser's own didn't take part, with Try again or Add where either helps; or
 *  what this browser can't do, by platform. Never Chrome on Android for a code it keeps its scanner out of. */
function lineTwo(rec) {
  const part = rec.part || {};
  const away = (key) => ({ key: (rec.truthsDiffer && NO_ANDROID[key]) || key });
  if (took(part)) return away(part.name === 'apple' ? 'test.missing.google' : 'test.missing.apple');
  if (['start', 'stopped', 'slow'].includes(part.end)) return { key: `test.fallback.${part.end}`, act: 'again' };
  if (part.end === 'left' || part.decision === 'offered') return { key: 'test.missing.left_out', act: 'add' };
  if (part.decision === 'save_data') return { key: 'test.missing.save_data', act: 'again' };
  if (part.decision === 'late' || part.decision === 'broken') return { key: 'test.fallback.start', act: 'again' };
  const kind = platformKind(); // no Try again: trying again can't help
  const which = { 'chrome-mac': 'mac_none', 'chrome-android': 'android_none' }[kind] || kind;
  return away(`test.missing.${which}`);
}

/** The size line while the test waits or runs: this browser's scanner joins (with Leave it out while its part runs),
 *  or can join (with Add); gone once its part ends by a fallback, the budget or Leave it out. {mb} is the most a test
 *  of the code's version range downloads, with the frames it takes. */
function sizeLine(rec, plan) {
  const part = rec.part;
  if (!part || !['joins', 'offered'].includes(part.decision)) return null;
  if (part.decision === 'joins' && (part.left || (part.over && !took(part)))) return null; // Leave it out: at once
  const range = S.mb[part.frames] || S.mb.jpeg;
  const tops = Object.keys(range).map(Number).sort((a, b) => a - b);
  const vars = { name: t(`test.name.${part.name}`), mb: range[String(tops.find((v) => plan.v <= v) ?? tops.at(-1))] };
  if (part.decision === 'offered') return { text: t('test.hint_offer', vars), offer: true };
  return { text: t('test.hint_browser', vars), leave: Boolean(part.running) };
}

/** The limits' figures in words, from test.json's [a, b]: a share of the scans ("3 in 10"), and how often a design
 *  still passes ("1 time in 30"). */
const share = ([a, b]) => t('test.more.limits_share', { a, b });
const times = ([a, b]) => t(a === 1 ? 'test.more.limits_times_one' : 'test.more.limits_times_many', { a, b });

/** Behind "+", after an answer, each where it applies: the method, the rule, each scanner's own answer (never its
 *  reads), the Chrome builds measured, what the figures say of the answer's path, the limits of its scenes, the
 *  figures' scope, and that this browser's reads stayed in the page. */
function moreLines(rec, plan, kind) {
  const F = S.figures;
  const lim = F.limits;
  const limits = {
    big: share(lim.big), big_pass: times(lim.big_pass), small: share(lim.small), small_pass: times(lim.small_pass),
  };
  const own = took(rec.part) ? rec.part.name : '';
  const fair = kind !== 'worse';
  const cover = (key, figures) => t(`test.more.${key}`, { N: F.N, ...figures });
  const pathLine = own ? (fair ? cover(`cover_${own}`, F.cover[own]) : '')
    : cover(fair ? 'cover_open' : 'cover_open_worse', F.cover[fair ? 'open' : 'open_worse']);
  const [vlo, vhi] = F.scope.versions;
  const each = (x) => t('test.more.each', { name: t(`test.name.${x.key}`), result: t(`test.more.result.${x.answer}`) });
  const p = needFor(plan.v).ppm.toFixed(1); // p(v): the table's need for the version, as the test renders it
  return [
    t('test.more.method', { margin: S.frames.margin_squares, s: S.scenes.s, p, v: plan.v }),
    t('test.more.rule', { least: S.rule.least_worse, cost: S.rule.like_cost, q: S.rule.q }),
    ...ran(rec).map(each),
    own ? t(`test.more.${own}`, { os: F.chrome[own].os, n: count(F.chrome[own].n) }) : '',
    pathLine,
    kind === 'like' ? t('test.more.limits', { s: S.scenes.s, ...limits }) : '',
    t('test.more.scope', { N: F.N, styles: WORDS[F.scope.styles], vlo, vhi }),
    own ? t('test.more.private') : '',
  ].filter(Boolean);
}

let said = []; // what testNote says in the next frame, in order

/** testNote, the test's polite live region. what: 'queued', 'start', 'busy' or 'end' (the block's first line then),
 *  named for the picture when asked. Cleared, then written in the next animation frame, as the marking's note is. */
export function announce(p, what, named) {
  const rec = p.test;
  const plan = planFor(p);
  let line = '';
  if (what === 'queued') line = t('test.queued');
  else if (what === 'start') line = t('test.announce');
  else if (what === 'busy') line = t('test.busy', { n: rec.n });
  else if (plan) line = rec.state === 'done' ? lineOne(rec, plan).text : stateLine(rec, plan);
  sayTestNote(named ? t('test.announce_named', { n: p.n, name: p.name, line }) : line);
}

/** testNote, said once with what else is said there in the same frame, in order: a test's state, or the line
 *  saying a file's own details marked it as the original graphic (record.js). */
export function sayTestNote(text) {
  const node = $('testNote');
  if (!node || !text) return;
  if (!said.length) {
    node.textContent = '';
    requestAnimationFrame(() => {
      node.textContent = said.join(' ');
      said = [];
    });
  }
  said.push(text);
}

/** After Try again, Add or Leave it out: focus on the line that takes the button's place. */
function focusState(p) {
  const node = $('yourPicture')?.querySelector(`.test[data-n="${p.n}"] .test-state`);
  if (node && !node.closest('.test').hidden) node.focus();
}