Merge remote-tracking branch 'troolee/master' into tests

# Conflicts:
#	package.json
This commit is contained in:
Kevin Dietrich 2016-02-22 19:09:50 +01:00
commit 934863e285
21 changed files with 1298 additions and 582 deletions

11
.jscsrc
View file

@ -1,6 +1,6 @@
{
"preset": "google",
"validateIndentation": "\t",
"preset": "node-style-guide",
"validateIndentation": 4,
"maximumLineLength": 120,
"jsDoc": {
"checkAnnotations": {
@ -10,5 +10,10 @@
}
}
},
"requireCamelCaseOrUpperCaseIdentifiers": true
"requireCamelCaseOrUpperCaseIdentifiers": true,
"validateLineBreaks": false,
"requireTrailingComma": false,
"disallowTrailingWhitespace": true,
"requireCapitalizedComments": false,
"excludeFiles": ["dist/*.js", "demo/*"]
}

View file

@ -1,9 +1,12 @@
module.exports = function (grunt) {
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-doctoc');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-jscs');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
sass: {
@ -53,10 +56,46 @@ module.exports = function (grunt) {
removeAd: false
},
readme: {
target: "./README.md"
}
}
options: {
target: './README.md'
}
},
doc: {
options: {
target: './doc/README.md'
}
},
},
jshint: {
all: ['src/*.js']
},
jscs: {
all: ['*.js', 'src/*.js', ],
},
watch: {
scripts: {
files: ['src/*.js'],
tasks: ['uglify', 'copy'],
options: {
},
},
styles: {
files: ['src/*.scss'],
tasks: ['sass', 'cssmin'],
options: {
},
},
docs: {
files: ['README.md', 'doc/README.md'],
tasks: ['doctoc'],
options: {
},
},
},
});
grunt.registerTask('default', ['sass', 'cssmin', 'copy', 'uglify', 'doctoc']);
grunt.registerTask('default', ['sass', 'cssmin', 'jshint', 'jscs', 'copy', 'uglify', 'doctoc']);
};

412
README.md
View file

@ -20,46 +20,7 @@ Join gridstack.js on Slack: https://gridstackjs.troolee.com
- [Install](#install)
- [Basic usage](#basic-usage)
- [Migrating to v0.2.5](#migrating-to-v025)
- [Options](#options)
- [Grid attributes](#grid-attributes)
- [Item attributes](#item-attributes)
- [Events](#events)
- [onchange(items)](#onchangeitems)
- [ondragstart(event, ui)](#ondragstartevent-ui)
- [ondragstop(event, ui)](#ondragstopevent-ui)
- [onresizestart(event, ui)](#onresizestartevent-ui)
- [onresizestop(event, ui)](#onresizestopevent-ui)
- [disable(event)](#disableevent)
- [enable(event)](#enableevent)
- [API](#api)
- [addWidget(el, x, y, width, height, autoPosition)](#addwidgetel-x-y-width-height-autoposition)
- [batchUpdate()](#batchupdate)
- [cellHeight()](#cellheight)
- [cellHeight(val)](#cellheightval)
- [cellWidth()](#cellwidth)
- [commit()](#commit)
- [destroy()](#destroy)
- [disable()](#disable)
- [enable()](#enable)
- [getCellFromPixel(position)](#getcellfrompixelposition)
- [isAreaEmpty(x, y, width, height)](#isareaemptyx-y-width-height)
- [locked(el, val)](#lockedel-val)
- [makeWidget(el)](#makewidgetel)
- [maxHeight(el, val)](#maxheightel-val)
- [minHeight(el, val)](#minheightel-val)
- [maxWidth(el, val)](#maxwidthel-val)
- [minWidth(el, val)](#minwidthel-val)
- [movable(el, val)](#movableel-val)
- [move(el, x, y)](#moveel-x-y)
- [removeWidget(el, detachNode)](#removewidgetel-detachnode)
- [removeAll()](#removeall)
- [resize(el, width, height)](#resizeel-width-height)
- [resizable(el, val)](#resizableel-val)
- [setStatic(static_value)](#setstaticstatic_value)
- [update(el, x, y, width, height)](#updateel-x-y-width-height)
- [willItFit(x, y, width, height, autoPosition)](#willitfitx-y-width-height-autoposition)
- [Utils](#utils)
- [GridStackUI.Utils.sort(nodes[, dir[, width]])](#gridstackuiutilssortnodes-dir-width)
- [API Documentation](#api-documentation)
- [Touch devices support](#touch-devices-support)
- [Use with knockout.js](#use-with-knockoutjs)
- [Use with angular.js](#use-with-angularjs)
@ -72,6 +33,7 @@ Join gridstack.js on Slack: https://gridstackjs.troolee.com
- [Override resizable/draggable options](#override-resizabledraggable-options)
- [IE8 support](#ie8-support)
- [Nested grids](#nested-grids)
- [Resizing active grid](#resizing-active-grid)
- [Changes](#changes)
- [v0.2.5-dev (Development version)](#v025-dev-development-version)
- [v0.2.4 (2016-02-15)](#v024-2016-02-15)
@ -145,8 +107,8 @@ You can download files from `dist` directory as well.
<script type="text/javascript">
$(function () {
var options = {
cell_height: 80,
vertical_margin: 10
cellHeight: 80,
verticalMargin: 10
};
$('.grid-stack').gridstack(options);
});
@ -159,341 +121,9 @@ As of v0.2.5 all methods and parameters are in camel case to respect [JavaScript
All old methods and parameters are marked as deprecated and still available but a warning will be displayed in js console. They will be available until v1.0
when they will be completely removed.
## Options
## API Documentation
- `alwaysShowResizeHandle` - if `true` the resizing handles are shown even if the user is not hovering over the widget
(default: `false`)
- `animate` - turns animation on (default: `false`)
- `auto` - if `false` gridstack will not initialize existing items (default: `true`)
- `cellHeight` - one cell height (default: `60`). Can be:
- an integer (px)
- a string (ex: '10em', '100px', '10rem')
- 0 or null, in which case the library will not generate styles for rows. Everything will have to be defined in CSS files.
- `draggable` - allows to override jQuery UI draggable options. (default: `{handle: '.grid-stack-item-content', scroll: true, appendTo: 'body'}`)
- `handle` - draggable handle selector (default: `'.grid-stack-item-content'`)
- `handleClass` - draggable handle class (e.g. `'grid-stack-item-content'`). If set `handle` is ignored (default: `null`)
- `height` - maximum rows amount. Default is `0` which means no maximum rows
- `float` - enable floating widgets (default: `false`) See [example](http://troolee.github.io/gridstack.js/demo/float.html)
- `itemClass` - widget class (default: `'grid-stack-item'`)
- `minWidth` - minimal width. If window width is less, grid will be shown in one-column mode. You need also update your css file (`@media (max-width: 768px) {...}`) with corresponding value (default: `768`)
- `placeholderClass` - class for placeholder (default: `'grid-stack-placeholder'`)
- `placeholderText` - placeholder default content (default: `''`)
- `resizable` - allows to override jQuery UI resizable options. (default: `{autoHide: true, handles: 'se'}`)
- `staticGrid` - makes grid static (default `false`). If true widgets are not movable/resizable. You don't even need jQueryUI draggable/resizable. A CSS class `grid-stack-static` is also added to the container.
- `verticalMargin` - vertical gap size (default: `20`). Can be:
- an integer (px)
- a string (ex: '2em', '20px', '2rem')
- `width` - amount of columns (default: `12`)
## Grid attributes
- `data-gs-animate` - turns animation on
- `data-gs-width` - amount of columns
- `data-gs-height` - maximum rows amount. Default is `0` which means no maximum rows.
- `data-gs-current-height` - current rows amount. Set by the library only. Can be used by the CSS rules.
## Item attributes
- `data-gs-x`, `data-gs-y` - element position
- `data-gs-width`, `data-gs-height` - element size
- `data-gs-max-width`, `data-gs-min-width`, `data-gs-max-height`, `data-gs-min-height` - element constraints
- `data-gs-no-resize` - disable element resizing
- `data-gs-no-move` - disable element moving
- `data-gs-auto-position` - tells to ignore `data-gs-x` and `data-gs-y` attributes and to place element to the first
available position
- `data-gs-locked` - the widget will be locked. It means another widget wouldn't be able to move it during dragging or resizing.
The widget can still be dragged or resized. You need to add `data-gs-no-resize` and `data-gs-no-move` attributes
to completely lock the widget.
## Events
### onchange(items)
Occurs when adding/removing widgets or existing widgets change their position/size
```javascript
var serializeWidgetMap = function (items) {
console.log(items);
};
$('.grid-stack').on('change', function (e, items) {
serializeWidgetMap(items);
});
```
### ondragstart(event, ui)
```javascript
$('.grid-stack').on('dragstart', function (event, ui) {
var grid = this;
var element = event.target;
});
```
### ondragstop(event, ui)
```javascript
$('.grid-stack').on('dragstop', function (event, ui) {
var grid = this;
var element = event.target;
});
```
### onresizestart(event, ui)
```javascript
$('.grid-stack').on('resizestart', function (event, ui) {
var grid = this;
var element = event.target;
});
```
### onresizestop(event, ui)
```javascript
$('.grid-stack').on('resizestop', function (event, ui) {
var grid = this;
var element = event.target;
});
```
### disable(event)
```javascript
$('.grid-stack').on('disable', function(event) {
var grid = event.target;
});
```
### enable(event)
```javascript
$('.grid-stack').on('enable', function(event) {
var grid = event.target;
});
```
## API
### addWidget(el, x, y, width, height, autoPosition)
Creates new widget and returns it.
Parameters:
- `el` - widget to add
- `x`, `y`, `width`, `height` - widget position/dimensions (Optional)
- `autoPosition` - if `true` then `x`, `y` parameters will be ignored and widget will be places on the first available
position
Widget will be always placed even if result height is more than actual grid height. You need to use `will_it_fit` method
before calling `add_widget` for additional check.
```javascript
$('.grid-stack').gridstack();
var grid = $('.grid-stack').data('gridstack');
grid.addWidget(el, 0, 0, 3, 2, true);
```
### batchUpdate()
Initailizes batch updates. You will see no changes until `commit` method is called.
### cellHeight()
Gets current cell height.
### cellHeight(val)
Update current cell height. This method rebuilds an internal CSS stylesheet. Note: You can expect performance issues if
call this method too often.
```javascript
grid.cellHeight(grid.cellWidth() * 1.2);
```
### cellWidth()
Gets current cell width.
### commit()
Finishes batch updates. Updates DOM nodes. You must call it after `batchUpdate`.
### destroy()
Destroys a grid instance.
### disable()
Disables widgets moving/resizing. This is a shortcut for:
```javascript
grid.movable('.grid-stack-item', false);
grid.resizable('.grid-stack-item', false);
```
### enable()
Enables widgets moving/resizing. This is a shortcut for:
```javascript
grid.movable('.grid-stack-item', true);
grid.resizable('.grid-stack-item', true);
```
### getCellFromPixel(position)
Get the position of the cell under a pixel on screen.
Parameters :
- `position` - the position of the pixel to resolve in absolute coordinates, as an object with `top` and `left`properties
Returns an object with properties `x` and `y` i.e. the column and row in the grid.
### isAreaEmpty(x, y, width, height)
Checks if specified area is empty.
### locked(el, val)
Locks/unlocks widget.
- `el` - widget to modify.
- `val` - if `true` widget will be locked.
### makeWidget(el)
If you add elements to your gridstack container by hand, you have to tell gridstack afterwards to make them widgets. If you want gridstack to add the elements for you, use `add_widget` instead.
Makes the given element a widget and returns it.
Parameters:
- `el` - element to convert to a widget
```javascript
$('.grid-stack').gridstack();
$('.grid-stack').append('<div id="gsi-1" data-gs-x="0" data-gs-y="0" data-gs-width="3" data-gs-height="2" data-gs-auto-position="1"></div>')
var grid = $('.grid-stack').data('gridstack');
grid.makeWidget('gsi-1');
```
### maxHeight(el, val)
Set the `maxHeight` for a widget.
- `el` - widget to modify.
- `val` - A numeric value of the number of rows
### minHeight(el, val)
Set the `minHeight` for a widget.
- `el` - widget to modify.
- `val` - A numeric value of the number of rows
### maxWidth(el, val)
Set the `maxWidth` for a widget.
- `el` - widget to modify.
- `val` - A numeric value of the number of columns
### minWidth(el, val)
Set the `minWidth` for a widget.
- `el` - widget to modify.
- `val` - A numeric value of the number of columns
### movable(el, val)
Enables/Disables moving.
- `el` - widget to modify
- `val` - if `true` widget will be draggable.
### move(el, x, y)
Changes widget position
Parameters:
- `el` - widget to move
- `x`, `y` - new position. If value is `null` or `undefined` it will be ignored.
### removeWidget(el, detachNode)
Removes widget from the grid.
Parameters:
- `el` - widget to remove.
- `detachNode` - if `false` DOM node won't be removed from the tree (Optional. Default `true`).
### removeAll()
Removes all widgets from the grid.
### resize(el, width, height)
Changes widget size
Parameters:
- `el` - widget to resize
- `width`, `height` - new dimensions. If value is `null` or `undefined` it will be ignored.
### resizable(el, val)
Enables/Disables resizing.
- `el` - widget to modify
- `val` - if `true` widget will be resizable.
### setStatic(static_value)
Toggle the grid static state. Also toggle the `grid-stack-static` class.
- `static_value` - if `true` the grid become static.
### update(el, x, y, width, height)
Parameters:
- `el` - widget to move
- `x`, `y` - new position. If value is `null` or `undefined` it will be ignored.
- `width`, `height` - new dimensions. If value is `null` or `undefined` it will be ignored.
Updates widget position/size.
### willItFit(x, y, width, height, autoPosition)
Returns `true` if the `height` of the grid will be less the vertical constraint. Always returns `true` if grid doesn't
have `height` constraint.
```javascript
if (grid.willItFit(newNode.x, newNode.y, newNode.width, newNode.height, true)) {
grid.addWidget(newNode.el, newNode.x, newNode.y, newNode.width, newNode.height, true);
}
else {
alert('Not enough free space to place the widget');
}
```
## Utils
### GridStackUI.Utils.sort(nodes[, dir[, width]])
Sorts array of nodes
- `nodes` - array to sort
- `dir` - `1` for asc, `-1` for desc (optional)
- `width` - width of the grid. If `undefined` the width will be calculated automatically (optional).
Please check out `doc/README.md` for more information about gridstack.js API.
## Touch devices support
@ -514,7 +144,7 @@ Also `alwaysShowResizeHandle` option may be useful:
```javascript
$(function () {
var options = {
always_show_resize_handle: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
alwaysShowResizeHandle: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
};
$('.grid-stack').gridstack(options);
});
@ -552,7 +182,7 @@ ko.components.register('dashboard-grid', {
template:
[
'<div class="grid-stack" data-bind="foreach: {data: widgets, afterRender: afterAddWidget}">',
' <div class="grid-stack-item" data-bind="attr: {\'data-gs-x\': $data.x, \'data-gs-y\': $data.y, \'data-gs-width\': $data.width, \'data-gs-height\': $data.height, \'data-gs-auto-position\': $data.auto_position}">',
' <div class="grid-stack-item" data-bind="attr: {\'data-gs-x\': $data.x, \'data-gs-y\': $data.y, \'data-gs-width\': $data.width, \'data-gs-height\': $data.height, \'data-gs-auto-position\': $data.autoPosition}">',
' <div class="grid-stack-item-content">...</div>',
' </div>',
'</div> '
@ -589,7 +219,7 @@ See examples: [example 1](http://troolee.github.io/gridstack.js/demo/knockout.ht
template:
[
'<div class="grid-stack" data-bind="foreach: {data: widgets, afterRender: afterAddWidget}">',
' <div class="grid-stack-item" data-bind="attr: {\'data-gs-x\': $data.x, \'data-gs-y\': $data.y, \'data-gs-width\': $data.width, \'data-gs-height\': $data.height, \'data-gs-auto-position\': $data.auto_position}">',
' <div class="grid-stack-item" data-bind="attr: {\'data-gs-x\': $data.x, \'data-gs-y\': $data.y, \'data-gs-width\': $data.width, \'data-gs-height\': $data.height, \'data-gs-auto-position\': $data.autoPosition}">',
' ....',
' </div>', // <-- NO SPACE **AFTER** </div>
'</div> ' // <-- NO SPACE **BEFORE** </div>
@ -797,14 +427,34 @@ during initialization.
See example: [Nested grid demo](http://troolee.github.io/gridstack.js/demo/nested.html)
## Resizing active grid
Resizing on-the-fly is possible, though experimental. This may be used to make gridstack responsive. gridstack will change the total number of columns and will attempt to update the width and x values of each widget to be more logical.
See example: [Responsive grid demo](http://troolee.github.io/gridstack.js/demo/responsive.html)
Changes
=======
#### v0.2.5-dev (Development version)
- update names to respect js naming convention
- `cellHeight` and `verticalMargin` can now be string (e.g. '3em', '20px') (Thanks to @jlowcs)
- update names to respect js naming convention.
- `cellHeight` and `verticalMargin` can now be string (e.g. '3em', '20px') (Thanks to @jlowcs).
- add `maxWidth`/`maxHeight` methods.
- add `enableMove`/`enableResize` methods.
- fix window resize issue #331.
- add options `disableDrag` and `disableResize`.
- fix `batchUpdate`/`commit` (Thank to @radiolips)
- remove dependency of FontAwesome
- RTL support
- `'auto'` value for `cellHeight` option
- fix `setStatic` method
- add `setAnimation` method to API
- add `setGridWidth` method ([#227](https://github.com/troolee/gridstack.js/issues/227))
- add `removable`/`removeTimeout`
- add `detachGrid` parameter to `destroy` method ([#216](https://github.com/troolee/gridstack.js/issues/216))
- add `useOffset` parameter to `getCellFromPixel` method ([#237](https://github.com/troolee/gridstack.js/issues/237))
- add `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `id` parameters to `addWidget` ([#188](https://github.com/troolee/gridstack.js/issues/188))
#### v0.2.4 (2016-02-15)

View file

@ -11,7 +11,6 @@
<title>Float grid demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="../dist/gridstack.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

18
demo/index.html Normal file
View file

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<ul>
<li><a href="float.html">Float grid demo</a></li>
<li><a href="knockout.js">Knockout.js demo</a></li>
<li><a href="knockout2.js">Knockout.js demo (2)</a></li>
<li><a href="nested.html">Nested grids demo</a></li>
<li><a href="rtl.html">RTL demo</a></li>
<li><a href="serialization.html">Serialization demo</a></li>
<li><a href="two.html">Two grids demo</a></li>
</ul>
</body>
</html>

View file

@ -11,7 +11,6 @@
<title>Knockout.js demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="../dist/gridstack.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

View file

@ -11,7 +11,6 @@
<title>Knockout.js demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="../dist/gridstack.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

View file

@ -11,7 +11,6 @@
<title>Nested grids demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="../dist/gridstack.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

122
demo/responsive.html Normal file
View file

@ -0,0 +1,122 @@
<!DOCTYPE html>
<html lang="en">
<head>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Responsive grid demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="../dist/gridstack.css"/>
<link rel="stylesheet" href="../dist/gridstack-extra.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.0/jquery-ui.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js"></script>
<script src="../dist/gridstack.js"></script>
<style type="text/css">
.grid-stack {
background: lightgoldenrodyellow;
}
.grid-stack-item-content {
color: #2c3e50;
text-align: center;
background-color: #18bc9c;
}
</style>
</head>
<body>
<div class="device-xs visible-xs"></div>
<div class="device-sm visible-sm"></div>
<div class="device-md visible-md"></div>
<div class="device-lg visible-lg"></div>
<div class="device-xl visible-xl"></div>
<div class="container-fluid">
<h1>Responsive grid demo</h1>
<div>
<span>Number of Columns:</span> <span id="grid-size"></span>
</div>
<br/>
<div class="grid-stack">
</div>
</div>
<script type="text/javascript">
$(function () {
// thanks to http://stackoverflow.com/a/22885503
var waitForFinalEvent=function(){var b={};return function(c,d,a){a||(a="I am a banana!");b[a]&&clearTimeout(b[a]);b[a]=setTimeout(c,d)}}();
var fullDateString = new Date();
function isBreakpoint(alias) {
return $('.device-' + alias).is(':visible');
}
var options = {
float: false
};
$('.grid-stack').gridstack(options);
function resizeGrid() {
var grid = $('.grid-stack').data('gridstack');
if (isBreakpoint('xs')) {
$('#grid-size').text('One column mode');
} else if (isBreakpoint('sm')) {
grid.setGridWidth(3);
$('#grid-size').text(3);
} else if (isBreakpoint('md')) {
grid.setGridWidth(6);
$('#grid-size').text(6);
} else if (isBreakpoint('lg')) {
grid.setGridWidth(12);
$('#grid-size').text(12);
}
};
$(window).resize(function () {
waitForFinalEvent(function() {
resizeGrid();
}, 300, fullDateString.getTime());
});
new function () {
this.serializedData = [
{x: 0, y: 0, width: 4, height: 2},
{x: 3, y: 1, width: 4, height: 2},
{x: 4, y: 1, width: 4, height: 1},
{x: 2, y: 3, width: 8, height: 1},
{x: 0, y: 4, width: 4, height: 1},
{x: 0, y: 3, width: 4, height: 1},
{x: 2, y: 4, width: 4, height: 1},
{x: 2, y: 5, width: 4, height: 1},
{x: 0, y: 6, width: 12, height: 1}
];
this.grid = $('.grid-stack').data('gridstack');
this.loadGrid = function () {
this.grid.removeAll();
var items = GridStackUI.Utils.sort(this.serializedData);
_.each(items, function (node, i) {
this.grid.addWidget($('<div><div class="grid-stack-item-content">' + i + '</div></div>'),
node.x, node.y, node.width, node.height);
}, this);
return false;
}.bind(this);
this.loadGrid();
resizeGrid();
};
});
</script>
</script>
</body>
</html>

120
demo/rtl.html Normal file
View file

@ -0,0 +1,120 @@
<!DOCTYPE html>
<html lang="en" dir="rtl">
<head>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RTL demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="../dist/gridstack.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.0/jquery-ui.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="../dist/gridstack.js"></script>
<style type="text/css">
.grid-stack {
background: lightgoldenrodyellow;
}
.grid-stack-item-content {
color: #2c3e50;
background-color: #18bc9c;
}
</style>
</head>
<body>
<div class="container-fluid">
<h1>RTL Demo</h1>
<div>
<button data-bind="click: addNewWidget">Add new widget</button>
</div>
<br>
<div data-bind="component: {name: 'dashboard-grid', params: $data}"></div>
</div>
<script type="text/javascript">
ko.components.register('dashboard-grid', {
viewModel: {
createViewModel: function (controller, componentInfo) {
var ViewModel = function (controller, componentInfo) {
var grid = null;
this.widgets = controller.widgets;
this.afterAddWidget = function (items) {
if (grid == null) {
grid = $(componentInfo.element).find('.grid-stack').gridstack({
auto: false
}).data('gridstack');
}
var item = _.find(items, function (i) { return i.nodeType == 1 });
grid.addWidget(item);
ko.utils.domNodeDisposal.addDisposeCallback(item, function () {
grid.removeWidget(item);
});
};
};
return new ViewModel(controller, componentInfo);
}
},
template:
[
'<div class="grid-stack" data-bind="foreach: {data: widgets, afterRender: afterAddWidget}">',
' <div class="grid-stack-item" data-bind="attr: {\'data-gs-x\': $data.x, \'data-gs-y\': $data.y, \'data-gs-width\': $data.width, \'data-gs-height\': $data.height, \'data-gs-auto-position\': $data.auto_position}">',
' <div class="grid-stack-item-content"><center><button data-bind="click: $root.deleteWidget">Delete me</button><br><h5 data-bind="text: index" /></center><br><p>lorem ipsum</p></div>',
' </div>',
'</div> '
].join('')
});
$(function () {
var Controller = function (widgets) {
var self = this;
this.widgets = ko.observableArray(widgets);
this.addNewWidget = function () {
this.widgets.push({
x: 0,
y: 0,
width: Math.floor(1 + 3 * Math.random()),
height: Math.floor(1 + 3 * Math.random()),
auto_position: true
});
return false;
};
this.deleteWidget = function (item) {
self.widgets.remove(item);
return false;
};
};
var widgets = [
{x: 0, y: 0, width: 2, height: 2, index: 1},
{x: 2, y: 0, width: 4, height: 2, index: 2},
{x: 6, y: 0, width: 2, height: 4, index: 3},
{x: 1, y: 2, width: 4, height: 2, index: 4}
];
var controller = new Controller(widgets);
ko.applyBindings(controller);
});
</script>
</body>
</html>

View file

@ -11,7 +11,6 @@
<title>Serialization demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="../dist/gridstack.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

View file

@ -11,7 +11,6 @@
<title>Two grids demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="../dist/gridstack.css"/>
<link rel="stylesheet" href="../dist/gridstack-extra.css"/>
@ -35,6 +34,14 @@
text-align: center;
background-color: #18bc9c;
}
#grid2 .grid-stack-item-content {
background-color: #9caabc;
}
.grid-stack-item-removing {
opacity: 0.5;
}
</style>
</head>
<body>
@ -58,7 +65,8 @@
$(function () {
var options = {
width: 6,
float: true
float: true,
removable: true
};
$('#grid1').gridstack(options);
$('#grid2').gridstack(options);

52
dist/gridstack.css vendored
View file

@ -6,6 +6,14 @@
position: relative;
}
.grid-stack.grid-stack-rtl {
direction: ltr;
}
.grid-stack.grid-stack-rtl > .grid-stack-item {
direction: rtl;
}
.grid-stack .grid-stack-placeholder > .placeholder-content {
border: 1px dashed lightgray;
margin: 0;
@ -64,29 +72,22 @@
.grid-stack > .grid-stack-item > .ui-resizable-se,
.grid-stack > .grid-stack-item > .ui-resizable-sw {
text-align: right;
color: gray;
padding: 2px 3px 0 0;
margin: 0;
font: normal normal normal 10px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.grid-stack > .grid-stack-item > .ui-resizable-se::before,
.grid-stack > .grid-stack-item > .ui-resizable-sw::before {
content: "\f065";
background-image: url(data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjE2cHgiIGhlaWdodD0iMTZweCIgdmlld0JveD0iMCAwIDUxMS42MjYgNTExLjYyNyIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNTExLjYyNiA1MTEuNjI3OyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxnPgoJPHBhdGggZD0iTTMyOC45MDYsNDAxLjk5NGgtMzYuNTUzVjEwOS42MzZoMzYuNTUzYzQuOTQ4LDAsOS4yMzYtMS44MDksMTIuODQ3LTUuNDI2YzMuNjEzLTMuNjE1LDUuNDIxLTcuODk4LDUuNDIxLTEyLjg0NSAgIGMwLTQuOTQ5LTEuODAxLTkuMjMxLTUuNDI4LTEyLjg1MWwtNzMuMDg3LTczLjA5QzI2NS4wNDQsMS44MDksMjYwLjc2LDAsMjU1LjgxMywwYy00Ljk0OCwwLTkuMjI5LDEuODA5LTEyLjg0Nyw1LjQyNCAgIGwtNzMuMDg4LDczLjA5Yy0zLjYxOCwzLjYxOS01LjQyNCw3LjkwMi01LjQyNCwxMi44NTFjMCw0Ljk0NiwxLjgwNyw5LjIyOSw1LjQyNCwxMi44NDVjMy42MTksMy42MTcsNy45MDEsNS40MjYsMTIuODUsNS40MjYgICBoMzYuNTQ1djI5Mi4zNThoLTM2LjU0MmMtNC45NTIsMC05LjIzNSwxLjgwOC0xMi44NSw1LjQyMWMtMy42MTcsMy42MjEtNS40MjQsNy45MDUtNS40MjQsMTIuODU0ICAgYzAsNC45NDUsMS44MDcsOS4yMjcsNS40MjQsMTIuODQ3bDczLjA4OSw3My4wODhjMy42MTcsMy42MTcsNy44OTgsNS40MjQsMTIuODQ3LDUuNDI0YzQuOTUsMCw5LjIzNC0xLjgwNywxMi44NDktNS40MjQgICBsNzMuMDg3LTczLjA4OGMzLjYxMy0zLjYyLDUuNDIxLTcuOTAxLDUuNDIxLTEyLjg0N2MwLTQuOTQ4LTEuODA4LTkuMjMyLTUuNDIxLTEyLjg1NCAgIEMzMzguMTQyLDQwMy44MDIsMzMzLjg1Nyw0MDEuOTk0LDMyOC45MDYsNDAxLjk5NHoiIGZpbGw9IiM2NjY2NjYiLz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8L3N2Zz4K);
background-repeat: no-repeat;
background-position: center;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
}
.grid-stack > .grid-stack-item > .ui-resizable-se {
display: inline-block;
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
-o-transform: rotate(90deg);
transform: rotate(90deg);
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
}
.grid-stack > .grid-stack-item > .ui-resizable-nw {
@ -153,6 +154,10 @@
bottom: 15px;
}
.grid-stack > .grid-stack-item.ui-draggable-dragging > .ui-resizable-handle {
display: none !important;
}
.grid-stack > .grid-stack-item[data-gs-width='1'] {
width: 8.3333333333%;
}
@ -364,13 +369,6 @@
transition: left 0s, top 0s, height 0s, width 0s;
}
/** Uncomment this to show bottom-left resize handle **/
/*
.grid-stack > .grid-stack-item > .ui-resizable-sw {
display: inline-block;
@include vendor(transform, rotate(180deg));
}
*/
@media (max-width: 768px) {
.grid-stack-item {
position: relative !important;

290
dist/gridstack.js vendored
View file

@ -22,8 +22,8 @@
var obsolete = function(f, oldName, newName) {
var wrapper = function() {
console.warn('gridstack.js: Function `' + oldName + '` is deprecated as of v0.2.5 and has been replaced with `' +
newName + '`. It will be **completely** removed in v1.0.');
console.warn('gridstack.js: Function `' + oldName + '` is deprecated as of v0.2.5 and has been replaced ' +
'with `' + newName + '`. It will be **completely** removed in v1.0.');
return f.apply(this, arguments);
};
wrapper.prototype = f.prototype;
@ -50,7 +50,7 @@
createStylesheet: function(id) {
var style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.setAttribute('data-gs-id', id);
style.setAttribute('data-gs-style-id', id);
if (style.styleSheet) {
style.styleSheet.cssText = '';
} else {
@ -61,7 +61,7 @@
},
removeStylesheet: function(id) {
$('STYLE[data-gs-id=' + id + ']').remove();
$('STYLE[data-gs-style-id=' + id + ']').remove();
},
insertCSSRule: function(sheet, selector, rules, index) {
@ -98,6 +98,20 @@
_isAddNodeIntercepted: function(n) {
return Utils.isIntercepted({x: this.x, y: this.y, width: this.node.width, height: this.node.height}, n);
},
parseHeight: function(val) {
var height = val;
var heightUnit = 'px';
if (height && _.isString(height)) {
var match = height.match(/^([0-9]*\.[0-9]+|[0-9]+)(px|em|rem|vh|vw)?$/);
if (!match) {
throw new Error('Invalid height');
}
heightUnit = match[2];
height = parseFloat(match[1]);
}
return {height: height, unit: heightUnit};
}
};
@ -131,14 +145,19 @@
};
GridStackEngine.prototype.commit = function() {
this._updateCounter = 0;
if (this._updateCounter === 0) {
if (this._updateCounter !== 0) {
this._updateCounter = 0;
this.float = this._float;
this._packNodes();
this._notify();
}
};
// For Meteor support: https://github.com/troolee/gridstack.js/pull/272
GridStackEngine.prototype.getNodeDataByDOMEl = function(el) {
return _.find(this.nodes, function(n) { return el.get(0) === n.el.get(0); });
};
GridStackEngine.prototype._fixCollisions = function(node) {
var self = this;
this._sortNodes(-1);
@ -269,6 +288,9 @@
};
GridStackEngine.prototype.cleanNodes = function() {
if (this._updateCounter) {
return;
}
_.each(this.nodes, function(n) {n._dirty = false; });
};
@ -427,7 +449,7 @@
var GridStack = function(el, opts) {
var self = this;
var oneColumnMode;
var oneColumnMode, isAutoCellHeight;
opts = opts || {};
@ -509,11 +531,30 @@
'.grid-stack-item-content',
scroll: false,
appendTo: 'body'
})
}),
disableDrag: opts.disableDrag || false,
disableResize: opts.disableResize || false,
rtl: 'auto',
removable: false,
removeTimeout: 2000
});
if (this.opts.rtl === 'auto') {
this.opts.rtl = this.container.css('direction') === 'rtl';
}
if (this.opts.rtl) {
this.container.addClass('grid-stack-rtl');
}
this.opts.isNested = isNested;
this.cellHeight(this.opts.cellHeight, true);
isAutoCellHeight = this.opts.cellHeight === 'auto';
if (isAutoCellHeight) {
self.cellHeight(self.cellWidth(), true);
} else {
this.cellHeight(this.opts.cellHeight, true);
}
this.verticalMargin(this.opts.verticalMargin, true);
this.container.addClass(this.opts._class);
@ -567,7 +608,15 @@
this._updateContainerHeight();
this._updateHeightsOnResize = _.throttle(function() {
self.cellHeight(self.cellWidth(), false);
}, 100);
this.onResizeHandler = function() {
if (isAutoCellHeight) {
self._updateHeightsOnResize();
}
if (self._isOneColumnMode()) {
if (oneColumnMode) {
return;
@ -582,10 +631,10 @@
if (self.opts.staticGrid) {
return;
}
if (!node.noMove) {
if (node.noMove || self.opts.disableDrag) {
node.el.draggable('disable');
}
if (!node.noResize) {
if (node.noResize || self.opts.disableResize) {
node.el.resizable('disable');
}
});
@ -601,10 +650,10 @@
}
_.each(self.grid.nodes, function(node) {
if (!node.noMove) {
if (!node.noMove && !self.opts.disableDrag) {
node.el.draggable('enable');
}
if (!node.noResize) {
if (!node.noResize && !self.opts.disableResize) {
node.el.resizable('enable');
}
});
@ -631,21 +680,18 @@
};
GridStack.prototype._initStyles = function() {
if (!this.opts.cellHeight) { //that will be handled by CSS
return ;
}
if (this._stylesId) {
$('[data-gs-id="' + this._stylesId + '"]').remove();
Utils.removeStylesheet(this._stylesId);
}
this._stylesId = 'gridstack-style-' + (Math.random() * 100000).toFixed();
this._styles = Utils.createStylesheet(this._stylesId);
if (this._styles != null) {
if (this._styles !== null) {
this._styles._max = 0;
}
};
GridStack.prototype._updateStyles = function(maxHeight) {
if (this._styles === null) {
if (this._styles === null || typeof this._styles === 'undefined') {
return;
}
@ -658,7 +704,7 @@
this._initStyles();
this._updateContainerHeight();
}
if (!this.opts.cellHeight) { //the rest will be handled by CSS
if (!this.opts.cellHeight) { // The rest will be handled by CSS
return ;
}
if (this._styles._max !== 0 && maxHeight <= this._styles._max) {
@ -667,12 +713,14 @@
if (!this.opts.verticalMargin || this.opts.cellHeightUnit === this.opts.verticalMarginUnit) {
getHeight = function(nbRows, nbMargins) {
return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) + self.opts.cellHeightUnit;
return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) +
self.opts.cellHeightUnit;
};
} else {
getHeight = function(nbRows, nbMargins) {
if (!nbRows || !nbMargins) {
return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) + self.opts.cellHeightUnit;
return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) +
self.opts.cellHeightUnit;
}
return 'calc(' + ((self.opts.cellHeight * nbRows) + self.opts.cellHeightUnit) + ' + ' +
((self.opts.verticalMargin * nbMargins) + self.opts.verticalMarginUnit) + ')';
@ -753,27 +801,80 @@
noResize: Utils.toBool(el.attr('data-gs-no-resize')),
noMove: Utils.toBool(el.attr('data-gs-no-move')),
locked: Utils.toBool(el.attr('data-gs-locked')),
el: el
el: el,
id: el.attr('data-gs-id')
});
el.data('_gridstack_node', node);
if (self.opts.staticGrid) {
return;
}
var cellWidth;
var cellHeight;
var removeTimeout;
var setupRemovingTimeout = function() {
if (removeTimeout || !self.opts.removable) {
return;
}
removeTimeout = setTimeout(function() {
el.addClass('grid-stack-item-removing');
node._isAboutToRemove = true;
}, self.opts.removeTimeout);
};
var clearRemovingTimeout = function() {
if (!removeTimeout) {
return;
}
clearTimeout(removeTimeout);
removeTimeout = null;
el.removeClass('grid-stack-item-removing');
node._isAboutToRemove = false;
};
var dragOrResize = function(event, ui) {
var x = Math.round(ui.position.left / cellWidth);
var y = Math.floor((ui.position.top + cellHeight / 2) / cellHeight);
var width;
var height;
if (event.type != 'drag') {
width = Math.round(ui.size.width / cellWidth);
height = Math.round(ui.size.height / cellHeight);
}
if (event.type == 'drag') {
if (x < 0 || x >= self.grid.width || y < 0) {
setupRemovingTimeout();
x = node._beforeDragX;
y = node._beforeDragY;
self.placeholder.detach();
self.placeholder.hide();
self.grid.removeNode(node);
self._updateContainerHeight();
node._temporaryRemoved = true;
} else {
clearRemovingTimeout();
if (node._temporaryRemoved) {
self.grid.addNode(node);
self.placeholder
.attr('data-gs-x', x)
.attr('data-gs-y', y)
.attr('data-gs-width', width)
.attr('data-gs-height', height)
.show();
self.container.append(self.placeholder);
node.el = self.placeholder;
node._temporaryRemoved = false;
}
}
} else if (event.type == 'resize') {
if (x < 0) {
return;
}
}
if (!self.grid.canMoveNode(node, x, y, width, height)) {
return;
}
@ -796,6 +897,8 @@
.attr('data-gs-height', o.attr('data-gs-height'))
.show();
node.el = self.placeholder;
node._beforeDragX = node.x;
node._beforeDragY = node.y;
el.resizable('option', 'minWidth', cellWidth * (node.minWidth || 1));
el.resizable('option', 'minHeight', strictCellHeight * (node.minHeight || 1));
@ -806,18 +909,39 @@
};
var onEndMoving = function(event, ui) {
var forceNotify = false;
self.placeholder.detach();
var o = $(this);
node.el = o;
self.placeholder.hide();
o
.attr('data-gs-x', node.x)
.attr('data-gs-y', node.y)
.attr('data-gs-width', node.width)
.attr('data-gs-height', node.height)
.removeAttr('style');
if (node._isAboutToRemove) {
forceNotify = true;
el.removeData('_gridstack_node');
el.remove();
} else {
clearRemovingTimeout();
if (!node._temporaryRemoved) {
o
.attr('data-gs-x', node.x)
.attr('data-gs-y', node.y)
.attr('data-gs-width', node.width)
.attr('data-gs-height', node.height)
.removeAttr('style');
} else {
o
.attr('data-gs-x', node._beforeDragX)
.attr('data-gs-y', node._beforeDragY)
.attr('data-gs-width', node.width)
.attr('data-gs-height', node.height)
.removeAttr('style');
node.x = node._beforeDragX;
node.y = node._beforeDragY;
self.grid.addNode(node);
}
}
self._updateContainerHeight();
self._triggerChangeEvent();
self._triggerChangeEvent(forceNotify);
self.grid.endUpdate();
@ -843,11 +967,11 @@
resize: dragOrResize
}));
if (node.noMove || this._isOneColumnMode()) {
if (node.noMove || this._isOneColumnMode() || this.opts.staticGrid || this.opts.disableDrag) {
el.draggable('disable');
}
if (node.noResize || this._isOneColumnMode()) {
if (node.noResize || this._isOneColumnMode() || this.opts.staticGrid || this.opts.disableResize) {
el.resizable('disable');
}
@ -862,13 +986,19 @@
}
};
GridStack.prototype.addWidget = function(el, x, y, width, height, autoPosition) {
GridStack.prototype.addWidget = function(el, x, y, width, height, autoPosition, minWidth, maxWidth,
minHeight, maxHeight, id) {
el = $(el);
if (typeof x != 'undefined') { el.attr('data-gs-x', x); }
if (typeof y != 'undefined') { el.attr('data-gs-y', y); }
if (typeof width != 'undefined') { el.attr('data-gs-width', width); }
if (typeof height != 'undefined') { el.attr('data-gs-height', height); }
if (typeof autoPosition != 'undefined') { el.attr('data-gs-auto-position', autoPosition ? 'yes' : null); }
if (typeof minWidth != 'undefined') { el.attr('data-gs-min-width', minWidth); }
if (typeof maxWidth != 'undefined') { el.attr('data-gs-max-width', maxWidth); }
if (typeof minHeight != 'undefined') { el.attr('data-gs-min-height', minHeight); }
if (typeof maxHeight != 'undefined') { el.attr('data-gs-max-height', maxHeight); }
if (typeof id != 'undefined') { el.attr('data-gs-id', id); }
this.container.append(el);
this._prepareElement(el);
this._updateContainerHeight();
@ -895,6 +1025,12 @@
detachNode = typeof detachNode === 'undefined' ? true : detachNode;
el = $(el);
var node = el.data('_gridstack_node');
// For Meteor support: https://github.com/troolee/gridstack.js/pull/272
if (!node) {
node = this.grid.getNodeDataByDOMEl(el);
}
this.grid.removeNode(node);
el.removeData('_gridstack_node');
this._updateContainerHeight();
@ -912,10 +1048,14 @@
this._updateContainerHeight();
};
GridStack.prototype.destroy = function() {
GridStack.prototype.destroy = function(detachGrid) {
$(window).off('resize', this.onResizeHandler);
this.disable();
this.container.remove();
if (typeof detachGrid != 'undefined' && !detachGrid) {
this.removeAll(true);
} else {
this.container.remove();
}
Utils.removeStylesheet(this._stylesId);
if (this.grid) {
this.grid = null;
@ -964,6 +1104,20 @@
return this;
};
GridStack.prototype.enableMove = function(doEnable, includeNewWidgets) {
this.movable(this.container.children('.' + this.opts.itemClass), doEnable);
if (includeNewWidgets) {
this.opts.disableDrag = !doEnable;
}
};
GridStack.prototype.enableResize = function(doEnable, includeNewWidgets) {
this.resizable(this.container.children('.' + this.opts.itemClass), doEnable);
if (includeNewWidgets) {
this.opts.disableResize = !doEnable;
}
};
GridStack.prototype.disable = function() {
this.movable(this.container.children('.' + this.opts.itemClass), false);
this.resizable(this.container.children('.' + this.opts.itemClass), false);
@ -996,7 +1150,7 @@
el.each(function(index, el) {
el = $(el);
var node = el.data('_gridstack_node');
if (typeof node == 'undefined' || node == null) {
if (typeof node === 'undefined' || node === null) {
return;
}
@ -1013,7 +1167,7 @@
el.each(function(index, el) {
el = $(el);
var node = el.data('_gridstack_node');
if (typeof node == 'undefined' || node == null) {
if (typeof node === 'undefined' || node === null) {
return;
}
@ -1030,7 +1184,7 @@
el.each(function(index, el) {
el = $(el);
var node = el.data('_gridstack_node');
if (typeof node == 'undefined' || node == null) {
if (typeof node === 'undefined' || node === null) {
return;
}
@ -1047,7 +1201,7 @@
el.each(function(index, el) {
el = $(el);
var node = el.data('_gridstack_node');
if (typeof node == 'undefined' || node == null) {
if (typeof node === 'undefined' || node === null) {
return;
}
@ -1108,26 +1262,12 @@
});
};
function parseHeight(val) {
var height = val;
var heightUnit = 'px';
if (height && _.isString(height)) {
var match = height.match(/^([0-9]+)(px|em|rem)?$/);
if (!match) {
throw new Error('Invalid height');
}
heightUnit = match[2];
height = parseInt(match[1]);
}
return {height: height, unit: heightUnit};
}
GridStack.prototype.verticalMargin = function(val, noUpdate) {
if (typeof val == 'undefined') {
return this.opts.verticalMargin;
}
var heightData = parseHeight(val);
var heightData = Utils.parseHeight(val);
if (this.opts.verticalMarginUnit === heightData.unit && this.opts.height === heightData.height) {
return ;
@ -1144,13 +1284,11 @@
if (typeof val == 'undefined') {
if (this.opts.cellHeight) {
return this.opts.cellHeight;
} else {
var o = this.container.children('.' + this.opts.itemClass).first();
return Math.ceil(o.outerHeight() / o.attr('data-gs-height'));
}
var o = this.container.children('.' + this.opts.itemClass).first();
return Math.ceil(o.outerHeight() / o.attr('data-gs-height'));
}
var heightData = parseHeight(val);
var heightData = Utils.parseHeight(val);
if (this.opts.cellHeightUnit === heightData.heightUnit && this.opts.height === heightData.height) {
return ;
@ -1169,8 +1307,9 @@
return Math.ceil(o.outerWidth() / o.attr('data-gs-width'));
};
GridStack.prototype.getCellFromPixel = function(position) {
var containerPos = this.container.position();
GridStack.prototype.getCellFromPixel = function(position, useOffset) {
var containerPos = (typeof useOffset != 'undefined' && useOffset) ?
this.container.offset() : this.container.position();
var relativeLeft = position.left - containerPos.left;
var relativeTop = position.top - containerPos.top;
@ -1195,6 +1334,8 @@
GridStack.prototype.setStatic = function(staticValue) {
this.opts.staticGrid = (staticValue === true);
this.enableMove(!staticValue);
this.enableResize(!staticValue);
this._setStaticClass();
};
@ -1208,6 +1349,25 @@
}
};
GridStack.prototype._updateNodeWidths = function(oldWidth, newWidth) {
this.grid._sortNodes();
this.grid.batchUpdate();
var node = {};
for (var i = 0; i < this.grid.nodes.length; i++) {
node = this.grid.nodes[i];
this.update(node.el, Math.round(node.x * newWidth / oldWidth), undefined,
Math.round(node.width * newWidth / oldWidth), undefined);
}
this.grid.commit();
};
GridStack.prototype.setGridWidth = function(gridWidth) {
this.container.removeClass('grid-stack-' + this.opts.width);
this._updateNodeWidths(this.opts.width, gridWidth);
this.opts.width = gridWidth;
this.container.addClass('grid-stack-' + gridWidth);
};
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
GridStackEngine.prototype.batch_update = obsolete(GridStackEngine.prototype.batchUpdate);
GridStackEngine.prototype._fix_collisions = obsolete(GridStackEngine.prototype._fixCollisions,

File diff suppressed because one or more lines are too long

12
dist/gridstack.min.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

437
doc/README.md Normal file
View file

@ -0,0 +1,437 @@
gridstack.js API
================
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents** *generated with [DocToc](http://doctoc.herokuapp.com/)*
- [Options](#options)
- [Grid attributes](#grid-attributes)
- [Item attributes](#item-attributes)
- [Events](#events)
- [onchange(items)](#onchangeitems)
- [ondragstart(event, ui)](#ondragstartevent-ui)
- [ondragstop(event, ui)](#ondragstopevent-ui)
- [onresizestart(event, ui)](#onresizestartevent-ui)
- [onresizestop(event, ui)](#onresizestopevent-ui)
- [disable(event)](#disableevent)
- [enable(event)](#enableevent)
- [API](#api)
- [addWidget(el[, x, y, width, height, autoPosition, minWidth, maxWidth, minHeight, maxHeight, id])](#addwidgetel-x-y-width-height-autoposition-minwidth-maxwidth-minheight-maxheight-id)
- [batchUpdate()](#batchupdate)
- [cellHeight()](#cellheight)
- [cellHeight(val)](#cellheightval)
- [cellWidth()](#cellwidth)
- [commit()](#commit)
- [destroy([detachGrid])](#destroydetachgrid)
- [disable()](#disable)
- [enable()](#enable)
- [enableMove(doEnable, includeNewWidgets)](#enablemovedoenable-includenewwidgets)
- [enableResize(doEnable, includeNewWidgets)](#enableresizedoenable-includenewwidgets)
- [getCellFromPixel(position[, useOffset])](#getcellfrompixelposition-useoffset)
- [isAreaEmpty(x, y, width, height)](#isareaemptyx-y-width-height)
- [locked(el, val)](#lockedel-val)
- [makeWidget(el)](#makewidgetel)
- [maxHeight(el, val)](#maxheightel-val)
- [minHeight(el, val)](#minheightel-val)
- [maxWidth(el, val)](#maxwidthel-val)
- [minWidth(el, val)](#minwidthel-val)
- [movable(el, val)](#movableel-val)
- [move(el, x, y)](#moveel-x-y)
- [removeWidget(el[, detachNode])](#removewidgetel-detachnode)
- [removeAll([detachNode])](#removealldetachnode)
- [resize(el, width, height)](#resizeel-width-height)
- [resizable(el, val)](#resizableel-val)
- [setAnimation(doAnimate)](#setanimationdoanimate)
- [setGridWidth(gridWidth)](#setgridwidthgridwidth)
- [setStatic(staticValue)](#setstaticstaticvalue)
- [update(el, x, y, width, height)](#updateel-x-y-width-height)
- [willItFit(x, y, width, height, autoPosition)](#willitfitx-y-width-height-autoposition)
- [Utils](#utils)
- [GridStackUI.Utils.sort(nodes[, dir[, width]])](#gridstackuiutilssortnodes-dir-width)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Options
- `alwaysShowResizeHandle` - if `true` the resizing handles are shown even if the user is not hovering over the widget
(default: `false`)
- `animate` - turns animation on (default: `false`)
- `auto` - if `false` gridstack will not initialize existing items (default: `true`)
- `cellHeight` - one cell height (default: `60`). Can be:
- an integer (px)
- a string (ex: '10em', '100px', '10rem')
- 0 or null, in which case the library will not generate styles for rows. Everything must be defined in CSS files.
- `'auto'` - height will be calculated from cell width.
- `disableDrag` - disallows dragging of widgets (default: `false`).
- `disableResize` - disallows resizing of widgets (default: `false`).
- `draggable` - allows to override jQuery UI draggable options. (default: `{handle: '.grid-stack-item-content', scroll: true, appendTo: 'body'}`)
- `handle` - draggable handle selector (default: `'.grid-stack-item-content'`)
- `handleClass` - draggable handle class (e.g. `'grid-stack-item-content'`). If set `handle` is ignored (default: `null`)
- `height` - maximum rows amount. Default is `0` which means no maximum rows
- `float` - enable floating widgets (default: `false`) See [example](http://troolee.github.io/gridstack.js/demo/float.html)
- `itemClass` - widget class (default: `'grid-stack-item'`)
- `minWidth` - minimal width. If window width is less, grid will be shown in one-column mode. You need also update your css file (`@media (max-width: 768px) {...}`) with corresponding value (default: `768`)
- `placeholderClass` - class for placeholder (default: `'grid-stack-placeholder'`)
- `placeholderText` - placeholder default content (default: `''`)
- `resizable` - allows to override jQuery UI resizable options. (default: `{autoHide: true, handles: 'se'}`)
- `removable` - if `true` widgets could be removed by dragging outside of the grid (default: `false`)
- `removeTimeout` - time in milliseconds before widget is being removed while dragging outside of the grid. (default: `2000`)
- `rtl` - if `true` turns grid to RTL. Possible values are `true`, `false`, `'auto'` (default: `'auto'`) See [example](http://troolee.github.io/gridstack.js/demo/rtl.html)
- `staticGrid` - makes grid static (default `false`). If true widgets are not movable/resizable. You don't even need jQueryUI draggable/resizable. A CSS class `grid-stack-static` is also added to the container.
- `verticalMargin` - vertical gap size (default: `20`). Can be:
- an integer (px)
- a string (ex: '2em', '20px', '2rem')
- `width` - amount of columns (default: `12`)
## Grid attributes
- `data-gs-animate` - turns animation on
- `data-gs-width` - amount of columns
- `data-gs-height` - maximum rows amount. Default is `0` which means no maximum rows.
- `data-gs-current-height` - current rows amount. Set by the library only. Can be used by the CSS rules.
## Item attributes
- `data-gs-x`, `data-gs-y` - element position
- `data-gs-width`, `data-gs-height` - element size
- `data-gs-max-width`, `data-gs-min-width`, `data-gs-max-height`, `data-gs-min-height` - element constraints
- `data-gs-no-resize` - disable element resizing
- `data-gs-no-move` - disable element moving
- `data-gs-auto-position` - tells to ignore `data-gs-x` and `data-gs-y` attributes and to place element to the first
available position
- `data-gs-locked` - the widget will be locked. It means another widget wouldn't be able to move it during dragging or resizing.
The widget can still be dragged or resized. You need to add `data-gs-no-resize` and `data-gs-no-move` attributes
to completely lock the widget.
## Events
### onchange(items)
Occurs when adding/removing widgets or existing widgets change their position/size
```javascript
var serializeWidgetMap = function (items) {
console.log(items);
};
$('.grid-stack').on('change', function (e, items) {
serializeWidgetMap(items);
});
```
### ondragstart(event, ui)
```javascript
$('.grid-stack').on('dragstart', function (event, ui) {
var grid = this;
var element = event.target;
});
```
### ondragstop(event, ui)
```javascript
$('.grid-stack').on('dragstop', function (event, ui) {
var grid = this;
var element = event.target;
});
```
### onresizestart(event, ui)
```javascript
$('.grid-stack').on('resizestart', function (event, ui) {
var grid = this;
var element = event.target;
});
```
### onresizestop(event, ui)
```javascript
$('.grid-stack').on('resizestop', function (event, ui) {
var grid = this;
var element = event.target;
});
```
### disable(event)
```javascript
$('.grid-stack').on('disable', function(event) {
var grid = event.target;
});
```
### enable(event)
```javascript
$('.grid-stack').on('enable', function(event) {
var grid = event.target;
});
```
## API
### addWidget(el[, x, y, width, height, autoPosition, minWidth, maxWidth, minHeight, maxHeight, id])
Creates new widget and returns it.
Parameters:
- `el` - widget to add
- `x`, `y`, `width`, `height` - widget position/dimensions (optional)
- `autoPosition` - if `true` then `x`, `y` parameters will be ignored and widget will be places on the first available
position (optional)
- `minWidth` minimum width allowed during resize/creation (optional)
- `maxWidth` maximum width allowed during resize/creation (optional)
- `minHeight` minimum height allowed during resize/creation (optional)
- `maxHeight` maximum height allowed during resize/creation (optional)
- `id` value for `data-gs-id` (optional)
Widget will be always placed even if result height is more than actual grid height. You need to use `willItFit` method
before calling `addWidget` for additional check.
```javascript
$('.grid-stack').gridstack();
var grid = $('.grid-stack').data('gridstack');
grid.addWidget(el, 0, 0, 3, 2, true);
```
### batchUpdate()
Initailizes batch updates. You will see no changes until `commit` method is called.
### cellHeight()
Gets current cell height.
### cellHeight(val)
Update current cell height. This method rebuilds an internal CSS stylesheet. Note: You can expect performance issues if
call this method too often.
```javascript
grid.cellHeight(grid.cellWidth() * 1.2);
```
### cellWidth()
Gets current cell width.
### commit()
Finishes batch updates. Updates DOM nodes. You must call it after `batchUpdate`.
### destroy([detachGrid])
Destroys a grid instance.
Parameters:
- `detachGrid` - if `false` nodes and grid will not be removed from the DOM (Optional. Default `true`).
### disable()
Disables widgets moving/resizing. This is a shortcut for:
```javascript
grid.movable('.grid-stack-item', false);
grid.resizable('.grid-stack-item', false);
```
### enable()
Enables widgets moving/resizing. This is a shortcut for:
```javascript
grid.movable('.grid-stack-item', true);
grid.resizable('.grid-stack-item', true);
```
### enableMove(doEnable, includeNewWidgets)
Enables/disables widget moving. `includeNewWidgets` will force new widgets to be draggable as per `doEnable`'s value by changing the `disableDrag` grid option. This is a shortcut for:
```javascript
grid.movable(this.container.children('.' + this.opts.itemClass), doEnable);
```
### enableResize(doEnable, includeNewWidgets)
Enables/disables widget resizing. `includeNewWidgets` will force new widgets to be resizable as per `doEnable`'s value by changing the `disableResize` grid option. This is a shortcut for:
```javascript
grid.resizable(this.container.children('.' + this.opts.itemClass), doEnable);
```
### getCellFromPixel(position[, useOffset])
Get the position of the cell under a pixel on screen.
Parameters :
- `position` - the position of the pixel to resolve in absolute coordinates, as an object with `top` and `left` properties
- `useOffset` - if `true`, value will be based on offset vs position (Optional. Default `false`). Useful when grid is within `position: relative` element.
Returns an object with properties `x` and `y` i.e. the column and row in the grid.
### isAreaEmpty(x, y, width, height)
Checks if specified area is empty.
### locked(el, val)
Locks/unlocks widget.
- `el` - widget to modify.
- `val` - if `true` widget will be locked.
### makeWidget(el)
If you add elements to your gridstack container by hand, you have to tell gridstack afterwards to make them widgets. If you want gridstack to add the elements for you, use `addWidget` instead.
Makes the given element a widget and returns it.
Parameters:
- `el` - element to convert to a widget
```javascript
$('.grid-stack').gridstack();
$('.grid-stack').append('<div id="gsi-1" data-gs-x="0" data-gs-y="0" data-gs-width="3" data-gs-height="2" data-gs-auto-position="1"></div>')
var grid = $('.grid-stack').data('gridstack');
grid.makeWidget('gsi-1');
```
### maxHeight(el, val)
Set the `maxHeight` for a widget.
- `el` - widget to modify.
- `val` - A numeric value of the number of rows
### minHeight(el, val)
Set the `minHeight` for a widget.
- `el` - widget to modify.
- `val` - A numeric value of the number of rows
### maxWidth(el, val)
Set the `maxWidth` for a widget.
- `el` - widget to modify.
- `val` - A numeric value of the number of columns
### minWidth(el, val)
Set the `minWidth` for a widget.
- `el` - widget to modify.
- `val` - A numeric value of the number of columns
### movable(el, val)
Enables/Disables moving.
- `el` - widget to modify
- `val` - if `true` widget will be draggable.
### move(el, x, y)
Changes widget position
Parameters:
- `el` - widget to move
- `x`, `y` - new position. If value is `null` or `undefined` it will be ignored.
### removeWidget(el[, detachNode])
Removes widget from the grid.
Parameters:
- `el` - widget to remove.
- `detachNode` - if `false` node won't be removed from the DOM (Optional. Default `true`).
### removeAll([detachNode])
Removes all widgets from the grid.
Parameters:
- `detachNode` - if `false` nodes won't be removed from the DOM (Optional. Default `true`).
### resize(el, width, height)
Changes widget size
Parameters:
- `el` - widget to resize
- `width`, `height` - new dimensions. If value is `null` or `undefined` it will be ignored.
### resizable(el, val)
Enables/Disables resizing.
- `el` - widget to modify
- `val` - if `true` widget will be resizable.
### setAnimation(doAnimate)
Toggle the grid animation state. Toggles the `grid-stack-animate` class.
- `doAnimate` - if `true` the grid will animate.
### setGridWidth(gridWidth)
(Experimental) Modify number of columns in the grid. Will attempt to update existing widgets to conform to new number of columns. Requires `gridstack-extra.css` or `gridstack-extra.min.css`.
- `gridWidth` - Integer between 1 and 12.
### setStatic(staticValue)
Toggle the grid static state. Also toggle the `grid-stack-static` class.
- `staticValue` - if `true` the grid becomes static.
### update(el, x, y, width, height)
Parameters:
- `el` - widget to move
- `x`, `y` - new position. If value is `null` or `undefined` it will be ignored.
- `width`, `height` - new dimensions. If value is `null` or `undefined` it will be ignored.
Updates widget position/size.
### willItFit(x, y, width, height, autoPosition)
Returns `true` if the `height` of the grid will be less the vertical constraint. Always returns `true` if grid doesn't
have `height` constraint.
```javascript
if (grid.willItFit(newNode.x, newNode.y, newNode.width, newNode.height, true)) {
grid.addWidget(newNode.el, newNode.x, newNode.y, newNode.width, newNode.height, true);
}
else {
alert('Not enough free space to place the widget');
}
```
## Utils
### GridStackUI.Utils.sort(nodes[, dir[, width]])
Sorts array of nodes
- `nodes` - array to sort
- `dir` - `1` for asc, `-1` for desc (optional)
- `width` - width of the grid. If `undefined` the width will be calculated automatically (optional).

View file

@ -24,6 +24,7 @@
"grunt": "^0.4.5",
"grunt-contrib-copy": "^0.8.2",
"grunt-contrib-cssmin": "^0.14.0",
"grunt-contrib-jshint": "^1.0.0",
"grunt-contrib-uglify": "^0.10.1",
"grunt-doctoc": "^0.1.1",
"grunt-sass": "^1.1.0",
@ -34,5 +35,7 @@
"karma-phantomjs-launcher": "^1.0.0",
"phantomjs": "^2.1.3",
"phantomjs-prebuilt": "^2.1.4"
"grunt-contrib-watch": "^0.6.1",
"grunt-jscs": "^2.7.0"
}
}

View file

@ -22,8 +22,8 @@
var obsolete = function(f, oldName, newName) {
var wrapper = function() {
console.warn('gridstack.js: Function `' + oldName + '` is deprecated as of v0.2.5 and has been replaced with `' +
newName + '`. It will be **completely** removed in v1.0.');
console.warn('gridstack.js: Function `' + oldName + '` is deprecated as of v0.2.5 and has been replaced ' +
'with `' + newName + '`. It will be **completely** removed in v1.0.');
return f.apply(this, arguments);
};
wrapper.prototype = f.prototype;
@ -50,7 +50,7 @@
createStylesheet: function(id) {
var style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.setAttribute('data-gs-id', id);
style.setAttribute('data-gs-style-id', id);
if (style.styleSheet) {
style.styleSheet.cssText = '';
} else {
@ -61,7 +61,7 @@
},
removeStylesheet: function(id) {
$('STYLE[data-gs-id=' + id + ']').remove();
$('STYLE[data-gs-style-id=' + id + ']').remove();
},
insertCSSRule: function(sheet, selector, rules, index) {
@ -98,6 +98,20 @@
_isAddNodeIntercepted: function(n) {
return Utils.isIntercepted({x: this.x, y: this.y, width: this.node.width, height: this.node.height}, n);
},
parseHeight: function(val) {
var height = val;
var heightUnit = 'px';
if (height && _.isString(height)) {
var match = height.match(/^([0-9]*\.[0-9]+|[0-9]+)(px|em|rem|vh|vw)?$/);
if (!match) {
throw new Error('Invalid height');
}
heightUnit = match[2];
height = parseFloat(match[1]);
}
return {height: height, unit: heightUnit};
}
};
@ -131,14 +145,19 @@
};
GridStackEngine.prototype.commit = function() {
this._updateCounter = 0;
if (this._updateCounter === 0) {
if (this._updateCounter !== 0) {
this._updateCounter = 0;
this.float = this._float;
this._packNodes();
this._notify();
}
};
// For Meteor support: https://github.com/troolee/gridstack.js/pull/272
GridStackEngine.prototype.getNodeDataByDOMEl = function(el) {
return _.find(this.nodes, function(n) { return el.get(0) === n.el.get(0); });
};
GridStackEngine.prototype._fixCollisions = function(node) {
var self = this;
this._sortNodes(-1);
@ -269,6 +288,9 @@
};
GridStackEngine.prototype.cleanNodes = function() {
if (this._updateCounter) {
return;
}
_.each(this.nodes, function(n) {n._dirty = false; });
};
@ -427,7 +449,7 @@
var GridStack = function(el, opts) {
var self = this;
var oneColumnMode;
var oneColumnMode, isAutoCellHeight;
opts = opts || {};
@ -509,11 +531,30 @@
'.grid-stack-item-content',
scroll: false,
appendTo: 'body'
})
}),
disableDrag: opts.disableDrag || false,
disableResize: opts.disableResize || false,
rtl: 'auto',
removable: false,
removeTimeout: 2000
});
if (this.opts.rtl === 'auto') {
this.opts.rtl = this.container.css('direction') === 'rtl';
}
if (this.opts.rtl) {
this.container.addClass('grid-stack-rtl');
}
this.opts.isNested = isNested;
this.cellHeight(this.opts.cellHeight, true);
isAutoCellHeight = this.opts.cellHeight === 'auto';
if (isAutoCellHeight) {
self.cellHeight(self.cellWidth(), true);
} else {
this.cellHeight(this.opts.cellHeight, true);
}
this.verticalMargin(this.opts.verticalMargin, true);
this.container.addClass(this.opts._class);
@ -567,7 +608,15 @@
this._updateContainerHeight();
this._updateHeightsOnResize = _.throttle(function() {
self.cellHeight(self.cellWidth(), false);
}, 100);
this.onResizeHandler = function() {
if (isAutoCellHeight) {
self._updateHeightsOnResize();
}
if (self._isOneColumnMode()) {
if (oneColumnMode) {
return;
@ -582,10 +631,10 @@
if (self.opts.staticGrid) {
return;
}
if (!node.noMove) {
if (node.noMove || self.opts.disableDrag) {
node.el.draggable('disable');
}
if (!node.noResize) {
if (node.noResize || self.opts.disableResize) {
node.el.resizable('disable');
}
});
@ -601,10 +650,10 @@
}
_.each(self.grid.nodes, function(node) {
if (!node.noMove) {
if (!node.noMove && !self.opts.disableDrag) {
node.el.draggable('enable');
}
if (!node.noResize) {
if (!node.noResize && !self.opts.disableResize) {
node.el.resizable('enable');
}
});
@ -631,21 +680,18 @@
};
GridStack.prototype._initStyles = function() {
if (!this.opts.cellHeight) { //that will be handled by CSS
return ;
}
if (this._stylesId) {
$('[data-gs-id="' + this._stylesId + '"]').remove();
Utils.removeStylesheet(this._stylesId);
}
this._stylesId = 'gridstack-style-' + (Math.random() * 100000).toFixed();
this._styles = Utils.createStylesheet(this._stylesId);
if (this._styles != null) {
if (this._styles !== null) {
this._styles._max = 0;
}
};
GridStack.prototype._updateStyles = function(maxHeight) {
if (this._styles === null) {
if (this._styles === null || typeof this._styles === 'undefined') {
return;
}
@ -658,7 +704,7 @@
this._initStyles();
this._updateContainerHeight();
}
if (!this.opts.cellHeight) { //the rest will be handled by CSS
if (!this.opts.cellHeight) { // The rest will be handled by CSS
return ;
}
if (this._styles._max !== 0 && maxHeight <= this._styles._max) {
@ -667,12 +713,14 @@
if (!this.opts.verticalMargin || this.opts.cellHeightUnit === this.opts.verticalMarginUnit) {
getHeight = function(nbRows, nbMargins) {
return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) + self.opts.cellHeightUnit;
return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) +
self.opts.cellHeightUnit;
};
} else {
getHeight = function(nbRows, nbMargins) {
if (!nbRows || !nbMargins) {
return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) + self.opts.cellHeightUnit;
return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) +
self.opts.cellHeightUnit;
}
return 'calc(' + ((self.opts.cellHeight * nbRows) + self.opts.cellHeightUnit) + ' + ' +
((self.opts.verticalMargin * nbMargins) + self.opts.verticalMarginUnit) + ')';
@ -753,27 +801,80 @@
noResize: Utils.toBool(el.attr('data-gs-no-resize')),
noMove: Utils.toBool(el.attr('data-gs-no-move')),
locked: Utils.toBool(el.attr('data-gs-locked')),
el: el
el: el,
id: el.attr('data-gs-id')
});
el.data('_gridstack_node', node);
if (self.opts.staticGrid) {
return;
}
var cellWidth;
var cellHeight;
var removeTimeout;
var setupRemovingTimeout = function() {
if (removeTimeout || !self.opts.removable) {
return;
}
removeTimeout = setTimeout(function() {
el.addClass('grid-stack-item-removing');
node._isAboutToRemove = true;
}, self.opts.removeTimeout);
};
var clearRemovingTimeout = function() {
if (!removeTimeout) {
return;
}
clearTimeout(removeTimeout);
removeTimeout = null;
el.removeClass('grid-stack-item-removing');
node._isAboutToRemove = false;
};
var dragOrResize = function(event, ui) {
var x = Math.round(ui.position.left / cellWidth);
var y = Math.floor((ui.position.top + cellHeight / 2) / cellHeight);
var width;
var height;
if (event.type != 'drag') {
width = Math.round(ui.size.width / cellWidth);
height = Math.round(ui.size.height / cellHeight);
}
if (event.type == 'drag') {
if (x < 0 || x >= self.grid.width || y < 0) {
setupRemovingTimeout();
x = node._beforeDragX;
y = node._beforeDragY;
self.placeholder.detach();
self.placeholder.hide();
self.grid.removeNode(node);
self._updateContainerHeight();
node._temporaryRemoved = true;
} else {
clearRemovingTimeout();
if (node._temporaryRemoved) {
self.grid.addNode(node);
self.placeholder
.attr('data-gs-x', x)
.attr('data-gs-y', y)
.attr('data-gs-width', width)
.attr('data-gs-height', height)
.show();
self.container.append(self.placeholder);
node.el = self.placeholder;
node._temporaryRemoved = false;
}
}
} else if (event.type == 'resize') {
if (x < 0) {
return;
}
}
if (!self.grid.canMoveNode(node, x, y, width, height)) {
return;
}
@ -796,6 +897,8 @@
.attr('data-gs-height', o.attr('data-gs-height'))
.show();
node.el = self.placeholder;
node._beforeDragX = node.x;
node._beforeDragY = node.y;
el.resizable('option', 'minWidth', cellWidth * (node.minWidth || 1));
el.resizable('option', 'minHeight', strictCellHeight * (node.minHeight || 1));
@ -806,18 +909,39 @@
};
var onEndMoving = function(event, ui) {
var forceNotify = false;
self.placeholder.detach();
var o = $(this);
node.el = o;
self.placeholder.hide();
o
.attr('data-gs-x', node.x)
.attr('data-gs-y', node.y)
.attr('data-gs-width', node.width)
.attr('data-gs-height', node.height)
.removeAttr('style');
if (node._isAboutToRemove) {
forceNotify = true;
el.removeData('_gridstack_node');
el.remove();
} else {
clearRemovingTimeout();
if (!node._temporaryRemoved) {
o
.attr('data-gs-x', node.x)
.attr('data-gs-y', node.y)
.attr('data-gs-width', node.width)
.attr('data-gs-height', node.height)
.removeAttr('style');
} else {
o
.attr('data-gs-x', node._beforeDragX)
.attr('data-gs-y', node._beforeDragY)
.attr('data-gs-width', node.width)
.attr('data-gs-height', node.height)
.removeAttr('style');
node.x = node._beforeDragX;
node.y = node._beforeDragY;
self.grid.addNode(node);
}
}
self._updateContainerHeight();
self._triggerChangeEvent();
self._triggerChangeEvent(forceNotify);
self.grid.endUpdate();
@ -843,11 +967,11 @@
resize: dragOrResize
}));
if (node.noMove || this._isOneColumnMode()) {
if (node.noMove || this._isOneColumnMode() || this.opts.staticGrid || this.opts.disableDrag) {
el.draggable('disable');
}
if (node.noResize || this._isOneColumnMode()) {
if (node.noResize || this._isOneColumnMode() || this.opts.staticGrid || this.opts.disableResize) {
el.resizable('disable');
}
@ -862,13 +986,19 @@
}
};
GridStack.prototype.addWidget = function(el, x, y, width, height, autoPosition) {
GridStack.prototype.addWidget = function(el, x, y, width, height, autoPosition, minWidth, maxWidth,
minHeight, maxHeight, id) {
el = $(el);
if (typeof x != 'undefined') { el.attr('data-gs-x', x); }
if (typeof y != 'undefined') { el.attr('data-gs-y', y); }
if (typeof width != 'undefined') { el.attr('data-gs-width', width); }
if (typeof height != 'undefined') { el.attr('data-gs-height', height); }
if (typeof autoPosition != 'undefined') { el.attr('data-gs-auto-position', autoPosition ? 'yes' : null); }
if (typeof minWidth != 'undefined') { el.attr('data-gs-min-width', minWidth); }
if (typeof maxWidth != 'undefined') { el.attr('data-gs-max-width', maxWidth); }
if (typeof minHeight != 'undefined') { el.attr('data-gs-min-height', minHeight); }
if (typeof maxHeight != 'undefined') { el.attr('data-gs-max-height', maxHeight); }
if (typeof id != 'undefined') { el.attr('data-gs-id', id); }
this.container.append(el);
this._prepareElement(el);
this._updateContainerHeight();
@ -895,6 +1025,12 @@
detachNode = typeof detachNode === 'undefined' ? true : detachNode;
el = $(el);
var node = el.data('_gridstack_node');
// For Meteor support: https://github.com/troolee/gridstack.js/pull/272
if (!node) {
node = this.grid.getNodeDataByDOMEl(el);
}
this.grid.removeNode(node);
el.removeData('_gridstack_node');
this._updateContainerHeight();
@ -912,10 +1048,14 @@
this._updateContainerHeight();
};
GridStack.prototype.destroy = function() {
GridStack.prototype.destroy = function(detachGrid) {
$(window).off('resize', this.onResizeHandler);
this.disable();
this.container.remove();
if (typeof detachGrid != 'undefined' && !detachGrid) {
this.removeAll(true);
} else {
this.container.remove();
}
Utils.removeStylesheet(this._stylesId);
if (this.grid) {
this.grid = null;
@ -964,6 +1104,20 @@
return this;
};
GridStack.prototype.enableMove = function(doEnable, includeNewWidgets) {
this.movable(this.container.children('.' + this.opts.itemClass), doEnable);
if (includeNewWidgets) {
this.opts.disableDrag = !doEnable;
}
};
GridStack.prototype.enableResize = function(doEnable, includeNewWidgets) {
this.resizable(this.container.children('.' + this.opts.itemClass), doEnable);
if (includeNewWidgets) {
this.opts.disableResize = !doEnable;
}
};
GridStack.prototype.disable = function() {
this.movable(this.container.children('.' + this.opts.itemClass), false);
this.resizable(this.container.children('.' + this.opts.itemClass), false);
@ -996,7 +1150,7 @@
el.each(function(index, el) {
el = $(el);
var node = el.data('_gridstack_node');
if (typeof node == 'undefined' || node == null) {
if (typeof node === 'undefined' || node === null) {
return;
}
@ -1013,7 +1167,7 @@
el.each(function(index, el) {
el = $(el);
var node = el.data('_gridstack_node');
if (typeof node == 'undefined' || node == null) {
if (typeof node === 'undefined' || node === null) {
return;
}
@ -1030,7 +1184,7 @@
el.each(function(index, el) {
el = $(el);
var node = el.data('_gridstack_node');
if (typeof node == 'undefined' || node == null) {
if (typeof node === 'undefined' || node === null) {
return;
}
@ -1047,7 +1201,7 @@
el.each(function(index, el) {
el = $(el);
var node = el.data('_gridstack_node');
if (typeof node == 'undefined' || node == null) {
if (typeof node === 'undefined' || node === null) {
return;
}
@ -1108,26 +1262,12 @@
});
};
function parseHeight(val) {
var height = val;
var heightUnit = 'px';
if (height && _.isString(height)) {
var match = height.match(/^([0-9]+)(px|em|rem)?$/);
if (!match) {
throw new Error('Invalid height');
}
heightUnit = match[2];
height = parseInt(match[1]);
}
return {height: height, unit: heightUnit};
}
GridStack.prototype.verticalMargin = function(val, noUpdate) {
if (typeof val == 'undefined') {
return this.opts.verticalMargin;
}
var heightData = parseHeight(val);
var heightData = Utils.parseHeight(val);
if (this.opts.verticalMarginUnit === heightData.unit && this.opts.height === heightData.height) {
return ;
@ -1144,13 +1284,11 @@
if (typeof val == 'undefined') {
if (this.opts.cellHeight) {
return this.opts.cellHeight;
} else {
var o = this.container.children('.' + this.opts.itemClass).first();
return Math.ceil(o.outerHeight() / o.attr('data-gs-height'));
}
var o = this.container.children('.' + this.opts.itemClass).first();
return Math.ceil(o.outerHeight() / o.attr('data-gs-height'));
}
var heightData = parseHeight(val);
var heightData = Utils.parseHeight(val);
if (this.opts.cellHeightUnit === heightData.heightUnit && this.opts.height === heightData.height) {
return ;
@ -1169,8 +1307,9 @@
return Math.ceil(o.outerWidth() / o.attr('data-gs-width'));
};
GridStack.prototype.getCellFromPixel = function(position) {
var containerPos = this.container.position();
GridStack.prototype.getCellFromPixel = function(position, useOffset) {
var containerPos = (typeof useOffset != 'undefined' && useOffset) ?
this.container.offset() : this.container.position();
var relativeLeft = position.left - containerPos.left;
var relativeTop = position.top - containerPos.top;
@ -1195,6 +1334,8 @@
GridStack.prototype.setStatic = function(staticValue) {
this.opts.staticGrid = (staticValue === true);
this.enableMove(!staticValue);
this.enableResize(!staticValue);
this._setStaticClass();
};
@ -1208,6 +1349,25 @@
}
};
GridStack.prototype._updateNodeWidths = function(oldWidth, newWidth) {
this.grid._sortNodes();
this.grid.batchUpdate();
var node = {};
for (var i = 0; i < this.grid.nodes.length; i++) {
node = this.grid.nodes[i];
this.update(node.el, Math.round(node.x * newWidth / oldWidth), undefined,
Math.round(node.width * newWidth / oldWidth), undefined);
}
this.grid.commit();
};
GridStack.prototype.setGridWidth = function(gridWidth) {
this.container.removeClass('grid-stack-' + this.opts.width);
this._updateNodeWidths(this.opts.width, gridWidth);
this.opts.width = gridWidth;
this.container.addClass('grid-stack-' + gridWidth);
};
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
GridStackEngine.prototype.batch_update = obsolete(GridStackEngine.prototype.batchUpdate);
GridStackEngine.prototype._fix_collisions = obsolete(GridStackEngine.prototype._fixCollisions,

View file

@ -16,6 +16,14 @@ $animation_speed: .3s !default;
.grid-stack {
position: relative;
&.grid-stack-rtl {
direction: ltr;
> .grid-stack-item {
direction: rtl;
}
}
.grid-stack-placeholder > .placeholder-content {
border: 1px dashed lightgray;
margin: 0;
@ -71,26 +79,17 @@ $animation_speed: .3s !default;
> .ui-resizable-se,
> .ui-resizable-sw {
text-align: right;
color: gray;
padding: 2px 3px 0 0;
margin: 0;
font: normal normal normal 10px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
&::before { content: "\f065"; }
background-image: url(data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjE2cHgiIGhlaWdodD0iMTZweCIgdmlld0JveD0iMCAwIDUxMS42MjYgNTExLjYyNyIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNTExLjYyNiA1MTEuNjI3OyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxnPgoJPHBhdGggZD0iTTMyOC45MDYsNDAxLjk5NGgtMzYuNTUzVjEwOS42MzZoMzYuNTUzYzQuOTQ4LDAsOS4yMzYtMS44MDksMTIuODQ3LTUuNDI2YzMuNjEzLTMuNjE1LDUuNDIxLTcuODk4LDUuNDIxLTEyLjg0NSAgIGMwLTQuOTQ5LTEuODAxLTkuMjMxLTUuNDI4LTEyLjg1MWwtNzMuMDg3LTczLjA5QzI2NS4wNDQsMS44MDksMjYwLjc2LDAsMjU1LjgxMywwYy00Ljk0OCwwLTkuMjI5LDEuODA5LTEyLjg0Nyw1LjQyNCAgIGwtNzMuMDg4LDczLjA5Yy0zLjYxOCwzLjYxOS01LjQyNCw3LjkwMi01LjQyNCwxMi44NTFjMCw0Ljk0NiwxLjgwNyw5LjIyOSw1LjQyNCwxMi44NDVjMy42MTksMy42MTcsNy45MDEsNS40MjYsMTIuODUsNS40MjYgICBoMzYuNTQ1djI5Mi4zNThoLTM2LjU0MmMtNC45NTIsMC05LjIzNSwxLjgwOC0xMi44NSw1LjQyMWMtMy42MTcsMy42MjEtNS40MjQsNy45MDUtNS40MjQsMTIuODU0ICAgYzAsNC45NDUsMS44MDcsOS4yMjcsNS40MjQsMTIuODQ3bDczLjA4OSw3My4wODhjMy42MTcsMy42MTcsNy44OTgsNS40MjQsMTIuODQ3LDUuNDI0YzQuOTUsMCw5LjIzNC0xLjgwNywxMi44NDktNS40MjQgICBsNzMuMDg3LTczLjA4OGMzLjYxMy0zLjYyLDUuNDIxLTcuOTAxLDUuNDIxLTEyLjg0N2MwLTQuOTQ4LTEuODA4LTkuMjMyLTUuNDIxLTEyLjg1NCAgIEMzMzguMTQyLDQwMy44MDIsMzMzLjg1Nyw0MDEuOTk0LDMyOC45MDYsNDAxLjk5NHoiIGZpbGw9IiM2NjY2NjYiLz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8L3N2Zz4K);
background-repeat: no-repeat;
background-position: center;
@include vendor(transform, rotate(45deg));
}
> .ui-resizable-se {
display: inline-block;
@include vendor(transform, rotate(90deg));
@include vendor(transform, rotate(-45deg));
}
> .ui-resizable-nw { cursor: nw-resize; width: 20px; height: 20px; left: 10px; top: 0; }
> .ui-resizable-n { cursor: n-resize; height: 10px; top: 0; left: 25px; right: 25px; }
> .ui-resizable-ne { cursor: ne-resize; width: 20px; height: 20px; right: 10px; top: 0; }
@ -100,6 +99,12 @@ $animation_speed: .3s !default;
> .ui-resizable-sw { cursor: sw-resize; width: 20px; height: 20px; left: 10px; bottom: 0; }
> .ui-resizable-w { cursor: w-resize; width: 10px; left: $horizontal_padding / 2; top: 15px; bottom: 15px; }
&.ui-draggable-dragging {
&> .ui-resizable-handle {
display: none !important;
}
}
@for $i from 1 through $gridstack-columns {
&[data-gs-width='#{$i}'] { width: (100% / $gridstack-columns) * $i; }
&[data-gs-x='#{$i}'] { left: (100% / $gridstack-columns) * $i; }
@ -120,14 +125,6 @@ $animation_speed: .3s !default;
}
}
/** Uncomment this to show bottom-left resize handle **/
/*
.grid-stack > .grid-stack-item > .ui-resizable-sw {
display: inline-block;
@include vendor(transform, rotate(180deg));
}
*/
@media (max-width: 768px) {
.grid-stack-item {
position: relative !important;