@makechart/viewer 0.0.1 → 0.0.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Change Logs
2
2
 
3
+ ## v0.0.3
4
+
5
+ - ignore empty `style=""` attributes when serializing and comparing: whether one is left depends on
6
+ how a style was set before ( e.g. `style.x = ''` ), not on what is drawn. existing baselines that
7
+ still contain it compare equal without updating
8
+
9
+
10
+ ## v0.0.2
11
+
12
+ - add playground ( `/playground` in `mctest serve` ): apply any test case's data / config / size,
13
+ replay its steps in real time, swap data from `mod.sample` or suite data, edit raw as CSV and
14
+ binding as JSON, and tweak config from a panel generated from `mod.config`
15
+ - modules not found locally are fetched from npm CDN ( jsdelivr ) and cached in `~/.cache/mctest`.
16
+ add `--offline` to disable it
17
+ - add `ctx.capture(label)`: save the current markup without waiting or flushing, for animation
18
+ frames driven by `chart.anim.step`. `steps` / `cases` accept a single item without an array
19
+ - drag helper sends both pointer and mouse events with integer coordinates ( d3-brush listens to mouse )
20
+ - normalize csscope scope tokens, hex colors as `rgb()` and transform spacing, so d3 / lite
21
+ variants of the same chart compare equal
22
+
3
23
  ## v0.0.1
4
24
 
5
25
  - init release
package/README.md CHANGED
@@ -27,6 +27,16 @@ makechart 圖表的 test suite engine。每張圖在自己的 repo 放 test case
27
27
  `npx mctest -h` 看全部選項。結束碼不是 0 代表有 case 失敗,失敗的 markup 與截圖放在 `test/output/`。
28
28
 
29
29
 
30
+ ## playground
31
+
32
+ `npx mctest serve` 之後開 `/playground` ( UI 右上角也有連結 ),拿圖來玩:
33
+
34
+ - 上方選一個 test case 就套用它的資料、config 與大小;有 steps 的 ( 標 ▶ ) 可以按「跑 steps」,用真實時間看動畫
35
+ - 「換資料」可以換成 `mod.sample` 或 suite 裡任一份 data,設定保留
36
+ - 左側設定面板依 `mod.config` 自動產生 ( number / boolean / choice / color / format / text );palette 給幾組現成的,font / quantity 沒有元件
37
+ - raw 用 CSV 編輯、binding 用 JSON,按「套用資料」
38
+ - 圖的容器可以拖右下角改大小;`window.chart` 是圖的實例,可以在 console 直接操作
39
+
30
40
  ## 依賴從哪裡來
31
41
 
32
42
  engine 自己起一個 server,前端依賴走與 makechart 相同的路徑 `/assets/lib/<name>/<version>/<path>`,版本一律忽略,依序找:
@@ -91,4 +101,5 @@ snapshot 一律由 headless 產生 ( viewport 1600x1000,DPR 預設 2,`--dpr`
91
101
  - `lib/server.js` — http server:依賴解析、test case 編譯、snapshot API
92
102
  - `lib/runner.js` — headless 瀏覽器 ( playwright-core )
93
103
  - `src/suite.ls` — 瀏覽器端 engine:case 定義、執行、正規化、比對
104
+ - `src/playground.ls`、`web/playground.html` — playground
94
105
  - `src/ui.ls`、`web/index.html` — UI ( headless 也是跑這頁 )
package/bin/cli.js CHANGED
@@ -15,7 +15,8 @@
15
15
  // --loose 數字差在 tolerance 內 ( near ) 也算過. 預設不算: 真的差 1px 的改動也要抓到
16
16
  // --dpr n headless 的 devicePixelRatio ( 預設 2, 同 Mac 螢幕 ). 文字寬度會隨它有小數誤差
17
17
  // --headed run 時顯示瀏覽器視窗
18
- // -v 印出 404 與頁面的 console
18
+ // --offline 本機找不到的模組不向 npm CDN 拿
19
+ // -v 印出 404、從 CDN 拿的檔案與頁面的 console
19
20
  const fs = require('fs'), path = require('path');
20
21
  const {create, parseLinks} = require('../lib/server');
21
22
  const {Runner, writeSnapshot} = require('../lib/runner');
@@ -32,6 +33,7 @@ function parseArgs(argv) {
32
33
  else if (a === '-p' || a === '--port') o.port = +next();
33
34
  else if (a === '-o' || a === '--open') o.open = true;
34
35
  else if (a === '--ci') o.ci = true;
36
+ else if (a === '--offline') o.offline = true;
35
37
  else if (a === '--loose') o.loose = true;
36
38
  else if (a === '--dpr') o.dpr = +next();
37
39
  else if (a === '--browser') o.browser = next();
@@ -107,6 +109,6 @@ if (o.cmd === 'help') {
107
109
  process.exit(0);
108
110
  }
109
111
  if (!fs.existsSync('package.json')) { console.error('[mctest] run it in the root of a chart repo ( package.json not found )'); process.exit(2); }
110
- const srv = create({links: o.links, verbose: o.verbose});
112
+ const srv = create({links: o.links, verbose: o.verbose, offline: o.offline});
111
113
  (o.cmd === 'serve' ? serve(o, srv) : run(o, srv).then(c => process.exit(c)))
112
114
  .catch(e => { console.error(e.stack || e); process.exit(1); });
package/lib/server.js CHANGED
@@ -1,12 +1,14 @@
1
1
  // mctest server: 在受測 chart 的 repo ( cwd ) 裡起一個 http server.
2
2
  //
3
3
  // / engine 的 UI ( web/index.html )
4
+ // /playground 拿圖來玩: 改設定、資料, 套用 test case ( web/playground.html )
4
5
  // /engine/<file> engine 的前端檔案 ( <name>.js 由 src/<name>.ls 即時編譯, 其餘在 web/ )
5
6
  // /assets/lib/<name>/<ver>/<path>
6
7
  // 前端依賴, 規則同 makechart server / fedep ( 版本一律忽略, 用找到的那份 ):
7
8
  // 1. -l 指定的本地目錄 ( 有 dist/ 先找 dist/ )
8
9
  // 2. 受測的 chart 自己 ( package.json name -> cwd/dist )
9
10
  // 3. node_modules ( 先 cwd 再 engine 自己的 ), 含 npm link 的 symlink
11
+ // 4. npm CDN ( jsdelivr ), 快取在 ~/.cache/mctest. --offline 時不拿
10
12
  // /test/index.js chart 的 test case ( test/index.ls 即時編譯, 或 test/index.js )
11
13
  // /test/<path> chart 的 test/ 目錄 ( 放資料檔用 )
12
14
  // /api/info {name, version, links}
@@ -41,6 +43,30 @@ function findModule(name, from) {
41
43
 
42
44
  function isFile(f) { try { return fs.statSync(f).isFile(); } catch (e) { return false; } }
43
45
 
46
+ // 本機找不到的模組改向 npm CDN 拿 ( 同 makechart 的 registry 最後去 npm 抓 ), 快取在 ~/.cache/mctest.
47
+ // 版本是 main 就拿 latest. 快取以 <name>/<version>/<path> 存, latest 的快取一天後重抓
48
+ const cacheRoot = process.env.MCTEST_CACHE || path.join(require('os').homedir(), '.cache', 'mctest');
49
+ const pending = {};
50
+ function fetchRemote(name, version, rest, cdn) {
51
+ const ver = (!version || version === 'main') ? 'latest' : version;
52
+ const f = path.join(cacheRoot, name, ver, rest);
53
+ if (!f.startsWith(cacheRoot + path.sep)) return Promise.resolve(null);
54
+ try {
55
+ const st = fs.statSync(f);
56
+ if (st.isFile() && (ver !== 'latest' || Date.now() - st.mtimeMs < 86400000)) return Promise.resolve(f);
57
+ } catch (e) {}
58
+ const miss = f + '.404';
59
+ if (isFile(miss) && Date.now() - fs.statSync(miss).mtimeMs < 86400000) return Promise.resolve(null);
60
+ if (pending[f]) return pending[f];
61
+ const url = `${cdn}/${name}@${ver}/${rest}`;
62
+ return pending[f] = fetch(url).then(async (r) => {
63
+ fs.mkdirSync(path.dirname(f), {recursive: true});
64
+ if (!r.ok) { fs.writeFileSync(miss, String(r.status)); return null; }
65
+ fs.writeFileSync(f, Buffer.from(await r.arrayBuffer()));
66
+ return f;
67
+ }).catch(() => null).finally(() => { delete pending[f]; });
68
+ }
69
+
44
70
  function create(opt = {}) {
45
71
  const cwd = path.resolve(opt.cwd || '.');
46
72
  const pkg = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json')));
@@ -113,16 +139,22 @@ function create(opt = {}) {
113
139
  try { p = decodeURIComponent(req.url.split('?')[0]); } catch (e) { return send(res, 400, 'bad url'); }
114
140
  let m;
115
141
  if (p === '/' || p === '/index.html') return sendFile(res, path.join(engineRoot, 'web', 'index.html'));
142
+ if (p === '/playground') return sendFile(res, path.join(engineRoot, 'web', 'playground.html'));
116
143
  if ((m = /^\/engine\/(.+)$/.exec(p))) {
117
144
  let r;
118
145
  try { r = engineFile(m[1]); } catch (e) { return send(res, 500, String(e.stack || e)); }
119
146
  if (!r) return send(res, 404, 'not found');
120
147
  return r.file ? sendFile(res, r.file) : send(res, 200, r.body, r.type);
121
148
  }
122
- if ((m = /^\/assets\/lib\/((?:@[^/]+\/)?[^/]+)\/[^/]+\/(.+)$/.exec(p))) {
123
- const f = resolveLib(m[1], m[2]);
124
- if (!f) { if (opt.verbose) console.log('[mctest] 404', p); return send(res, 404, 'not found'); }
125
- return sendFile(res, f);
149
+ if ((m = /^\/assets\/lib\/((?:@[^/]+\/)?[^/]+)\/([^/]+)\/(.+)$/.exec(p))) {
150
+ const f = resolveLib(m[1], m[3]);
151
+ if (f) return sendFile(res, f);
152
+ if (opt.offline) { if (opt.verbose) console.log('[mctest] 404', p); return send(res, 404, 'not found'); }
153
+ return fetchRemote(m[1], m[2], m[3], opt.cdn || 'https://cdn.jsdelivr.net/npm').then((f) => {
154
+ if (!f) { if (opt.verbose) console.log('[mctest] 404', p); return send(res, 404, 'not found'); }
155
+ if (opt.verbose) console.log('[mctest] remote', p);
156
+ sendFile(res, f);
157
+ });
126
158
  }
127
159
  if (p === '/test/index.js') {
128
160
  try { return send(res, 200, caseFile(), types['.js']); } catch (e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@makechart/viewer",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "makechart 圖表的 test suite engine: 用不同資料、參數跑圖, 比對輸出 snapshot, 並以 @plotdb/dash 測 crossfilter",
5
5
  "homepage": "https://github.com/makechart/viewer",
6
6
  "repository": {
@@ -47,5 +47,8 @@
47
47
  "proxise": "^1.0.1",
48
48
  "wrap-svg-text": "^0.0.8",
49
49
  "zmgr": "^2.2.3"
50
+ },
51
+ "devDependencies": {
52
+ "fedep": "^1.9.0"
50
53
  }
51
54
  }
@@ -0,0 +1,256 @@
1
+ # mctest playground: 拿一張圖來玩. `mctest serve` 之後開 /playground
2
+ #
3
+ # - 資料與設定的起點直接取自 chart 的 test case ( test/index.ls ) 與 mod.sample, 不必另外準備
4
+ # - 選一個 case 就套用它的資料、config 與大小; 有 steps 的可以按「跑 steps」看動畫
5
+ # - 設定面板依 mod.config 自動產生 ( number / boolean / choice / color / format / text ),
6
+ # font / palette / quantity 沒有元件, palette 給幾組現成的
7
+ # - 資料用 CSV 編輯 ( raw ), binding 用 JSON. 動畫是真實時間, 不切 manual
8
+
9
+ $ = (s) -> document.querySelector s
10
+ el = (tag, attr = {}, txt) ->
11
+ n = document.createElement tag
12
+ for k, v of attr => n.setAttribute k, v
13
+ if txt? => n.textContent = txt
14
+ n
15
+ clone = (o) -> if o? => JSON.parse(JSON.stringify o) else o
16
+ wait = (ms) -> new Promise (res) -> setTimeout res, ms
17
+
18
+ pg = mctest.playground = {}
19
+
20
+ # ---------------------------------------------------------------- csv
21
+ # 只處理常見情形: 逗號分隔, 雙引號包住的欄位可以含逗號 / 換行 / "" 跳脫
22
+ csv =
23
+ parse: (s) ->
24
+ [rows, row, cur, q, i] = [[], [], '', false, 0]
25
+ while i < s.length
26
+ c = s[i]
27
+ if q =>
28
+ if c == '"' and s[i + 1] == '"' => cur += '"'; i++
29
+ else if c == '"' => q = false
30
+ else cur += c
31
+ else if c == '"' => q = true
32
+ else if c == ',' => row.push cur; cur = ''
33
+ else if c == '\n' or c == '\r' =>
34
+ if c == '\r' and s[i + 1] == '\n' => i++
35
+ row.push cur
36
+ rows.push row
37
+ [row, cur] = [[], '']
38
+ else cur += c
39
+ i++
40
+ if cur or row.length => row.push cur; rows.push row
41
+ rows.filter -> it.some (v) -> v.trim! != ''
42
+ cell: (v) ->
43
+ v = if v? => "#v" else ''
44
+ if /[",\n\r]/.exec(v) => "\"#{v.replace(/"/g, '""')}\"" else v
45
+ # rows ( 物件陣列 ) -> csv. 欄位取所有列的聯集, 依第一次出現的順序
46
+ from: (raw = []) ->
47
+ keys = []
48
+ raw.map (r) -> for k of r => if !(k in keys) => keys.push k
49
+ if !keys.length => return ''
50
+ ([keys] ++ raw.map((r) -> keys.map (k) -> r[k])).map((r) -> r.map(csv.cell).join \,).join \\n
51
+ # csv -> rows. 看起來是數字的轉成數字, 空格留空字串
52
+ to: (s) ->
53
+ rows = csv.parse s
54
+ if !rows.length => return []
55
+ [head, ...body] = rows
56
+ body.map (r) ->
57
+ Object.fromEntries head.map (h, i) ->
58
+ v = (r[i] or '').trim!
59
+ [h.trim!, (if v != '' and !isNaN(+v) => +v else v)]
60
+
61
+ # ---------------------------------------------------------------- config panel
62
+ is-leaf = (o) -> o and typeof(o) == \object and typeof(o.type) == \string
63
+ defaults = (o) ->
64
+ ret = {}
65
+ for k, v of o =>
66
+ if is-leaf v => (if v.default? => ret[k] = clone v.default)
67
+ else if v and typeof(v) == \object => ret[k] = defaults v
68
+ ret
69
+ get-at = (o, path) -> path.reduce ((a, k) -> (a or {})[k]), o
70
+ patch-of = (path, v) ->
71
+ ret = p = {}
72
+ for k in path.slice(0, -1) => p = p[k] = {}
73
+ p[path[* - 1]] = v
74
+ ret
75
+
76
+ palettes =
77
+ "預設": null
78
+ tableau: <[#4e79a7 #f28e2b #e15759 #76b7b2 #59a14f #edc948 #b07aa1 #ff9da7 #9c755f #bab0ac]>
79
+ "冷色": <[#264653 #2a9d8f #8ab17d #457b9d #1d3557 #a8dadc]>
80
+ "暖色": <[#9b2226 #ae2012 #bb3e03 #ca6702 #ee9b00 #e9d8a6]>
81
+
82
+ control = (def, path) ->
83
+ v = get-at pg.chart.config!, path
84
+ row = el \div, {class: \row}
85
+ row.appendChild el(\label, {title: path.join(\.)}, path[* - 1])
86
+ c = row.appendChild el(\div, {class: \ctrl})
87
+ set = (v) -> pg.set path, v
88
+ switch def.type
89
+ | \number =>
90
+ [min, max, step] = [(def.min ? 0), (def.max ? Math.max(100, (v or 0) * 2)), (def.step ? 1)]
91
+ n = c.appendChild el(\input, {type: \range, min, max, step})
92
+ o = c.appendChild el(\span, {class: \v})
93
+ n.value = v ? min
94
+ o.textContent = n.value
95
+ n.oninput = -> o.textContent = n.value; set +n.value
96
+ | \boolean =>
97
+ n = c.appendChild el(\input, {type: \checkbox})
98
+ n.checked = !!v
99
+ n.onchange = -> set n.checked
100
+ | \choice =>
101
+ n = c.appendChild el(\select)
102
+ (def.values or []).map (o) ->
103
+ [val, name] = if o and typeof(o) == \object => [o.value, o.name] else [o, o]
104
+ n.appendChild el(\option, {value: JSON.stringify(val)}, name)
105
+ n.value = JSON.stringify v
106
+ n.onchange = -> set JSON.parse(n.value)
107
+ | \color =>
108
+ n = c.appendChild el(\input, {type: \color})
109
+ if /^#[0-9a-f]{6}$/i.exec(v or '') => n.value = v
110
+ n.oninput = -> set n.value
111
+ b = c.appendChild el(\button, {}, \預設)
112
+ b.onclick = -> set def.default
113
+ | \format, \text =>
114
+ n = c.appendChild el(\input, {type: \text})
115
+ n.value = v ? ''
116
+ n.onchange = -> set n.value
117
+ | otherwise => return null
118
+ row
119
+
120
+ # 群組攤平成一層 ( legend 寫完整路徑 ), 只有子群組、沒有直接設定項的群組不出現
121
+ build-panel = (o, path, root, fs) ->
122
+ subs = []
123
+ for k, v of o =>
124
+ p = path ++ [k]
125
+ if is-leaf v => (if fs and (r = control v, p) => fs.appendChild r)
126
+ else if v and typeof(v) == \object => subs.push [v, p]
127
+ if fs and fs.querySelector(\.row) => root.appendChild fs
128
+ for [v, p] in subs =>
129
+ g = el \fieldset
130
+ g.appendChild el(\legend, {}, p.join \.)
131
+ build-panel v, p, root, g
132
+
133
+ render-panel = ->
134
+ root = $ \#cfg
135
+ root.textContent = ''
136
+ row = root.appendChild el(\div, {class: \row})
137
+ row.appendChild el(\label, {}, \palette)
138
+ sel = row.appendChild(el \div, {class: \ctrl}).appendChild el(\select)
139
+ for k of palettes => sel.appendChild el(\option, {value: k}, k)
140
+ sel.onchange = ->
141
+ p = palettes[sel.value]
142
+ pg.set [\palette], (if p => {key: sel.value, colors: p} else null)
143
+ # 最上層的設定項放在沒有 legend 的那一組
144
+ build-panel pg.chart.mod.config, [], root, el(\fieldset)
145
+
146
+ # ---------------------------------------------------------------- chart
147
+ redraw = ->
148
+ c = pg.chart
149
+ c.parse!; c.bind!; c.resize!; c.render!
150
+
151
+ pg.set = (path, v) ->
152
+ pg.chart.config patch-of(path, v)
153
+ redraw!
154
+
155
+ # 設定整個換掉: 回到預設再套 cfg
156
+ pg.reset-config = (cfg = {}) ->
157
+ c = pg.chart
158
+ c.cfg = {}
159
+ c.config (mctest.merge defaults(c.mod.config), clone(cfg))
160
+ redraw!
161
+ render-panel!
162
+
163
+ pg.set-data = (d) ->
164
+ $(\#err).textContent = ''
165
+ pg.data = d = clone d
166
+ $(\#csv).value = csv.from d.raw
167
+ $(\#binding).value = JSON.stringify(d.binding or {}, null, 2)
168
+ pg.chart.set-raw (if d.subset? => d else {raw: d.raw, binding: d.binding, subset: null})
169
+
170
+ apply-editor = ->
171
+ $(\#err).textContent = ''
172
+ try
173
+ pg.data = {raw: csv.to($(\#csv).value), binding: JSON.parse($(\#binding).value or '{}')}
174
+ pg.chart.set-raw {raw: pg.data.raw, binding: pg.data.binding, subset: null}
175
+ catch e => $(\#err).textContent = String(e.message or e)
176
+
177
+ set-size = ([w, h]) -> $(\#stage).style <<< {width: "#{w}px", height: "#{h}px"}
178
+
179
+ # 資料來源: mod.sample, 各 suite 的 data. case: 不含 dash 的 test case
180
+ sources = ->
181
+ ret = []
182
+ if pg.chart.mod.sample => ret.push {name: "sample ( mod.sample )", get: -> pg.chart.mod.sample!}
183
+ for s in mctest.suites => for k, v of (s.data or {}) => let v
184
+ ret.push {name: "data: #k", get: -> clone(if typeof(v) == \function => v! else v)}
185
+ ret
186
+
187
+ case-data = (c) ->
188
+ s = c.suite
189
+ d = c.data or Object.keys(s.data or {}).0
190
+ if typeof(d) == \string => d = (s.data or {})[d]
191
+ if typeof(d) == \function => d = d!
192
+ clone d
193
+
194
+ pg.apply-case = (c) ->
195
+ set-size (c.size or c.suite.size)
196
+ pg.reset-config mctest.merge({}, clone(c.suite.config or {}), clone(c.config or {}))
197
+ if (d = case-data c) => pg.set-data d
198
+ $(\#steps).disabled = !c.steps
199
+ pg.case = c
200
+
201
+ # steps 拿到的 ctx 是簡化過的: snap 只是停一下讓人看得到那一格
202
+ pg.run-steps = ->
203
+ if !(c = pg.case and pg.case.steps) => return
204
+ c = [].concat c
205
+ ctx =
206
+ root: $(\#stage), wait: wait, random: mctest.random, drag: mctest.drag
207
+ snap: -> wait 800
208
+ capture: -> Promise.resolve!
209
+ c.reduce ((p, f) -> p.then(-> f pg.chart, ctx).then(-> wait 600)), Promise.resolve!
210
+ .catch (e) -> $(\#err).textContent = String(e.stack or e)
211
+
212
+ mctest.boot!
213
+ .then ->
214
+ $(\#target).textContent = "#{mctest.info.name}@#{mctest.info.version}"
215
+ document.title = "playground · #{mctest.info.name}"
216
+ mctest.manager.get {name: mctest.info.name, version: \main}
217
+ .then (bc) -> bc.create {data: {}}
218
+ .then (bi) -> bi.attach({root: $(\#stage)}).then -> bi.interface!
219
+ .then (chart) ->
220
+ pg.chart = window.chart = chart
221
+ # case 選單
222
+ sel = $ \#case
223
+ cases = mctest.cases.filter -> !it.dash and !it.skip
224
+ sel.appendChild el(\option, {value: ''}, "-- 選一個 case ( #{cases.length} ) --")
225
+ cases.map (c, i) -> sel.appendChild el(\option, {value: i}, c.name + (if c.steps => ' ▶' else ''))
226
+ sel.onchange = -> if sel.value != '' => pg.apply-case cases[+sel.value]
227
+ # 資料選單
228
+ src = $ \#source
229
+ list = sources!
230
+ src.appendChild el(\option, {value: ''}, "-- 換資料 ( 保留設定 ) --")
231
+ list.map (s, i) -> src.appendChild el(\option, {value: i}, s.name)
232
+ src.onchange = ->
233
+ if src.value == '' => return
234
+ try pg.set-data list[+src.value].get! catch e => $(\#err).textContent = String(e.stack or e)
235
+ src.value = ''
236
+ $(\#apply).onclick = apply-editor
237
+ $(\#steps).onclick = pg.run-steps
238
+ $(\#reset).onclick = -> pg.reset-config!
239
+ $(\#dump).onclick = ->
240
+ cfg = pg.chart.config!
241
+ console.log cfg
242
+ $(\#out).textContent = JSON.stringify cfg, null, 2
243
+ $(\#rerender).onclick = redraw
244
+ new ResizeObserver(->
245
+ b = $(\#stage).getBoundingClientRect!
246
+ $(\#size).textContent = "#{Math.round b.width} × #{Math.round b.height} · 拖右下角改大小"
247
+ ).observe $(\#stage)
248
+ # 起點: 第一個 case, 沒有就用 sample
249
+ if cases.length => sel.value = 0; pg.apply-case cases.0
250
+ else
251
+ set-size [640, 400]
252
+ pg.reset-config!
253
+ if list.length => pg.set-data list.0.get!
254
+ .catch (e) ->
255
+ $(\#err).textContent = String(e.stack or e)
256
+ console.error e
package/src/suite.ls CHANGED
@@ -10,8 +10,9 @@
10
10
  # data suite.data 裡的名字, 或直接給 {raw, binding}
11
11
  # config chart.config 的內容 ( 會跟 suite.config 深層合併 )
12
12
  # size [w, h] px, 預設 suite.size
13
- # steps [(chart, ctx) -> ...] 依序執行, 每步之後等畫面穩定. 可回傳 promise
14
- # ctx.snap(label) 在當下多存一格 ( 預設只存最後的樣子 ). ctx.root 是這個 case 的容器
13
+ # steps [(chart, ctx) -> ...] 依序執行, 每步之後等畫面穩定. 可回傳 promise. 只有一步時可以不包成陣列
14
+ # ctx.snap(label) 等畫面穩定後多存一格 ( 預設只存最後的樣子 ); ctx.capture(label) 不等不 flush,
15
+ # 直接存當下 ( 配 chart.anim.step 驗證動畫中間格 ). ctx.root 是這個 case 的容器
15
16
  # dash {def, size} 用 @plotdb/dash 的 board 跑多張圖 ( 測 crossfilter ).
16
17
  # 此時 steps 拿到的是 (board, ctx), ctx.chart(id) 取得某個 panel 的圖
17
18
  # skip true 時略過
@@ -62,16 +63,21 @@ mctest.file = (n) -> n.replace /[^\w.=,+@-]+/g, \_
62
63
 
63
64
  wait = (t = 0) -> new Promise (res) -> setTimeout res, t
64
65
 
65
- # 模擬拖曳 ( 例如 brush ). p0 / p1 是 node 內的相對座標 ( 0 ~ 1 )
66
+ # 模擬拖曳 ( 例如 brush ). p0 / p1 是 node 內的相對座標 ( 0 ~ 1 ).
67
+ # 跟真的滑鼠一樣 pointer 與 mouse 事件都送: chart.utils.brush 聽 pointer, d3-brush 聽 mouse
66
68
  mctest.drag = (node, p0, p1, n = 6) ->
67
69
  r = node.getBoundingClientRect!
68
- pt = ([x, y]) -> {clientX: r.left + r.width * x, clientY: r.top + r.height * y}
69
- opt = {bubbles: true, cancelable: true, pointerId: 1, isPrimary: true, button: 0, buttons: 1}
70
- node.dispatchEvent new PointerEvent \pointerdown, ({} <<< opt <<< pt p0)
70
+ # 座標取整: MouseEvent 的 clientX 是整數, PointerEvent 可以有小數, 不取整兩邊收到的位置會不一樣
71
+ pt = ([x, y]) -> {clientX: Math.round(r.left + r.width * x), clientY: Math.round(r.top + r.height * y)}
72
+ opt = {bubbles: true, cancelable: true, view: window, pointerId: 1, isPrimary: true, button: 0, buttons: 1}
73
+ fire = (target, type, p, extra = {}) ->
74
+ o = {} <<< opt <<< pt(p) <<< extra
75
+ target.dispatchEvent new PointerEvent "pointer#type", o
76
+ target.dispatchEvent new MouseEvent "mouse#type", o
77
+ fire node, \down, p0
71
78
  for i from 1 to n =>
72
- p = [p0.0 + (p1.0 - p0.0) * i / n, p0.1 + (p1.1 - p0.1) * i / n]
73
- window.dispatchEvent new PointerEvent \pointermove, ({} <<< opt <<< pt p)
74
- window.dispatchEvent new PointerEvent \pointerup, ({} <<< opt <<< pt(p1) <<< {buttons: 0})
79
+ fire window, \move, [p0.0 + (p1.0 - p0.0) * i / n, p0.1 + (p1.1 - p0.1) * i / n]
80
+ fire window, \up, p1, {buttons: 0}
75
81
  node.dispatchEvent new MouseEvent \click, ({bubbles: true, cancelable: true} <<< pt p1)
76
82
 
77
83
  # ---------------------------------------------------------------- normalize
@@ -80,10 +86,28 @@ mctest.drag = (node, p0, p1, n = 6) ->
80
86
  volatile = [
81
87
  # ldview 的 scope 屬性名字是亂數
82
88
  [/ld-scope-ld-[a-z0-9]+/g, \ld-scope-ld-x]
89
+ # @plotdb/csscope 的 scope 名稱是依賴的路徑編出來的 ( base64, _Q 開頭 ). 換依賴 ( 例如 d3 版換成 lite ) 就會變,
90
+ # 跟畫面無關, 拿掉
91
+ [/\s*\b_Q[A-Za-z0-9_]+/g, '']
83
92
  # @plotdb/chart 的 legend id ( Math.random )
84
93
  [/(pdlg-[a-z]+-)[a-z0-9]+(-)/g, '$1x$2']
85
94
  ]
86
95
 
96
+ # 顏色統一寫成 rgb(): d3 transition 補完會留下 rgb(...), 直接設的是 #hex - 同一個顏色不該算不同
97
+ hex-rgb = (m, h) ->
98
+ if h.length == 3 => h = h.split('').map(-> it + it).join('')
99
+ "rgb(#{parseInt(h.substr(0, 2), 16)}, #{parseInt(h.substr(2, 2), 16)}, #{parseInt(h.substr(4, 2), 16)})"
100
+ volatile.push [/#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b(?![0-9a-fA-F])/g, hex-rgb]
101
+
102
+ # transform 統一寫法: d3 的 transform 補間會把結果重排成 translate(x,y) ( 逗號後沒空白 ), 恆等轉換則是空字串
103
+ norm-transform = (m, v) ->
104
+ v = v.replace(/\s*,\s*/g, ',').replace(/\(\s+/g, '(').replace(/\s+\)/g, ')').replace(/\s+/g, ' ').trim!
105
+ if /^translate\(0(,0)?\)$/.test(v) => v = ''
106
+ "transform=\"#v\""
107
+ volatile.push [/transform="([^"]*)"/g, norm-transform]
108
+ # rgb() / rgba() 統一成逗號後一個空白 ( d3 的寫法 )
109
+ volatile.push [/(rgba?)\(\s*([^)]*?)\s*\)/g, (m, f, v) -> "#f(#{v.split(/\s*,\s*/).join(', ')})"]
110
+
87
111
  # DOM -> markup. 自己序列化而不用 innerHTML: 屬性依名字排序 ( 設定順序會隨執行順序變, 例如頁面上
88
112
  # 第一張圖跟之後的不同 ), 一個 tag 一行方便 diff. 產生的 markup 可以直接塞回 innerHTML 重現畫面
89
113
  void-tags = <[area base br col embed hr img input link meta source track wbr]>
@@ -98,7 +122,9 @@ mctest.serialize = serialize = (root) ->
98
122
  if n.nodeType != 1 => return
99
123
  tag = n.tagName
100
124
  if !n.namespaceURI or n.namespaceURI == "http://www.w3.org/1999/xhtml" => tag = tag.toLowerCase!
125
+ # 空的 style 屬性對畫面沒有作用, 有沒有留下來卻看設定過的歷程 ( 例如 style.x = '' 之前有沒有值 ), 略過
101
126
  attrs = Array.from(n.attributes)
127
+ .filter -> !(it.name == \style and !it.value.trim!)
102
128
  .map -> [it.name, it.value]
103
129
  .sort (a, b) -> if a.0 < b.0 => -1 else if a.0 > b.0 => 1 else 0
104
130
  .map ([k, v]) -> " #k=\"#{esc-attr v}\""
@@ -159,7 +185,7 @@ settle = (root, list, quiet = 250, limit = 10000) ->
159
185
  mctest.suite = (s = {}) ->
160
186
  s.size = s.size or [480, 320]
161
187
  mctest.suites.push s
162
- (s.cases or []).map (c) ->
188
+ ([].concat(s.cases or [])).map (c) ->
163
189
  mctest.cases.push ({} <<< c <<< {suite: s, file: mctest.file(c.name)})
164
190
  s
165
191
 
@@ -207,12 +233,16 @@ mctest.run-case = (c, root) ->
207
233
  root: root
208
234
  snap: (label) ->
209
235
  settle(root, list, q).then -> snaps.push {label: (label or "step#{snaps.length}"), markup: normalize(root, s.normalize)}
236
+ # 不等穩定、不 flush, 直接存當下的樣子 ( 配合 chart.anim.step 驗證動畫的中間格 )
237
+ capture: (label) ->
238
+ snaps.push {label: (label or "frame#{snaps.length}"), markup: normalize(root, s.normalize)}
239
+ Promise.resolve!
210
240
  drag: mctest.drag
211
241
  wait: wait
212
242
  random: mctest.random
213
243
  run-steps = (target) ->
214
244
  # 先等第一次畫完, step 才找得到節點
215
- (c.steps or []).reduce ((p, f) -> p.then(-> f target, ctx).then -> settle(root, list, q)), settle(root, list, q)
245
+ ([].concat(c.steps or [])).reduce ((p, f) -> p.then(-> f target, ctx).then -> settle(root, list, q)), settle(root, list, q)
216
246
  .then -> snaps.push {label: \final, markup: normalize(root, s.normalize)}
217
247
  .then -> {snaps, target}
218
248
  if c.dash => return load-dash!then (dash) ->
@@ -256,6 +286,8 @@ mctest.compare = (c, snaps) ->
256
286
  .then (r) -> if r.status == 204 => null else r.text!
257
287
  .then (baseline) ->
258
288
  if !(baseline?) => return {status: \new, current}
289
+ # 舊的 baseline 可能還留著空的 style 屬性 ( serialize 現在會略過 )
290
+ baseline = baseline.replace /\s+style=""/g, ''
259
291
  if baseline.trim! == current.trim! => return {status: \pass, current, baseline}
260
292
  a = baseline.trim!split \\n
261
293
  b = current.trim!split \\n
package/web/index.html CHANGED
@@ -43,6 +43,7 @@ body.only-fail .case.pass, body.only-fail .case.near { display: none; }
43
43
  <label><input type="checkbox" id="only-fail"> 只看沒過的</label>
44
44
  <button id="accept-all">accept all</button>
45
45
  <span id="summary"></span>
46
+ <a href="/playground" style="margin-left:auto;color:inherit">playground →</a>
46
47
  </header>
47
48
  <main id="cases"></main>
48
49
  <script src="/assets/lib/proxise/main/index.min.js"></script>
@@ -0,0 +1,85 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <title>playground</title>
7
+ <style>
8
+ :root { --fg: #222; --dim: #888; --line: #ddd; --bg: #fff; --panel: #f8f9fa; --err: #c92a2a; }
9
+ * { box-sizing: border-box; }
10
+ body { margin: 0; font: 13px/1.5 system-ui, sans-serif; color: var(--fg); background: var(--bg); display: flex; flex-direction: column; height: 100vh; }
11
+ header { display: flex; gap: .6em; align-items: center; flex-wrap: wrap; padding: .6em 1em; background: var(--panel); border-bottom: 1px solid var(--line); }
12
+ header b { font-size: 1.1em; }
13
+ header a { color: inherit; margin-left: auto; }
14
+ .body { flex: 1; display: flex; min-height: 0; }
15
+ aside { width: 340px; flex: none; overflow-y: auto; border-right: 1px solid var(--line); background: var(--panel); padding: .8em 1em 2em; }
16
+ main { flex: 1; overflow: auto; padding: 1.5em; }
17
+ h2 { font-size: .85em; margin: 1.4em 0 .4em; color: var(--dim); text-transform: uppercase; letter-spacing: .05em; }
18
+ h2:first-child { margin-top: 0; }
19
+ fieldset { border: 0; padding: 0; margin: 0 0 .4em; }
20
+ legend { font-weight: bold; padding: .3em 0 .1em; font-size: .9em; }
21
+ .row { display: flex; align-items: center; gap: .5em; padding: .15em 0 .15em .6em; }
22
+ .row > label { flex: 0 0 7.5em; color: #555; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
23
+ .row > .ctrl { flex: 1; display: flex; gap: .4em; align-items: center; min-width: 0; }
24
+ .row input[type=range] { flex: 1; min-width: 0; }
25
+ .row .v { width: 3em; text-align: right; font-family: ui-monospace, monospace; font-size: .9em; }
26
+ .row select, .row input[type=text] { width: 100%; min-width: 0; }
27
+ select, button { font: inherit; }
28
+ header select { max-width: 22em; }
29
+ textarea { width: 100%; font: 12px/1.4 ui-monospace, monospace; }
30
+ #csv { height: 14em; }
31
+ #binding { height: 8em; }
32
+ button { padding: .15em .7em; border: 1px solid var(--line); border-radius: 3px; background: #fff; cursor: pointer; }
33
+ button:hover:not(:disabled) { border-color: var(--fg); }
34
+ button:disabled { opacity: .4; cursor: default; }
35
+ .btns { display: flex; flex-wrap: wrap; gap: .4em; margin: .4em 0; }
36
+ .hint { color: var(--dim); font-size: .85em; }
37
+ #err { color: var(--err); white-space: pre-wrap; font-size: .85em; }
38
+ #err:empty { display: none; }
39
+ #stage { width: 640px; height: 400px; resize: both; overflow: hidden; border: 1px dashed var(--line); position: relative; }
40
+ #size { color: var(--dim); font-size: .85em; margin-top: .3em; }
41
+ #out { font: 12px/1.4 ui-monospace, monospace; color: #555; white-space: pre; }
42
+ </style>
43
+ </head>
44
+ <body>
45
+ <header>
46
+ <b>playground</b><span id="target"></span>
47
+ <select id="case"></select>
48
+ <button id="steps" disabled title="依序執行這個 case 的 steps ( 真實時間 )">跑 steps</button>
49
+ <select id="source"></select>
50
+ <a href="/">← cases</a>
51
+ </header>
52
+ <div class="body">
53
+ <aside>
54
+ <div id="err"></div>
55
+ <h2>設定</h2>
56
+ <div class="btns">
57
+ <button id="reset">回預設</button>
58
+ <button id="rerender">重畫</button>
59
+ <button id="dump">印出 config</button>
60
+ </div>
61
+ <div id="cfg"></div>
62
+ <h2>資料 ( raw )</h2>
63
+ <textarea id="csv" spellcheck="false"></textarea>
64
+ <h2>binding</h2>
65
+ <textarea id="binding" spellcheck="false"></textarea>
66
+ <div class="btns"><button id="apply">套用資料</button></div>
67
+ <div class="hint">raw 用 CSV 編輯, 看起來是數字的欄位會轉成數字.</div>
68
+ </aside>
69
+ <main>
70
+ <div id="stage"></div>
71
+ <div id="size"></div>
72
+ <pre id="out"></pre>
73
+ </main>
74
+ </div>
75
+ <script src="/assets/lib/proxise/main/index.min.js"></script>
76
+ <script src="/assets/lib/@loadingio/ldquery/main/index.min.js"></script>
77
+ <script src="/assets/lib/ldview/main/index.min.js"></script>
78
+ <script src="/assets/lib/@plotdb/semver/main/index.min.js"></script>
79
+ <script src="/assets/lib/@plotdb/csscope/main/index.min.js"></script>
80
+ <script src="/assets/lib/@plotdb/rescope/main/index.min.js"></script>
81
+ <script src="/assets/lib/@plotdb/block/main/index.min.js"></script>
82
+ <script src="/engine/suite.js"></script>
83
+ <script src="/engine/playground.js"></script>
84
+ </body>
85
+ </html>