diff --git a/spec/bb-spec.js b/spec/bb-spec.js index 8a60cea97..9c361b70c 100644 --- a/spec/bb-spec.js +++ b/spec/bb-spec.js @@ -24,4 +24,33 @@ describe("Interface & initialization", () => { expect(chart).not.to.be.null; expect(chart.internal.svg.node().tagName).to.be.equal("svg"); }); + + it("should resize correctly in flex container", done => { + // set flex container + document.body.innerHTML = '
'; + const chart = bb.generate({ + bindto: "#flex-container", + data: { + columns: [ + ["data1", 30, 200, 100, 400], + ["data2", 500, 800, 500, 2000] + ] + } + }); + + const chartWidth = +chart.internal.svg.attr("width"); + const diff = 50; + + // shrink width & resize + document.body.style.width = `${document.body.offsetWidth - diff}px`; + chart.internal.resizeFunction(); + + setTimeout(() => { + expect(+chart.internal.svg.attr("width")).to.be.equal(chartWidth - diff); + + // reset the body + document.body.innerHTML = ""; + done(); + }, 100); + }); }); diff --git a/src/internals/size.js b/src/internals/size.js index 44f22b797..26d5371df 100644 --- a/src/internals/size.js +++ b/src/internals/size.js @@ -4,7 +4,7 @@ */ import ChartInternal from "./ChartInternal"; import CLASS from "../config/classes"; -import {isValue, ceil10, extend} from "./util"; +import {isValue, ceil10, extend, capitalize} from "./util"; extend(ChartInternal.prototype, { getCurrentWidth() { @@ -85,28 +85,38 @@ extend(ChartInternal.prototype, { return paddingRight; }, + /** + * Get the parent rect element's size + * @param {String} key property/attribute name + * @private + */ getParentRectValue(key) { + const offsetName = `offset${capitalize(key)}`; let parent = this.selectChart.node(); let v; - while (parent && parent.tagName !== "BODY") { + while (!v && parent && parent.tagName !== "BODY") { try { v = parent.getBoundingClientRect()[key]; } catch (e) { - if (key === "width") { + if (offsetName in parent) { // In IE in certain cases getBoundingClientRect // will cause an "unspecified error" - v = parent.offsetWidth; + v = parent[offsetName]; } } - if (v) { - break; - } - parent = parent.parentNode; } + if (key === "width") { + // Sometimes element's width value is incorrect(ex. flex container) + // In this case, use body's offsetWidth instead. + const bodyWidth = document.body.offsetWidth; + + v > bodyWidth && (v = bodyWidth); + } + return v; }, diff --git a/src/internals/util.js b/src/internals/util.js index 4c6896312..87edba1a8 100644 --- a/src/internals/util.js +++ b/src/internals/util.js @@ -170,9 +170,16 @@ function removeEvent(element, type, handler) { } } +/** + * Return first letter capitalized + * @param {String} str + * @private + */ +const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1); + /** * Check if is array - * @param arr * + * @param {Array} arr * @returns {Boolean} * @private */ @@ -245,6 +252,7 @@ export { removeEvent, getRectSegList, merge, + capitalize, isArray, isObject };