@grafana/ui
Version:
Grafana Components Library
1 lines • 3.19 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,uBAAA,GAA0B,CACrC,WAAA,EACA,YAAA,EACA,aACA,gBAAA,KACG;AACH,EAAA,MAAM,QAAA,GAAW,oBAAA,CAAqB,WAAA,EAAa,YAAA,EAAc,gBAAgB,CAAA;AACj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