All files / src/plugins/yagr/renderer utils.ts

31.25% Statements 30/96
13.23% Branches 9/68
28.57% Functions 4/14
32.58% Lines 29/89

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216                  1x 1x                 1x                                                                                                         1x                                     1x                                                           1x 4x                                       4x 4x 4x 4x 4x   4x   4x     1x 4x 4x           4x   4x             4x   4x   4x                                         4x 4x   4x         4x       4x 4x         4x    
import {dateTime} from '@gravity-ui/date-utils';
import {defaults} from '@gravity-ui/yagr';
import merge from 'lodash/merge';
 
import {settings} from '../../../libs';
import type {MinimalValidConfig, Yagr, YagrChartOptions, YagrTheme, YagrWidgetData} from '../types';
 
import {getRenderTooltip} from './tooltip';
 
const TOOLTIP_HEADER_CLASS_NAME = '_tooltip-header';
const TOOLTIP_LIST_CLASS_NAME = '_tooltip-list';
 
type ShapeYagrConfigArgs = {
    data: YagrWidgetData['data'];
    libraryConfig: YagrWidgetData['libraryConfig'];
    theme: YagrTheme;
    customTooltip?: boolean;
};
 
export const synchronizeTooltipTablesCellsWidth = (tooltipContainer: HTMLElement) => {
    const tHeadNode = tooltipContainer.querySelector(`.${TOOLTIP_HEADER_CLASS_NAME}`);
    const tBodyNode = tooltipContainer.querySelector(`.${TOOLTIP_LIST_CLASS_NAME}`);
 
    if (!tHeadNode || !tBodyNode || !tHeadNode.children.length) {
        return;
    }
 
    const tHeadNodeFirstRow = tHeadNode.children[0];
 
    for (let j = 0; j < tHeadNodeFirstRow.children.length; j++) {
        const cell = tHeadNodeFirstRow.children[j];
        cell.removeAttribute('style');
        if (tBodyNode?.children.length === 1) {
            cell.innerHTML = '&nbsp;';
        }
    }
 
    const tBodyNodeFirstRow = tBodyNode.children[0];
 
    for (let j = 0; j < tBodyNodeFirstRow.children.length; j++) {
        const cell = tBodyNodeFirstRow.children[j];
        cell.removeAttribute('style');
    }
 
    const tHeadRowsWidth = tHeadNode.children[0].getBoundingClientRect().width;
    const tBodyRowsWidth = tBodyNode.children[0].getBoundingClientRect().width;
 
    const nodeWithWidesRows = tHeadRowsWidth > tBodyRowsWidth ? tHeadNode : tBodyNode;
    const nodeWithWidesRowsCellsWidth = Array.prototype.reduce.call(
        nodeWithWidesRows.children[0].children,
        (accum, cellNode) => {
            (accum as number[]).push(cellNode.getBoundingClientRect().width);
            return accum;
        },
        [],
    ) as number[];
 
    const nodeToSetCellsWidth = nodeWithWidesRows === tHeadNode ? tBodyNode : tHeadNode;
    const nodeToSetCellsWidthFirstRow = nodeToSetCellsWidth.children[0];
 
    for (let j = 0; j < nodeToSetCellsWidthFirstRow.children.length; j++) {
        const cell = nodeToSetCellsWidthFirstRow.children[j];
        cell.setAttribute('style', `width: ${nodeWithWidesRowsCellsWidth[j]}px`);
    }
 
    if (tBodyNode.children.length === 1) {
        for (const cell of tHeadNodeFirstRow.children) {
            cell.innerHTML = '';
        }
    }
};
 
export const checkFocus = (args: {tooltip: HTMLElement; yagr?: Yagr}) => (event: MouseEvent) => {
    const {tooltip, yagr} = args;
 
    if (!yagr) {
        return;
    }
 
    const target = event.target as HTMLElement | null;
    const seriesIdx =
        target && tooltip.contains(target) && target.tagName === 'TD'
            ? target.parentElement?.dataset['seriesIdx']
            : undefined;
 
    const serie = seriesIdx ? yagr.uplot.series[Number(seriesIdx)] : null;
 
    yagr.setFocus(serie ? serie.id : null, true);
};
 
export const detectClickOutside =
    (args: {
        tooltip: HTMLElement;
        actions: {
            pin: (state: boolean) => void;
            hide: () => void;
        };
        yagr?: Yagr;
    }) =>
    (event: MouseEvent) => {
        const {tooltip, actions, yagr} = args;
 
        if (!yagr) {
            return;
        }
 
        const target = event.target;
 
        if (target instanceof Element) {
            const isClickInsideTooltip = target && tooltip.contains(target);
            const isClickOnUplotOver =
                target && yagr.root.querySelector('.u-over')?.contains(target);
 
            if (!isClickInsideTooltip && !isClickOnUplotOver) {
                actions.pin(false);
                actions.hide();
            }
        }
    };
 
const getXAxisFormatter =
    (msm = 1, timeZone?: string) =>
    (_: unknown, ticks: number[]) => {
        const range = (ticks[ticks.length - 1] - ticks[0]) / msm;
        return ticks.map((rawValue) => {
            const d = dateTime({input: rawValue / msm, timeZone});
 
            if (d.hour() === 0 && d.minute() === 0 && d.second() === 0) {
                return d.format('DD.MM.YY');
            }
 
            return d.format(range < 300 ? 'HH:mm:ss' : 'HH:mm');
        });
    };
 
/**
 * This function needs to align timezone that uplot is processing.
 * Uplot uses simple new Date() when [processing ticks](https://github.com/leeoniya/uPlot/blob/master/src/opts.js#L177) on axis.
 * It leads that timestamp will be converted to user browser timezone.
 * In this function we artificially add shift diff between browser timezone and user timeozne to reset new Date() affects.
 */
export const getUplotTimezoneAligner =
    (chart?: YagrChartOptions, timeZone?: string) => (ts: number) => {
        const dt = ts / (chart?.timeMultiplier || 1);
        const browserDate = dateTime({input: dt});
        const browserTimezone = browserDate.utcOffset();
        const timestampRealTimezone = dateTime({input: dt, timeZone}).utcOffset();
 
        const uPlotOffset = (browserTimezone - timestampRealTimezone) * 60 * 1000;
 
        return new Date(browserDate.valueOf() - uPlotOffset);
    };
 
export const shapeYagrConfig = (args: ShapeYagrConfigArgs): MinimalValidConfig => {
    const {data, libraryConfig, theme} = args;
    const config: MinimalValidConfig = {
        ...libraryConfig,
        timeline: data.timeline,
        series: data.graphs,
    };
 
    const {timeZone} = data;
 
    const chart: YagrChartOptions = {
        appearance: {
            locale: settings.get('lang'),
            theme,
        },
    };
 
    merge(chart, config.chart);
 
    config.chart = chart;
 
    Iif (config.tooltip?.show) {
        config.tooltip = config.tooltip || {};
        config.tooltip.render = config.tooltip?.render || getRenderTooltip(data);
 
        if (!config.tooltip.className) {
            // "className" property prevent default yagr styles adding
            config.tooltip.className = 'chartkit-yagr-tooltip';
        }
 
        if (args.customTooltip) {
            config.tooltip.virtual = true;
        }
 
        /**
         * @todo remove this on next chartkit major release
         * This added to prevent breaking changes in chartkit, while updating yagr@4 which
         * has fixed tooltip sorting (@see https://github.com/gravity-ui/yagr/issues/149)
         */
        config.tooltip.sort = config.tooltip.sort || ((a, b) => b.rowIdx - a.rowIdx);
    }
 
    config.axes = config.axes || {};
    const xAxis = config.axes[defaults.DEFAULT_X_SCALE];
 
    config.editUplotOptions = (opts) => ({
        ...opts,
        tzDate: timeZone ? getUplotTimezoneAligner(config.chart, timeZone) : undefined,
    });
 
    Iif (xAxis && !xAxis.values) {
        xAxis.values = getXAxisFormatter(config.chart.timeMultiplier, timeZone);
    }
 
    Eif (!xAxis) {
        config.axes[defaults.DEFAULT_X_SCALE] = {
            values: getXAxisFormatter(config.chart.timeMultiplier, timeZone),
        };
    }
 
    return config;
};