### Initial Grid Setup and Widget Addition
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/transform.html
Applies initial scaling and adds three new widgets to the grid. This is the final setup step to render the grid with its initial state and transformations.
```javascript
updateScaleCssVariable();
addNewWidget();
addNewWidget();
addNewWidget();
```
--------------------------------
### ontouchstart
Source: https://github.com/gridstack/gridstack.js/blob/master/angular/doc/api/gridstack.component.md
Handles the touch start event.
```APIDOC
## ontouchstart
### Description
Handles the touch start event.
### Type
`null` | (`this`, `ev`) => `any`
### Remarks
This property corresponds to the `ontouchstart` event of the underlying `GridHTMLElement`.
```
--------------------------------
### Install and Run Vitest Tests
Source: https://github.com/gridstack/gridstack.js/blob/master/TESTING.md
Commands to install dependencies and run tests using npm scripts. Includes options for watch mode, coverage, and UI interface.
```bash
yarn install
yarn test
yarn test:watch
yarn test:coverage
yarn test:coverage:html
yarn test:ui
```
--------------------------------
### onselectstart
Source: https://github.com/gridstack/gridstack.js/blob/master/angular/doc/api/gridstack.component.md
Handles the select start event.
```APIDOC
## onselectstart
### Description
Handles the select start event.
### Type
`null` | (`this`, `ev`) => `any`
### Remarks
This property corresponds to the `onselectstart` event of the underlying `GridHTMLElement`.
```
--------------------------------
### ontransitionstart
Source: https://github.com/gridstack/gridstack.js/blob/master/angular/doc/api/gridstack.component.md
Handles the transition start event.
```APIDOC
## ontransitionstart
### Description
Handles the transition start event.
### Type
`null` | (`this`, `ev`) => `any`
### Remarks
This property corresponds to the `ontransitionstart` event of the underlying `GridHTMLElement`.
```
--------------------------------
### GridStack Vue Component Setup
Source: https://github.com/gridstack/gridstack.js/blob/master/vue/README.md
Example of setting up the GridStack component in a Vue 3 application. It includes defining options, components, and rendering the GridStack.
```vue
```
--------------------------------
### Install Gridstack.js with Yarn or NPM
Source: https://github.com/gridstack/gridstack.js/blob/master/README.md
Use these commands to add Gridstack.js to your project dependencies.
```bash
yarn add gridstack
# or
npm install --save gridstack
```
--------------------------------
### enable()
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Enables the drag & drop implementation. Subclasses should override this method to perform additional setup tasks.
```APIDOC
## enable()
### Description
Enable this drag & drop implementation. Subclasses should override to perform additional setup.
### Method
```ts
enable(): void;
```
### Returns
`void`
```
--------------------------------
### Initialize GridStack with Serialization Options
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/serialization.html
Initializes GridStack with basic configuration and drag options. This setup is common before loading or saving grid states.
```javascript
let serializedData = [
{x: 0, y: 0, w: 2, h: 2},
{x: 2, y: 1, w: 2, h: 3, content: `
text area
Input Field
Editable Div
no drag
`
},
{x: 4, y: 1},
{x: 1, y: 3},
{x: 2, y: 3, w:3},
];
serializedData.forEach((n, i) => {
n.id = String(i);
n.content = ` ${i} ${n.content ? n.content : ''}
`;
});
let serializedFull;
let grid = GridStack.init({
minRow: 1, // don't let it collapse when empty
cellHeight: 80,
float: true,
draggable: { cancel: '.no-drag' } // example of additional custom elements to skip drag on
}).load(serializedData);
addEvents(grid);
```
--------------------------------
### Vue 3 App Initialization
Source: https://github.com/gridstack/gridstack.js/blob/master/vue/README.md
Basic setup for a Vue 3 application using Vite. Ensure GridStack CSS is imported for proper styling.
```ts
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
```
--------------------------------
### Initialize GridStack with ES Module
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/esmodule.html
Import GridStack and initialize it with options, then load an array of items. Ensure the path to 'gridstack.js' is correct for your module setup.
```javascript
import { GridStack } from '../dist/gridstack.js';
let items = [{x: 1, y: 1}, {x: 2, y: 2, w: 3}];
let count = 0;
items.forEach(e => e.content = String(count++));
GridStack.init({float: true}).load(items);
```
--------------------------------
### enable()
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Enables the drag & drop implementation. Subclasses should override this method to perform additional setup.
```APIDOC
## enable()
### Description
Enable this drag & drop implementation. Subclasses should override to perform additional setup.
### Method
```typescript
enable(): void;
```
### Returns
`void`
```
--------------------------------
### enable()
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Enables the drag & drop implementation. Subclasses should override this method to perform additional setup.
```APIDOC
## enable()
### Description
Enable this drag & drop implementation. Subclasses should override to perform additional setup.
### Method
void
### Returns
`void`
```
--------------------------------
### DDResizableHandleOpt
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Options for configuring a resizable handle, including element reference and callback functions for drag start, move, and stop events.
```APIDOC
## DDResizableHandleOpt
### Description
Options for configuring a resizable handle.
### Properties
#### Optional Properties
- **element** (string | HTMLElement) - The DOM element or selector for the resizable handle.
- **move** ((event) => void) - Callback function executed when the resize handle is moved.
- **start** ((event) => void) - Callback function executed when the resize operation starts.
- **stop** ((event) => void) - Callback function executed when the resize operation stops.
```
--------------------------------
### Initialize GridStack with Options
Source: https://github.com/gridstack/gridstack.js/blob/master/spec/e2e/html/141_1534_swap.html
Initializes a new GridStack instance with specified options for float, cell height, margin, max row, and resizable handles. This is the setup for the swap collision demo.
```javascript
let floatButton = document.getElementById('float');
let maxButton = document.getElementById('max');
let bigButton = document.getElementById('big');
let size = 1;
let layout = 5;
let opt = {
float: false,
cellHeight: 70,
margin: 5,
maxRow: 0,
resizable: {handles: 'sw,w,e,se'}
};
let grid = GridStack.init(opt);
addEvents(grid);
```
--------------------------------
### Development Commands
Source: https://github.com/gridstack/gridstack.js/blob/master/vue/README.md
Common npm commands for developing the gridstack-vue library and its demo application. Includes installation, running the dev server, building, and testing.
```sh
cd vue
npm install
npm run dev # Vite dev server (demo app)
npm run build # production build of the demo
npm run build:lib # compile the library to dist/vue/
npm run test # vitest
```
--------------------------------
### DOM Testing with Vitest
Source: https://github.com/gridstack/gridstack.js/blob/master/TESTING.md
Example demonstrating how to test DOM manipulation within a test environment. Uses `beforeEach` to set up the DOM and `toBeInTheDocument` matcher.
```typescript
describe('GridStack DOM', () => {
beforeEach(() => {
document.body.innerHTML = '';
});
it('should create grid element', () => {
const grid = document.querySelector('.grid-stack');
expect(grid).toBeInTheDocument();
});
});
```
--------------------------------
### Initialize GridStack with Mobile Support
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/mobile.html
Initializes a GridStack instance with 3 columns and loads initial items. This setup is suitable for mobile devices, enabling resize handles and touch events.
```javascript
let grid = GridStack.init({ column: 3, });
grid.load([
{x:0, y:0, content: '1'},
{x:1, y:0, h:2, content: '2'},
{x:2, y:0, content: '3'}
])
```
--------------------------------
### Accessing GridStack Instance API
Source: https://github.com/gridstack/gridstack.js/blob/master/angular/doc/api/gridstack.component.md
Example demonstrating how to access the underlying GridStack instance from the GridstackComponent. This allows direct use of the GridStack API, such as adding a new widget.
```typescript
this.gridComponent.grid.addWidget({x: 0, y: 0, w: 2, h: 1});
```
--------------------------------
### Gulp Command for SCSS Column Generation
Source: https://github.com/gridstack/gridstack.js/blob/master/README.md
Example Gulp command to process the `gridstack-extra.scss` file, modify column counts, and compile it to compressed CSS.
```js
gulp.src('node_modules/gridstack/dist/src/gridstack-extra.scss')
.pipe(replace('$start: 2 !default;','$start: 30;'))
.pipe(replace('$end: 11 !default;','$end: 30;'))
.pipe(sass({outputStyle: 'compressed'}))
.pipe(rename({extname: '.min.css'}))
.pipe(gulp.dest('dist/css'))
```
--------------------------------
### Mocking Modules and DOM APIs with Vitest
Source: https://github.com/gridstack/gridstack.js/blob/master/TESTING.md
Examples of how to mock external modules and DOM APIs using Vitest's `vi.mock` and `Object.defineProperty` for isolated testing.
```typescript
// Mock a module
vi.mock('../src/utils', () => ({
Utils: {
toBool: vi.fn()
}
}));
// Mock DOM APIs
Object.defineProperty(window, 'ResizeObserver', {
value: vi.fn().mockImplementation(() => ({
observe: vi.fn(),
unobserve: vi.fn(),
disconnect: vi.fn()
}))
});
```
--------------------------------
### Setup Drag-In for New Widgets
Source: https://github.com/gridstack/gridstack.js/blob/master/spec/e2e/html/1143_nested_acceptWidget_types.html
Configures elements with the class 'newWidget' to be draggable and insertable into the GridStack instance. The `helper: 'clone'` option ensures that a clone of the dragged element is used as the visual helper during the drag operation.
```javascript
GridStack.setupDragIn('.newWidget', { appendTo: 'body', helper: 'clone' });
```
--------------------------------
### Initialize GridStack with Custom Engine and Items (JavaScript)
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/custom-engine.html
Initialize GridStack with float enabled and load initial items. This example uses the globally registered custom engine implicitly.
```javascript
let count = 0;
let items = [
{x: 0, y: 0},
{x: 1, y: 0},
{x: 1, y: 2, w: 3},
];
items.forEach(n => n.content = String(count++));
let grid = GridStack.init({
float: true,
cellHeight: 70
}).load(items);
```
--------------------------------
### Basic Gridstack Component Setup in Angular
Source: https://github.com/gridstack/gridstack.js/blob/master/angular/README.md
Use the component in your HTML template and import GridstackComponent and GridstackItemComponent for standalone Angular applications. Ensure CSS is imported for styling.
```html
```
```css
@import "gridstack/dist/gridstack.min.css";
.grid-stack {
background: #fafad2;
}
.grid-stack-item-content {
text-align: center;
background-color: #18bc9c;
}
```
--------------------------------
### Initialize Gridstack and Add Widgets
Source: https://github.com/gridstack/gridstack.js/blob/master/spec/e2e/html/1785_column_many_switch.html
Initializes Gridstack with specified cell height and margin, loads existing items, and adds new random widgets. This setup is used to test column switching behavior.
```javascript
let count = 0; let grid; let items = []; items.forEach(item => item.content = String(count++)); function addNewWidget() { var node = items[count] || { x: Math.round(12 * Math.random()), y: Math.round(5 * Math.random()), w: Math.round(1 + 3 * Math.random()), h: Math.round(1 + 3 * Math.random()) }; node.content = String(count++); if (grid) { grid.addWidget(node); } else { items.push(node); } }; grid = GridStack.init({cellHeight: 50, margin: 5}).load(items); let column = 1; for (i=0; i<7; i++) addNewWidget();
```
--------------------------------
### Basic Test Structure in TypeScript
Source: https://github.com/gridstack/gridstack.js/blob/master/TESTING.md
Example of a basic test case using Vitest's `describe` and `it` blocks to test a utility function. Requires importing the module under test.
```typescript
import { Utils } from '../src/utils';
describe('Utils', () => {
it('should parse boolean values correctly', () => {
expect(Utils.toBool(true)).toBe(true);
expect(Utils.toBool(false)).toBe(false);
expect(Utils.toBool(1)).toBe(true);
expect(Utils.toBool(0)).toBe(false);
});
});
```
--------------------------------
### Build React Components from React Directory
Source: https://github.com/gridstack/gridstack.js/blob/master/react/README.md
Alternatively, navigate to the 'react/' directory and run this command to build the React components.
```bash
yarn build:lib
```
--------------------------------
### Build React Components from Repository Root
Source: https://github.com/gridstack/gridstack.js/blob/master/react/README.md
Run this command from the root of the repository to build the React components.
```bash
yarn build:react
```
--------------------------------
### Setup Drag-In for New Widgets
Source: https://github.com/gridstack/gridstack.js/blob/master/spec/e2e/html/1704_scroll_bar.html
Configures the drag-in behavior for elements with the class '.newWidget'. This allows external elements to be dragged into the GridStack container. The helper option 'clone' ensures the original element is not moved.
```javascript
GridStack.setupDragIn('.newWidget', {
appendTo: 'body',
helper: 'clone'
});
```
--------------------------------
### Gridstack Item Options Configuration
Source: https://github.com/gridstack/gridstack.js/blob/master/angular/doc/api/gridstack-item.component.md
Defines the configuration options for a grid item, including its position, size, and behavior. This example shows setting initial properties like 'noResize' and 'content'.
```typescript
itemOptions: GridStackNode = {
x: 0, y: 0, w: 2, h: 1,
noResize: true,
content: 'Item content'
};
```
--------------------------------
### DDResizable.disabled Accessor
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Gets the disabled state of the DDResizable instance.
```APIDOC
## DDResizable.disabled Accessor
### Description
Gets the disabled state of the DDResizable instance. Use enable()/disable() methods to change state.
### Signature
```ts
get disabled(): boolean;
```
### Returns
- `boolean`: The current disabled state.
```
--------------------------------
### DDElement setupResizable Method
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Sets up the resizable functionality for a DDElement with specified options. Returns the DDElement instance.
```typescript
setupResizable(opts): DDElement;
```
--------------------------------
### GitHub Actions CI/CD Integration for Tests
Source: https://github.com/gridstack/gridstack.js/blob/master/TESTING.md
Example GitHub Actions workflow snippet to run tests and upload coverage reports. Uses `yarn test:ci` for CI-optimized runs and `codecov/codecov-action`.
```yaml
- name: Run Tests
run: yarn test:ci
- name: Upload Coverage
uses: codecov/codecov-action@v3
with:
file: ./coverage/lcov.info
```
--------------------------------
### getMargin()
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Gets the current margin value of the grid. Returns a number only if all sides have the same margin.
```APIDOC
## getMargin()
### Description
Returns the current margin value as a number (undefined if the 4 sides don't match). This only returns a number if all sides have the same margin value.
### Method
`getMargin(): number`
### Returns
`number` - The margin value in pixels, or undefined if sides have different values.
### Example
```ts
const margin = grid.getMargin();
if (margin !== undefined) {
console.log('Uniform margin:', margin, 'px');
} else {
console.log('Margins are different on different sides');
}
```
```
--------------------------------
### setupDragIn()
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Sets up drag-in functionality from external elements into the GridStack grid. This allows items from outside the grid, such as a toolbar, to be dragged and dropped into the grid, creating new widgets.
```APIDOC
## setupDragIn()
### Description
Allows dragging in elements from outside the grid (e.g., a toolbar) to create new widgets within the grid. It can be called during `GridStack.init()` as an option or directly later if the toolbar is dynamically created.
### Method
`static setupDragIn(dragIn?, dragInOptions?, widgets?, root?): void`
### Parameters
#### Path Parameters
* None
#### Query Parameters
* None
#### Request Body
* None
### Parameters
* `dragIn?` (string | HTMLElement[]) - A string selector (e.g., '.sidebar-item') or a list of DOM elements to be made draggable.
* `dragInOptions?` (DDDragOpt) - Options for the drag-and-drop behavior. Defaults to `{handle: '.grid-stack-item-content', appendTo: 'body'}`.
* `widgets?` (GridStackWidget[]) - An array of `GridStackWidget` definitions to assign to each dragged element, specifying how to create the widget on drop.
* `root?` (HTMLElement | Document) - The root element or document to search for drag-in elements. Defaults to the current `document`.
### Response
#### Success Response (void)
This method does not return a value.
### Request Example
```javascript
// Setup drag-in for elements with class 'sidebar-item'
GridStack.setupDragIn('.sidebar-item', {
handle: '.drag-handle',
append: true
}, [
{ w: 2, content: 'Widget A' },
{ w: 1, content: 'Widget B' }
]);
```
```
--------------------------------
### Initialize Knockout Bindings with Sample Data
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/knockout.html
Initializes the Knockout.js bindings with sample widget data and applies the controller to the DOM.
```javascript
let widgets = [
{ x: 0, y: 0, w: 2, h: 2, id: '0' },
{ x: 2, y: 0, w: 4, h: 2, id: '1' },
{ x: 6, y: 0, w: 2, h: 4, id: '2' },
{ x: 1, y: 2, w: 4, h: 2, id: '3' }
];
let controller = new Controller(widgets);
ko.applyBindings(controller);
```
--------------------------------
### DDElement setupResizable()
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Configures the DDElement to be resizable. This method allows for customization of the resize behavior.
```APIDOC
## setupResizable() DDElement
### Description
Configures the DDElement to be resizable.
### Method
```ts
setupResizable(opts: DDResizableOpt): DDElement;
```
### Parameters
#### Parameters
- **opts** (DDResizableOpt) - Options to configure the resizable behavior.
```
--------------------------------
### Initialize Nested Grids with Constraints
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/nested_constraint.html
Configure a main grid with nested sub-grids, each having distinct `acceptWidgets` settings. Sub-grids are styled with `itemClass: 'sub'` and only accept widgets matching `.grid-stack-item.sub`.
```javascript
let sub1 = [ {x:0, y:0}, {x:1, y:0}, {x:2, y:0}, {x:3, y:0}, {x:0, y:1}, {x:1, y:1} ]; let sub2 = [ {x:0, y:0}, {x:0, y:1, w:2} ]; let count = 0;
[...sub1, ...sub2].forEach(d => d.content = String(count++));
let subOptions = {
cellHeight: 50,
column: 'auto',
// size to match container
itemClass: 'sub', // style sub items differently and use to prevent dragging in/out
acceptWidgets: '.grid-stack-item.sub', // only pink sub items can be inserted
margin: 2,
minRow: 1, // don't collapse when empty
};
let options = {
// main grid options
cellHeight: 50,
margin: 5,
minRow: 2, // don't collapse when empty
acceptWidgets: true,
id: 'main',
children: [
{y:0, content: 'regular item'},
{x:1, w:4, h:4, subGridOpts: {children: sub1, class: 'sub1', ...subOptions}},
{x:5, w:4, h:4, subGridOpts: {children: sub2, class: 'sub2', ...subOptions}},
]
};
// create and load it all from JSON above
let grid = GridStack.addGrid(document.querySelector('.container-fluid'), options);
```
--------------------------------
### DDElement setupDroppable Method
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Sets up the droppable functionality for a DDElement with specified options. Returns the DDElement instance.
```typescript
setupDroppable(opts): DDElement;
```
--------------------------------
### DDBaseImplement: Enable Method
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Enables the drag and drop implementation. Subclasses may override for additional setup.
```typescript
enable(): void;
```
--------------------------------
### Initialize Gridstack with Items and Event Handling
Source: https://github.com/gridstack/gridstack.js/blob/master/spec/e2e/html/2206_load_collision.html
Initializes a Gridstack instance with predefined items and sets up event listeners. This is the recommended way to manage grid items.
```javascript
let items = [ {id: '0', x: 0, y: 0, w: 12, content: '0'}, {id: '1', x: 0, y: 1, w: 12, content: '1'}, {id: '2', x: 0, y: 2, w: 12, content: '2'}, {id: '3', x: 0, y: 3, w: 12, content: '3'}, ]; let grid = GridStack.init({ cellHeight: 70, children: items, }); addEvents(grid);
```
--------------------------------
### Get Margin
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Returns the current uniform margin value in pixels. Returns undefined if margins differ across sides.
```typescript
getMargin(): number;
```
```typescript
const margin = grid.getMargin();
if (margin !== undefined) {
console.log('Uniform margin:', margin, 'px');
} else {
console.log('Margins are different on different sides');
}
```
--------------------------------
### Initialize Nested Grids with Options
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/nested.html
Configures the main grid and its nested subgrids using a JSON-like structure. Use `sizeToContent: true` for subgrid parent items to allow them to grow or shrink as needed.
```javascript
let sub1 = [
{x:0, y:0}, {x:1, y:0}, {x:2, y:0}, {x:3, y:0}, {x:0, y:1}, {x:1, y:1}
];
let sub2 = [
{x:0, y:0, h:2}, {x:1, y:1, w:2}
];
let count = 0;
[...sub1, ...sub2].forEach(d => d.content = String(count++));
let options = {
// main grid options
staticGrid,
// test - force children to inherit too if we set to true above ^^^
// disableDrag: true,
// disableResize: true,
cellHeight: 50,
margin: 5,
minRow: 2, // don't collapse when empty
acceptWidgets: true,
id: 'main',
resizable: { handles: 'se,e,s,sw,w'},
// subGridOpts, // options for all subgrids, but defaults to column='auto' now so no need.
children: [
{x:0, y:0, content: 'regular item'},
{x:1, y:0, w:4, h:4, sizeToContent: true, content: '
nested grid sizeToContent:true with some header content
', subGridOpts: {children: sub1, id:'sub1_grid', class: 'sub1'}},
{x:5, y:0, w:3, h:4, subGridOpts: {children: sub2, id:'sub2_grid', class: 'sub2'}},
]
};
// create and load it all from JSON above
let grid = GridStack.addGrid(document.querySelector('.container-fluid'), options);
```
--------------------------------
### Get Current Grid Column Count
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Retrieves the number of columns currently configured for the grid. The default value is 12.
```typescript
const columnCount = grid.getColumn();
```
--------------------------------
### GridstackComponent HTML Usage
Source: https://github.com/gridstack/gridstack.js/blob/master/angular/doc/api/gridstack.component.md
Example of how to use the GridstackComponent in an Angular template. It shows how to bind options and listen for change events.
```html
Drag widgets here
```
--------------------------------
### Initialize GridStack with Options
Source: https://github.com/gridstack/gridstack.js/blob/master/spec/e2e/html/1571_drop_onto_full.html
Configure GridStack instances with specific settings like column count, row height, float behavior, and drag-in acceptance. Use this for custom grid layouts and behaviors.
```javascript
let options = { column: 6, row: 1, cellHeight: 70, float: false, removable: '.trash', // drag-out delete class acceptWidgets: function(el) { return true; } // function example, else can be simple: true | false | '.someClass' value };
```
--------------------------------
### Resize Columns to 2
Source: https://github.com/gridstack/gridstack.js/blob/master/spec/e2e/html/2406_inf_loop_autoPosition_column1.html
Resizes the grid to have 2 columns. This action is part of the scenario to reproduce the autoPosition bug after initial setup.
```javascript
resizeColumns = function () {
grid.column(2);
}
```
--------------------------------
### Initialize GridStack with Options
Source: https://github.com/gridstack/gridstack.js/blob/master/spec/e2e/html/1558-vertical-grids-scroll-too-much.html
Initializes all GridStack instances on the page with specified options, including float and acceptWidgets. Use this to configure grid behavior globally.
```javascript
var options = { float: true, acceptWidgets: true, cellHeight: 80 }; GridStack.initAll(options);
```
--------------------------------
### Get Grid Items
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Retrieves an array of all grid HTML elements, excluding placeholders. Useful for iterating through children in DOM order.
```typescript
getGridItems(): GridItemHTMLElement[];
```
```typescript
const items = grid.getGridItems();
items.forEach(item => {
console.log('Item ID:', item.gridstackNode.id);
});
```
--------------------------------
### Basic GridStack Usage in React
Source: https://github.com/gridstack/gridstack.js/blob/master/react/README.md
Demonstrates how to use the GridStack component with basic options and static HTML content for items. Ensure GridStack CSS is imported.
```tsx
import { GridStackOptions } from "gridstack";
import { GridStack } from "gridstack/dist/react";
const options: GridStackOptions = {
margin: 8,
cellHeight: 50,
column: 12,
children: [
{ id: "1", x: 0, y: 0, w: 2, h: 2, content: "Plain HTML item" },
],
};
export function Board() {
return ;
}
```
--------------------------------
### useGridStack Composable
Source: https://github.com/gridstack/gridstack.js/blob/master/vue/README.md
Example of using the `useGridStack` composable within a child component of `` to imperatively manage grid items and state.
```ts
const { grid, addWidget, removeWidget, removeAll, save, load, layoutVersion } = useGridStack()
```
--------------------------------
### Deep Clone Object
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Recursively clones an object, handling nested objects and arrays. Avoids cloning properties starting with double underscores.
```typescript
static cloneDeep(obj): T;
```
--------------------------------
### Initialize GridStack with Options
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/css_attributes.html
Initializes GridStack with float and resizable options. Ensure GridStack is loaded before this script.
```javascript
let grid = GridStack.init({ float: true, resizable: { handles: 'all'} }); addEvents(grid);
```
--------------------------------
### Initialize GridStack with Responsive Breakpoints
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/responsive_break.html
Initialize GridStack with responsive breakpoints defined in `columnOpts.breakpoints`. The `breakpointForWindow` option ensures breakpoints are tested against the window size. The grid's column count is updated on change events.
```javascript
let text = document.querySelector('#column-text');
function addWidget() {
grid.addWidget({x:0, y:0, w:4, id:count++, content: '4x1'});
};
let count = 0;
let items = [
// our initial 12 column layout loaded first so we can compare
{x: 0, y: 0},
{x: 1, y: 0, w: 2, h: 2},
{x: 4, y: 0, w: 2},
{x: 1, y: 3, w: 4},
{x: 5, y: 3, w: 2},
{x: 0, y: 4, w: 12}
];
items.forEach(n => {
n.id = count;
n.content = String(count++)
});
let grid = GridStack.init({
cellHeight: 80,
animate: false,
// show immediate (animate: true is nice for user dragging though)
columnOpts: {
breakpointForWindow: true,
// test window vs grid size
breakpoints: [
{w:700, c:1},
{w:850, c:3},
{w:950, c:6},
{w:1100, c:8}
]
},
children: items,
float: true
})
.on('change', (ev, gsItems) => text.innerHTML = grid.getColumn());
text.innerHTML = grid.getColumn();
```
--------------------------------
### DDBaseImplement: Get Disabled State
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Retrieves the current disabled state of the drag and drop implementation. Use enable() or disable() to change the state.
```typescript
get disabled(): boolean;
```
--------------------------------
### Get HTML Element from Selector
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Converts a selector string or an HTMLElement into a single HTML element. Searches within an optional root element.
```typescript
static getElement(els, root): HTMLElement;
```
```typescript
const element = Utils.getElement('#myWidget');
const first = Utils.getElement('.grid-item');
```
--------------------------------
### Get Current Floating Mode
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Checks if the floating mode is currently enabled for the grid. Returns true if floating is active, false otherwise.
```typescript
const isFloating = grid.getFloat();
console.log('Floating enabled:', isFloating);
```
--------------------------------
### Initialize Multiple Grids with Options
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/two.html
Initializes multiple Gridstack instances using GridStack.initAll with shared options. One grid is then configured to not float.
```javascript
let items = [
{x: 0, y: 0, w: 2, h: 2},
{x: 1, y: 1, h: 2}, // intentional overlap to test collision on load
{x: 1, y: 1}, // intentional overlap to test collision on load
{x: 3, y: 1},
{x: 2, y: 3, w: 3, maxW: 3, content: 'has maxW=3'},
{x: 2, y: 5, h:20}
];
items.forEach((item, i) => item.content = item.content || String(i)); // sidebar content (just 2, rest is other behavior) to create when we get dropped, instead of inserting the clone version
let sidebarContent = [
{content: 'dropped', id: 'dup_id'}, // test to make sure unique ids are created when dropped mutliple times...
{content: 'max=3', w:2, h:1, maxW: 3},
];
let options = {
column: 6,
minRow: 1, // don't collapse when empty
cellHeight: 70,
float: true,
removable: '.trash', // true or drag-out delete class
/** accepts everything fcn, not just .grid-stack-item (true case) but can also be: true | false | '.someClass' value */
acceptWidgets: function(el) {
return true
},
children: items, // itemClass: 'with-lines', // test a custom additional class #2110
};
let grids = GridStack.initAll(options);
grids[1].float(false); // new v4 static method instead of setting up options on every grid (never been per grid really)
```
--------------------------------
### Get Drag & Drop Instance
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Access the global drag and drop implementation instance. This allows for interaction with the underlying drag & drop functionality.
```typescript
const dd = GridStack.getDD();
```
--------------------------------
### Initialize GridStack with Fixed Layout 'none'
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/responsive_none.html
Use this configuration to create a grid with a fixed column width and a layout that does not change dynamically. The items will maintain their relative positions and sizes within the fixed column structure.
```javascript
let children = [
{},
{},
{}
];
children.forEach((w, i) => {
w.x = i,
w.y = i,
// comment out to have autoPosition:true which behaves differently
w.w = i + 2,
w.content = `${i} w:${w.w}`
})
GridStack.init({
children,
column: 6,
cellHeight: 100,
columnOpts: {
columnWidth: 150,
columnMax: 12,
layout: 'none',
},
});
```
--------------------------------
### initAll()
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Initializes multiple grid elements based on a selector and returns an array of GridStack instances.
```APIDOC
## initAll(options?, selector?)
### Description
Initializes a list of elements (given a selector) and returns an array of grids.
### Method
`static initAll(options?: GridStackOptions, selector?: string): GridStack[]`
### Parameters
#### Parameters
- **options** (`GridStackOptions`) - Optional - Grid options. Defaults to `{}`.
- **selector** (`string`) - Optional - Elements selector to convert to grids. Defaults to `'.grid-stack'` class selector.
### Returns
`GridStack[]` - An array of initialized GridStack instances.
### Example
```ts
const grids = GridStack.initAll();
grids.forEach(...)
```
```
--------------------------------
### Setup Drag-In for GridStack
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/static.html
Configures GridStack to accept items dragged from a specific selector. This is useful for adding new widgets to the grid from an external source.
```javascript
GridStack.setupDragIn('.sidebar > .grid-stack-item');
```
--------------------------------
### init()
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Initializes a DOM element or selector string into a GridStack instance. Subsequent calls return the existing instance.
```APIDOC
## init(options?, elOrString?)
### Description
Initializes the HTML element, or selector string, into a grid and returns the grid. Calling it again will simply return the existing instance (ignore any passed options). There is also an `initAll()` version that supports multiple grids initialization at once. Or you can use `addGrid()` to create the entire grid from JSON.
### Method
`static init(options?: GridStackOptions, elOrString?: GridStackElement): GridStack`
### Parameters
#### Parameters
- **options** (`GridStackOptions`) - Optional - Grid options. Defaults to `{}`.
- **elOrString** (`GridStackElement`) - Optional - Element or CSS selector (first one used) to convert to a grid. Defaults to `'.grid-stack'` class selector.
### Returns
`GridStack` - The initialized GridStack instance.
### Example
```ts
const grid = GridStack.init();
// Note: the HTMLElement (of type GridHTMLElement) will store a `gridstack: GridStack` value that can be retrieved later
const grid = document.querySelector('.grid-stack').gridstack;
```
```
--------------------------------
### prepareNode(node, resizing?)
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Prepares and validates a node's coordinates and values for the current grid, ensuring it has valid position, size, and properties before being added. It can adjust the node to fit if it's out of bounds.
```APIDOC
## prepareNode(node, resizing?)
### Description
Prepare and validate a node's coordinates and values for the current grid. This ensures the node has valid position, size, and properties before being added to the grid.
### Method
N/A (Method signature provided)
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
```javascript
const node = { w: 3, h: 2, content: 'Hello' };
const prepared = engine.prepareNode(node);
console.log('Node prepared at:', prepared.x, prepared.y);
```
### Response
#### Success Response (200)
N/A (Returns GridStackNode)
#### Response Example
N/A
```
--------------------------------
### Initialize GridStack with 1 Column
Source: https://github.com/gridstack/gridstack.js/blob/master/spec/e2e/html/2406_inf_loop_autoPosition_column1.html
Initializes GridStack with float disabled and set to a single column. Use this configuration when starting with a single column layout.
```javascript
var options = { float: false, column: 1, cellHeight: 100 };
var grid = GridStack.init(options);
```
--------------------------------
### Get All Drag Handles
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Retrieves all elements that serve as drag handles for the grid items. This method omits nested `.grid-stack-item` children to avoid conflicts.
```typescript
protected getAllHandles(): HTMLElement[];
```
--------------------------------
### Initialize Grids with Different Accept Widget Classes
Source: https://github.com/gridstack/gridstack.js/blob/master/spec/e2e/html/1143_nested_acceptWidget_types.html
Initializes the outer grid to accept widgets with the class 'otherWidgetType' and a nested grid to accept widgets with the class 'newWidget'. The nested grid is also configured with `itemClass: 'sub'` for its items.
```javascript
let grid = GridStack.init({ acceptWidgets: '.otherWidgetType' }, '.grid-stack.outer');
let gridNest = GridStack.init({ acceptWidgets: '.newWidget', itemClass: 'sub', }, '.grid-stack.nested');
```
--------------------------------
### Get Drag Transform Values
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Retrieves the scale and offset values from an HTML element that has been transformed, typically used for drag operations within the grid.
```typescript
static getValuesFromTransformedElement(parent): DragTransform;
```
--------------------------------
### initEvent
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Initializes an event with provided information, allowing for generic event handling across different event types. It uses type parameters for flexibility.
```APIDOC
## initEvent(e, info)
### Description
Initializes an event with provided information.
### Method
`static`
### Type Parameters
- `T`
### Parameters
#### Path Parameters
- `e` (MouseEvent | DragEvent) - Required - The event object.
- `info` ({ target?: EventTarget; type: string }) - Required - An object containing event target and type.
- `target?` (EventTarget) - Optional - The target of the event.
- `type` (string) - Required - The type of the event.
### Returns
`T` - The initialized event data.
```
--------------------------------
### Get Row Count
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Returns the current number of rows in the grid, which is at least the minimum row count if set. Determined by the highest positioned widget.
```typescript
getRow(): number;
```
```typescript
const rowCount = grid.getRow();
console.log('Grid has', rowCount, 'rows');
```
--------------------------------
### Handle 'added' Event (v1+)
Source: https://github.com/gridstack/gridstack.js/blob/master/README.md
Event listeners are now attached directly to the grid instance using `grid.on()`. This example shows how to listen for the 'added' event.
```js
grid.on('added', function(e, items) {/* items contains info */});
```
--------------------------------
### DDElement static init()
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
A static method to initialize a DDElement. This is a convenient way to create and set up a DDElement for a given host element.
```APIDOC
## static init() DDElement
### Description
Initializes a DDElement for a given host element.
### Method
```ts
static init(el: DDElementHost): DDElement;
```
### Parameters
#### Parameters
- **el** (DDElementHost) - The host element to initialize with DD functionality.
```
--------------------------------
### DDElement setupDraggable Method
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Sets up the draggable functionality for a DDElement with specified options. Returns the DDElement instance.
```typescript
setupDraggable(opts): DDElement;
```
--------------------------------
### GridstackComponent Options Configuration
Source: https://github.com/gridstack/gridstack.js/blob/master/angular/doc/api/gridstack.component.md
Example of configuring GridStack options for the GridstackComponent. This object defines grid behavior like columns, cell height, and animation.
```typescript
gridOptions: GridStackOptions = {
column: 12,
cellHeight: 'auto',
animate: true
};
```
--------------------------------
### on(event, callback)
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Registers an event callback for a specified event. This allows you to listen for events such as 'resize', 'resizestart', or 'resizestop' and execute a function when they occur.
```APIDOC
## on(event, callback)
### Description
Register an event callback for the specified event.
### Method
```ts
on(event, callback): void;
```
### Parameters
#### Path Parameters
- **event** (string) - Required - Event name to listen for (`"resize"` | `"resizestart"` | `"resizestop"`)
- **callback** (function) - Required - Function to call when event occurs (`(event) => void`)
### Returns
`void`
```
--------------------------------
### Setup Drag-In Functionality
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Configures GridStack to allow dragging items from an external source into the grid. Specify selectors for draggable elements and options for the drag-in behavior.
```typescript
static setupDragIn(
dragIn?,
dragInOptions?,
widgets?,
root?): void;
```
--------------------------------
### Vitest Test Scripts Overview
Source: https://github.com/gridstack/gridstack.js/blob/master/TESTING.md
Table summarizing the available npm scripts for running tests and generating coverage reports.
```bash
yarn test
yarn test:watch
yarn test:ui
yarn test:coverage
yarn test:coverage:ui
yarn test:coverage:detailed
yarn test:coverage:html
yarn test:coverage:lcov
yarn test:ci
```
--------------------------------
### GridstackComponent ngOnInit Method
Source: https://github.com/gridstack/gridstack.js/blob/master/angular/doc/api/gridstack.component.md
This method is part of the Angular lifecycle and is called once after the initial data-bound property checks. It's used for initial setup before the view is checked.
```typescript
ngOnInit(): void;
```
--------------------------------
### cloneDeep()
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Recursively clones an object, creating a full copy of nested objects and arrays. It handles circular dependencies by not copying properties starting with double underscores.
```APIDOC
## cloneDeep()
### Description
Recursively clones an object, creating a full copy of nested objects and arrays. It handles circular dependencies by not copying properties starting with double underscores.
### Method
`static cloneDeep(obj): T`
### Parameters
#### Type Parameters
- `T`: The type of the object to be cloned.
#### Parameters
- **obj** (`T`): The object to clone.
### Returns
`T`: A deep copy of the input object.
```
--------------------------------
### Get Floating Mode - GridStackEngine
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Retrieves the current floating mode setting of the GridStack engine. Use this to check if widgets can move to fill empty spaces.
```typescript
const isFloating = engine.float;
console.log('Floating enabled:', isFloating);
```
--------------------------------
### Initialize GridStack and Load Items
Source: https://github.com/gridstack/gridstack.js/blob/master/demo/web-comp.html
Initializes a GridStack instance and loads predefined items into it. Ensure GridStack library is loaded before this code.
```javascript
let items = [
{x:0, y:0, w:2, content: 'item 0'},
{x:0, y:1, content: 'item 1'}
];
let grid = GridStack.init();
grid.load(items);
```
--------------------------------
### DDBaseImplement Methods
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Provides common functionality for event handling, enable/disable state, and lifecycle management used by draggable, droppable, and resizable implementations.
```APIDOC
## DDBaseImplement
### Description
Abstract base class for all drag & drop implementations. Provides common functionality for event handling, enable/disable state, and lifecycle management.
### Methods
#### `on(event, callback)`
Register an event callback for the specified event.
- **event** (string) - Event name to listen for
- **callback** (EventCallback) - Function to call when event occurs
#### `off(event)`
Unregister an event callback for the specified event.
- **event** (string) - Event name to stop listening for
#### `enable()`
Enable this drag & drop implementation. Subclasses should override to perform additional setup.
#### `disable()`
Disable this drag & drop implementation. Subclasses should override to perform additional cleanup.
#### `destroy()`
Destroy this drag & drop implementation and clean up resources. Removes all event handlers and clears internal state.
#### `triggerEvent(eventName, event)`
Trigger a registered event callback if one exists and the implementation is enabled.
- **eventName** (string) - Name of the event to trigger
- **event** (Event) - DOM event object to pass to the callback
### Accessors
#### `disabled` (get)
Returns the current disabled state.
- **Returns**: `boolean`
### Constructor
#### `new DDBaseImplement()`
Creates an instance of DDBaseImplement.
```
--------------------------------
### Override Resizable Handles
Source: https://github.com/gridstack/gridstack.js/blob/master/README.md
Customize the available handles for resizing grid items. This example enables resizing from the east, south-east, south, south-west, and west sides.
```js
GridStack.init({
resizable: {
handles: 'e,se,s,sw,w'
}
});
```
--------------------------------
### Standalone vs. Legacy GridstackModule Usage
Source: https://github.com/gridstack/gridstack.js/blob/master/angular/doc/api/gridstack.module.md
Demonstrates the preferred approach using standalone components and the legacy approach with the deprecated GridstackModule.
```typescript
// Preferred approach - standalone components
@Component({
selector: 'my-app',
imports: [GridstackComponent, GridstackItemComponent],
template: ''
})
export class AppComponent {}
```
```typescript
// Legacy approach (deprecated)
@NgModule({
imports: [GridstackModule]
})
export class AppModule {}
```
--------------------------------
### on
Source: https://github.com/gridstack/gridstack.js/blob/master/doc/API.md
Registers an event handler for grid events. Supports listening to single or multiple events simultaneously. Events include 'added', 'change', 'disable', 'dragstart', 'drag', 'dragstop', 'dropped', 'enable', 'removed', 'resizestart', 'resize', and 'resizestop'.
```APIDOC
## on(name, callback)
### Description
Register event handler for grid events. You can call this on a single event name, or space separated list.
### Method
on
### Parameters
#### Path Parameters
- **name** (string) - Required - event name(s) to listen for (space separated for multiple)
- **callback** (GridStackElementHandler) - Required - function to call when event occurs
### Response
#### Success Response (200)
- **GridStack** - the grid instance for chaining
### Request Example
```ts
// Listen to multiple events at once
grid.on('added removed change', (event, items) => {
items.forEach(item => console.log('Item changed:', item));
});
// Listen to individual events
grid.on('added', (event, items) => {
items.forEach(item => console.log('Added item:', item));
});
```
```