• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

antvis / G2Plot / 4361169472

pending completion
4361169472

push

github

GitHub
chore: upgrade typescript to v4 (#3488)

2331 of 2660 branches covered (87.63%)

Branch coverage included in aggregate %.

1 of 1 new or added line in 1 file covered. (100.0%)

6918 of 7070 relevant lines covered (97.85%)

422671.35 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.75
/src/utils/transform/word-cloud.ts
1
import { assign, isFunction, isNil } from '@antv/util';
2
import { Tag, Word } from '../../plots/word-cloud/types';
5,854✔
3

5,854✔
4
type FontWeight = number | 'normal' | 'bold' | 'bolder' | 'lighter';
5,854✔
5

5,854✔
6
export interface Options {
1,305✔
7
  size: [number, number];
8
  font?: string | ((row: Word, index?: number, words?: Word[]) => string);
9
  fontSize?: number | ((row: Word, index?: number, words?: Word[]) => number);
10
  fontWeight?: FontWeight | ((row: Word, index?: number, words?: Word[]) => FontWeight);
11
  rotate?: number | ((row: Word, index?: number, words?: Word[]) => number);
12
  padding?: number | ((row: Word, index?: number, words?: Word[]) => number);
13
  spiral?: 'archimedean' | 'rectangular' | ((size: [number, number]) => (t: number) => number[]);
14
  random?: number | (() => number);
15
  timeInterval?: number;
16
  imageMask?: HTMLImageElement;
17
}
18

19
const DEFAULT_OPTIONS: Options = {
20
  font: () => 'serif',
21
  padding: 1,
22
  size: [500, 500],
23
  spiral: 'archimedean', // 'archimedean' || 'rectangular' || {function}
834✔
24
  // timeInterval: Infinity // max execute time
834✔
25
  timeInterval: 3000, // max execute time
26
  // imageMask: '', // instance of Image, must be loaded
5,854✔
27
};
28

29
/**
30
 * 根据对应的数据对象,计算每个
31
 * 词语在画布中的渲染位置,并返回
32
 * 计算后的数据对象
33
 * @param words
34
 * @param options
979✔
35
 */
979✔
36
export function wordCloud(words: Word[], options?: Partial<Options>): Tag[] {
8,811✔
37
  // 混入默认配置
6,440✔
38
  options = assign({} as Options, DEFAULT_OPTIONS, options);
39
  return transform(words, options as Options);
40
}
979✔
41

979✔
42
/**
58✔
43
 * 抛出没有混入默认配置的方法,用于测试。
44
 * @param words
979✔
45
 * @param options
979✔
46
 */
979✔
47
export function transform(words: Word[], options: Options) {
9,511✔
48
  // 布局对象
9,511✔
49
  const layout = tagCloud();
50
  ['font', 'fontSize', 'fontWeight', 'padding', 'rotate', 'size', 'spiral', 'timeInterval', 'random'].forEach(
979✔
51
    (key: string) => {
52
      if (!isNil(options[key])) {
53
        layout[key](options[key]);
54
      }
55
    }
979✔
56
  );
57

58
  layout.words(words);
59
  if (options.imageMask) {
60
    layout.createMask(options.imageMask);
61
  }
62

979✔
63
  const result = layout.start();
64
  const tags: any[] = result._tags;
65

66
  tags.forEach((tag) => {
67
    tag.x += options.size[0] / 2;
68
    tag.y += options.size[1] / 2;
69
  });
979✔
70

71
  const [w, h] = options.size;
5,854✔
72
  // 添加两个参照数据,分别表示左上角和右下角。
5,854✔
73
  // 不添加的话不会按照真实的坐标渲染,而是以
74
  // 数据中的边界坐标为边界进行拉伸,以铺满画布。
40,731✔
75
  // 这样的后果会导致词语之间的重叠。
76
  tags.push({
77
    text: '',
1,305✔
78
    value: 0,
79
    x: 0,
80
    y: 0,
43,341✔
81
    opacity: 0,
82
  });
83
  tags.push({
2,610✔
84
    text: '',
85
    value: 0,
86
    x: w,
2,349✔
87
    y: h,
88
    opacity: 0,
89
  });
1,044✔
90

91
  return tags;
92
}
93

94
/*
11,805✔
95
 * Synchronous version of d3-cloud
10,913✔
96
 */
892✔
97
// Word cloud layout by Jason Davies, https://www.jasondavies.com/wordcloud/
892✔
98
// Algorithm due to Jonathan Feinberg, http://static.mrfeinberg.com/bv_ch03.pdf
892✔
99
/* eslint-disable no-return-assign, no-cond-assign */
892✔
100

892✔
101
interface Item {
892✔
102
  value: number;
40,151✔
103
  text: string;
40,151✔
104
  sprite: boolean;
40,151✔
105
}
40,151✔
106

40,151✔
107
const cloudRadians = Math.PI / 180,
22,333✔
108
  cw = (1 << 11) >> 5,
22,333✔
109
  ch = 1 << 11;
22,333✔
110

111
function cloudText(d: Item) {
112
  return d.text;
17,818✔
113
}
114

40,151✔
115
function cloudFont() {
8,014✔
116
  return 'serif';
40,151✔
117
}
2,578✔
118

2,578✔
119
function cloudFontNormal() {
2,578✔
120
  return 'normal';
121
}
40,151!
122

×
123
function cloudFontSize(d: Item) {
40,151✔
124
  return d.value;
40,151✔
125
}
22,333✔
126

40,151✔
127
function cloudRotate() {
40,151!
128
  return ~~(Math.random() * 2) * 90;
40,151✔
129
}
40,151✔
130

131
function cloudPadding() {
40,151✔
132
  return 1;
40,151✔
133
}
40,151✔
134

40,151✔
135
// Fetches a monochrome sprite bitmap for the specified text.
40,151✔
136
// Load in batches for speed.
40,151✔
137
function cloudSprite(contextAndRatio, d, data, di) {
40,151✔
138
  if (d.sprite) return;
40,151✔
139
  const c = contextAndRatio.context,
40,151✔
140
    ratio = contextAndRatio.ratio;
40,151✔
141

40,151✔
142
  c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio);
143
  let x = 0,
892✔
144
    y = 0,
892✔
145
    maxh = 0;
40,209✔
146
  const n = data.length;
40,209!
147
  --di;
×
148
  while (++di < n) {
40,209✔
149
    d = data[di];
40,209✔
150
    c.save();
151
    c.font = d.style + ' ' + d.weight + ' ' + ~~((d.size + 1) / ratio) + 'px ' + d.font;
40,209✔
152
    let w = c.measureText(d.text + 'm').width * ratio,
18,685,244✔
153
      h = d.size << 1;
40,209✔
154
    if (d.rotate) {
40,209!
155
      const sr = Math.sin(d.rotate * cloudRadians),
×
156
        cr = Math.cos(d.rotate * cloudRadians),
40,209✔
157
        wcr = w * cr,
40,209✔
158
        wsr = w * sr,
40,209✔
159
        hcr = h * cr,
4,329,344✔
160
        hsr = h * sr;
597,927,808✔
161
      w = ((Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5) << 5;
597,927,808✔
162
      h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));
597,927,808✔
163
    } else {
164
      w = ((w + 0x1f) >> 5) << 5;
4,329,344✔
165
    }
3,950,101✔
166
    if (h > maxh) maxh = h;
167
    if (x + w >= cw << 5) {
379,243✔
168
      x = 0;
379,243✔
169
      y += maxh;
379,243✔
170
      maxh = 0;
379,243✔
171
    }
172
    if (y + h >= ch) break;
173
    c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio);
40,209✔
174
    if (d.rotate) c.rotate(d.rotate * cloudRadians);
40,209✔
175
    c.fillText(d.text, 0, 0);
176
    if (d.padding) {
177
      c.lineWidth = 2 * d.padding;
178
      c.strokeText(d.text, 0, 0);
179
    }
8,204,062✔
180
    c.restore();
8,204,062✔
181
    d.width = w;
8,204,062✔
182
    d.height = h;
8,204,062✔
183
    d.xoff = x;
65,348,881✔
184
    d.yoff = y;
65,348,881✔
185
    d.x1 = w >> 1;
242,620,522✔
186
    d.y1 = h >> 1;
6,969,983✔
187
    d.x0 = -d.x1;
188
    d.y0 = -d.y1;
58,378,898✔
189
    d.hasText = true;
190
    x += w;
1,234,079✔
191
  }
192
  const pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data,
193
    sprite = [];
8,394✔
194
  while (--di >= 0) {
8,394✔
195
    d = data[di];
1,298✔
196
    if (!d.hasText) continue;
8,394✔
197
    const w = d.width,
1,132✔
198
      w32 = w >> 5;
8,394✔
199
    let h = d.y1 - d.y0;
1,207✔
200
    // Zero the buffer
8,394✔
201
    for (let i = 0; i < h * w32; i++) sprite[i] = 0;
1,397✔
202
    x = d.xoff;
203
    if (x == null) return;
204
    y = d.yoff;
1,234,079✔
205
    let seen = 0,
206
      seenRow = -1;
207
    for (let j = 0; j < h; j++) {
11,457✔
208
      for (let i = 0; i < w; i++) {
11,457✔
209
        const k = w32 * j + (i >> 5),
25,822,011✔
210
          m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0;
211
        sprite[k] |= m;
212
        seen |= m;
213
      }
261✔
214
      if (seen) seenRow = j;
261✔
215
      else {
261✔
216
        d.y0++;
184,005✔
217
        h--;
218
        j--;
184,005✔
219
        y++;
220
      }
46,313✔
221
    }
46,313✔
222
    d.y1 = d.y0 + seenRow;
223
    d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32);
44,254✔
224
  }
44,254✔
225
}
226

46,690✔
227
// Use mask-based collision detection.
46,690✔
228
function cloudCollide(tag, board, sw) {
229
  sw >>= 5;
46,748✔
230
  const sprite = tag.sprite,
46,748✔
231
    w = tag.width >> 5,
232
    lx = tag.x - (w << 4),
184,005✔
233
    sx = lx & 0x7f,
234
    msx = 32 - sx,
235
    h = tag.y1 - tag.y0;
236
  let x = (tag.y + tag.y0) * sw + (lx >> 5),
237
    last;
979✔
238
  for (let j = 0; j < h; j++) {
979✔
239
    last = 0;
979✔
240
    for (let i = 0; i <= w; i++) {
8,557,300✔
241
      if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0)) & board[x + i]) return true;
979✔
242
    }
243
    x += sw;
244
  }
979✔
245
  return false;
246
}
247

10,964✔
248
function cloudBounds(bounds, d) {
249
  const b0 = bounds[0],
250
    b1 = bounds[1];
123,390✔
251
  if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0;
252
  if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0;
253
  if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1;
5,854✔
254
  if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1;
5,854✔
255
}
256

257
function collideRects(a, b) {
258
  return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y;
259
}
979✔
260

979✔
261
function archimedeanSpiral(size) {
979✔
262
  const e = size[0] / size[1];
979✔
263
  return function (t) {
979✔
264
    return [e * (t *= 0.1) * Math.cos(t), t * Math.sin(t)];
979✔
265
  };
979✔
266
}
979✔
267

268
function rectangularSpiral(size) {
40,731✔
269
  const dy = 4,
40,731✔
270
    dx = (dy * size[0]) / size[1];
40,731✔
271
  let x = 0,
40,731✔
272
    y = 0;
40,731✔
273
  return function (t) {
40,731✔
274
    const sign = t < 0 ? -1 : 1;
40,731✔
275
    // See triangular numbers: T_n = n * (n + 1) / 2.
40,731✔
276
    switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) {
277
      case 0:
278
        x += dx;
167,967✔
279
        break;
280
      case 1:
979✔
281
        y += dy;
282
        break;
283
      case 2:
284
        x -= dx;
285
        break;
286
      default:
287
        y -= dy;
288
        break;
289
    }
290
    return [x, y];
291
  };
292
}
979✔
293

294
// TODO reuse arrays?
979✔
295
function zeroArray(n) {
979✔
296
  const a = [];
11,805✔
297
  let i = -1;
11,805✔
298
  while (++i < n) a[i] = 0;
11,805✔
299
  return a;
11,805✔
300
}
11,805✔
301

9,511✔
302
function cloudCanvas() {
9,511✔
303
  return document.createElement('canvas');
8,655✔
304
}
305

8,394✔
306
export function functor(d) {
307
  return isFunction(d)
308
    ? d
309
    : function () {
856✔
310
        return d;
311
      };
312
}
313

314
const spirals = {
315
  archimedean: archimedeanSpiral,
9,511✔
316
  rectangular: rectangularSpiral,
9,511✔
317
};
318

319
function tagCloud() {
979✔
320
  let size = [256, 256],
979✔
321
    font = cloudFont,
322
    fontSize = cloudFontSize,
979✔
323
    fontWeight = cloudFontNormal,
324
    rotate = cloudRotate,
325
    padding = cloudPadding,
979✔
326
    spiral = archimedeanSpiral,
979✔
327
    random = Math.random,
328
    words = [],
979✔
329
    timeInterval = Infinity;
979✔
330

979✔
331
  const text = cloudText;
979✔
332
  const fontStyle = cloudFontNormal;
979✔
333
  const canvas = cloudCanvas;
979✔
334
  const cloud: any = {};
335

336
  cloud.start = function () {
337
    const [width, height] = size;
11,805✔
338
    const contextAndRatio = getContext(canvas()),
11,805✔
339
      board = cloud.board ? cloud.board : zeroArray((size[0] >> 5) * size[1]),
11,805✔
340
      n = words.length,
26,071,237✔
341
      tags = [],
26,071,237✔
342
      data = words
26,071,237✔
343
        .map(function (d, i, data) {
2,294✔
344
          d.text = text.call(this, d, i, data);
26,068,943✔
345
          d.font = font.call(this, d, i, data);
26,068,943✔
346
          d.style = fontStyle.call(this, d, i, data);
26,068,943✔
347
          d.weight = fontWeight.call(this, d, i, data);
17,864,025✔
348
          d.rotate = rotate.call(this, d, i, data);
349
          d.size = ~~fontSize.call(this, d, i, data);
8,204,918✔
350
          d.padding = padding.call(this, d, i, data);
1,234,935✔
351
          return d;
9,511✔
352
        })
9,511✔
353
        .sort(function (a, b) {
9,511✔
354
          return b.size - a.size;
677,997✔
355
        });
677,997✔
356
    let i = -1,
3,566,000✔
357
      bounds = !cloud.board
358
        ? null
677,997✔
359
        : [
360
            {
9,511✔
361
              x: 0,
9,511✔
362
              y: 0,
363
            },
364
            {
365
              x: width,
2,294✔
366
              y: height,
367
            },
979✔
368
          ];
58✔
369

58✔
370
    step();
371

58✔
372
    function step() {
29✔
373
      const start = Date.now();
374
      while (Date.now() - start < timeInterval && ++i < n) {
29✔
375
        const d = data[i];
29✔
376
        d.x = (width * (random() + 0.5)) >> 1;
29✔
377
        d.y = (height * (random() + 0.5)) >> 1;
29✔
378
        cloudSprite(contextAndRatio, d, data, i);
29✔
379
        if (d.hasText && place(board, d, bounds)) {
29✔
380
          tags.push(d);
29✔
381
          if (bounds) {
29✔
382
            if (!cloud.hasImage) {
14,500✔
383
              // update bounds if image mask not set
7,250,000✔
384
              cloudBounds(bounds, d);
7,250,000✔
385
            }
7,250,000✔
386
          } else {
7,250,000✔
387
            bounds = [
7,250,000✔
388
              { x: d.x + d.x0, y: d.y + d.y0 },
389
              { x: d.x + d.x1, y: d.y + d.y1 },
390
            ];
29✔
391
          }
29✔
392
          // Temporary hack
393
          d.x -= size[0] >> 1;
979✔
394
          d.y -= size[1] >> 1;
863!
395
        }
396
      }
979✔
397
      cloud._tags = tags;
979✔
398
      cloud._bounds = bounds;
399
    }
979✔
400

979✔
401
    return cloud;
402
  };
979✔
403

834✔
404
  function getContext(canvas: HTMLCanvasElement) {
405
    canvas.width = canvas.height = 1;
979✔
406
    const ratio = Math.sqrt(
660✔
407
      (canvas.getContext('2d', { willReadFrequently: true }) as CanvasRenderingContext2D)!.getImageData(0, 0, 1, 1).data
408
        .length >> 2
979✔
409
    );
689✔
410
    canvas.width = (cw << 5) / ratio;
411
    canvas.height = ch / ratio;
979✔
412

834✔
413
    const context = canvas.getContext('2d', { willReadFrequently: true }) as CanvasRenderingContext2D;
414
    context.fillStyle = context.strokeStyle = 'red';
979✔
415
    context.textAlign = 'center';
660✔
416
    return { context, ratio };
417
  }
979✔
418

863✔
419
  function place(board, tag, bounds) {
420
    // const perimeter = [{ x: 0, y: 0 }, { x: size[0], y: size[1] }],
979✔
421
    const startX = tag.x,
58✔
422
      startY = tag.y,
423
      maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]),
979✔
424
      s = spiral(size),
425
      dt = random() < 0.5 ? 1 : -1;
426
    let dxdy,
427
      t = -dt,
428
      dx,
429
      dy;
430

431
    while ((dxdy = s((t += dt)))) {
432
      dx = ~~dxdy[0];
433
      dy = ~~dxdy[1];
434

435
      if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break;
436

437
      tag.x = startX + dx;
438
      tag.y = startY + dy;
439

440
      if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 || tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue;
441
      // TODO only check for collisions within current bounds.
442
      if (!bounds || !cloudCollide(tag, board, size[0])) {
443
        if (!bounds || collideRects(tag, bounds)) {
444
          const sprite = tag.sprite,
445
            w = tag.width >> 5,
446
            sw = size[0] >> 5,
447
            lx = tag.x - (w << 4),
448
            sx = lx & 0x7f,
449
            msx = 32 - sx,
450
            h = tag.y1 - tag.y0;
451
          let last,
452
            x = (tag.y + tag.y0) * sw + (lx >> 5);
453
          for (let j = 0; j < h; j++) {
454
            last = 0;
455
            for (let i = 0; i <= w; i++) {
456
              board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0);
457
            }
458
            x += sw;
459
          }
460
          delete tag.sprite;
461
          return true;
462
        }
463
      }
464
    }
465
    return false;
466
  }
467

468
  cloud.createMask = (img: HTMLImageElement) => {
469
    const can: HTMLCanvasElement = document.createElement('canvas');
470
    const [width, height] = size;
471

472
    // 当 width 或 height 为 0 时,调用 cxt.getImageData 会报错
473
    if (!width || !height) {
474
      return;
475
    }
476
    const w32 = width >> 5;
477
    const board = zeroArray((width >> 5) * height);
478
    can.width = width;
479
    can.height = height;
480
    const cxt = can.getContext('2d') as CanvasRenderingContext2D;
481
    cxt.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);
482
    const imageData = cxt.getImageData(0, 0, width, height).data;
483
    for (let j = 0; j < height; j++) {
484
      for (let i = 0; i < width; i++) {
485
        const k = w32 * j + (i >> 5);
486
        const tmp = (j * width + i) << 2;
487
        const flag = imageData[tmp] >= 250 && imageData[tmp + 1] >= 250 && imageData[tmp + 2] >= 250;
488
        const m = flag ? 1 << (31 - (i % 32)) : 0;
489
        board[k] |= m;
490
      }
491
    }
492
    cloud.board = board;
493
    cloud.hasImage = true;
494
  };
495

496
  cloud.timeInterval = function (_) {
497
    timeInterval = _ == null ? Infinity : _;
498
  };
499

500
  cloud.words = function (_) {
501
    words = _;
502
  };
503

504
  cloud.size = function (_) {
505
    size = [+_[0], +_[1]];
506
  };
507

508
  cloud.font = function (_) {
509
    font = functor(_);
510
  };
511

512
  cloud.fontWeight = function (_) {
513
    fontWeight = functor(_);
514
  };
515

516
  cloud.rotate = function (_) {
517
    rotate = functor(_);
518
  };
519

520
  cloud.spiral = function (_) {
521
    spiral = spirals[_] || _;
522
  };
523

524
  cloud.fontSize = function (_) {
525
    fontSize = functor(_);
526
  };
527

528
  cloud.padding = function (_) {
529
    padding = functor(_);
530
  };
531

532
  cloud.random = function (_) {
533
    random = functor(_);
534
  };
535

536
  return cloud;
537
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc