"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BulletRenderer = void 0;
const react_1 = __importDefault(require("react"));
const react_redux_1 = require("react-redux");
const redux_1 = require("redux");
const bullet_1 = require("./bullet");
const color_library_wrappers_1 = require("../../../../common/color_library_wrappers");
const colors_1 = require("../../../../common/colors");
const accessibility_1 = require("../../../../components/accessibility");
const aligned_grid_1 = require("../../../../components/grid/aligned_grid");
const specs_1 = require("../../../../specs");
const chart_1 = require("../../../../state/actions/chart");
const get_accessibility_config_1 = require("../../../../state/selectors/get_accessibility_config");
const get_chart_theme_1 = require("../../../../state/selectors/get_chart_theme");
const get_internal_is_intialized_1 = require("../../../../state/selectors/get_internal_is_intialized");
const get_resolved_background_color_1 = require("../../../../state/selectors/get_resolved_background_color");
const get_settings_spec_1 = require("../../../../state/selectors/get_settings_spec");
const common_1 = require("../../../../utils/common");
const fast_deep_equal_1 = require("../../../../utils/fast_deep_equal");
const light_theme_1 = require("../../../../utils/themes/light_theme");
const metric_1 = require("../../../metric/renderer/dom/metric");
const text_measurements_1 = require("../../../metric/renderer/dom/text_measurements");
const get_active_values_1 = require("../../selectors/get_active_values");
const get_bullet_spec_1 = require("../../selectors/get_bullet_spec");
const get_chart_size_1 = require("../../selectors/get_chart_size");
const get_panel_dimensions_1 = require("../../selectors/get_panel_dimensions");
const has_chart_titles_1 = require("../../selectors/has_chart_titles");
const spec_1 = require("../../spec");
class Component extends react_1.default.Component {
    static displayName = 'Bullet';
    ctx;
    devicePixelRatio;
    constructor(props) {
        super(props);
        this.ctx = null;
        this.devicePixelRatio = window.devicePixelRatio;
    }
    componentDidMount() {
        this.tryCanvasContext();
        if (this.props.initialized) {
            this.drawCanvas();
            this.props.onChartRendered();
        }
    }
    shouldComponentUpdate(nextProps) {
        return !(0, fast_deep_equal_1.deepEqual)(this.props, nextProps);
    }
    componentDidUpdate() {
        if (!this.ctx) {
            this.tryCanvasContext();
        }
        if (this.props.initialized) {
            this.drawCanvas();
            this.props.onChartRendered();
        }
    }
    tryCanvasContext() {
        const canvas = this.props.forwardStageRef.current;
        this.ctx = canvas && canvas.getContext('2d');
    }
    drawCanvas() {
        if (this.ctx) {
            (0, bullet_1.renderBullet)(this.ctx, this.devicePixelRatio, this.props);
        }
    }
    render() {
        const { initialized, size, forwardStageRef, a11y, dimensions, spec, style, backgroundColor, locale, metricStyle, } = this.props;
        const contrastOptions = {
            lightColor: (0, color_library_wrappers_1.colorToRgba)(metricStyle.textLightColor),
            darkColor: (0, color_library_wrappers_1.colorToRgba)(metricStyle.textDarkColor),
        };
        if (!initialized || size.width === 0 || size.height === 0 || !spec) {
            return null;
        }
        const valueLabels = (0, spec_1.mergeValueLabels)(spec.valueLabels);
        return (react_1.default.createElement("figure", { "aria-labelledby": a11y.labelId, "aria-describedby": a11y.descriptionId, style: { width: '100%', height: '100%' } },
            react_1.default.createElement("canvas", { ref: forwardStageRef, className: "echCanvasRenderer", width: size.width * this.devicePixelRatio, height: size.height * this.devicePixelRatio, style: size, role: "presentation" },
                react_1.default.createElement(accessibility_1.ScreenReaderSummary, null)),
            dimensions.shouldRenderMetric && (react_1.default.createElement("div", { className: "echBulletAsMetric", style: { width: '100%', height: '100%' } },
                react_1.default.createElement(aligned_grid_1.AlignedGrid, { data: spec.data, contentComponent: ({ datum, stats }) => {
                        const colorScale = this.props.dimensions.rows[stats.rowIndex]?.[stats.columnIndex]?.colorScale ??
                            (() => ({ hex: () => this.props.style.fallbackBandColor }));
                        const bulletDatum = {
                            value: datum.value,
                            target: datum.target,
                            valueFormatter: datum.valueFormatter,
                            targetFormatter: datum.targetFormatter,
                            color: style.barBackground,
                            progressBarDirection: spec.subtype === spec_1.BulletSubtype.vertical ? 'vertical' : 'horizontal',
                            title: datum.title,
                            subtitle: datum.subtitle,
                            domain: datum.domain,
                            niceDomain: datum.niceDomain,
                            valueLabels,
                            extra: datum.target
                                ? {
                                    value: datum.target.toString(),
                                    label: `${valueLabels.target}:`,
                                }
                                : undefined,
                        };
                        const bulletToMetricStyle = (0, common_1.mergePartial)(metricStyle, {
                            fontFamily: style.fontFamily,
                            barBackground: colorScale(datum.value).hex(),
                            emptyBackground: colors_1.Colors.Transparent.keyword,
                            border: 'gray',
                            minHeight: 0,
                            textLightColor: 'white',
                            textDarkColor: 'black',
                            nonFiniteText: 'N/A',
                            valueFontSize: 'default',
                        });
                        const panel = { width: size.width / stats.columns, height: size.height / stats.rows };
                        const textDimensions = (0, text_measurements_1.getMetricTextPartDimensions)(bulletDatum, panel, bulletToMetricStyle, locale);
                        const fittedValueFontSize = (0, text_measurements_1.getFitValueFontSize)(textDimensions.heightBasedSizes.valueFontSize, panel.width - textDimensions.progressBarWidth, textDimensions.visibility.availableHeightWithoutValue, textDimensions.textParts, bulletToMetricStyle.minValueFontSize, false, false, textDimensions.metricSpacing.panelPadding, bulletToMetricStyle.fontFamily);
                        const sizes = (0, text_measurements_1.getSnappedFontSizes)(fittedValueFontSize, panel.height, bulletToMetricStyle);
                        textDimensions.heightBasedSizes.valueFontSize = sizes.valueFontSize;
                        textDimensions.heightBasedSizes.valuePartFontSize = sizes.valuePartFontSize;
                        return (react_1.default.createElement(metric_1.Metric, { chartId: `${this.props.chartId}-${stats.rowIndex}-${stats.columnIndex}`, datum: bulletDatum, hasTitles: this.props.hasTitles, totalRows: stats.rows, totalColumns: stats.columns, columnIndex: stats.columnIndex, rowIndex: stats.rowIndex, style: bulletToMetricStyle, backgroundColor: backgroundColor, contrastOptions: contrastOptions, textDimensions: textDimensions }));
                    } }),
                ");"))));
    }
}
const mapDispatchToProps = (dispatch) => (0, redux_1.bindActionCreators)({
    onChartRendered: chart_1.onChartRendered,
}, dispatch);
const DEFAULT_PROPS = {
    initialized: false,
    debug: false,
    chartId: '',
    spec: undefined,
    hasTitles: false,
    size: {
        width: 0,
        height: 0,
    },
    a11y: get_accessibility_config_1.DEFAULT_A11Y_SETTINGS,
    dimensions: {
        rows: [],
        panel: { height: 0, width: 0 },
        layoutAlignment: [],
        shouldRenderMetric: false,
    },
    activeValues: [],
    style: light_theme_1.LIGHT_THEME.bulletGraph,
    metricStyle: light_theme_1.LIGHT_THEME.metric,
    backgroundColor: light_theme_1.LIGHT_THEME.background.color,
    locale: specs_1.settingsBuildProps.defaults.locale,
    colorBands: light_theme_1.LIGHT_THEME.bulletGraph.colorBands,
};
const mapStateToProps = (state) => {
    if ((0, get_internal_is_intialized_1.getInternalIsInitializedSelector)(state) !== get_internal_is_intialized_1.InitStatus.Initialized) {
        return DEFAULT_PROPS;
    }
    const { bulletGraph: style, metric: metricStyle } = (0, get_chart_theme_1.getChartThemeSelector)(state);
    const { debug, onElementOver, locale } = (0, get_settings_spec_1.getSettingsSpecSelector)(state);
    return {
        initialized: true,
        debug,
        chartId: state.chartId,
        hasTitles: (0, has_chart_titles_1.hasChartTitles)(state),
        spec: (0, get_bullet_spec_1.getBulletSpec)(state),
        size: (0, get_chart_size_1.getChartSize)(state),
        a11y: (0, get_accessibility_config_1.getA11ySettingsSelector)(state),
        dimensions: (0, get_panel_dimensions_1.getPanelDimensions)(state),
        activeValues: (0, get_active_values_1.getActiveValues)(state),
        style,
        locale,
        backgroundColor: (0, get_resolved_background_color_1.getResolvedBackgroundColorSelector)(state),
        colorBands: style.colorBands,
        onElementOver,
        metricStyle,
    };
};
exports.BulletRenderer = (0, react_redux_1.connect)(mapStateToProps, mapDispatchToProps)(Component);
//# sourceMappingURL=index.js.map