### Usage Patterns and Examples
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/_SUMMARY.txt
Guides and examples for various usage patterns, including initialization, responsive design, and framework integration.
```APIDOC
## Usage Patterns
Explore different ways to use BentoGrid.js effectively.
### Supported Patterns:
- Initialization patterns
- Mobile-first responsive design
- Container-based responsive design
- Dynamic content handling
- Framework integration (Vue, React, Vanilla JS)
- Performance optimization
Refer to `patterns-and-examples.md` for practical examples and guides.
```
--------------------------------
### Example Breakpoint Configuration
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/types.md
Illustrates how to structure the `breakpoints` object in the user configuration. This example shows overrides for mobile, tablet, and desktop screen sizes.
```javascript
// Breakpoints object structure
{
breakpoints: {
0: {
minCellWidth: 80,
cellGap: 8,
aspectRatio: 1
},
768: {
minCellWidth: 100,
cellGap: 12
},
1024: {
minCellWidth: 150,
cellGap: 20,
aspectRatio: 16/9
}
}
}
```
--------------------------------
### Full BentoGrid Configuration with Breakpoints
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/types.md
Example of initializing BentoGrid with a comprehensive configuration, including detailed breakpoint settings for responsive adjustments.
```javascript
// Full config with breakpoints
const grid2 = new BentoGrid({
target: document.getElementById('grid'),
minCellWidth: 120,
cellGap: 16,
aspectRatio: 4/3,
breakpoints: {
480: { minCellWidth: 80, cellGap: 8 },
768: { minCellWidth: 100, cellGap: 12 },
1024: { minCellWidth: 150, cellGap: 20 }
},
breakpointReference: 'target',
balanceFillers: true
});
```
--------------------------------
### Install BentoGrid Core
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/README.md
Install the core package using npm. This is the first step to using BentoGrid.js in your project.
```bash
npm install @bentogrid/core
```
--------------------------------
### Setup CSS Grid Styles
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/implementation-details.md
Initializes the necessary CSS grid properties on the container and calculates initial dimensions for the grid layout.
```javascript
this.setupGrid();
```
--------------------------------
### Minimal BentoGrid Configuration
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/types.md
Example of initializing BentoGrid with the minimum required configuration, specifying only the target element.
```javascript
// Minimal config
const grid1 = new BentoGrid({
target: '.grid-container'
});
```
--------------------------------
### Minimal BentoGrid Setup
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
The most basic way to initialize BentoGrid. Requires a target container with the class 'bentogrid' and child elements with 'data-bento' attributes.
```javascript
import BentoGrid from '@bentogrid/core';
const grid = new BentoGrid({
target: '.bentogrid'
});
```
--------------------------------
### Recommended Breakpoint Configurations
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/configuration.md
Examples demonstrate clear configurations using either `columns` for a fixed count or `minCellWidth` for responsive calculation. Mixing both in a single breakpoint is discouraged.
```javascript
// Good: columns-based
breakpoints: {
0: { columns: 2 },
768: { columns: 3 },
1024: { columns: 4 }
}
```
```javascript
// Good: width-based
breakpoints: {
0: { minCellWidth: 80 },
768: { minCellWidth: 100 },
1024: { minCellWidth: 150 }
}
```
```javascript
// Avoid: mixing both
breakpoints: {
1024: { columns: 4, minCellWidth: 150 } // Undefined behavior
}
```
--------------------------------
### Example Grid Item Placement
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/grid-calculation.md
Illustrates the HTML structure and the step-by-step processing of grid items with different dimensions, showing their calculated positions and matrix occupation.
```html
Item A
Item B
```
```javascript
// Processing
// Item A (2x1):
// - Position: { column: 0, row: 0 }
// - gridColumn: "1 / span 2"
// - gridRow: "1 / span 1"
// - Matrix occupation: [0,0], [1,0]
// Item B (1x2):
// - Position: { column: 2, row: 0 } (first available)
// - gridColumn: "3 / span 1"
// - gridRow: "1 / span 2"
// - Matrix occupation: [2,0], [2,1]
```
--------------------------------
### Example Breakpoint Configuration with Fixed Columns
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/types.md
Demonstrates using the `columns` property to set a fixed number of columns for different breakpoints, overriding the `minCellWidth` behavior.
```javascript
// Fixed columns per breakpoint
{
breakpoints: {
0: { columns: 2 },
768: { columns: 3 },
1024: { columns: 4 }
}
}
```
--------------------------------
### Style Bento-Filler Elements
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/events-and-attributes.md
Example CSS to style the dynamically added filler elements within a bento-grid.
```css
.bentogrid > .bento-filler {
background-color: #f0f0f0;
border: 1px solid #ddd;
opacity: 0.5;
}
```
--------------------------------
### Calculate --bento-row-height Example
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/events-and-attributes.md
A scenario illustrating the calculation of the --bento-row-height CSS variable based on container width, aspect ratio, columns, and gap.
```javascript
// Config with aspect ratio 16/9
// Container width 1000px, 5 columns, 16px gap
// Cell width: (1000 - 4*16) / 5 = 192.8px
// Row height: 192.8 / (16/9) = 108.45px
// Result: --bento-row-height: 108.45px
```
--------------------------------
### HTML Structure with Filler Elements
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/events-and-attributes.md
An example of the resulting HTML structure when filler elements are dynamically added by BentoGrid.
```html
```
--------------------------------
### Enable Balanced Fillers Layout
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/BentoGrid.md
This example shows how to enable the `balanceFillers` option, which allows BentoGrid to swap filler elements with grid items of the same size for a more balanced visual distribution. This option is useful for aesthetic control in complex layouts.
```javascript
const grid = new BentoGrid({
target: '.bentogrid',
balanceFillers: true, // Enables swapping to distribute fillers evenly
minCellWidth: 100
});
```
--------------------------------
### Fixed Column BentoGrid Configuration
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/types.md
Example of initializing BentoGrid to use a fixed number of columns, overriding the automatic calculation based on cell width.
```javascript
// Fixed column layout
const grid3 = new BentoGrid({
target: '.grid',
columns: 3,
cellGap: 12
});
```
--------------------------------
### Configure Responsive Grid with Breakpoints
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/BentoGrid.md
This example demonstrates how to configure BentoGrid for responsive layouts using breakpoints. It specifies different `minCellWidth` and `cellGap` values for various screen sizes, referencing the target element for breakpoint detection.
```javascript
const grid = new BentoGrid({
target: '#my-grid',
minCellWidth: 100,
cellGap: 16,
aspectRatio: 4/3,
breakpoints: {
// Mobile
0: { minCellWidth: 80, cellGap: 8 },
// Tablet
768: { minCellWidth: 100, cellGap: 12 },
// Desktop
1024: { minCellWidth: 150, cellGap: 20 }
},
breakpointReference: 'target'
});
```
--------------------------------
### HTML Structure for BentoGrid Fillers
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/events-and-attributes.md
Example HTML demonstrating a BentoGrid container with a data-bento item and two 'card-template' elements intended as filler templates. After initialization, these templates are hidden and cloned for dynamic placement.
```html
Item
Template 1
Template 2
```
--------------------------------
### HTML Structure for BentoGrid Items
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/events-and-attributes.md
Example HTML demonstrating how to define grid items using the 'data-bento' attribute to specify their column and row spans. Elements without this attribute are treated as fillers.
```html
```
--------------------------------
### Animate Items into View on Layout Completion
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
Apply animations to grid items after the layout is complete. This example uses a `fadeIn` animation with a staggered delay based on item index.
```javascript
grid.gridContainer.addEventListener('calculationDone', () => {
// Get newly positioned items
const items = grid.gridContainer.querySelectorAll('[data-bento]');
items.forEach((item, index) => {
item.style.animation = `fadeIn 0.5s ease-out ${index * 0.1}s both`;
});
});
```
```css
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
```
--------------------------------
### Vanilla JS Custom Element for BentoGrid
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
Create a custom HTML element for BentoGrid using Vanilla JavaScript. This example demonstrates lazy loading the core library and defining custom element lifecycle callbacks.
```javascript
class BentoGridElement extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
const BentoGrid = (await import('@bentogrid/core')).default;
this.grid = new BentoGrid({
target: this
});
this.addEventListener('calculationDone', () => {
this.dispatchEvent(new CustomEvent('grid-ready'));
});
}
recalculate() {
if (this.grid) {
this.grid.recalculate();
}
}
}
customElements.define('bento-grid', BentoGridElement);
```
--------------------------------
### Vue.js BentoGrid Integration
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
Integrate BentoGrid into a Vue.js application using refs and lifecycle hooks. This example demonstrates initializing the grid, listening for calculation events, and adding items dynamically.
```javascript
// Vue component
import { ref, onMounted } from 'vue';
import BentoGrid from '@bentogrid/core';
export default {
setup() {
const gridRef = ref(null);
let grid = null;
onMounted(() => {
grid = new BentoGrid({
target: gridRef.value
});
gridRef.value.addEventListener('calculationDone', () => {
console.log('Layout calculated');
});
});
const addItem = () => {
const item = document.createElement('div');
item.setAttribute('data-bento', '1x1');
item.textContent = 'New Item';
gridRef.value.appendChild(item);
grid.recalculate();
};
return { gridRef, addItem };
}
};
```
--------------------------------
### React BentoGrid Integration
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
Integrate BentoGrid into a React component using `useEffect` and `useRef`. This example shows grid initialization with custom options, event handling, and dynamic item addition.
```javascript
import { useEffect, useRef } from 'react';
import BentoGrid from '@bentogrid/core';
export default function GridComponent() {
const containerRef = useRef(null);
const gridRef = useRef(null);
useEffect(() => {
gridRef.current = new BentoGrid({
target: containerRef.current,
minCellWidth: 120,
cellGap: 16
});
const handleCalculationDone = () => {
console.log('Layout calculated');
};
containerRef.current.addEventListener('calculationDone', handleCalculationDone);
return () => {
containerRef.current?.removeEventListener('calculationDone', handleCalculationDone);
};
}, []);
const addItem = () => {
const item = document.createElement('div');
item.setAttribute('data-bento', '1x1');
item.textContent = 'New Item';
containerRef.current.appendChild(item);
gridRef.current.recalculate();
};
return (
);
}
```
--------------------------------
### Include Hidden Elements in Grid Recalculation
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/events-and-attributes.md
This example shows how to temporarily hide an element by setting its `display` style to 'none', which makes its `offsetParent` null. Later, the element can be made visible again, and the grid can be recalculated to include it.
```javascript
// Hide an item
item.style.display = 'none'; // offsetParent becomes null
// Later: show it again and recalculate
item.style.display = 'block'; // offsetParent is restored
grid.recalculate();
```
--------------------------------
### HTML Structure with data-bento-no-swap
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/events-and-attributes.md
Example HTML showing the use of the optional 'data-bento-no-swap' attribute. This attribute prevents a grid item from being swapped with fillers when filler balancing is active, useful for preserving the position of important elements.
```html
Primary Content (Fixed)
Important Section
Can be swapped
```
--------------------------------
### Parse Grid Column Style String
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/implementation-details.md
Parses a CSS grid-column style string to extract the start and span values. Assumes the format "{start} / span {span}".
```javascript
const gridColumnStart = parseInt(item.style.gridColumn.split(" / ")[0]);
const gridColumnEnd = parseInt(item.style.gridColumn.split(" / ")[1].split(" ")[1]);
```
--------------------------------
### setupGrid()
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/BentoGrid.md
Initializes the CSS grid styles on the container element. This includes setting `display: grid`, calculating `gridTemplateColumns`, and setting `gridGap`.
```APIDOC
## setupGrid()
### Description
Initializes CSS grid styles on the container:
- Sets `display: grid`
- Calculates `gridTemplateColumns` based on available width and cell dimensions
- Sets `gridGap` style
- Calculates row height and stores in `--bento-row-height` CSS variable
### Returns
The calculated total number of columns.
```
--------------------------------
### Set Up Responsive Behavior
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/implementation-details.md
Configures event listeners or observers to handle layout adjustments based on screen size or other defined breakpoints.
```javascript
this.handleResponsiveBehavior();
```
--------------------------------
### Algorithm Documentation
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/_SUMMARY.txt
In-depth explanation of the grid positioning algorithm, filler placement strategy, and responsive breakpoint system.
```APIDOC
## Algorithm Documentation
Understand the core logic behind BentoGrid.js.
### Key Aspects:
- Grid positioning algorithm (9 phases)
- Filler placement strategy
- Responsive breakpoint system
- Complete example walkthrough
Refer to `grid-calculation.md` for detailed algorithm explanations.
```
--------------------------------
### Conditional Filler Behavior
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
Control whether the grid attempts to balance fillers based on a condition, such as screen width. This example enables balancing only on desktop.
```javascript
const grid = new BentoGrid({
target: '.bentogrid',
balanceFillers: window.innerWidth > 768 // Enable on desktop only
});
```
--------------------------------
### Configuration Options
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/_SUMMARY.txt
Detailed documentation for all configuration options, including default values and explanations of the breakpoint system.
```APIDOC
## Configuration Guide
This guide covers all configuration options available for BentoGrid.js.
### Key Features:
- All 8 options documented
- Default values specified
- Configuration merging explained
- Breakpoint system detailed
- Real-world examples provided
Refer to `configuration.md` for comprehensive details.
```
--------------------------------
### Accessing Grid Container and Event Listener
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/exported-api.md
Get a direct reference to the grid's container element and attach an event listener for the 'calculationDone' event.
```javascript
const items = grid.gridContainer.querySelectorAll('[data-bento]');
grid.gridContainer.addEventListener('calculationDone', () => {
console.log('Layout complete');
});
```
--------------------------------
### Initialize Gallery Layout
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/README.md
Use this snippet to create a gallery layout with a specified aspect ratio. Ensure the target element exists in the DOM.
```javascript
new BentoGrid({
target: '.gallery',
minCellWidth: 150,
cellGap: 16,
aspectRatio: 16/9
});
```
--------------------------------
### Initialize State Variables
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/implementation-details.md
Sets up variables to track previous column counts for detecting changes during responsive updates.
```javascript
this.prevTotalColumns = null;
this.prevColumnCount = null;
```
--------------------------------
### Set Grid Row Style
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/implementation-details.md
Sets the grid-row CSS property for an item. Use when defining the start position and span of an item within a grid row.
```javascript
item.style.gridRow = `${position.row + 1} / span ${gridRowSpan}`;
```
--------------------------------
### Initialize Fixed Column Layout
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/README.md
Set up a grid with a fixed number of columns and a consistent aspect ratio for all cells. This is useful for uniform grid structures.
```javascript
new BentoGrid({
target: '.bentogrid',
columns: 3,
cellGap: 20,
aspectRatio: 1
});
```
--------------------------------
### Initialize BentoGrid with Configuration
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/configuration.md
Create a new BentoGrid instance with initial configuration options like `target` and `minCellWidth`. To update configuration later, create a new instance with the desired settings.
```javascript
let grid = new BentoGrid({ target: '.bentogrid', minCellWidth: 100 });
// Later: need different config
grid = new BentoGrid({ target: '.bentogrid', minCellWidth: 150 });
```
--------------------------------
### Set Grid Column Style
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/implementation-details.md
Sets the grid-column CSS property for an item. Use when defining the start position and span of an item within a grid column.
```javascript
item.style.gridColumn = `${position.column + 1} / span ${gridColumnSpan}`;
```
--------------------------------
### Initialize BentoGrid with Full Configuration
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/exported-api.md
Utilize the full configuration object to define advanced settings including aspect ratio, breakpoints, and filler balancing. This provides maximum control over the grid's appearance and behavior.
```javascript
const grid3 = new BentoGrid({
target: '.bentogrid',
minCellWidth: 100,
columns: undefined,
cellGap: 12,
aspectRatio: 4/3,
breakpoints: {
768: { minCellWidth: 100, cellGap: 12 },
1024: { minCellWidth: 150, cellGap: 20 }
},
breakpointReference: 'target',
balanceFillers: true
});
```
--------------------------------
### Initialize Mobile-First Responsive Layout
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/README.md
Configure a mobile-first responsive layout with defined breakpoints for different screen sizes. Adjust breakpoints as needed for your design.
```javascript
new BentoGrid({
target: '.bentogrid',
minCellWidth: 80,
cellGap: 8,
breakpoints: {
768: { minCellWidth: 120, cellGap: 12 },
1024: { minCellWidth: 150, cellGap: 16 }
}
});
```
--------------------------------
### Check Position Availability
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/grid-calculation.md
Determines if a given starting position and span (column and row) are free within the grid matrix. It checks all cells the item would occupy.
```javascript
function isPositionAvailable(column, row, gridColumnSpan, gridRowSpan) {
for (let c = column; c < column + gridColumnSpan; c++) {
for (let r = row; r < row + gridRowSpan; r++) {
if (gridMatrix[c] && gridMatrix[c][r]) {
return false;
}
}
}
return true;
}
```
--------------------------------
### Initialize Container-Based Responsive Layout
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/README.md
Create a responsive grid that adjusts based on the dimensions of its target container. This ensures the grid scales with its parent element.
```javascript
new BentoGrid({
target: '.bentogrid',
minCellWidth: 120,
breakpointReference: 'target',
breakpoints: {
400: { minCellWidth: 80 },
600: { minCellWidth: 100 }
}
});
```
--------------------------------
### Filter Visible Grid Items
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/events-and-attributes.md
This snippet demonstrates how to filter out hidden grid items by checking if their `offsetParent` is not null. Hidden elements are skipped during setup and layout calculations.
```javascript
.filter(item => item.offsetParent !== null);
```
--------------------------------
### BentoGrid Layout Calculation Steps
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/grid-calculation.md
Illustrates the manual calculation process for determining grid dimensions and item placement, including column and row calculations, matrix initialization, item placement, and CSS Grid property generation.
```text
1. Column Calculation
Available: 1000 + 16 = 1016
Per cell: 100 + 16 = 116
Columns: floor(1016 / 116) = 8
2. Row Height Calculation
Cell width: (1000 - 7*16) / 8 = 112.5px
Row height: 112.5 / 1 = 112.5px
3. Matrix Initialization
gridMatrix = [[], [], [], [], [], [], [], []]
4. Place Item A (2x1)
Next available: { column: 0, row: 0 }
gridColumn: "1 / span 2"
gridRow: "1 / span 1"
Occupied: [0,0], [1,0]
5. Place Item B (1x2)
Next available: { column: 2, row: 0 }
gridColumn: "3 / span 1"
gridRow: "1 / span 2"
Occupied: [2,0], [2,1]
6. Place Item C (1x1)
Next available: { column: 3, row: 0 }
gridColumn: "4 / span 1"
gridRow: "1 / span 1"
Occupied: [3,0]
7. Fill Empty Cells
Row 0: columns 4-7 available
Row 1: columns 0-1, 3-7 available
Create fillers for gaps, clone templates as needed
8. CSS Grid Setup
gridTemplateColumns: repeat(8, minmax(100px, 1fr))
gridGap: 16px
gridTemplateRows: repeat(2, minmax(112.5px, 1fr))
```
--------------------------------
### Calculate Filler Span
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/grid-calculation.md
Determines the maximum possible column and row span for a filler element starting at a given cell. It extends spans as long as adjacent cells are unoccupied.
```javascript
// Find the maximum gridColumnSpan
while (
column + gridColumnSpan < totalColumns &&
!gridMatrix[column + gridColumnSpan][row]
) {
gridColumnSpan++;
}
// Find the maximum gridRowSpan
for (let r = row + 1; r < maxRow; r++) {
let rowSpanValid = true;
for (let c = column; c < column + gridColumnSpan; c++) {
if (gridMatrix[c][r]) {
rowSpanValid = false;
break;
}
}
if (!rowSpanValid) {
break;
}
gridRowSpan++;
}
```
--------------------------------
### Complete API Reference
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/_SUMMARY.txt
Documentation for every exported symbol, including full method signatures, parameter types, and return types.
```APIDOC
## API Reference
This section details all exported symbols from the BentoGrid.js library.
### Key Features:
- Full method signatures
- All parameter types documented
- Return types and descriptions provided
Refer to `exported-api.md` and `api-reference/BentoGrid.md` for detailed information.
```
--------------------------------
### Perform Initial Grid Layout
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/implementation-details.md
Calculates and applies the initial positioning for all grid items and fills any available gaps.
```javascript
this.updateGrid();
```
--------------------------------
### Responsive Breakpoints Configuration
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/README.md
Defines how to configure responsive overrides for grid layout based on screen size.
```APIDOC
## Responsive Breakpoints
### Description
Allows defining specific configuration overrides for different screen widths. Breakpoints are defined as numeric keys in the `breakpoints` object, each mapping to a `Breakpoint` object.
### Example
```javascript
breakpoints: {
768: { minCellWidth: 100, cellGap: 12 },
1024: { minCellWidth: 150, cellGap: 20 }
}
```
### Breakpoint Object Properties
Each breakpoint can override the following properties:
- **minCellWidth** (number): Minimum cell width in pixels.
- **columns** (number): Fixed column count.
- **cellGap** (number): Gap between cells in pixels.
- **aspectRatio** (number): Aspect ratio for row height.
```
--------------------------------
### Initialize BentoGrid Instance
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/BentoGrid.md
Instantiate BentoGrid with a configuration object. This sets up the grid container, defines cell dimensions and gaps, and configures responsive breakpoints.
```javascript
const grid = new BentoGrid({
target: '.bentogrid',
minCellWidth: 100,
cellGap: 16,
aspectRatio: 1,
breakpoints: {
768: { minCellWidth: 80, cellGap: 12 },
1024: { minCellWidth: 120, cellGap: 20 }
}
});
```
--------------------------------
### Initialize BentoGrid with Default Configuration
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/BentoGrid.md
This snippet shows the basic initialization of BentoGrid. It assumes the target element exists and grid items have data-bento attributes. Default settings for cell width, gap, and aspect ratio are used.
```javascript
const grid = new BentoGrid({
target: '.bentogrid'
});
```
--------------------------------
### Initialize BentoGrid with Custom Options
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/exported-api.md
Configure the grid with specific minimum cell width and cell gap for a more tailored layout. This is useful for controlling spacing and item sizing.
```javascript
const grid2 = new BentoGrid({
target: document.getElementById('grid'),
minCellWidth: 120,
cellGap: 16
});
```
--------------------------------
### Dynamic Grid Configuration by Screen Size
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
Configure grid properties like `minCellWidth` and `cellGap` dynamically based on the current screen width. This allows for responsive grid layouts without recreating the grid instance.
```javascript
function getConfig() {
if (window.innerWidth < 640) {
return { minCellWidth: 60, cellGap: 8 };
} else if (window.innerWidth < 1024) {
return { minCellWidth: 100, cellGap: 12 };
} else {
return { minCellWidth: 150, cellGap: 20 };
}
}
const grid = new BentoGrid({
target: '.bentogrid',
...getConfig()
});
```
--------------------------------
### Package JSON Configuration (JSON)
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/exported-api.md
Configuration for the package, specifying the main entry point as an ES Module.
```json
{
"main": "./BentoGrid.js",
"type": "module"
}
```
--------------------------------
### Mobile-First Responsive Design with Breakpoints
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/configuration.md
Configure a mobile-first responsive grid by defining base styles and overriding them at specific breakpoints for tablet and desktop sizes. The breakpoint reference is set to the window.
```javascript
const grid = new BentoGrid({
target: '.bentogrid',
// Mobile base config
minCellWidth: 80,
cellGap: 8,
aspectRatio: 1,
// Tablet and desktop overrides
breakpoints: {
768: {
minCellWidth: 100,
cellGap: 12,
aspectRatio: 4/3
},
1024: {
minCellWidth: 150,
cellGap: 16,
aspectRatio: 16/9
}
},
breakpointReference: 'window'
});
```
--------------------------------
### BentoGrid Constructor
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/INDEX.md
Initializes a new BentoGrid instance with the provided user configuration. The configuration options allow customization of the grid's behavior and appearance.
```APIDOC
## constructor(userConfig: UserConfig)
### Description
Initializes the BentoGrid with a user-defined configuration object. This allows for customization of grid behavior, such as target element, cell dimensions, and responsive breakpoints.
### Method
constructor
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **userConfig** (UserConfig) - Required - An object containing configuration options for the grid. See Configuration Overview for available options.
```
--------------------------------
### Initialize BentoGrid with User Configuration
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/exported-api.md
Use this configuration to initialize a new BentoGrid instance with custom settings for target element, cell dimensions, gaps, aspect ratio, and responsive breakpoints. Ensure the `UserConfig` object is correctly structured before passing it to the constructor.
```typescript
const config: UserConfig = {
target: '#grid',
minCellWidth: 150,
cellGap: 20,
aspectRatio: 4/3,
breakpoints: {
768: { minCellWidth: 100 },
1024: { minCellWidth: 150 }
},
balanceFillers: true
};
const grid = new BentoGrid(config);
```
--------------------------------
### Grid Container Styles (CSS)
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/exported-api.md
These styles are applied to the main grid container by the `setupGrid()` function. They define the grid layout, column and row configurations, and spacing.
```css
display: grid;
grid-template-columns: repeat({n}, minmax({w}px, 1fr));
grid-gap: {gap}px;
grid-template-rows: repeat({m}, minmax(var(--bento-row-height), 1fr));
--bento-row-height: {height}px;
```
--------------------------------
### ResizeObserver vs Window Resize Event Handling
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/implementation-details.md
Adapts the resize detection mechanism based on the breakpoint reference configuration. For 'window' mode, it simulates the ResizeObserver interface using window event listeners.
```javascript
if (this.config.breakpointReference === 'window') {
this.resizeObserver = {
observe: () => {
window.addEventListener('resize', onResize);
},
unobserve: () => {
window.removeEventListener('resize', onResize);
},
};
} else {
this.resizeObserver = new ResizeObserver(onResize);
}
```
--------------------------------
### Initialize BentoGrid with Default and User Configuration
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/configuration.md
User-provided `userConfig` completely overrides any default properties. Properties not specified in `userConfig` retain their default values.
```javascript
this.config = {
...{
target: '.bentogrid',
minCellWidth: 100,
cellGap: 0,
aspectRatio: 1 / 1,
breakpoints: [],
balanceFillers: false,
breakpointReference: 'target',
},
...userConfig,
};
```
--------------------------------
### BentoGrid Constructor
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/exported-api.md
Initializes a new BentoGrid instance. It merges user-provided configuration with default settings, resolves the target element, collects grid items, and sets up the necessary CSS Grid styles and responsive behavior.
```APIDOC
## constructor(userConfig: UserConfig)
### Description
Initializes a new BentoGrid instance by merging user configuration, resolving the target element, collecting grid items, setting up CSS Grid styles, and establishing responsive behavior.
### Method
constructor
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **userConfig** (UserConfig) - Required - Configuration object for the grid
### Request Example
```javascript
// Minimal
const grid1 = new BentoGrid({ target: '.bentogrid' });
// With options
const grid2 = new BentoGrid({
target: document.getElementById('grid'),
minCellWidth: 120,
cellGap: 16
});
// Full config
const grid3 = new BentoGrid({
target: '.bentogrid',
minCellWidth: 100,
columns: undefined,
cellGap: 12,
aspectRatio: 4/3,
breakpoints: {
768: { minCellWidth: 100, cellGap: 12 },
1024: { minCellWidth: 150, cellGap: 20 }
},
breakpointReference: 'target',
balanceFillers: true
});
```
### Response
#### Success Response (200)
BentoGrid instance
#### Response Example
None provided in source.
### Throws
Error if target element cannot be found.
```
--------------------------------
### Type Definitions
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/_SUMMARY.txt
Documentation for all defined types, including UserConfig and Breakpoint, with explanations of their properties and relationships.
```APIDOC
## Type System
Details on the type definitions used within BentoGrid.js.
### Defined Types:
- UserConfig type (8 properties)
- Breakpoint type (4 properties)
- Type relationships and flow diagrams
Refer to `types.md` for comprehensive type information.
```
--------------------------------
### Set Grid Container Styles
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/grid-calculation.md
Configures the grid container's display property, column template with responsive breakpoints, and gap between grid items. Applied in `setupGrid()`.
```javascript
this.gridContainer.style.display = "grid";
this.gridContainer.style.gridTemplateColumns = `repeat(${totalColumns}, minmax(${breakpoint.minCellWidth}px, 1fr))`
this.gridContainer.style.gridGap = `${breakpoint.cellGap}px`;
```
--------------------------------
### BentoGrid Configuration Object
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/grid-calculation.md
Configure BentoGrid with target selector, minimum cell width, cell gap, and desired aspect ratio.
```javascript
{
target: '.bentogrid',
minCellWidth: 100,
cellGap: 16,
aspectRatio: 1
}
```
--------------------------------
### Initialize Grid Matrix
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/grid-calculation.md
Creates a 2D array to represent the grid, where each element tracks occupied cells. Columns are initialized, and rows expand dynamically.
```javascript
const gridMatrix = [];
let maxRow = 0;
// Initialize the grid matrix
for (let i = 0; i < totalColumns; i++) {
gridMatrix[i] = [];
}
```
--------------------------------
### Initialize Multiple Independent Grids
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
Manage multiple distinct BentoGrids on the same page. Each grid can have its own configuration, and they operate independently.
```javascript
const grid1 = new BentoGrid({
target: '#grid-1',
minCellWidth: 100
});
const grid2 = new BentoGrid({
target: '#grid-2',
minCellWidth: 150,
cellGap: 20
});
// Each grid is independent
grid1.recalculate();
grid2.recalculate();
```
--------------------------------
### BentoGrid Class
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/_SUMMARY.txt
Documentation for the main BentoGrid class, including its constructor and public methods.
```APIDOC
## Class: BentoGrid
### Description
The main class for creating and managing Bento Grid layouts. It handles initialization, recalculations, and responsive behavior.
### Constructor
- **constructor(userConfig: UserConfig)**: Initializes a new instance of BentoGrid.
- **userConfig** (UserConfig) - Optional. An object containing configuration options for the grid.
### Public Methods
- **recalculate(): void**
- Description: Triggers a recalculation of the grid layout, useful after manual DOM changes or configuration updates.
- Returns: void
```
--------------------------------
### Breakpoint Activation Logic with Merging
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/configuration.md
This method measures the current width, sorts breakpoint thresholds, and merges configurations from all matching breakpoints in ascending order. The final merged configuration is returned.
```javascript
getBreakpoint() {
const width = this.config.breakpointReference === "target"
? this.gridContainer.clientWidth
: window.innerWidth;
let activeBreakpoint = { ...this.config };
const breakpointKeys = Object.keys(this.config.breakpoints)
.map(Number)
.sort((a, b) => a - b);
for (const breakpointKey of breakpointKeys) {
if (width >= breakpointKey) {
activeBreakpoint = { ...activeBreakpoint, ...this.config.breakpoints[breakpointKey] };
}
}
return activeBreakpoint;
}
```
--------------------------------
### Define Responsive Breakpoints for BentoGrid
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/exported-api.md
Configure responsive behavior by defining an object where keys are minimum screen widths and values are `Breakpoint` objects. Each `Breakpoint` object can override `minCellWidth`, `cellGap`, `columns`, and `aspectRatio` for specific screen sizes. This allows the grid to adapt its layout dynamically.
```typescript
const breakpoints: { [minWidth: number]: Breakpoint } = {
480: {
minCellWidth: 80,
cellGap: 8,
aspectRatio: 1
},
768: {
minCellWidth: 100,
cellGap: 12,
aspectRatio: 4/3
},
1024: {
minCellWidth: 150,
cellGap: 20,
aspectRatio: 16/9
}
};
```
--------------------------------
### resizeObserver
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/exported-api.md
The observer instance used for managing responsive behavior. It can be either the native ResizeObserver or a custom object depending on the `breakpointReference` configuration.
```APIDOC
## resizeObserver: ResizeObserver | CustomResizeObserver
### Description
The observer used for responsive behavior.
### Variants
- **ResizeObserver:** When `breakpointReference: 'target'` (default)
- Native ResizeObserver observing the grid container
- Has `observe()` and `unobserve()` methods
- **Custom Object:** When `breakpointReference: 'window'`
- Custom object with `observe()` and `unobserve()` methods
- Internally uses window `resize` event listener
### Signature (Custom Object)
```typescript
interface CustomResizeObserver {
observe(): void; // Attaches window resize listener
unobserve(): void; // Removes window resize listener
_timeoutId?: number; // Debounce timeout ID
}
```
```
--------------------------------
### Fixed Column Responsive Layout
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/configuration.md
Create a responsive grid with a fixed number of columns that adjusts at different screen sizes. Breakpoints are defined to change the column count.
```javascript
const grid = new BentoGrid({
target: '#grid',
columns: 2,
cellGap: 12,
breakpoints: {
768: { columns: 3 },
1024: { columns: 4 },
1440: { columns: 5 }
}
});
```
--------------------------------
### Add Elements After Initialization
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
Create and append new elements to the grid after initialization. Ensure to call `recalculate()` to update the layout.
```javascript
const grid = new BentoGrid({ target: '.bentogrid' });
// Create new element
const newItem = document.createElement('div');
newItem.setAttribute('data-bento', '2x1');
newItem.className = 'grid-item';
newItem.textContent = 'New Item';
// Add to DOM
grid.gridContainer.appendChild(newItem);
// Recalculate layout
grid.recalculate();
```
--------------------------------
### Balance Fillers with Grid Items
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/grid-calculation.md
When enabled, this logic attempts to swap filler elements with existing grid items of the same size to improve visual balance. It identifies suitable candidates and performs the swap.
```javascript
if (this.config.balanceFillers) {
const availableSwaps = Array.from(this.gridItems)
.filter(item => !item.hasAttribute("data-bento-no-swap"))
.filter((item) => {
// Check if item has the same size as the filler
const itemSpan = { column: gridColumnEnd, row: gridRowEnd };
const fillerSpan = { column: gridColumnSpan, row: gridRowSpan };
return itemSpan.column === fillerSpan.column &&
itemSpan.row === fillerSpan.row &&
(itemSpan.column !== column + 1 || itemSpan.row !== row + 1);
});
if (availableSwaps.length > 0) {
// Calculate distances and find best swap
const bestSwap = /* ... */;
// Perform swap
bestSwap.style.gridColumn = filler.style.gridColumn;
bestSwap.style.gridRow = filler.style.gridRow;
filler.style.gridColumn = originalGridColumn;
filler.style.gridRow = originalGridRow;
}
}
```
--------------------------------
### handleResponsiveBehavior()
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/BentoGrid.md
Configures resize observers or event listeners based on the `breakpointReference` setting to manage responsive behavior.
```APIDOC
## handleResponsiveBehavior()
### Description
Sets up resize observers or event listeners based on `breakpointReference`:
- If `'target'`: Uses ResizeObserver on gridContainer
- If `'window'`: Attaches window resize event listener
Includes debouncing (10ms timeout) to prevent excessive recalculations during rapid resize events.
```
--------------------------------
### Initialize Grid Matrix
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/implementation-details.md
Initializes an empty grid matrix with arrays for each column. This structure is used to store grid items and their spans.
```javascript
const gridMatrix = [];
for (let i = 0; i < totalColumns; i++) {
gridMatrix[i] = [];
}
```
--------------------------------
### Configure Fixed Column Count
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/api-reference/BentoGrid.md
This snippet demonstrates how to set a fixed number of columns for the grid, overriding the `minCellWidth` behavior. It's useful when a consistent column structure is required regardless of cell width.
```javascript
const grid = new BentoGrid({
target: '.bentogrid',
columns: 4, // Always 4 columns
cellGap: 12,
aspectRatio: 1
});
```
--------------------------------
### Container-Based Responsiveness
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/configuration.md
Configure the grid to be responsive based on its container's width rather than the window. This is useful for grids embedded within other components. The breakpoint reference is set to 'target'.
```javascript
const grid = new BentoGrid({
target: '.grid-container',
minCellWidth: 120,
cellGap: 16,
breakpoints: {
400: { minCellWidth: 80, cellGap: 8 },
600: { minCellWidth: 100, cellGap: 12 },
900: { minCellWidth: 150, cellGap: 20 }
},
breakpointReference: 'target' // Container width
});
```
--------------------------------
### Configure Responsive Breakpoints
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/README.md
Define responsive overrides for grid properties like `minCellWidth` and `cellGap` at specific screen widths. These settings are applied when the viewport or target element width matches or exceeds the breakpoint key.
```javascript
breakpoints: {
768: { minCellWidth: 100, cellGap: 12 },
1024: { minCellWidth: 150, cellGap: 20 }
}
```
--------------------------------
### BentoGrid Class - Constructor
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/INDEX.md
The constructor for the BentoGrid class initializes a new instance of the grid. It accepts a configuration object to customize its behavior.
```APIDOC
## BentoGrid Constructor
### Description
Initializes a new BentoGrid instance with optional configuration.
### Method
`new BentoGrid(config?: UserConfig)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **config** (UserConfig) - Optional - An object containing configuration options for the grid.
```
--------------------------------
### CSS Classes and Variables
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/_SUMMARY.txt
Information on CSS classes and variables used for styling BentoGrid.
```APIDOC
## CSS Classes and Variables
### Description
Styling hooks provided by BentoGrid for customization.
### CSS Classes
- **.bento-filler**: A class applied to filler elements.
### CSS Variables
- **--bento-row-height**: A variable that can be used to control the height of rows in the grid.
```
--------------------------------
### Desktop-First Breakpoints for BentoGrid
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
Configure BentoGrid with desktop-first defaults and simplify for smaller screen sizes using the 'breakpoints' option. Breakpoints are defined by pixel width.
```javascript
const grid = new BentoGrid({
target: '.bentogrid',
// Desktop (default)
minCellWidth: 150,
cellGap: 20,
aspectRatio: 1,
breakpoints: {
// Tablet
1023: {
minCellWidth: 100,
cellGap: 12
},
// Mobile
640: {
minCellWidth: 60,
cellGap: 8
}
}
});
```
--------------------------------
### Initialize BentoGrid with Element Reference
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
Initialize BentoGrid by passing a DOM element directly to the 'target' option instead of a selector string. Useful for dynamic containers or multiple grids.
```javascript
const container = document.getElementById('my-grid');
const grid = new BentoGrid({
target: container
});
```
--------------------------------
### Container-Based Responsiveness for BentoGrid
Source: https://github.com/mariohamann/bentogrid.js/blob/main/_autodocs/patterns-and-examples.md
Configure BentoGrid to use container size for breakpoints instead of viewport size by setting 'breakpointReference' to 'target'. Useful for grids within specific layout areas.
```javascript
const grid = new BentoGrid({
target: '.bentogrid',
minCellWidth: 120,
breakpointReference: 'target', // Use container width
breakpoints: {
400: { minCellWidth: 80 },
600: { minCellWidth: 100 },
900: { minCellWidth: 140 }
}
});
```