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

naver / billboard.js / 14590453034

22 Apr 2025 08:38AM UTC coverage: 87.038% (-7.1%) from 94.132%
14590453034

push

github

web-flow
chore(deps-dev): update dependency (#3977)

Co-authored-by: netil <netil@netilui-Mac-Studio.local>

5621 of 6951 branches covered (80.87%)

Branch coverage included in aggregate %.

7446 of 8062 relevant lines covered (92.36%)

12074.19 hits per line

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

85.92
/src/ChartInternal/data/data.ts
1
/**
2
 * Copyright (c) 2017 ~ present NAVER Corp.
3
 * billboard.js project is licensed under the MIT license
4
 */
5
import {select as d3Select} from "d3-selection";
6
import {$BAR, $CANDLESTICK, $COMMON} from "../../config/classes";
7
import {KEY} from "../../module/Cache";
8
import {
9
        findIndex,
10
        getScrollPosition,
11
        getTransformCTM,
12
        getUnique,
13
        hasValue,
14
        hasViewBox,
15
        isArray,
16
        isBoolean,
17
        isDefined,
18
        isFunction,
19
        isNumber,
20
        isObject,
21
        isObjectType,
22
        isString,
23
        isUndefined,
24
        isValue,
25
        mergeArray,
26
        notEmpty,
27
        parseDate,
28
        sortValue
29
} from "../../module/util";
30
import type {IData, IDataPoint, IDataRow} from "./IData";
31

32
export default {
33
        isX(key) {
34
                const $$ = this;
14,910✔
35
                const {config} = $$;
14,910✔
36
                const dataKey = config.data_x && key === config.data_x;
14,910✔
37
                const existValue = notEmpty(config.data_xs) && hasValue(config.data_xs, key);
14,910✔
38

39
                return dataKey || existValue;
14,910✔
40
        },
41

42
        isNotX(key): boolean {
43
                return !this.isX(key);
7,455✔
44
        },
45

46
        isStackNormalized(): boolean {
47
                const {config} = this;
55,876✔
48

49
                return !!(config.data_stack_normalize && config.data_groups.length);
55,876!
50
        },
51

52
        /**
53
         * Check if given id is grouped data or has grouped data
54
         * @param {string} id Data id value
55
         * @returns {boolean} is grouped data or has grouped data
56
         * @private
57
         */
58
        isGrouped(id?: string): boolean {
59
                const groups = this.config.data_groups;
85,692✔
60

61
                return id ? groups.some(v => v.indexOf(id) >= 0 && v.length > 1) : groups.length > 0;
85,692!
62
        },
63

64
        getXKey(id) {
65
                const $$ = this;
13,392✔
66
                const {config} = $$;
13,392✔
67

68
                return config.data_x ?
13,392✔
69
                        config.data_x :
70
                        (notEmpty(config.data_xs) ? config.data_xs[id] : null);
10,668✔
71
        },
72

73
        getXValuesOfXKey(key, targets) {
74
                const $$ = this;
3✔
75
                const ids = targets && notEmpty(targets) ? $$.mapToIds(targets) : [];
3!
76
                let xValues;
77

78
                ids.forEach(id => {
3✔
79
                        if ($$.getXKey(id) === key) {
6✔
80
                                xValues = $$.data.xs[id];
3✔
81
                        }
82
                });
83

84
                return xValues;
3✔
85
        },
86

87
        /**
88
         * Get index number based on given x Axis value
89
         * @param {Date|number|string} x x Axis to be compared
90
         * @param {Array} basedX x Axis list to be based on
91
         * @returns {number} index number
92
         * @private
93
         */
94
        getIndexByX(x: Date | number | string, basedX: (Date | number | string)[]): number {
95
                const $$ = this;
12,600✔
96

97
                return basedX ?
12,600✔
98
                        basedX.indexOf(isString(x) ? x : +x) :
12,438!
99
                        ($$.filterByX($$.data.targets, x)[0] || {index: null}).index;
165✔
100
        },
101

102
        getXValue(id: string, i: number): number {
103
                const $$ = this;
126✔
104

105
                return id in $$.data.xs &&
126✔
106
                                $$.data.xs[id] &&
107
                                isValue($$.data.xs[id][i]) ?
108
                        $$.data.xs[id][i] :
109
                        i;
110
        },
111

112
        getOtherTargetXs(): string | null {
113
                const $$ = this;
30✔
114
                const idsForX = Object.keys($$.data.xs);
30✔
115

116
                return idsForX.length ? $$.data.xs[idsForX[0]] : null;
30!
117
        },
118

119
        getOtherTargetX(index: number): string | null {
120
                const xs = this.getOtherTargetXs();
27✔
121

122
                return xs && index < xs.length ? xs[index] : null;
27!
123
        },
124

125
        addXs(xs): void {
126
                const $$ = this;
6✔
127
                const {config} = $$;
6✔
128

129
                Object.keys(xs).forEach(id => {
6✔
130
                        config.data_xs[id] = xs[id];
6✔
131
                });
132
        },
133

134
        /**
135
         * Determine if x axis is multiple
136
         * @returns {boolean} true: multiple, false: single
137
         * @private
138
         */
139
        isMultipleX(): boolean {
140
                return !this.config.axis_x_forceAsSingle && (
42,816✔
141
                        notEmpty(this.config.data_xs) ||
142
                        this.hasType("bubble") ||
143
                        this.hasType("scatter")
144
                );
145
        },
146

147
        addName(data) {
148
                const $$ = this;
1,041✔
149
                const {config} = $$;
1,041✔
150
                let name;
151

152
                if (data) {
1,041✔
153
                        name = config.data_names[data.id];
1,026✔
154
                        data.name = name !== undefined ? name : data.id;
1,026!
155
                }
156

157
                return data;
1,041✔
158
        },
159

160
        /**
161
         * Get all values on given index
162
         * @param {number} index Index
163
         * @param {boolean} filterNull Filter nullish value
164
         * @returns {Array}
165
         * @private
166
         */
167
        getAllValuesOnIndex(index: number, filterNull = false) {
390✔
168
                const $$ = this;
396✔
169

170
                let value = $$.filterTargetsToShow($$.data.targets)
396✔
171
                        .map(t => $$.addName($$.getValueOnIndex(t.values, index)));
912✔
172

173
                if (filterNull) {
396✔
174
                        value = value.filter(v => v && "value" in v && isValue(v.value));
18✔
175
                }
176

177
                return value;
396✔
178
        },
179

180
        getValueOnIndex(values, index: number) {
181
                const valueOnIndex = values.filter(v => v.index === index);
4,818✔
182

183
                return valueOnIndex.length ? valueOnIndex[0] : null;
990✔
184
        },
185

186
        updateTargetX(targets, x) {
187
                const $$ = this;
9✔
188

189
                targets.forEach(t => {
9✔
190
                        t.values.forEach((v, i) => {
12✔
191
                                v.x = $$.generateTargetX(x[i], t.id, i);
36✔
192
                        });
193

194
                        $$.data.xs[t.id] = x;
12✔
195
                });
196
        },
197

198
        updateTargetXs(targets, xs) {
199
                const $$ = this;
3✔
200

201
                targets.forEach(t => {
3✔
202
                        xs[t.id] && $$.updateTargetX([t], xs[t.id]);
6✔
203
                });
204
        },
205

206
        generateTargetX(rawX, id: string, index: number) {
207
                const $$ = this;
32,469✔
208
                const {axis} = $$;
32,469✔
209
                let x = axis?.isCategorized() ? index : (rawX || index);
32,469✔
210

211
                if (axis?.isTimeSeries()) {
32,469✔
212
                        const fn = parseDate.bind($$);
3,216✔
213

214
                        x = rawX ? fn(rawX) : fn($$.getXValue(id, index));
3,216✔
215
                } else if (axis?.isCustomX() && !axis?.isCategorized()) {
29,253✔
216
                        x = isValue(rawX) ? +rawX : $$.getXValue(id, index);
9,522✔
217
                }
218

219
                return x;
32,469✔
220
        },
221

222
        updateXs(values): void {
223
                if (values.length) {
3,019✔
224
                        this.axis.xs = values.map(v => v.x);
16,929✔
225
                }
226
        },
227

228
        getPrevX(i: number): number[] | null {
229
                const x = this.axis.xs[i - 1];
29,670✔
230

231
                return isDefined(x) ? x : null;
29,670✔
232
        },
233

234
        getNextX(i: number): number[] | null {
235
                const x = this.axis.xs[i + 1];
29,670✔
236

237
                return isDefined(x) ? x : null;
29,670✔
238
        },
239

240
        /**
241
         * Get base value isAreaRangeType
242
         * @param {object} data Data object
243
         * @returns {number}
244
         * @private
245
         */
246
        getBaseValue(data): number {
247
                const $$ = this;
156,622✔
248
                const {hasAxis} = $$.state;
156,622✔
249
                let {value} = data;
156,622✔
250

251
                // In case of area-range, data is given as: [low, mid, high] or {low, mid, high}
252
                // will take the 'mid' as the base value
253
                if (value && hasAxis) {
156,622✔
254
                        if ($$.isAreaRangeType(data)) {
142,647✔
255
                                value = $$.getRangedData(data, "mid");
1,026✔
256
                        } else if ($$.isBubbleZType(data)) {
141,621✔
257
                                value = $$.getBubbleZData(value, "y");
252✔
258
                        }
259
                }
260

261
                return value;
156,622✔
262
        },
263

264
        /**
265
         * Get min/max value from the data
266
         * @private
267
         * @param {Array} data array data to be evaluated
268
         * @returns {{min: {number}, max: {number}}}
269
         */
270
        getMinMaxValue(data): {min: number, max: number} {
271
                const getBaseValue = this.getBaseValue.bind(this);
285✔
272
                let min;
273
                let max;
274

275
                (data || this.data.targets.map(t => t.values))
285!
276
                        .forEach((v, i) => {
277
                                const value = v.map(getBaseValue).filter(isNumber);
774✔
278

279
                                min = Math.min(i ? min : Infinity, ...value);
774✔
280
                                max = Math.max(i ? max : -Infinity, ...value);
774✔
281
                        });
282

283
                return {min, max};
285✔
284
        },
285

286
        /**
287
         * Get the min/max data
288
         * @private
289
         * @returns {{min: Array, max: Array}}
290
         */
291
        getMinMaxData(): {min: IDataRow[], max: IDataRow[]} {
292
                const $$ = this;
2,130✔
293
                const cacheKey = KEY.dataMinMax;
2,130✔
294
                let minMaxData = $$.cache.get(cacheKey);
2,130✔
295

296
                if (!minMaxData) {
2,130✔
297
                        const data = $$.data.targets.map(t => t.values);
774✔
298
                        const minMax = $$.getMinMaxValue(data);
285✔
299

300
                        let min = [];
285✔
301
                        let max = [];
285✔
302

303
                        data.forEach(v => {
285✔
304
                                const minData = $$.getFilteredDataByValue(v, minMax.min);
774✔
305
                                const maxData = $$.getFilteredDataByValue(v, minMax.max);
774✔
306

307
                                if (minData.length) {
774✔
308
                                        min = min.concat(minData);
288✔
309
                                }
310

311
                                if (maxData.length) {
774✔
312
                                        max = max.concat(maxData);
285✔
313
                                }
314
                        });
315

316
                        // update the cached data
317
                        $$.cache.add(cacheKey, minMaxData = {min, max});
285✔
318
                }
319

320
                return minMaxData;
2,130✔
321
        },
322

323
        /**
324
         * Get sum of data per index
325
         * @private
326
         * @returns {Array}
327
         */
328
        getTotalPerIndex() {
329
                const $$ = this;
3,618✔
330
                const cacheKey = KEY.dataTotalPerIndex;
3,618✔
331
                let sum = $$.cache.get(cacheKey);
3,618✔
332

333
                if (($$.config.data_groups.length || $$.isStackNormalized()) && !sum) {
3,618!
334
                        sum = [];
3,618✔
335

336
                        $$.data.targets.forEach(row => {
3,618✔
337
                                row.values.forEach((v, i) => {
10,890✔
338
                                        if (!sum[i]) {
59,046✔
339
                                                sum[i] = 0;
19,938✔
340
                                        }
341

342
                                        sum[i] += isNumber(v.value) ? v.value : 0;
59,046!
343
                                });
344
                        });
345
                }
346

347
                return sum;
3,618✔
348
        },
349

350
        /**
351
         * Get total data sum
352
         * @param {boolean} subtractHidden Subtract hidden data from total
353
         * @returns {number}
354
         * @private
355
         */
356
        getTotalDataSum(subtractHidden) {
357
                const $$ = this;
2,724✔
358
                const cacheKey = KEY.dataTotalSum;
2,724✔
359
                let total = $$.cache.get(cacheKey);
2,724✔
360

361
                if (!isNumber(total)) {
2,724✔
362
                        const sum = mergeArray($$.data.targets.map(t => t.values))
1,242✔
363
                                .map(v => v.value);
1,350✔
364

365
                        total = sum.length ? sum.reduce((p, c) => p + c) : 0;
993!
366

367
                        $$.cache.add(cacheKey, total);
357✔
368
                }
369

370
                if (subtractHidden) {
2,724✔
371
                        total -= $$.getHiddenTotalDataSum();
1,851✔
372
                }
373

374
                return total;
2,724✔
375
        },
376

377
        /**
378
         * Get total hidden data sum
379
         * @returns {number}
380
         * @private
381
         */
382
        getHiddenTotalDataSum() {
383
                const $$ = this;
1,851✔
384
                const {api, state: {hiddenTargetIds}} = $$;
1,851✔
385
                let total = 0;
1,851✔
386

387
                if (hiddenTargetIds.length) {
1,851✔
388
                        total = api.data.values.bind(api)(hiddenTargetIds)
192✔
389
                                .reduce((p, c) => p + c);
12✔
390
                }
391

392
                return total;
1,851✔
393
        },
394

395
        /**
396
         * Get filtered data by value
397
         * @param {object} data Data
398
         * @param {number} value Value to be filtered
399
         * @returns {Array} filtered array data
400
         * @private
401
         */
402
        getFilteredDataByValue(data, value) {
403
                return data.filter(t => this.getBaseValue(t) === value);
3,240✔
404
        },
405

406
        /**
407
         * Return the max length of the data
408
         * @returns {number} max data length
409
         * @private
410
         */
411
        getMaxDataCount(): number {
412
                return Math.max(...this.data.targets.map(t => t.values.length), 0);
8,919✔
413
        },
414

415
        getMaxDataCountTarget() {
416
                let target = this.filterTargetsToShow() || [];
3,019!
417
                const length = target.length;
3,019✔
418
                const isInverted = this.config.axis_x_inverted;
3,019✔
419

420
                if (length > 1) {
3,019✔
421
                        target = target.map(t => t.values)
4,581✔
422
                                .reduce((a, b) => a.concat(b))
2,676✔
423
                                .map(v => v.x);
23,181✔
424

425
                        target = sortValue(getUnique(target))
1,905✔
426
                                .map((x, index, array) => ({
9,666✔
427
                                        x,
428
                                        index: isInverted ? array.length - index - 1 : index
9,666!
429
                                }));
430
                } else if (length) {
1,114✔
431
                        target = target[0].values.concat();
1,042✔
432
                }
433

434
                return target;
3,019✔
435
        },
436

437
        mapToIds(targets): string[] {
438
                return targets.map(d => d.id);
77,945✔
439
        },
440

441
        mapToTargetIds(ids) {
442
                const $$ = this;
3,315✔
443

444
                return ids ? (isArray(ids) ? ids.concat() : [ids]) : $$.mapToIds($$.data.targets);
3,315✔
445
        },
446

447
        hasTarget(targets, id): boolean {
448
                const ids = this.mapToIds(targets);
81✔
449

450
                for (let i = 0, val; (val = ids[i]); i++) {
81✔
451
                        if (val === id) {
168✔
452
                                return true;
81✔
453
                        }
454
                }
455

456
                return false;
×
457
        },
458

459
        isTargetToShow(targetId): boolean {
460
                return this.state.hiddenTargetIds.indexOf(targetId) < 0;
184,856✔
461
        },
462

463
        isLegendToShow(targetId): boolean {
464
                return this.state.hiddenLegendIds.indexOf(targetId) < 0;
19,442✔
465
        },
466

467
        filterTargetsToShow(targets?) {
468
                const $$ = this;
72,121✔
469

470
                return (targets || $$.data.targets).filter(t => $$.isTargetToShow(t.id));
167,410✔
471
        },
472

473
        mapTargetsToUniqueXs(targets) {
474
                const $$ = this;
11,683✔
475
                const {axis} = $$;
11,683✔
476
                let xs: any[] = [];
11,683✔
477

478
                if (targets?.length) {
11,683✔
479
                        xs = getUnique(
11,605✔
480
                                mergeArray(targets.map(t => t.values.map(v => +v.x)))
111,561✔
481
                        );
482

483
                        xs = axis?.isTimeSeries() ? xs.map(x => new Date(+x)) : xs.map(Number);
11,605✔
484
                }
485

486
                return sortValue(xs);
11,683✔
487
        },
488

489
        /**
490
         * Add to the state target Ids
491
         * @param {string} type State's prop name
492
         * @param {Array|string} targetIds Target ids array
493
         * @private
494
         */
495
        addTargetIds(type: string, targetIds: string[] | string): void {
496
                const {state} = this;
156✔
497
                const ids = (isArray(targetIds) ? targetIds : [targetIds]) as [];
156✔
498

499
                ids.forEach(v => {
156✔
500
                        state[type].indexOf(v) < 0 &&
207✔
501
                                state[type].push(v);
502
                });
503
        },
504

505
        /**
506
         * Remove from the state target Ids
507
         * @param {string} type State's prop name
508
         * @param {Array|string} targetIds Target ids array
509
         * @private
510
         */
511
        removeTargetIds(type: string, targetIds: string[] | string): void {
512
                const {state} = this;
165✔
513
                const ids = (isArray(targetIds) ? targetIds : [targetIds]) as [];
165!
514

515
                ids.forEach(v => {
165✔
516
                        const index = state[type].indexOf(v);
351✔
517

518
                        index >= 0 && state[type].splice(index, 1);
351✔
519
                });
520
        },
521

522
        addHiddenTargetIds(targetIds: string[]): void {
523
                this.addTargetIds("hiddenTargetIds", targetIds);
135✔
524
        },
525

526
        removeHiddenTargetIds(targetIds: string[]): void {
527
                this.removeTargetIds("hiddenTargetIds", targetIds);
54✔
528
        },
529

530
        addHiddenLegendIds(targetIds: string[]): void {
531
                this.addTargetIds("hiddenLegendIds", targetIds);
21✔
532
        },
533

534
        removeHiddenLegendIds(targetIds: string[]): void {
535
                this.removeTargetIds("hiddenLegendIds", targetIds);
111✔
536
        },
537

538
        getValuesAsIdKeyed(targets) {
539
                const $$ = this;
30,912✔
540
                const {hasAxis} = $$.state;
30,912✔
541
                const ys = {};
30,912✔
542
                const isMultipleX = $$.isMultipleX();
30,912✔
543
                const xs = isMultipleX ?
30,912✔
544
                        $$.mapTargetsToUniqueXs(targets)
545
                                .map(v => (isString(v) ? v : +v)) :
8,802!
546
                        null;
547

548
                targets.forEach(t => {
30,912✔
549
                        const data: any[] = [];
54,834✔
550

551
                        t.values
54,834✔
552
                                .filter(({value}) => isValue(value) || value === null)
286,110✔
553
                                .forEach(v => {
554
                                        let {value} = v;
286,110✔
555

556
                                        // exclude 'volume' value to correct mis domain calculation
557
                                        if (value !== null && $$.isCandlestickType(v)) {
286,110✔
558
                                                value = isArray(value) ?
360✔
559
                                                        value.slice(0, 4) :
560
                                                        [value.open, value.high, value.low, value.close];
561
                                        }
562

563
                                        if (isArray(value)) {
286,110✔
564
                                                data.push(...value);
2,178✔
565
                                        } else if (isObject(value) && "high" in value) {
283,932!
566
                                                data.push(...Object.values(value));
×
567
                                        } else if ($$.isBubbleZType(v)) {
283,932✔
568
                                                data.push(hasAxis && $$.getBubbleZData(value, "y"));
540✔
569
                                        } else {
570
                                                if (isMultipleX) {
283,392✔
571
                                                        data[$$.getIndexByX(v.x, xs)] = value;
12,438✔
572
                                                } else {
573
                                                        data.push(value);
270,954✔
574
                                                }
575
                                        }
576
                                });
577

578
                        ys[t.id] = data;
54,834✔
579
                });
580

581
                return ys;
30,912✔
582
        },
583

584
        checkValueInTargets(targets, checker: Function): boolean {
585
                const ids = Object.keys(targets);
9,048✔
586
                let values;
587

588
                for (let i = 0; i < ids.length; i++) {
9,048✔
589
                        values = targets[ids[i]].values;
14,070✔
590

591
                        for (let j = 0; j < values.length; j++) {
14,070✔
592
                                if (checker(values[j].value)) {
45,234✔
593
                                        return true;
4,578✔
594
                                }
595
                        }
596
                }
597

598
                return false;
4,470✔
599
        },
600

601
        hasMultiTargets(): boolean {
602
                return this.filterTargetsToShow().length > 1;
240✔
603
        },
604

605
        hasNegativeValueInTargets(targets): boolean {
606
                return this.checkValueInTargets(targets, v => v < 0);
40,155✔
607
        },
608

609
        hasPositiveValueInTargets(targets): boolean {
610
                return this.checkValueInTargets(targets, v => v > 0);
5,079✔
611
        },
612

613
        /**
614
         * Sort targets data
615
         * Note: For stacked bar, will sort from the total sum of data series, not for each stacked bar
616
         * @param {Array} targetsValue Target value
617
         * @returns {Array}
618
         * @private
619
         */
620
        orderTargets(targetsValue: IData[]): IData[] {
621
                const $$ = this;
11,082✔
622
                const targets = [...targetsValue];
11,082✔
623
                const fn = $$.getSortCompareFn();
11,082✔
624

625
                fn && targets.sort(fn);
11,082✔
626

627
                return targets;
11,082✔
628
        },
629

630
        /**
631
         * Get data.order compare function
632
         * @param {boolean} isReversed for Arc & Treemap type sort order needs to be reversed
633
         * @returns {Function} compare function
634
         * @private
635
         */
636
        getSortCompareFn(isReversed = false): Function | null {
11,082✔
637
                const $$ = this;
11,772✔
638
                const {config} = $$;
11,772✔
639
                const order = config.data_order;
11,772✔
640
                const orderAsc = /asc/i.test(order);
11,772✔
641
                const orderDesc = /desc/i.test(order);
11,772✔
642
                let fn;
643

644
                if (orderAsc || orderDesc) {
11,772✔
645
                        const reducer = (p, c) => p + Math.abs(c.value);
169,014✔
646
                        const sum = v => (isNumber(v) ? v : (
62,118✔
647
                                "values" in v ? v.values.reduce(reducer, 0) : v.value
61,638✔
648
                        ));
649

650
                        fn = (t1: IData | IDataRow, t2: IData | IDataRow) => {
11,499✔
651
                                const t1Sum = sum(t1);
31,059✔
652
                                const t2Sum = sum(t2);
31,059✔
653

654
                                return isReversed ?
31,059✔
655
                                        (orderAsc ? t1Sum - t2Sum : t2Sum - t1Sum) :
19,983!
656
                                        (orderAsc ? t2Sum - t1Sum : t1Sum - t2Sum);
11,076✔
657
                        };
658
                } else if (isFunction(order)) {
273!
659
                        fn = order.bind($$.api);
×
660
                }
661

662
                return fn || null;
11,772✔
663
        },
664

665
        filterByX(targets, x) {
666
                return mergeArray(targets.map(t => t.values)).filter(v => v.x - x === 0);
1,788✔
667
        },
668

669
        filterNullish(data) {
670
                const filter = v => isValue(v.value);
35,070✔
671

672
                return data ?
10,046!
673
                        data.filter(
674
                                v => "value" in v ? filter(v) : v.values.some(filter)
34,986✔
675
                        ) :
676
                        data;
677
        },
678

679
        filterRemoveNull(data) {
680
                return data.filter(d => isValue(this.getBaseValue(d)));
×
681
        },
682

683
        filterByXDomain(targets, xDomain) {
684
                return targets.map(t => ({
153✔
685
                        id: t.id,
686
                        id_org: t.id_org,
687
                        values: t.values.filter(v => xDomain[0] <= v.x && v.x <= xDomain[1])
1,842✔
688
                }));
689
        },
690

691
        hasDataLabel() {
692
                const dataLabels = this.config.data_labels;
35,031✔
693

694
                return (isBoolean(dataLabels) && dataLabels) ||
35,031✔
695
                        (isObjectType(dataLabels) && notEmpty(dataLabels));
696
        },
697

698
        /**
699
         * Determine if has null value
700
         * @param {Array} targets Data array to be evaluated
701
         * @returns {boolean}
702
         * @private
703
         */
704
        hasNullDataValue(targets: IDataRow[]): boolean {
705
                return targets.some(({value}) => value === null);
102✔
706
        },
707

708
        /**
709
         * Get data index from the event coodinates
710
         * @param {Event} event Event object
711
         * @returns {number}
712
         * @private
713
         */
714
        getDataIndexFromEvent(event): number {
715
                const $$ = this;
432✔
716
                const {
717
                        $el,
718
                        config,
719
                        state: {hasRadar, inputType, eventReceiver: {coords, rect}}
720
                } = $$;
432✔
721
                let index;
722

723
                if (hasRadar) {
432✔
724
                        let target = event.target;
12✔
725

726
                        // in case of multilined axis text
727
                        if (/tspan/i.test(target.tagName)) {
12!
728
                                target = target.parentNode;
×
729
                        }
730

731
                        const d: any = d3Select(target).datum();
12✔
732

733
                        index = d && Object.keys(d).length === 1 ? d.index : undefined;
12!
734
                } else {
735
                        const isRotated = config.axis_rotated;
420✔
736
                        const scrollPos = getScrollPosition($el.chart.node());
420✔
737

738
                        // get data based on the mouse coords
739
                        const e = inputType === "touch" && event.changedTouches ?
420✔
740
                                event.changedTouches[0] :
741
                                event;
742

743
                        let point = isRotated ? e.clientY + scrollPos.y : e.clientX + scrollPos.x;
420✔
744

745
                        if (hasViewBox($el.svg)) {
420!
746
                                const pos = [point, 0];
×
747

748
                                isRotated && pos.reverse();
×
749
                                point = getTransformCTM($el.eventRect.node(), ...pos)[isRotated ? "y" : "x"];
×
750
                        } else {
751
                                point -= isRotated ? rect.top : rect.left;
420✔
752
                        }
753

754
                        index = findIndex(
420✔
755
                                coords,
756
                                point,
757
                                0,
758
                                coords.length - 1,
759
                                isRotated
760
                        );
761
                }
762

763
                return index;
432✔
764
        },
765

766
        getDataLabelLength(min, max, key) {
767
                const $$ = this;
543✔
768
                const lengths = [0, 0];
543✔
769
                const paddingCoef = 1.3;
543✔
770

771
                $$.$el.chart.select("svg").selectAll(".dummy")
543✔
772
                        .data([min, max])
773
                        .enter()
774
                        .append("text")
775
                        .text(d => $$.dataLabelFormat(d.id)(d))
888✔
776
                        .each(function(d, i) {
777
                                lengths[i] = this.getBoundingClientRect()[key] * paddingCoef;
888✔
778
                        })
779
                        .remove();
780

781
                return lengths;
543✔
782
        },
783

784
        isNoneArc(d) {
785
                return this.hasTarget(this.data.targets, d.id);
×
786
        },
787

788
        isArc(d) {
789
                return "data" in d && this.hasTarget(this.data.targets, d.data.id);
×
790
        },
791

792
        findSameXOfValues(values, index) {
793
                const targetX = values[index].x;
×
794
                const sames: any[] = [];
×
795
                let i;
796

797
                for (i = index - 1; i >= 0; i--) {
×
798
                        if (targetX !== values[i].x) {
×
799
                                break;
×
800
                        }
801

802
                        sames.push(values[i]);
×
803
                }
804

805
                for (i = index; i < values.length; i++) {
×
806
                        if (targetX !== values[i].x) {
×
807
                                break;
×
808
                        }
809

810
                        sames.push(values[i]);
×
811
                }
812

813
                return sames;
×
814
        },
815

816
        findClosestFromTargets(targets, pos: [number, number]): IDataRow | undefined {
817
                const $$ = this;
63✔
818
                const candidates = targets.map(target => $$.findClosest(target.values, pos)); // map to array of closest points of each target
132✔
819

820
                // decide closest point and return
821
                return $$.findClosest(candidates, pos);
63✔
822
        },
823

824
        findClosest(values, pos: [number, number]): IDataRow | undefined {
825
                const $$ = this;
177✔
826
                const {$el: {main}} = $$;
177✔
827
                const data = values.filter(v => v && isValue(v.value));
780✔
828

829
                let minDist;
830
                let closest;
831

832
                // find mouseovering bar/candlestick
833
                // https://github.com/naver/billboard.js/issues/2434
834
                data
177✔
835
                        .filter(v => $$.isBarType(v.id) || $$.isCandlestickType(v.id))
726✔
836
                        .forEach(v => {
837
                                const selector = $$.isBarType(v.id) ?
6!
838
                                        `.${$BAR.chartBar}.${$COMMON.target}${
839
                                                $$.getTargetSelectorSuffix(v.id)
840
                                        } .${$BAR.bar}-${v.index}` :
841
                                        `.${$CANDLESTICK.chartCandlestick}.${$COMMON.target}${
842
                                                $$.getTargetSelectorSuffix(v.id)
843
                                        } .${$CANDLESTICK.candlestick}-${v.index} path`;
844

845
                                if (!closest && $$.isWithinBar(main.select(selector).node())) {
6!
846
                                        closest = v;
6✔
847
                                }
848
                        });
849

850
                // find closest point from non-bar/candlestick
851
                data
177✔
852
                        .filter(v => !$$.isBarType(v.id) && !$$.isCandlestickType(v.id))
726✔
853
                        .forEach((v: IDataPoint) => {
854
                                const d = $$.dist(v, pos);
720✔
855

856
                                minDist = $$.getPointSensitivity(v);
720✔
857

858
                                if (d < minDist) {
720✔
859
                                        minDist = d;
120✔
860
                                        closest = v;
120✔
861
                                }
862
                        });
863

864
                return closest;
177✔
865
        },
866

867
        dist(data: IDataPoint, pos: [number, number]) {
868
                const $$ = this;
798✔
869
                const {config: {axis_rotated: isRotated}, scale} = $$;
798✔
870
                const xIndex = +isRotated; // true: 1, false: 0
798✔
871
                const yIndex = +!isRotated; // true: 0, false: 1
798✔
872
                const y = $$.circleY(data, data.index);
798✔
873
                const x = (scale.zoom || scale.x)(data.x);
798✔
874

875
                return Math.sqrt(Math.pow(x - pos[xIndex], 2) + Math.pow(y - pos[yIndex], 2));
798✔
876
        },
877

878
        /**
879
         * Convert data for step type
880
         * @param {Array} values Object data values
881
         * @returns {Array}
882
         * @private
883
         */
884
        convertValuesToStep(values) {
885
                const $$ = this;
684✔
886
                const {axis, config} = $$;
684✔
887
                const stepType = config.line_step_type;
684✔
888
                const isCategorized = axis ? axis.isCategorized() : false;
684!
889
                const converted = isArray(values) ? values.concat() : [values];
684!
890

891
                if (!(isCategorized || /step\-(after|before)/.test(stepType))) {
684!
892
                        return values;
684✔
893
                }
894

895
                // when all datas are null, return empty array
896
                // https://github.com/naver/billboard.js/issues/3124
897
                if (converted.length) {
×
898
                        // insert & append cloning first/last value to be fully rendered covering on each gap sides
899
                        const head = converted[0];
×
900
                        const tail = converted[converted.length - 1];
×
901
                        const {id} = head;
×
902
                        let {x} = head;
×
903

904
                        // insert head
905
                        converted.unshift({x: --x, value: head.value, id});
×
906

907
                        isCategorized && stepType === "step-after" &&
×
908
                                converted.unshift({x: --x, value: head.value, id});
909

910
                        // append tail
911
                        x = tail.x;
×
912
                        converted.push({x: ++x, value: tail.value, id});
×
913

914
                        isCategorized && stepType === "step-before" &&
×
915
                                converted.push({x: ++x, value: tail.value, id});
916
                }
917

918
                return converted;
×
919
        },
920

921
        convertValuesToRange(values) {
922
                const converted = isArray(values) ? values.concat() : [values];
×
923
                const ranges: {x: string | number, id: string, value: number}[] = [];
×
924

925
                converted.forEach(range => {
×
926
                        const {x, id} = range;
×
927

928
                        ranges.push({
×
929
                                x,
930
                                id,
931
                                value: range.value[0]
932
                        });
933

934
                        ranges.push({
×
935
                                x,
936
                                id,
937
                                value: range.value[2]
938
                        });
939
                });
940

941
                return ranges;
×
942
        },
943

944
        updateDataAttributes(name, attrs) {
945
                const $$ = this;
21✔
946
                const {config} = $$;
21✔
947
                const current = config[`data_${name}`];
21✔
948

949
                if (isUndefined(attrs)) {
21✔
950
                        return current;
12✔
951
                }
952

953
                Object.keys(attrs).forEach(id => {
9✔
954
                        current[id] = attrs[id];
18✔
955
                });
956

957
                $$.redraw({withLegend: true});
9✔
958

959
                return current;
9✔
960
        },
961

962
        getRangedData(d, key = "", type = "areaRange"): number | undefined {
1,386!
963
                const value = d?.value;
1,605✔
964

965
                if (isArray(value)) {
1,605✔
966
                        if (type === "bar") {
1,443!
967
                                return value.reduce((a, c) => c - a);
×
968
                        } else {
969
                                // @ts-ignore
970
                                const index = {
1,443✔
971
                                        areaRange: ["high", "mid", "low"],
972
                                        candlestick: ["open", "high", "low", "close", "volume"]
973
                                }[type].indexOf(key);
974

975
                                return index >= 0 && value ? value[index] : undefined;
1,443!
976
                        }
977
                } else if (value && key) {
162✔
978
                        return value[key];
30✔
979
                }
980

981
                return value;
132✔
982
        },
983

984
        /**
985
         * Set ratio for grouped data
986
         * @param {Array} data Data array
987
         * @private
988
         */
989
        setRatioForGroupedData(data: (IDataRow | IData)[]): void {
990
                const $$ = this;
855✔
991
                const {config} = $$;
855✔
992

993
                // calculate ratio if grouped data exists
994
                if (config.data_groups.length && data.some(d => $$.isGrouped(d.id))) {
855✔
995
                        const setter = (d: IDataRow) => $$.getRatio("index", d, true);
3,618✔
996

997
                        data.forEach(v => {
237✔
998
                                "values" in v ? v.values.forEach(setter) : setter(v);
3,366✔
999
                        });
1000
                }
1001
        },
1002

1003
        /**
1004
         * Get ratio value
1005
         * @param {string} type Ratio for given type
1006
         * @param {object} d Data value object
1007
         * @param {boolean} asPercent Convert the return as percent or not
1008
         * @returns {number} Ratio value
1009
         * @private
1010
         */
1011
        getRatio(type: string, d, asPercent = false): number {
4,208✔
1012
                const $$ = this;
7,826✔
1013
                const {config, state} = $$;
7,826✔
1014
                const api = $$.api;
7,826✔
1015
                let ratio = 0;
7,826✔
1016

1017
                if (d && api.data.shown().length) {
7,826✔
1018
                        ratio = d.ratio || d.value;
7,781✔
1019

1020
                        if (type === "arc") {
7,781✔
1021
                                // if has padAngle set, calculate rate based on value
1022
                                if ($$.pie.padAngle()()) {
1,799✔
1023
                                        ratio = d.value / $$.getTotalDataSum(true);
48✔
1024

1025
                                        // otherwise, based on the rendered angle value
1026
                                } else {
1027
                                        const gaugeArcLength = config.gauge_fullCircle ?
1,751✔
1028
                                                $$.getArcLength() :
1029
                                                $$.getStartingAngle() * -2;
1030
                                        const arcLength = $$.hasType("gauge") ? gaugeArcLength : Math.PI * 2;
1,751✔
1031

1032
                                        ratio = (d.endAngle - d.startAngle) / arcLength;
1,751✔
1033
                                }
1034
                        } else if (type === "index") {
5,982✔
1035
                                const dataValues = api.data.values.bind(api);
3,618✔
1036
                                let total = this.getTotalPerIndex();
3,618✔
1037

1038
                                if (state.hiddenTargetIds.length) {
3,618!
1039
                                        let hiddenSum = dataValues(state.hiddenTargetIds, false);
×
1040

1041
                                        if (hiddenSum.length) {
×
1042
                                                hiddenSum = hiddenSum
×
1043
                                                        .reduce((acc, curr) =>
1044
                                                                acc.map((v, i) => (isNumber(v) ? v : 0) + curr[i])
×
1045
                                                        );
1046

1047
                                                total = total.map((v, i) => v - hiddenSum[i]);
×
1048
                                        }
1049
                                }
1050

1051
                                const divisor = total[d.index];
3,618✔
1052

1053
                                d.ratio = isNumber(d.value) && total && divisor ? d.value / divisor : 0;
3,618✔
1054

1055
                                ratio = d.ratio;
3,618✔
1056
                        } else if (type === "radar") {
2,364✔
1057
                                ratio = (
1,290✔
1058
                                        parseFloat(String(Math.max(d.value, 0))) / state.current.dataMax
1059
                                ) * config.radar_size_ratio;
1060
                        } else if (type === "bar") {
1,074✔
1061
                                const yScale = $$.getYScaleById.bind($$)(d.id);
132✔
1062
                                const max = yScale.domain().reduce((a, c) => c - a);
132✔
1063

1064
                                // when all data are 0, return 0
1065
                                ratio = max === 0 ? 0 : Math.abs(
132!
1066
                                        $$.getRangedData(d, null, type) / max
1067
                                );
1068
                        } else if (type === "treemap") {
942!
1069
                                ratio /= $$.getTotalDataSum(true);
942✔
1070
                        }
1071
                }
1072

1073
                return asPercent && ratio ? ratio * 100 : ratio;
7,826✔
1074
        },
1075

1076
        /**
1077
         * Sort data index to be aligned with x axis.
1078
         * @param {Array} tickValues Tick array values
1079
         * @private
1080
         */
1081
        updateDataIndexByX(tickValues) {
1082
                const $$ = this;
3,019✔
1083

1084
                const tickValueMap = tickValues.reduce((out, tick, index) => {
3,019✔
1085
                        out[Number(tick.x)] = index;
16,929✔
1086
                        return out;
16,929✔
1087
                }, {});
1088

1089
                $$.data.targets.forEach(t => {
3,019✔
1090
                        t.values.forEach((value, valueIndex) => {
5,755✔
1091
                                let index = tickValueMap[Number(value.x)];
30,960✔
1092

1093
                                if (index === undefined) {
30,960✔
1094
                                        index = valueIndex;
252✔
1095
                                }
1096
                                value.index = index;
30,960✔
1097
                        });
1098
                });
1099
        },
1100

1101
        /**
1102
         * Determine if bubble has dimension data
1103
         * @param {object|Array} d data value
1104
         * @returns {boolean}
1105
         * @private
1106
         */
1107
        isBubbleZType(d): boolean {
1108
                const $$ = this;
441,612✔
1109

1110
                return $$.isBubbleType(d) && (
441,612!
1111
                        (isObject(d.value) && ("z" in d.value || "y" in d.value)) ||
1112
                        (isArray(d.value) && d.value.length >= 2)
1113
                );
1114
        },
1115

1116
        /**
1117
         * Determine if bar has ranged data
1118
         * @param {Array} d data value
1119
         * @returns {boolean}
1120
         * @private
1121
         */
1122
        isBarRangeType(d): boolean {
1123
                const $$ = this;
27,483✔
1124
                const {value} = d;
27,483✔
1125

1126
                return $$.isBarType(d) && isArray(value) && value.length >= 2 &&
27,483✔
1127
                        value.every(v => isNumber(v));
312✔
1128
        },
1129

1130
        /**
1131
         * Get data object by id
1132
         * @param {string} id data id
1133
         * @returns {object}
1134
         * @private
1135
         */
1136
        getDataById(id: string) {
1137
                const d = this.cache.get(id) || this.api.data(id);
13,253!
1138

1139
                return d?.[0] ?? d;
13,253✔
1140
        }
1141
};
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