@grafana/ui
Version:
Grafana Components Library
1 lines • 3.18 kB
Source Map (JSON)
{"version":3,"file":"squares.mjs","sources":["../../../src/utils/squares.ts"],"sourcesContent":["/**\n * This function will calculate how many squares we can fit inside a rectangle.\n * Please have a look at this post for more details about the implementation:\n * https://math.stackexchange.com/questions/466198/algorithm-to-get-the-maximum-size-of-n-squares-that-fit-into-a-rectangle-with-a\n *\n * @param parentWidth width of the parent container\n * @param parentHeight height of the parent container\n * @param numberOfChildren number of children that should fit in the parent container\n */\nexport const calculateGridDimensions = (\n parentWidth: number,\n parentHeight: number,\n itemSpacing: number,\n numberOfChildren: number\n) => {\n const vertical = calculateSizeOfChild(parentWidth, parentHeight, numberOfChildren);\n const horizontal = calculateSizeOfChild(parentHeight, parentWidth, numberOfChildren);\n const square = Math.max(vertical, horizontal);\n let xCount = Math.floor(parentWidth / square);\n let yCount = Math.ceil(numberOfChildren / xCount);\n\n // after yCount update xCount to make split between rows more even\n xCount = Math.ceil(numberOfChildren / yCount);\n\n const itemsOnLastRow = xCount - (xCount * yCount - numberOfChildren);\n const widthOnLastRow = parentWidth / itemsOnLastRow - itemSpacing + itemSpacing / itemsOnLastRow;\n\n return {\n width: parentWidth / xCount - itemSpacing + itemSpacing / xCount,\n height: parentHeight / yCount - itemSpacing + itemSpacing / yCount,\n widthOnLastRow,\n xCount,\n yCount,\n };\n};\n\nfunction calculateSizeOfChild(parentWidth: number, parentHeight: number, numberOfChildren: number): number {\n const parts = Math.ceil(Math.sqrt((numberOfChildren * parentWidth) / parentHeight));\n\n if (Math.floor((parts * parentHeight) / parentWidth) * parts < numberOfChildren) {\n return parentHeight / Math.ceil((parts * parentHeight) / parentWidth);\n }\n\n return parentWidth / parts;\n}\n"],"names":[],"mappings":"AASO,MAAM,uBAA0B,GAAA,CACrC,WACA,EAAA,YAAA,EACA,aACA,gBACG,KAAA;AACH,EAAA,MAAM,QAAW,GAAA,oBAAA,CAAqB,WAAa,EAAA,YAAA,EAAc,gBAAgB,CAAA;AACj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