squarified 0.3.6 → 0.4.0

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/dist/index.mjs CHANGED
@@ -1,1695 +1,72 @@
1
- var __defProp$c = Object.defineProperty;
2
- var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField$c = (obj, key, value) => __defNormalProp$c(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- const DEG_TO_RAD = Math.PI / 180;
5
- class Matrix2D {
6
- constructor(loc = {}) {
7
- __publicField$c(this, "a");
8
- __publicField$c(this, "b");
9
- __publicField$c(this, "c");
10
- __publicField$c(this, "d");
11
- __publicField$c(this, "e");
12
- __publicField$c(this, "f");
13
- this.a = loc.a || 1;
14
- this.b = loc.b || 0;
15
- this.c = loc.c || 0;
16
- this.d = loc.d || 1;
17
- this.e = loc.e || 0;
18
- this.f = loc.f || 0;
19
- }
20
- create(loc) {
21
- Object.assign(this, loc);
22
- return this;
23
- }
24
- transform(x, y, scaleX, scaleY, rotation, skewX, skewY) {
25
- this.scale(scaleX, scaleY).translation(x, y);
26
- if (skewX || skewY) {
27
- this.skew(skewX, skewY);
28
- } else {
29
- this.roate(rotation);
30
- }
31
- return this;
32
- }
33
- translation(x, y) {
34
- this.e += x;
35
- this.f += y;
36
- return this;
37
- }
38
- scale(a, d) {
39
- this.a *= a;
40
- this.d *= d;
41
- return this;
42
- }
43
- skew(x, y) {
44
- const tanX = Math.tan(x * DEG_TO_RAD);
45
- const tanY = Math.tan(y * DEG_TO_RAD);
46
- const a = this.a + this.b * tanX;
47
- const b = this.b + this.a * tanY;
48
- const c = this.c + this.d * tanX;
49
- const d = this.d + this.c * tanY;
50
- this.a = a;
51
- this.b = b;
52
- this.c = c;
53
- this.d = d;
54
- return this;
55
- }
56
- roate(rotation) {
57
- if (rotation > 0) {
58
- const rad = rotation * DEG_TO_RAD;
59
- const cosTheta = Math.cos(rad);
60
- const sinTheta = Math.sin(rad);
61
- const a = this.a * cosTheta - this.b * sinTheta;
62
- const b = this.a * sinTheta + this.b * cosTheta;
63
- const c = this.c * cosTheta - this.d * sinTheta;
64
- const d = this.c * sinTheta + this.d * cosTheta;
65
- this.a = a;
66
- this.b = b;
67
- this.c = c;
68
- this.d = d;
69
- }
70
- return this;
71
- }
72
- }
73
-
74
- var __defProp$b = Object.defineProperty;
75
- var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
76
- var __publicField$b = (obj, key, value) => __defNormalProp$b(obj, typeof key !== "symbol" ? key + "" : key, value);
77
- const SELF_ID = {
78
- id: 0,
79
- get() {
80
- return this.id++;
81
- }
82
- };
83
- var DisplayType = /* @__PURE__ */ ((DisplayType2) => {
84
- DisplayType2["Graph"] = "Graph";
85
- DisplayType2["Box"] = "Box";
86
- DisplayType2["Text"] = "Text";
87
- DisplayType2["RoundRect"] = "RoundRect";
88
- DisplayType2["Bitmap"] = "Bitmap";
89
- return DisplayType2;
90
- })(DisplayType || {});
91
- class Display {
92
- constructor() {
93
- __publicField$b(this, "parent");
94
- __publicField$b(this, "id");
95
- __publicField$b(this, "matrix");
96
- this.parent = null;
97
- this.id = SELF_ID.get();
98
- this.matrix = new Matrix2D();
99
- }
100
- destory() {
101
- }
102
- }
103
- const ASSIGN_MAPPINGS = {
104
- fillStyle: 1,
105
- strokeStyle: 2,
106
- font: 4,
107
- lineWidth: 8,
108
- textAlign: 16,
109
- textBaseline: 32
110
- };
111
- const ASSIGN_MAPPINGS_MODE = ASSIGN_MAPPINGS.fillStyle | ASSIGN_MAPPINGS.strokeStyle | ASSIGN_MAPPINGS.font | ASSIGN_MAPPINGS.lineWidth | ASSIGN_MAPPINGS.textAlign | ASSIGN_MAPPINGS.textBaseline;
112
- const CALL_MAPPINGS_MODE = 0;
113
- function createInstruction() {
114
- return {
115
- mods: [],
116
- fillStyle(...args) {
117
- this.mods.push({ mod: ["fillStyle", args], type: ASSIGN_MAPPINGS.fillStyle });
118
- },
119
- fillRect(...args) {
120
- this.mods.push({ mod: ["fillRect", args], type: CALL_MAPPINGS_MODE });
121
- },
122
- strokeStyle(...args) {
123
- this.mods.push({ mod: ["strokeStyle", args], type: ASSIGN_MAPPINGS.strokeStyle });
124
- },
125
- lineWidth(...args) {
126
- this.mods.push({ mod: ["lineWidth", args], type: ASSIGN_MAPPINGS.lineWidth });
127
- },
128
- strokeRect(...args) {
129
- this.mods.push({ mod: ["strokeRect", args], type: CALL_MAPPINGS_MODE });
130
- },
131
- fillText(...args) {
132
- this.mods.push({ mod: ["fillText", args], type: CALL_MAPPINGS_MODE });
133
- },
134
- font(...args) {
135
- this.mods.push({ mod: ["font", args], type: ASSIGN_MAPPINGS.font });
136
- },
137
- textBaseline(...args) {
138
- this.mods.push({ mod: ["textBaseline", args], type: ASSIGN_MAPPINGS.textBaseline });
139
- },
140
- textAlign(...args) {
141
- this.mods.push({ mod: ["textAlign", args], type: ASSIGN_MAPPINGS.textAlign });
142
- },
143
- beginPath() {
144
- this.mods.push({ mod: ["beginPath", []], type: CALL_MAPPINGS_MODE });
145
- },
146
- moveTo(...args) {
147
- this.mods.push({ mod: ["moveTo", args], type: CALL_MAPPINGS_MODE });
148
- },
149
- arcTo(...args) {
150
- this.mods.push({ mod: ["arcTo", args], type: CALL_MAPPINGS_MODE });
151
- },
152
- closePath() {
153
- this.mods.push({ mod: ["closePath", []], type: CALL_MAPPINGS_MODE });
154
- },
155
- fill() {
156
- this.mods.push({ mod: ["fill", []], type: CALL_MAPPINGS_MODE });
157
- },
158
- stroke() {
159
- this.mods.push({ mod: ["stroke", []], type: CALL_MAPPINGS_MODE });
160
- },
161
- drawImage(...args) {
162
- this.mods.push({ mod: ["drawImage", args], type: CALL_MAPPINGS_MODE });
163
- }
164
- };
165
- }
166
- class S extends Display {
167
- constructor(options = {}) {
168
- super();
169
- __publicField$b(this, "width");
170
- __publicField$b(this, "height");
171
- __publicField$b(this, "x");
172
- __publicField$b(this, "y");
173
- __publicField$b(this, "scaleX");
174
- __publicField$b(this, "scaleY");
175
- __publicField$b(this, "rotation");
176
- __publicField$b(this, "skewX");
177
- __publicField$b(this, "skewY");
178
- this.width = options.width || 0;
179
- this.height = options.height || 0;
180
- this.x = options.x || 0;
181
- this.y = options.y || 0;
182
- this.scaleX = options.scaleX || 1;
183
- this.scaleY = options.scaleY || 1;
184
- this.rotation = options.rotation || 0;
185
- this.skewX = options.skewX || 0;
186
- this.skewY = options.skewY || 0;
187
- }
188
- }
189
- class Graph extends S {
190
- constructor(options = {}) {
191
- super(options);
192
- __publicField$b(this, "instruction");
193
- __publicField$b(this, "__options__");
194
- __publicField$b(this, "__widget__");
195
- this.instruction = createInstruction();
196
- this.__options__ = options;
197
- this.__widget__ = null;
198
- }
199
- render(ctx) {
200
- this.create();
201
- const cap = this.instruction.mods.length;
202
- for (let i = 0; i < cap; i++) {
203
- const { mod, type } = this.instruction.mods[i];
204
- const [direct, ...args] = mod;
205
- if (type & ASSIGN_MAPPINGS_MODE) {
206
- ctx[direct] = args[0];
207
- continue;
208
- }
209
- ctx[direct].apply(ctx, ...args);
210
- }
211
- }
212
- get __instanceOf__() {
213
- return "Graph" /* Graph */;
214
- }
215
- }
216
-
217
- function isGraph(display) {
218
- return display.__instanceOf__ === DisplayType.Graph;
219
- }
220
- function isBox(display) {
221
- return display.__instanceOf__ === DisplayType.Box;
222
- }
223
- function isRoundRect(display) {
224
- return isGraph(display) && display.__shape__ === DisplayType.RoundRect;
225
- }
226
- function isText(display) {
227
- return isGraph(display) && display.__shape__ === DisplayType.Text;
228
- }
229
- function isBitmap(display) {
230
- return isGraph(display) && display.__shape__ === DisplayType.Bitmap;
231
- }
232
- const asserts = {
233
- isGraph,
234
- isBox,
235
- isText,
236
- isRoundRect,
237
- isBitmap
238
- };
239
-
240
- var __defProp$a = Object.defineProperty;
241
- var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
242
- var __publicField$a = (obj, key, value) => __defNormalProp$a(obj, typeof key !== "symbol" ? key + "" : key, value);
243
- class C extends Display {
244
- constructor() {
245
- super();
246
- __publicField$a(this, "elements");
247
- this.elements = [];
248
- }
249
- add(...elements) {
250
- const cap = elements.length;
251
- for (let i = 0; i < cap; i++) {
252
- const element = elements[i];
253
- if (element.parent) ;
254
- this.elements.push(element);
255
- element.parent = this;
256
- }
257
- }
258
- remove(...elements) {
259
- const cap = elements.length;
260
- for (let i = 0; i < cap; i++) {
261
- for (let j = this.elements.length - 1; j >= 0; j--) {
262
- const element = this.elements[j];
263
- if (element.id === elements[i].id) {
264
- this.elements.splice(j, 1);
265
- element.parent = null;
266
- }
267
- }
268
- }
269
- }
270
- destory() {
271
- this.elements.forEach((element) => element.parent = null);
272
- this.elements.length = 0;
273
- }
274
- }
275
- class Box extends C {
276
- constructor() {
277
- super();
278
- __publicField$a(this, "elements");
279
- this.elements = [];
280
- }
281
- add(...elements) {
282
- const cap = elements.length;
283
- for (let i = 0; i < cap; i++) {
284
- const element = elements[i];
285
- if (element.parent) ;
286
- this.elements.push(element);
287
- element.parent = this;
288
- }
289
- }
290
- remove(...elements) {
291
- const cap = elements.length;
292
- for (let i = 0; i < cap; i++) {
293
- for (let j = this.elements.length - 1; j >= 0; j--) {
294
- const element = this.elements[j];
295
- if (element.id === elements[i].id) {
296
- this.elements.splice(j, 1);
297
- element.parent = null;
298
- }
299
- }
300
- }
301
- }
302
- destory() {
303
- this.elements.forEach((element) => element.parent = null);
304
- this.elements.length = 0;
305
- }
306
- get __instanceOf__() {
307
- return DisplayType.Box;
308
- }
309
- clone() {
310
- const box = new Box();
311
- if (this.elements.length) {
312
- const stack = [{ elements: this.elements, parent: box }];
313
- while (stack.length > 0) {
314
- const { elements, parent } = stack.pop();
315
- const cap = elements.length;
316
- for (let i = 0; i < cap; i++) {
317
- const element = elements[i];
318
- if (asserts.isBox(element)) {
319
- const newBox = new Box();
320
- newBox.parent = parent;
321
- parent.add(newBox);
322
- stack.push({ elements: element.elements, parent: newBox });
323
- } else if (asserts.isGraph(element)) {
324
- const el = element.clone();
325
- el.parent = parent;
326
- parent.add(el);
327
- }
328
- }
329
- }
330
- }
331
- return box;
332
- }
333
- }
334
-
335
- var __defProp$9 = Object.defineProperty;
336
- var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
337
- var __publicField$9 = (obj, key, value) => __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
338
- class Bitmap extends Graph {
339
- constructor(options = {}) {
340
- super(options);
341
- __publicField$9(this, "bitmap");
342
- __publicField$9(this, "style");
343
- __publicField$9(this, "dpi");
344
- this.bitmap = options.bitmap || null;
345
- this.style = options.style || /* @__PURE__ */ Object.create(null);
346
- this.dpi = options.dpi || 1;
347
- }
348
- create() {
349
- if (this.bitmap) {
350
- this.instruction.drawImage(this.bitmap, 0, 0, this.bitmap.width / this.dpi, this.bitmap.height / this.dpi);
351
- }
352
- }
353
- clone() {
354
- return new Bitmap({ ...this.style, ...this.__options__ });
355
- }
356
- get __shape__() {
357
- return DisplayType.Bitmap;
358
- }
359
- }
360
-
361
- function decodeHLS(meta) {
362
- const { h, l, s, a } = meta;
363
- if ("a" in meta) {
364
- return `hsla(${h}deg, ${s}%, ${l}%, ${a})`;
365
- }
366
- return `hsl(${h}deg, ${s}%, ${l}%)`;
367
- }
368
- function decodeRGB(meta) {
369
- const { r, g, b, a } = meta;
370
- if ("a" in meta) {
371
- return `rgba(${r}, ${g}, ${b}, ${a})`;
372
- }
373
- return `rgb(${r}, ${g}, ${b})`;
374
- }
375
- function decodeColor(meta) {
376
- return meta.mode === "rgb" ? decodeRGB(meta.desc) : decodeHLS(meta.desc);
377
- }
378
- function evaluateFillStyle(primitive, opacity = 1) {
379
- const descibe = { mode: primitive.mode, desc: { ...primitive.desc, a: opacity } };
380
- return decodeColor(descibe);
381
- }
382
- const runtime = {
383
- evaluateFillStyle
384
- };
385
-
386
- var __defProp$8 = Object.defineProperty;
387
- var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
388
- var __publicField$8 = (obj, key, value) => __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
389
- class RoundRect extends Graph {
390
- constructor(options = {}) {
391
- super(options);
392
- __publicField$8(this, "style");
393
- this.style = options.style || /* @__PURE__ */ Object.create(null);
394
- }
395
- get __shape__() {
396
- return DisplayType.RoundRect;
397
- }
398
- create() {
399
- const padding = this.style.padding;
400
- const x = 0;
401
- const y = 0;
402
- const width = this.width - padding * 2;
403
- const height = this.height - padding * 2;
404
- const radius = this.style.radius || 0;
405
- this.instruction.beginPath();
406
- this.instruction.moveTo(x + radius, y);
407
- this.instruction.arcTo(x + width, y, x + width, y + height, radius);
408
- this.instruction.arcTo(x + width, y + height, x, y + height, radius);
409
- this.instruction.arcTo(x, y + height, x, y, radius);
410
- this.instruction.arcTo(x, y, x + width, y, radius);
411
- this.instruction.closePath();
412
- if (this.style.fill) {
413
- this.instruction.closePath();
414
- this.instruction.fillStyle(runtime.evaluateFillStyle(this.style.fill, this.style.opacity));
415
- this.instruction.fill();
416
- }
417
- if (this.style.stroke) {
418
- if (typeof this.style.lineWidth === "number") {
419
- this.instruction.lineWidth(this.style.lineWidth);
420
- }
421
- this.instruction.strokeStyle(this.style.stroke);
422
- this.instruction.stroke();
423
- }
424
- }
425
- clone() {
426
- return new RoundRect({ ...this.style, ...this.__options__ });
427
- }
428
- }
429
-
430
- var __defProp$7 = Object.defineProperty;
431
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
432
- var __publicField$7 = (obj, key, value) => __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
433
- class Text extends Graph {
434
- constructor(options = {}) {
435
- super(options);
436
- __publicField$7(this, "text");
437
- __publicField$7(this, "style");
438
- this.text = options.text || "";
439
- this.style = options.style || /* @__PURE__ */ Object.create(null);
440
- }
441
- create() {
442
- if (this.style.fill) {
443
- this.instruction.font(this.style.font);
444
- this.instruction.lineWidth(this.style.lineWidth);
445
- this.instruction.textBaseline(this.style.baseline);
446
- this.instruction.fillStyle(this.style.fill);
447
- this.instruction.fillText(this.text, 0, 0);
448
- }
449
- }
450
- clone() {
451
- return new Text({ ...this.style, ...this.__options__ });
452
- }
453
- get __shape__() {
454
- return DisplayType.Text;
455
- }
456
- }
457
-
458
- function traverse(graphs, handler) {
459
- const len = graphs.length;
460
- for (let i = 0; i < len; i++) {
461
- const graph = graphs[i];
462
- if (asserts.isGraph(graph)) {
463
- handler(graph);
464
- } else if (asserts.isBox(graph)) {
465
- traverse(graph.elements, handler);
466
- }
467
- }
468
- }
469
- function getCanvasBoundarySize() {
470
- const ua = navigator.userAgent;
471
- let size = 16384;
472
- if (/Firefox\/(\d+)/.test(ua)) {
473
- const version = parseInt(RegExp.$1, 10);
474
- if (version >= 122) {
475
- size = 23168;
476
- } else {
477
- size = 11180;
478
- }
479
- }
480
- return { size };
481
- }
482
- const canvasBoundarySize = getCanvasBoundarySize();
483
-
484
- const easing = {
485
- linear: (k) => k,
486
- quadraticIn: (k) => k * k,
487
- quadraticOut: (k) => k * (2 - k),
488
- quadraticInOut: (k) => {
489
- if ((k *= 2) < 1) {
490
- return 0.5 * k * k;
491
- }
492
- return -0.5 * (--k * (k - 2) - 1);
493
- },
494
- cubicIn: (k) => k * k * k,
495
- cubicOut: (k) => {
496
- if ((k *= 2) < 1) {
497
- return 0.5 * k * k * k;
498
- }
499
- return 0.5 * ((k -= 2) * k * k + 2);
500
- },
501
- cubicInOut: (k) => {
502
- if ((k *= 2) < 1) {
503
- return 0.5 * k * k * k;
504
- }
505
- return 0.5 * ((k -= 2) * k * k + 2);
506
- }
507
- };
508
-
509
- var __defProp$6 = Object.defineProperty;
510
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
511
- var __publicField$6 = (obj, key, value) => __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
512
- class Event {
513
- constructor() {
514
- __publicField$6(this, "eventCollections");
515
- this.eventCollections = /* @__PURE__ */ Object.create(null);
516
- }
517
- on(evt, handler, c) {
518
- if (!(evt in this.eventCollections)) {
519
- this.eventCollections[evt] = [];
520
- }
521
- const data = {
522
- name: evt,
523
- handler,
524
- ctx: c || this,
525
- silent: false
526
- };
527
- this.eventCollections[evt].push(data);
528
- }
529
- off(evt, handler) {
530
- if (evt in this.eventCollections) {
531
- if (!handler) {
532
- this.eventCollections[evt] = [];
533
- return;
534
- }
535
- this.eventCollections[evt] = this.eventCollections[evt].filter((d) => d.handler !== handler);
536
- }
537
- }
538
- silent(evt, handler) {
539
- if (!(evt in this.eventCollections)) {
540
- return;
541
- }
542
- this.eventCollections[evt].forEach((d) => {
543
- if (!handler || d.handler === handler) {
544
- d.silent = true;
545
- }
546
- });
547
- }
548
- active(evt, handler) {
549
- if (!(evt in this.eventCollections)) {
550
- return;
551
- }
552
- this.eventCollections[evt].forEach((d) => {
553
- if (!handler || d.handler === handler) {
554
- d.silent = false;
555
- }
556
- });
557
- }
558
- emit(evt, ...args) {
559
- if (!this.eventCollections[evt]) {
560
- return;
561
- }
562
- const handlers = this.eventCollections[evt];
563
- if (handlers.length) {
564
- handlers.forEach((d) => {
565
- if (d.silent) {
566
- return;
567
- }
568
- d.handler.call(d.ctx, ...args);
569
- });
570
- }
571
- }
572
- bindWithContext(c) {
573
- return (evt, handler) => this.on(evt, handler, c);
574
- }
575
- }
576
-
577
- function hashCode(str) {
578
- let hash = 0;
579
- for (let i = 0; i < str.length; i++) {
580
- const code = str.charCodeAt(i);
581
- hash = (hash << 5) - hash + code;
582
- hash = hash & hash;
583
- }
584
- return hash;
585
- }
586
- function perferNumeric(s) {
587
- if (typeof s === "number") {
588
- return true;
589
- }
590
- return s.charCodeAt(0) >= 48 && s.charCodeAt(0) <= 57;
591
- }
592
- function createRoundBlock(x, y, width, height, style) {
593
- return new RoundRect({ width, height, x, y, style: { ...style } });
594
- }
595
- function createTitleText(text, x, y, font, color) {
596
- return new Text({
597
- text,
598
- x,
599
- y,
600
- style: { fill: color, textAlign: "center", baseline: "middle", font, lineWidth: 1 }
601
- });
602
- }
603
- const raf = window.requestAnimationFrame;
604
- function createCanvasElement() {
605
- return document.createElement("canvas");
606
- }
607
- function applyCanvasTransform(ctx, matrix, dpr) {
608
- ctx.setTransform(matrix.a * dpr, matrix.b * dpr, matrix.c * dpr, matrix.d * dpr, matrix.e * dpr, matrix.f * dpr);
609
- }
610
- function mixin(app, methods) {
611
- methods.forEach(({ name, fn }) => {
612
- Object.defineProperty(app, name, {
613
- value: fn(app),
614
- writable: false
615
- });
616
- });
617
- }
618
- function prettyStrJoin(...s) {
619
- return s.join("");
620
- }
621
-
622
- const NAME_SPACE = "etoile";
623
- const log = {
624
- error: (message) => {
625
- return `[${NAME_SPACE}] ${message}`;
626
- }
627
- };
628
-
629
- var __defProp$5 = Object.defineProperty;
630
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
631
- var __publicField$5 = (obj, key, value) => __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
632
- function writeBoundingRectForCanvas(c, w, h, dpr) {
633
- c.width = w * dpr;
634
- c.height = h * dpr;
635
- c.style.cssText = `width: ${w}px; height: ${h}px`;
636
- }
637
- class Canvas {
638
- constructor(options) {
639
- __publicField$5(this, "canvas");
640
- __publicField$5(this, "ctx");
641
- this.canvas = createCanvasElement();
642
- this.setOptions(options);
643
- this.ctx = this.canvas.getContext("2d");
644
- }
645
- setOptions(options) {
646
- writeBoundingRectForCanvas(this.canvas, options.width, options.height, options.devicePixelRatio);
647
- }
648
- }
649
- class Render {
650
- constructor(to, options) {
651
- __publicField$5(this, "options");
652
- __publicField$5(this, "container");
653
- this.container = new Canvas(options);
654
- this.options = options;
655
- this.initOptions(options);
656
- if (!options.shaow) {
657
- to.appendChild(this.container.canvas);
658
- }
659
- }
660
- clear(width, height) {
661
- this.ctx.clearRect(0, 0, width, height);
662
- }
663
- get canvas() {
664
- return this.container.canvas;
665
- }
666
- get ctx() {
667
- return this.container.ctx;
668
- }
669
- initOptions(userOptions = {}) {
670
- Object.assign(this.options, userOptions);
671
- this.container.setOptions(this.options);
672
- }
673
- destory() {
674
- }
675
- }
676
-
677
- var __defProp$4 = Object.defineProperty;
678
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
679
- var __publicField$4 = (obj, key, value) => __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
680
- function drawGraphIntoCanvas(graph, opts) {
681
- const { ctx, dpr } = opts;
682
- ctx.save();
683
- if (asserts.isBox(graph)) {
684
- const elements = graph.elements;
685
- const cap = elements.length;
686
- for (let i = 0; i < cap; i++) {
687
- const element = elements[i];
688
- drawGraphIntoCanvas(element, opts);
689
- }
690
- }
691
- if (asserts.isGraph(graph)) {
692
- const matrix = graph.matrix.create({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
693
- matrix.transform(graph.x, graph.y, graph.scaleX, graph.scaleY, graph.rotation, graph.skewX, graph.skewY);
694
- if (asserts.isRoundRect(graph)) {
695
- const effectiveWidth = graph.width - graph.style.padding * 2;
696
- const effectiveHeight = graph.height - graph.style.padding * 2;
697
- if (effectiveWidth <= 0 || effectiveHeight <= 0) {
698
- ctx.restore();
699
- return;
700
- }
701
- if (graph.style.radius >= effectiveHeight / 2 || graph.style.radius >= effectiveWidth / 2) {
702
- ctx.restore();
703
- return;
704
- }
705
- }
706
- applyCanvasTransform(ctx, matrix, dpr);
707
- graph.render(ctx);
708
- }
709
- ctx.restore();
710
- }
711
- class Schedule extends Box {
712
- constructor(to, renderOptions = {}) {
713
- super();
714
- __publicField$4(this, "render");
715
- __publicField$4(this, "to");
716
- __publicField$4(this, "event");
717
- this.to = typeof to === "string" ? document.querySelector(to) : to;
718
- if (!this.to) {
719
- throw new Error(log.error("The element to bind is not found."));
720
- }
721
- const { width, height } = this.to.getBoundingClientRect();
722
- Object.assign(renderOptions, { width, height }, { devicePixelRatio: window.devicePixelRatio || 1 });
723
- this.event = new Event();
724
- this.render = new Render(this.to, renderOptions);
725
- }
726
- update() {
727
- this.render.clear(this.render.options.width, this.render.options.height);
728
- this.execute(this.render, this);
729
- const matrix = this.matrix.create({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
730
- applyCanvasTransform(this.render.ctx, matrix, this.render.options.devicePixelRatio);
731
- }
732
- // execute all graph elements
733
- execute(render, graph = this) {
734
- drawGraphIntoCanvas(graph, { c: render.canvas, ctx: render.ctx, dpr: render.options.devicePixelRatio });
735
- }
736
- }
737
-
738
- var __defProp$3 = Object.defineProperty;
739
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
740
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
741
- class RenderCache extends Canvas {
742
- constructor(opts) {
743
- super(opts);
744
- __publicField$3(this, "key");
745
- __publicField$3(this, "$memory");
746
- this.key = "render-cache";
747
- this.$memory = false;
748
- }
749
- get state() {
750
- return this.$memory;
751
- }
752
- flush(treemap, matrix = new Matrix2D()) {
753
- const { devicePixelRatio, width, height } = treemap.render.options;
754
- const { a, d } = matrix;
755
- const { size } = canvasBoundarySize;
756
- if (width * a >= size || height * d >= size) {
757
- return;
758
- }
759
- if (width * a * height * d >= size * size) {
760
- return;
761
- }
762
- this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
763
- this.setOptions({ width: width * a, height: height * d, devicePixelRatio });
764
- resetLayout(treemap, width * a, height * d);
765
- drawGraphIntoCanvas(treemap, { c: this.canvas, ctx: this.ctx, dpr: devicePixelRatio });
766
- this.$memory = true;
767
- }
768
- destroy() {
769
- this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
770
- this.$memory = false;
771
- }
772
- }
773
- class FontCache {
774
- constructor() {
775
- __publicField$3(this, "key");
776
- __publicField$3(this, "fonts");
777
- __publicField$3(this, "ellispsis");
778
- this.key = "font-cache";
779
- this.fonts = {};
780
- this.ellispsis = {};
781
- }
782
- get state() {
783
- return true;
784
- }
785
- flush(treemap, matrix = new Matrix2D()) {
786
- const { width, height } = treemap.render.options;
787
- const { a, d } = matrix;
788
- const zoomedWidth = width * a;
789
- const zoomedHeight = height * d;
790
- if (zoomedWidth <= width || zoomedHeight <= height) {
791
- return;
792
- }
793
- traverse([treemap.elements[0]], (graph) => {
794
- if (asserts.isRoundRect(graph)) {
795
- const { x, y, height: graphHeight, width: graphWidth } = graph;
796
- if (!graphHeight || !graphWidth) {
797
- return;
798
- }
799
- if (x >= 0 && y >= 0 && x + graphWidth <= width && y + graphHeight <= height) {
800
- if (graph.__widget__) {
801
- const node = graph.__widget__.node;
802
- delete this.fonts[node.id];
803
- delete this.ellispsis[node.label];
804
- }
805
- }
806
- }
807
- });
808
- }
809
- destroy() {
810
- this.fonts = {};
811
- this.ellispsis = {};
812
- }
813
- queryFontById(id, byDefault) {
814
- if (!(id in this.fonts)) {
815
- this.fonts[id] = byDefault();
816
- }
817
- return this.fonts[id];
818
- }
819
- }
820
-
821
- var __defProp$2 = Object.defineProperty;
822
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
823
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
824
- const DOM_EVENTS = ["click", "mousedown", "mousemove", "mouseup", "mouseover", "mouseout", "wheel"];
825
- function getOffset(el) {
826
- let e = 0;
827
- let f = 0;
828
- if (document.documentElement.getBoundingClientRect && el.getBoundingClientRect) {
829
- const { top, left } = el.getBoundingClientRect();
830
- e = top;
831
- f = left;
832
- } else {
833
- for (let elt = el; elt; elt = el.offsetParent) {
834
- e += el.offsetLeft;
835
- f += el.offsetTop;
836
- }
837
- }
838
- return [
839
- e + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft),
840
- f + Math.max(document.documentElement.scrollTop, document.body.scrollTop)
841
- ];
842
- }
843
- function captureBoxXY(c, evt, a, d, translateX, translateY) {
844
- const boundingClientRect = c.getBoundingClientRect();
845
- if (evt instanceof MouseEvent) {
846
- const [e, f] = getOffset(c);
847
- return {
848
- x: (evt.clientX - boundingClientRect.left - e - translateX) / a,
849
- y: (evt.clientY - boundingClientRect.top - f - translateY) / d
850
- };
851
- }
852
- return { x: 0, y: 0 };
853
- }
854
- function createEffectRun(c) {
855
- return (fn) => {
856
- const effect = () => {
857
- const done = fn();
858
- if (!done) {
859
- c.animationFrameID = raf(effect);
860
- }
861
- };
862
- if (!c.animationFrameID) {
863
- c.animationFrameID = raf(effect);
864
- }
865
- };
866
- }
867
- function createEffectStop(c) {
868
- return () => {
869
- if (c.animationFrameID) {
870
- window.cancelAnimationFrame(c.animationFrameID);
871
- c.animationFrameID = null;
872
- }
873
- };
874
- }
875
- function createSmoothFrame() {
876
- const c = {
877
- animationFrameID: null
878
- };
879
- const run = createEffectRun(c);
880
- const stop = createEffectStop(c);
881
- return { run, stop };
882
- }
883
- function bindDOMEvent(el, evt, dom) {
884
- const handler = (e) => {
885
- const { x, y } = captureBoxXY(el, e, 1, 1, dom.matrix.e, dom.matrix.f);
886
- dom.emit(evt, { native: e, loc: { x, y } });
887
- };
888
- el.addEventListener(evt, handler);
889
- return handler;
890
- }
891
- class DOMEvent extends Event {
892
- constructor(el) {
893
- super();
894
- __publicField$2(this, "el");
895
- __publicField$2(this, "events");
896
- __publicField$2(this, "matrix");
897
- this.el = el;
898
- this.matrix = new Matrix2D();
899
- this.events = DOM_EVENTS.map((evt) => bindDOMEvent(this.el, evt, this));
900
- }
901
- }
902
-
903
- function useMagicTrackPad(event) {
904
- if (event.cancelable !== false) {
905
- event.preventDefault();
906
- }
907
- !event.ctrlKey;
908
- }
909
-
910
- function sortChildrenByKey(data, ...keys) {
911
- return data.sort((a, b) => {
912
- for (const key of keys) {
913
- const v = a[key];
914
- const v2 = b[key];
915
- if (perferNumeric(v) && perferNumeric(v2)) {
916
- if (v2 > v) {
917
- return 1;
918
- }
919
- if (v2 < v) {
920
- return -1;
921
- }
922
- continue;
923
- }
924
- const comparison = ("" + v).localeCompare("" + v2);
925
- if (comparison !== 0) {
926
- return comparison;
927
- }
928
- }
929
- return 0;
930
- });
931
- }
932
- function c2m(data, key, modifier) {
933
- if (Array.isArray(data.groups)) {
934
- data.groups = sortChildrenByKey(data.groups.map((d) => c2m(d, key, modifier)), "weight");
935
- }
936
- const obj = { ...data, weight: data[key] };
937
- if (modifier) {
938
- return modifier(obj);
939
- }
940
- return obj;
941
- }
942
- function flatten(data) {
943
- const result = [];
944
- for (let i = 0; i < data.length; i++) {
945
- const { groups, ...rest } = data[i];
946
- result.push(rest);
947
- if (groups) {
948
- result.push(...flatten(groups));
949
- }
950
- }
951
- return result;
952
- }
953
- function bindParentForModule(modules, parent) {
954
- return modules.map((module) => {
955
- const next = { ...module };
956
- next.parent = parent;
957
- if (next.groups && Array.isArray(next.groups)) {
958
- next.groups = bindParentForModule(next.groups, next);
959
- }
960
- return next;
961
- });
962
- }
963
- function getNodeDepth(node) {
964
- let depth = 0;
965
- while (node.parent) {
966
- node = node.parent;
967
- depth++;
968
- }
969
- return depth;
970
- }
971
- function visit(data, fn) {
972
- if (!data) {
973
- return null;
974
- }
975
- for (const d of data) {
976
- if (d.children) {
977
- const result = visit(d.children, fn);
978
- if (result) {
979
- return result;
980
- }
981
- }
982
- const stop = fn(d);
983
- if (stop) {
984
- return d;
985
- }
986
- }
987
- return null;
988
- }
989
- function findRelativeNode(p, layoutNodes) {
990
- return visit(layoutNodes, (node) => {
991
- const [x, y, w, h] = node.layout;
992
- if (p.x >= x && p.y >= y && p.x < x + w && p.y < y + h) {
993
- return true;
994
- }
995
- });
996
- }
997
- function findRelativeNodeById(id, layoutNodes) {
998
- return visit(layoutNodes, (node) => {
999
- if (node.node.id === id) {
1000
- return true;
1001
- }
1002
- });
1003
- }
1004
-
1005
- var __defProp$1 = Object.defineProperty;
1006
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1007
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1008
- function createTreemapEventState() {
1009
- return {
1010
- isDragging: false,
1011
- isWheeling: false,
1012
- isZooming: false,
1013
- currentNode: null,
1014
- forceDestroy: false,
1015
- dragX: 0,
1016
- dragY: 0
1017
- };
1018
- }
1019
- const INTERNAL_EVENT_MAPPINGS = {
1020
- ON_ZOOM: 1,
1021
- ON_CLEANUP: 3
1022
- };
1023
- const ANIMATION_DURATION = 300;
1024
- const fill = { desc: { r: 255, g: 255, b: 255 }, mode: "rgb" };
1025
- function smoothFrame(callback, opts) {
1026
- const frame = createSmoothFrame();
1027
- const startTime = Date.now();
1028
- const condtion = (process) => {
1029
- if (Array.isArray(opts.deps)) {
1030
- return opts.deps.some((dep) => dep());
1031
- }
1032
- return process >= 1;
1033
- };
1034
- frame.run(() => {
1035
- const elapsed = Date.now() - startTime;
1036
- const progress = Math.min(elapsed / opts.duration, 1);
1037
- if (condtion(progress)) {
1038
- frame.stop();
1039
- if (opts.onStop) {
1040
- opts.onStop();
1041
- }
1042
- return true;
1043
- }
1044
- return callback(progress, frame.stop);
1045
- });
1046
- }
1047
- const HIGH_LIGHT_OPACITY = 0.3;
1048
- function drawHighlight(treemap, evt) {
1049
- const { highlight } = treemap;
1050
- const { currentNode } = evt.state;
1051
- if (currentNode) {
1052
- const [x, y, w, h] = currentNode.layout;
1053
- smoothFrame((_, cleanup) => {
1054
- cleanup();
1055
- highlight.reset();
1056
- const mask = createRoundBlock(x, y, w, h, { fill, opacity: HIGH_LIGHT_OPACITY, radius: 4, padding: 2 });
1057
- highlight.add(mask);
1058
- highlight.setZIndexForHighlight("1");
1059
- stackMatrixTransform(mask, evt.matrix.e, evt.matrix.f, 1);
1060
- highlight.update();
1061
- if (!evt.state.currentNode) {
1062
- return true;
1063
- }
1064
- }, {
1065
- duration: ANIMATION_DURATION,
1066
- deps: [() => evt.state.isDragging, () => evt.state.isWheeling, () => evt.state.isZooming]
1067
- });
1068
- } else {
1069
- highlight.reset();
1070
- highlight.setZIndexForHighlight();
1071
- }
1072
- }
1073
- class TreemapEvent extends DOMEvent {
1074
- constructor(app, treemap) {
1075
- super(treemap.render.canvas);
1076
- __publicField$1(this, "exposedEvent");
1077
- __publicField$1(this, "state");
1078
- __publicField$1(this, "zoom");
1079
- this.exposedEvent = new Event();
1080
- this.state = createTreemapEventState();
1081
- const exposedMethods = [
1082
- { name: "on", fn: () => this.exposedEvent.bindWithContext(treemap.api) },
1083
- { name: "off", fn: () => this.exposedEvent.off.bind(this.exposedEvent) }
1084
- ];
1085
- DOM_EVENTS.forEach((evt) => {
1086
- this.on(evt, (metadata) => {
1087
- this.dispatch({ type: evt, treemap }, metadata);
1088
- });
1089
- });
1090
- mixin(app, exposedMethods);
1091
- treemap.event.on(INTERNAL_EVENT_MAPPINGS.ON_CLEANUP, () => {
1092
- this.matrix.create({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
1093
- this.state = createTreemapEventState();
1094
- });
1095
- this.zoom = createOnZoom(treemap, this);
1096
- treemap.event.on(INTERNAL_EVENT_MAPPINGS.ON_ZOOM, this.zoom);
1097
- }
1098
- dispatch(ctx, metadata) {
1099
- const node = findRelativeNode(metadata.loc, ctx.treemap.layoutNodes);
1100
- const fn = prettyStrJoin("on", ctx.type);
1101
- if (typeof this[fn] === "function") {
1102
- this[fn](ctx, metadata, node);
1103
- }
1104
- if (ctx.type === "mousemove") {
1105
- if (this.state.isDragging) {
1106
- this.exposedEvent.silent("click");
1107
- } else {
1108
- this.exposedEvent.active("click");
1109
- }
1110
- }
1111
- this.exposedEvent.emit(ctx.type === "macOSWheel" ? "wheel" : ctx.type, { native: metadata.native, module: node });
1112
- }
1113
- onmousemove(ctx, metadata, node) {
1114
- if (!this.state.isDragging) {
1115
- if (this.state.currentNode !== node || !node) {
1116
- this.state.currentNode = node;
1117
- }
1118
- drawHighlight(ctx.treemap, this);
1119
- } else {
1120
- const { treemap } = ctx;
1121
- smoothFrame((_, cleanup) => {
1122
- cleanup();
1123
- const { offsetX: x, offsetY: y } = metadata.native;
1124
- const { dragX: lastX, dragY: lastY } = this.state;
1125
- const drawX = x - lastX;
1126
- const drawY = y - lastY;
1127
- treemap.highlight.reset();
1128
- treemap.highlight.setZIndexForHighlight();
1129
- treemap.reset();
1130
- this.matrix.translation(drawX, drawY);
1131
- Object.assign(this.state, { isDragging: true, dragX: x, dragY: y });
1132
- stackMatrixTransformWithGraphAndLayer(treemap.elements, this.matrix.e, this.matrix.f, 1);
1133
- treemap.update();
1134
- return true;
1135
- }, {
1136
- duration: ANIMATION_DURATION,
1137
- deps: [() => this.state.forceDestroy],
1138
- onStop: () => {
1139
- this.state.isDragging = false;
1140
- }
1141
- });
1142
- }
1143
- }
1144
- onmouseout(ctx) {
1145
- this.state.currentNode = null;
1146
- drawHighlight(ctx.treemap, this);
1147
- }
1148
- onmousedown(ctx, metadata) {
1149
- if (isScrollWheelOrRightButtonOnMouseupAndDown(metadata.native)) {
1150
- return;
1151
- }
1152
- this.state.isDragging = true;
1153
- this.state.dragX = metadata.native.offsetX;
1154
- this.state.dragY = metadata.native.offsetY;
1155
- this.state.forceDestroy = false;
1156
- if (!ctx.treemap.renderCache.state) {
1157
- this.exposedEvent.silent("mousemove");
1158
- this.silent("mousemove");
1159
- ctx.treemap.renderCache.flush(ctx.treemap, this.matrix);
1160
- this.active("mousemove");
1161
- this.exposedEvent.active("mousemove");
1162
- }
1163
- }
1164
- onmouseup(ctx) {
1165
- if (!this.state.isDragging) {
1166
- return;
1167
- }
1168
- this.state.forceDestroy = true;
1169
- this.state.isDragging = false;
1170
- const { treemap } = ctx;
1171
- treemap.highlight.reset();
1172
- treemap.highlight.setZIndexForHighlight();
1173
- }
1174
- onwheel(ctx, metadata) {
1175
- ctx.treemap.renderCache.destroy();
1176
- ctx.treemap.event.silent(INTERNAL_EVENT_MAPPINGS.ON_ZOOM);
1177
- const { native } = metadata;
1178
- const { treemap } = ctx;
1179
- const wheelDelta = native.wheelDelta;
1180
- const absWheelDelta = Math.abs(wheelDelta);
1181
- const offsetX = native.offsetX;
1182
- const offsetY = native.offsetY;
1183
- if (wheelDelta === 0) {
1184
- return;
1185
- }
1186
- this.state.forceDestroy = true;
1187
- const factor = absWheelDelta > 3 ? 1.4 : absWheelDelta > 1 ? 1.2 : 1.1;
1188
- const delta = wheelDelta > 0 ? factor : 1 / factor;
1189
- const targetScaleRatio = this.matrix.a * delta;
1190
- const translateX = offsetX - (offsetX - this.matrix.e) * delta;
1191
- const translateY = offsetY - (offsetY - this.matrix.f) * delta;
1192
- smoothFrame((progress, cleanup) => {
1193
- this.exposedEvent.silent("mousemove");
1194
- this.silent("mousemove");
1195
- this.silent("click");
1196
- this.exposedEvent.silent("click");
1197
- treemap.highlight.reset();
1198
- treemap.highlight.setZIndexForHighlight();
1199
- treemap.fontCache.flush(treemap, this.matrix);
1200
- this.state.isWheeling = true;
1201
- const easedProgress = easing.cubicInOut(progress);
1202
- const scale = (targetScaleRatio - this.matrix.a) * easedProgress;
1203
- this.matrix.a += scale;
1204
- this.matrix.d += scale;
1205
- this.matrix.translation((translateX - this.matrix.e) * easedProgress, (translateY - this.matrix.f) * easedProgress);
1206
- resetLayout(
1207
- treemap,
1208
- treemap.render.canvas.width * this.matrix.a / treemap.render.options.devicePixelRatio,
1209
- treemap.render.canvas.height * this.matrix.d / treemap.render.options.devicePixelRatio
1210
- );
1211
- stackMatrixTransformWithGraphAndLayer(treemap.elements, this.matrix.e, this.matrix.f, 1);
1212
- treemap.update();
1213
- cleanup();
1214
- }, {
1215
- duration: ANIMATION_DURATION,
1216
- onStop: () => {
1217
- this.state.forceDestroy = false;
1218
- this.state.isWheeling = false;
1219
- this.active("mousemove");
1220
- this.exposedEvent.active("mousemove");
1221
- this.active("click");
1222
- this.exposedEvent.active("click");
1223
- treemap.event.active(INTERNAL_EVENT_MAPPINGS.ON_ZOOM);
1224
- }
1225
- });
1226
- }
1227
- onmacOSWheel(ctx, metadata) {
1228
- useMagicTrackPad(metadata.native);
1229
- }
1230
- }
1231
- function stackMatrixTransform(graph, e, f, scale) {
1232
- graph.x = graph.x * scale + e;
1233
- graph.y = graph.y * scale + f;
1234
- graph.scaleX = scale;
1235
- graph.scaleY = scale;
1236
- }
1237
- function stackMatrixTransformWithGraphAndLayer(graphs, e, f, scale) {
1238
- traverse(graphs, (graph) => stackMatrixTransform(graph, e, f, scale));
1239
- }
1240
- function isScrollWheelOrRightButtonOnMouseupAndDown(e) {
1241
- return e.which === 2 || e.which === 3;
1242
- }
1243
- function createOnZoom(treemap, evt) {
1244
- return (node) => {
1245
- treemap.renderCache.destroy();
1246
- evt.state.isZooming = true;
1247
- const c = treemap.render.canvas;
1248
- const boundingClientRect = c.getBoundingClientRect();
1249
- if (node) {
1250
- const [mx, my, mw, mh] = node.layout;
1251
- const factor = Math.min(boundingClientRect.width / mw, boundingClientRect.height / mh);
1252
- const targetScale = factor * evt.matrix.a;
1253
- const translateX = boundingClientRect.width / 2 - (mx + mw / 2) * factor;
1254
- const translateY = boundingClientRect.height / 2 - (my + mh / 2) * factor;
1255
- smoothFrame((progress, cleanup) => {
1256
- cleanup();
1257
- evt.silent("mousemove");
1258
- evt.exposedEvent.silent("mousemove");
1259
- treemap.fontCache.flush(treemap, evt.matrix);
1260
- const easedProgress = easing.cubicInOut(progress);
1261
- const scale = (targetScale - evt.matrix.a) * easedProgress;
1262
- evt.matrix.a += scale;
1263
- evt.matrix.d += scale;
1264
- evt.matrix.translation((translateX - evt.matrix.e) * easedProgress, (translateY - evt.matrix.f) * easedProgress);
1265
- resetLayout(
1266
- treemap,
1267
- treemap.render.canvas.width * evt.matrix.a / treemap.render.options.devicePixelRatio,
1268
- treemap.render.canvas.height * evt.matrix.d / treemap.render.options.devicePixelRatio
1269
- );
1270
- stackMatrixTransformWithGraphAndLayer(treemap.elements, evt.matrix.e, evt.matrix.f, 1);
1271
- treemap.update();
1272
- }, {
1273
- duration: ANIMATION_DURATION,
1274
- onStop: () => {
1275
- evt.state.isZooming = false;
1276
- evt.active("mousemove");
1277
- evt.exposedEvent.active("mousemove");
1278
- }
1279
- });
1280
- }
1281
- };
1282
- }
1283
-
1284
- function register(Mod) {
1285
- return (app, treemap) => {
1286
- new Mod(app, treemap);
1287
- };
1288
- }
1289
-
1290
- function squarify(data, rect, layoutDecorator) {
1291
- const result = [];
1292
- if (!data.length) {
1293
- return result;
1294
- }
1295
- const worst = (start, end, shortestSide, totalWeight, aspectRatio) => {
1296
- const max = data[start].weight * aspectRatio;
1297
- const min = data[end].weight * aspectRatio;
1298
- return Math.max(
1299
- shortestSide * shortestSide * max / (totalWeight * totalWeight),
1300
- totalWeight * totalWeight / (shortestSide * shortestSide * min)
1301
- );
1302
- };
1303
- const recursion = (start, rect2) => {
1304
- while (start < data.length) {
1305
- let totalWeight = 0;
1306
- for (let i = start; i < data.length; i++) {
1307
- totalWeight += data[i].weight;
1308
- }
1309
- const shortestSide = Math.min(rect2.w, rect2.h);
1310
- const aspectRatio = rect2.w * rect2.h / totalWeight;
1311
- let end = start;
1312
- let areaInRun = 0;
1313
- let oldWorst = 0;
1314
- while (end < data.length) {
1315
- const area = data[end].weight * aspectRatio;
1316
- const newWorst = worst(start, end, shortestSide, areaInRun + area, aspectRatio);
1317
- if (end > start && oldWorst < newWorst) {
1318
- break;
1319
- }
1320
- areaInRun += area;
1321
- oldWorst = newWorst;
1322
- end++;
1323
- }
1324
- const splited = Math.round(areaInRun / shortestSide);
1325
- let areaInLayout = 0;
1326
- for (let i = start; i < end; i++) {
1327
- const children = data[i];
1328
- const area = children.weight * aspectRatio;
1329
- const lower = Math.round(shortestSide * areaInLayout / areaInRun);
1330
- const upper = Math.round(shortestSide * (areaInLayout + area) / areaInRun);
1331
- const [x, y, w, h] = rect2.w >= rect2.h ? [rect2.x, rect2.y + lower, splited, upper - lower] : [rect2.x + lower, rect2.y, upper - lower, splited];
1332
- const depth = getNodeDepth(children) || 1;
1333
- const { titleAreaHeight, rectGap } = layoutDecorator;
1334
- const diff = titleAreaHeight.max / depth;
1335
- const hh = diff < titleAreaHeight.min ? titleAreaHeight.min : diff;
1336
- result.push({
1337
- layout: [x, y, w, h],
1338
- node: children,
1339
- decorator: {
1340
- ...layoutDecorator,
1341
- titleHeight: hh
1342
- },
1343
- children: w > rectGap * 2 && h > hh + rectGap ? squarify(children.groups || [], {
1344
- x: x + rectGap,
1345
- y: y + hh,
1346
- w: w - rectGap * 2,
1347
- h: h - hh - rectGap
1348
- }, layoutDecorator) : []
1349
- });
1350
- areaInLayout += area;
1351
- }
1352
- start = end;
1353
- if (rect2.w >= rect2.h) {
1354
- rect2.x += splited;
1355
- rect2.w -= splited;
1356
- } else {
1357
- rect2.y += splited;
1358
- rect2.h -= splited;
1359
- }
1360
- }
1361
- };
1362
- recursion(0, rect);
1363
- return result;
1364
- }
1365
-
1366
- var __defProp = Object.defineProperty;
1367
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1368
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1369
- function measureTextWidth(c, text) {
1370
- return c.measureText(text).width;
1371
- }
1372
- function evaluateOptimalFontSize(c, text, font, desiredW, desiredH) {
1373
- desiredW = Math.floor(desiredW);
1374
- desiredH = Math.floor(desiredH);
1375
- const { range, family } = font;
1376
- let min = range.min;
1377
- let max = range.max;
1378
- const cache = /* @__PURE__ */ new Map();
1379
- while (max - min >= 1) {
1380
- const current = min + (max - min) / 2;
1381
- if (!cache.has(current)) {
1382
- c.font = `${current}px ${family}`;
1383
- const metrics = c.measureText(text);
1384
- const width2 = metrics.width;
1385
- const height2 = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;
1386
- cache.set(current, { width: width2, height: height2 });
1387
- }
1388
- const { width, height } = cache.get(current);
1389
- if (width > desiredW || height > desiredH) {
1390
- max = current;
1391
- } else {
1392
- min = current;
1393
- }
1394
- }
1395
- return Math.floor(min);
1396
- }
1397
- function getSafeText(c, text, width, cache) {
1398
- let ellipsisWidth = 0;
1399
- if (text in cache) {
1400
- ellipsisWidth = cache[text];
1401
- } else {
1402
- ellipsisWidth = measureTextWidth(c, "...");
1403
- cache[text] = ellipsisWidth;
1404
- }
1405
- if (width < ellipsisWidth) {
1406
- return false;
1407
- }
1408
- const textWidth = measureTextWidth(c, text);
1409
- if (textWidth < width) {
1410
- return { text, width: textWidth };
1411
- }
1412
- return { text: "...", width: ellipsisWidth };
1413
- }
1414
- function resetLayout(treemap, w, h) {
1415
- treemap.layoutNodes = squarify(treemap.data, { w, h, x: 0, y: 0 }, treemap.decorator.layout);
1416
- treemap.reset(true);
1417
- }
1418
- class Highlight extends Schedule {
1419
- reset() {
1420
- this.destory();
1421
- this.update();
1422
- }
1423
- get canvas() {
1424
- return this.render.canvas;
1425
- }
1426
- setZIndexForHighlight(zIndex = "-1") {
1427
- this.canvas.style.zIndex = zIndex;
1428
- }
1429
- init() {
1430
- this.setZIndexForHighlight();
1431
- this.canvas.style.position = "absolute";
1432
- this.canvas.style.pointerEvents = "none";
1433
- }
1434
- }
1435
- class TreemapLayout extends Schedule {
1436
- constructor(...args) {
1437
- super(...args);
1438
- __publicField(this, "data");
1439
- __publicField(this, "layoutNodes");
1440
- __publicField(this, "decorator");
1441
- __publicField(this, "bgBox");
1442
- __publicField(this, "fgBox");
1443
- __publicField(this, "highlight");
1444
- __publicField(this, "renderCache");
1445
- __publicField(this, "fontCache");
1446
- this.data = [];
1447
- this.layoutNodes = [];
1448
- this.bgBox = new Box();
1449
- this.fgBox = new Box();
1450
- this.decorator = /* @__PURE__ */ Object.create(null);
1451
- this.highlight = new Highlight(this.to, { width: this.render.options.width, height: this.render.options.height });
1452
- this.renderCache = new RenderCache(this.render.options);
1453
- this.fontCache = new FontCache();
1454
- }
1455
- drawBackgroundNode(node) {
1456
- const [x, y, w, h] = node.layout;
1457
- const padding = 2;
1458
- if (w - padding * 2 <= 0 || h - padding * 2 <= 0) {
1459
- return;
1460
- }
1461
- const fill = this.decorator.color.mappings[node.node.id];
1462
- const rect = createRoundBlock(x, y, w, h, { fill, padding, radius: 4 });
1463
- rect.__widget__ = node;
1464
- this.bgBox.add(rect);
1465
- for (const child of node.children) {
1466
- this.drawBackgroundNode(child);
1467
- }
1468
- }
1469
- drawForegroundNode(node) {
1470
- const [x, y, w, h] = node.layout;
1471
- if (!w || !h) {
1472
- return;
1473
- }
1474
- const { titleHeight, rectGap } = node.decorator;
1475
- const { fontSize, fontFamily, color } = this.decorator.font;
1476
- const optimalFontSize = this.fontCache.queryFontById(node.node.id, () => evaluateOptimalFontSize(
1477
- this.render.ctx,
1478
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1479
- node.node.label,
1480
- {
1481
- range: fontSize,
1482
- family: fontFamily
1483
- },
1484
- w - rectGap * 2,
1485
- node.children.length ? Math.round(titleHeight / 2) + rectGap : h
1486
- ));
1487
- this.render.ctx.font = `${optimalFontSize}px ${fontFamily}`;
1488
- const result = getSafeText(this.render.ctx, node.node.label, w - rectGap * 2, this.fontCache.ellispsis);
1489
- if (!result) {
1490
- return;
1491
- }
1492
- if (result.width >= w || optimalFontSize >= h) {
1493
- return;
1494
- }
1495
- const { text, width } = result;
1496
- const textX = x + Math.round((w - width) / 2);
1497
- const textY = y + (node.children.length ? Math.round(titleHeight / 2) : Math.round(h / 2));
1498
- this.fgBox.add(createTitleText(text, textX, textY, `${optimalFontSize}px ${fontFamily}`, color));
1499
- for (const child of node.children) {
1500
- this.drawForegroundNode(child);
1501
- }
1502
- }
1503
- reset(refresh = false) {
1504
- this.remove(this.bgBox, this.fgBox);
1505
- this.bgBox.destory();
1506
- if (this.renderCache.state) {
1507
- this.fgBox.destory();
1508
- this.bgBox.add(new Bitmap({ bitmap: this.renderCache.canvas, dpi: this.render.options.devicePixelRatio }));
1509
- } else {
1510
- for (const node of this.layoutNodes) {
1511
- this.drawBackgroundNode(node);
1512
- }
1513
- if (!this.fgBox.elements.length || refresh) {
1514
- this.render.ctx.textBaseline = "middle";
1515
- this.fgBox.destory();
1516
- for (const node of this.layoutNodes) {
1517
- this.drawForegroundNode(node);
1518
- }
1519
- } else {
1520
- this.fgBox = this.fgBox.clone();
1521
- }
1522
- }
1523
- this.add(this.bgBox, this.fgBox);
1524
- }
1525
- get api() {
1526
- return {
1527
- zoom: (node) => {
1528
- if (!node) {
1529
- return;
1530
- }
1531
- this.event.emit(INTERNAL_EVENT_MAPPINGS.ON_ZOOM, node);
1532
- }
1533
- };
1534
- }
1535
- }
1536
- function createTreemap() {
1537
- let treemap = null;
1538
- let root = null;
1539
- let installed = false;
1540
- const uses = [];
1541
- const context = {
1542
- init,
1543
- dispose,
1544
- setOptions,
1545
- resize,
1546
- use,
1547
- zoom
1548
- };
1549
- function init(el) {
1550
- treemap = new TreemapLayout(el);
1551
- root = el;
1552
- root.style.position = "relative";
1553
- if (!installed) {
1554
- register(TreemapEvent)(context, treemap);
1555
- installed = true;
1556
- }
1557
- }
1558
- function dispose() {
1559
- if (root && treemap) {
1560
- treemap.destory();
1561
- root.removeChild(root.firstChild);
1562
- root = null;
1563
- treemap = null;
1564
- }
1565
- }
1566
- function resize() {
1567
- if (!treemap || !root) {
1568
- return;
1569
- }
1570
- treemap.renderCache.destroy();
1571
- treemap.fontCache.destroy();
1572
- const { width, height } = root.getBoundingClientRect();
1573
- treemap.render.initOptions({ height, width, devicePixelRatio: window.devicePixelRatio });
1574
- treemap.render.canvas.style.position = "absolute";
1575
- treemap.event.emit(INTERNAL_EVENT_MAPPINGS.ON_CLEANUP);
1576
- treemap.highlight.render.initOptions({ height, width, devicePixelRatio: window.devicePixelRatio });
1577
- treemap.highlight.reset();
1578
- treemap.highlight.init();
1579
- resetLayout(treemap, width, height);
1580
- treemap.update();
1581
- treemap.renderCache.flush(treemap, treemap.matrix);
1582
- }
1583
- function setOptions(options) {
1584
- if (!treemap) {
1585
- throw new Error(log.error("Treemap not initialized"));
1586
- }
1587
- treemap.data = bindParentForModule(options.data || []);
1588
- for (const use2 of uses) {
1589
- use2(treemap);
1590
- }
1591
- resize();
1592
- }
1593
- function use(key, register2) {
1594
- switch (key) {
1595
- case "decorator":
1596
- uses.push((treemap2) => register2(treemap2));
1597
- break;
1598
- }
1599
- }
1600
- function zoom(id) {
1601
- if (!treemap) {
1602
- throw new Error(log.error("treemap don't init."));
1603
- }
1604
- const node = findRelativeNodeById(id, treemap.layoutNodes);
1605
- if (node) {
1606
- treemap.api.zoom(node);
1607
- }
1608
- }
1609
- return context;
1610
- }
1611
-
1612
- const defaultLayoutOptions = {
1613
- titleAreaHeight: {
1614
- max: 60,
1615
- min: 30
1616
- },
1617
- rectGap: 5,
1618
- rectBorderRadius: 0.5,
1619
- rectBorderWidth: 1.5
1620
- };
1621
- const defaultFontOptions = {
1622
- color: "#000",
1623
- fontSize: {
1624
- max: 70,
1625
- min: 0
1626
- },
1627
- fontFamily: "sans-serif"
1628
- };
1629
- function presetDecorator(app) {
1630
- Object.assign(app.decorator, {
1631
- layout: defaultLayoutOptions,
1632
- font: defaultFontOptions,
1633
- color: { mappings: evaluateColorMappings(app.data) }
1634
- });
1635
- }
1636
- function evaluateColorMappings(data) {
1637
- const colorMappings = {};
1638
- const hashToHue = (id) => {
1639
- const hash = Math.abs(hashCode(id));
1640
- return hash % 360;
1641
- };
1642
- const lightScale = (depth) => 50 - depth * 5;
1643
- const baseSaturation = 80;
1644
- const siblingHueShift = 30;
1645
- const rc = 0.2126;
1646
- const gc = 0.7152;
1647
- const bc = 0.0722;
1648
- const hslToRgb = (h, s, l) => {
1649
- const a = s * Math.min(l, 1 - l);
1650
- const f = (n) => {
1651
- const k = (n + h / 30) % 12;
1652
- return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
1653
- };
1654
- return { r: f(0), g: f(8), b: f(4) };
1655
- };
1656
- const calculateLuminance = (r, g, b) => {
1657
- return rc * r + gc * g + bc * b;
1658
- };
1659
- const calculateColor = (module, depth, parentHue, siblingIndex, totalSiblings) => {
1660
- const nodeHue = hashToHue(module.id);
1661
- const hue = parentHue !== null ? (parentHue + siblingHueShift * siblingIndex / totalSiblings) % 360 : nodeHue;
1662
- const lightness = lightScale(depth);
1663
- const hslColor = {
1664
- h: hue,
1665
- s: baseSaturation,
1666
- l: lightness / 100
1667
- };
1668
- const { r, g, b } = hslToRgb(hslColor.h, hslColor.s / 100, hslColor.l);
1669
- const luminance = calculateLuminance(r, g, b);
1670
- if (luminance < 0.6) {
1671
- hslColor.l += 0.2;
1672
- } else if (luminance > 0.8) {
1673
- hslColor.l -= 0.1;
1674
- }
1675
- hslColor.l *= 100;
1676
- colorMappings[module.id] = {
1677
- mode: "hsl",
1678
- desc: hslColor
1679
- };
1680
- if (module.groups && Array.isArray(module.groups)) {
1681
- const totalChildren = module.groups.length;
1682
- for (let i = 0; i < totalChildren; i++) {
1683
- const child = module.groups[i];
1684
- calculateColor(child, depth + 1, hue, i, totalChildren);
1685
- }
1686
- }
1687
- };
1688
- for (let i = 0; i < data.length; i++) {
1689
- const module = data[i];
1690
- calculateColor(module, 0, null, i, data.length);
1691
- }
1692
- return colorMappings;
1693
- }
1694
-
1695
- export { TreemapLayout, c2m, createTreemap, defaultFontOptions, defaultLayoutOptions, findRelativeNode, findRelativeNodeById, flatten as flattenModule, getNodeDepth, presetDecorator, sortChildrenByKey, visit };
1
+ import { Component, DOMEvent, DefaultMap, Event, applyCanvasTransform, assertExists, bindParentForModule, c2m, createCanvasElement, createRoundBlock, createTitleText, definePlugin, findRelativeNode, findRelativeNodeById, flatten, getNodeDepth, hashCode, isClickEvent, isContextMenuEvent, isMacOS, isMouseEvent, isScrollWheelOrRightButtonOnMouseupAndDown, isWheelEvent, logger, mixin, mixinWithParams, noop, perferNumeric, prettyStrJoin, raf, smoothFrame, sortChildrenByKey, stackMatrixTransform, stackMatrixTransformWithGraphAndLayer, typedForIn, visit } from "./dom-event-DQ8OFrZa.mjs";
2
+
3
+ //#region src/index.ts
4
+ function createTreemap(options) {
5
+ const { plugins = [], graphic = {} } = options || {};
6
+ let root = null;
7
+ let installed = false;
8
+ let domEvent = null;
9
+ let component = null;
10
+ const exposedEvent = new Event();
11
+ if (!Array.isArray(plugins)) logger.panic("Plugins should be an array");
12
+ const api = { zoom: noop };
13
+ const ctx = {
14
+ init,
15
+ dispose,
16
+ resize,
17
+ setOptions
18
+ };
19
+ function init(el) {
20
+ component = new Component(graphic, el);
21
+ domEvent = new DOMEvent(component);
22
+ root = el;
23
+ root.style.position = "relative";
24
+ if (!installed) {
25
+ plugins.forEach((plugin) => component?.pluginDriver.use(plugin));
26
+ installed = true;
27
+ component.pluginDriver.runHook("onLoad", ctx, domEvent);
28
+ }
29
+ domEvent.on("__exposed__", (type, args) => exposedEvent.emit(type, args));
30
+ }
31
+ function dispose() {
32
+ if (root && component && domEvent) {
33
+ domEvent.destory();
34
+ component.destory();
35
+ root.removeChild(root.firstChild);
36
+ for (const evt in exposedEvent.eventCollections) exposedEvent.off(evt);
37
+ component.pluginDriver.runHook("onDispose");
38
+ root = null;
39
+ component = null;
40
+ domEvent = null;
41
+ }
42
+ }
43
+ function resize() {
44
+ if (!component || !root) return;
45
+ const { width, height } = root.getBoundingClientRect();
46
+ component.render.initOptions({
47
+ height,
48
+ width,
49
+ devicePixelRatio: window.devicePixelRatio
50
+ });
51
+ component.render.canvas.style.position = "absolute";
52
+ if (domEvent) component.pluginDriver.runHook("onResize", domEvent);
53
+ component.cleanup();
54
+ component.draw();
55
+ }
56
+ function setOptions(options$1) {
57
+ assertExists(component, logger, "Treemap not initialized. Please call `init()` before setOptions.");
58
+ component.data = bindParentForModule(options$1.data);
59
+ resize();
60
+ }
61
+ const base = mixin(ctx, [{
62
+ name: "on",
63
+ fn: () => exposedEvent.bindWithContext(api)
64
+ }, {
65
+ name: "off",
66
+ fn: () => exposedEvent.off.bind(exposedEvent)
67
+ }]);
68
+ return base;
69
+ }
70
+
71
+ //#endregion
72
+ export { DefaultMap, applyCanvasTransform, c2m, createCanvasElement, createRoundBlock, createTitleText, createTreemap, definePlugin, findRelativeNode, findRelativeNodeById, flatten as flattenModule, getNodeDepth, hashCode, isClickEvent, isContextMenuEvent, isMacOS, isMouseEvent, isScrollWheelOrRightButtonOnMouseupAndDown, isWheelEvent, mixin, mixinWithParams, noop, perferNumeric, prettyStrJoin, raf, smoothFrame, sortChildrenByKey, stackMatrixTransform, stackMatrixTransformWithGraphAndLayer, typedForIn, visit };