diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..e4a26aa
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,8 @@
+/.gitattributes export-ignore
+/.gitignore export-ignore
+/examples export-ignore
+/gulpfile.js export-ignore
+/package.json export-ignore
+/phpunit.xml.dist export-ignore
+/resources export-ignore
+/tests export-ignore
diff --git a/.gitbook.yaml b/.gitbook.yaml
new file mode 100644
index 0000000..e454be0
--- /dev/null
+++ b/.gitbook.yaml
@@ -0,0 +1 @@
+root: ./docs/
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
new file mode 100644
index 0000000..b276734
--- /dev/null
+++ b/.github/workflows/main.yml
@@ -0,0 +1,18 @@
+name: Publish docs via GitHub Pages
+on:
+ push:
+ branches:
+ - master
+
+jobs:
+ build:
+ name: Deploy docs
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout master
+ uses: actions/checkout@v1
+
+ - name: Deploy docs
+ uses: mhausenblas/mkdocs-deploy-gh-pages@master
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.gitignore b/.gitignore
index 766e96f..60ad359 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,5 @@
.idea/*
-/node_modules
\ No newline at end of file
+node_modules/
+vendor/
+composer.lock
+package-lock.json
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a75b0df..3eecd95 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,8 +1,252 @@
Yii2 multiple input change log
==============================
-1.3.2 in development
---------------------
+2.30.0 (in development)
+=======================
+- #363 fix rendering header and footer in case of using POS_ROWS_BEGIN in TableRenderer (unclead)
+
+2.30.0
+=======================
+- #369 fix rendering action buttons in case the dataset contains non-numeric indices (unclead)
+
+2.29.0
+=======================
+- fix addind active form fields doesn't work properly in case of 10 rows and more (unclead)
+- revert changes in normalize method because it affected ajax validation
+- fix addind active form fields in nested columns (unclead)
+
+2.28.0
+=======================
+- replace outdated jquery-sortable.js with a modern alternative (sortable.js) (sankam-nikolya)
+
+2.27.0
+======
+- #367 (fix) ajax validation doesn't work for newly added/cloned inputs
+
+2.26.2
+======
+- prevent error loop in case of undefined $wrapper.data('multipleInput') (cebe)
+
+2.26.1
+======
+- remove version from composer.json
+
+2.26.0
+======
+- fix calculation of the current row index
+- fix incrementing the current row index after adding a new row
+
+2.25.0
+======
+- rework cloning: fix #277, #351, #348 (unclead)
+
+2.24.0
+======
+- #339 don't set tabindex explicitly
+
+2.23.0
+======
+- always use `id` from the settings if it is specified
+- Ability to add custom tabindex via options array
+- #335 fix input name in case of one column and enabled sorting
+
+2.22.0
+======
+- Ignore dev files in zip distribution (sup-ham)
+- #292 Fixed tests for last PHPUnit
+- Added support prepare values of attributes with same name as the relation
+
+2.21.4
+======
+- Fix replaceAll unfinished modify
+- More completely type detect to replaceAll
+
+2.21.3
+======
+- fix retrieving AR relation data
+
+2.21.2
+======
+- FIX wrapper options for bootstrap theme
+
+2.21.1
+======
+- #286 avoid removal of all rows on the page when there are several widgets on the page and method `clear` was called
+
+2.21.0
+======
+- #279 ability to prepend new row instead of append
+
+2.20.6
+======
+
+- don't cast JsExpression to string after replace widget placeholder
+
+2.20.0
+======
+
+- #278 allow zero name
+- #261 replace the widget placeholder in all nested options
+
+2.19.0
+======
+- add template for input (bscheshirwork)
+- pass more params to a prepareValue closure (bscheshirwork)
+- add DivRenderer (bscheshirwork)
+
+2.18.0
+======
+- #246 accept `\Traversable` in model attribute for `yield` compatibility (bscheshirwork)
+- #250 accept `\Traversable` in TableRenderer and ListRenderer for `yield` compatibility (bscheshirwork)
+- #253 allow to omit a name for static column
+- #257 added `jsPositions` property for the `BaseRenderer` to set right order js-code in `jsInit` and `jsTemplates` (Spell6inder)
+- #259 added `columnOptions` property in the `BaseColumn` for TableRenderer and ListRenderer to support HTML options of individual column (InsaneSkull)
+
+2.17.0
+======
+- #215 collect all js script that has to be evaluate when add new row (not only from " on ready" section)
+- #198 introduce the option `theme` to disable all bootstrap css classes
+- #197 explicitly set tabindex for all inputs
+- #175 option `showGeneralError` to enable displaying of general error message
+
+2.16.0
+======
+- #220 fixed error message for clientValidation and ajaxValidation (antkaz)
+- #228 added `iconMap` and `iconSource`property for MultipleInput and TabularInput
+- #228 changed the following methods to support icon class:
+ BaseColumn->renderDragColumn(), TableRenderer->renderCellContent(), BaseRenderer->prepareButtons()
+- #194 added support of yii\base\DynamicModel
+- #186 added event `afterDropRow`
+
+2.15.0
+=======================
+- #217 added `layoutConfig` property for the ListRenderer (antkaz)
+
+2.14.0
+======
+- #202 added extra buttons (dimmitri)
+- PR#201 added optional clone button (alex-nesterov)
+
+2.13.0
+======
+- #152 added ability to allow an empty list (or set `min` property to 0) for TabularInput
+
+2.12.0
+======
+- Rename yii\base\Object to yii\base\BaseObject
+
+
+2.11.0
+======
+- Added the possibility to substitute buttons before rows
+
+2.10.0
+======
+- #170: Added global options `enableError`
+- #154: Added missing js event: beforeAddRow
+
+2.9.0
+=====
+
+- Pass the added row to `afterAddRow` event
+
+2.8.2
+=====
+
+- Fixed conflict with jQuery UI sortable
+
+2.8.1
+=====
+
+- Fixed client validation
+
+2.8.0
+=====
+
+- #137: added option `nameSuffix` to avoid errors related to duplication of id in case when you use several copies of the widget on a page
+
+2.7.1
+=====
+
+- Fixed assets
+
+2.7.0
+=====
+
+- Fixed an incorrect behavior of widget in case of ajax loading (e.g. in modal window)
+
+2.6.1
+=====
+
+- Fixed assets
+
+2.6.0
+=====
+
+- PR#132: Implemented `Sortting` (sankam-nikolya)
+- PR#132: fixed if attribute is set and hasProperty return false (sankam-nikolya)
+
+2.5.0
+=====
+
+- #127: fixed js actions
+
+2.4.0
+=====
+
+- Implemented `ListRenderer`
+
+2.3.1
+=====
+
+- Fixed ajax validation for embedded fields
+
+2.3.0
+=====
+
+- #107: render a hidden input when `MultipleInput` is used for active field
+- #109: respect ID when using a widget's placeholder
+
+2.2.0
+=====
+
+- #104: Fixed preparation of js attributes (Choate, unclead)
+- Fixed removal of row with index 0 via js api method (pvlg)
+
+
+2.1.1
+=====
+
+- Enh: Passing a deleted row to the event
+
+2.1.0
+=====
+
+- Enh #37: Support of client validation
+
+2.0.1
+=====
+
+- Bug #105: Change vendor name in namespace from yii to unclead to respect Yii recommendations
+
+2.0.0
+=====
+
+- Renamed `limit` option to `max`
+- Changed namespace from `unclead\widgets` to `yii\multipleinput`
+- #92: Adjustments for correct work with AR relations
+- Enh #104: Added method to set value of an particular option
+
+1.4.1
+=====
+
+- #99: Respect "defaultValue" if it is set and current value is empty (unclead)
+
+1.4.0
+-----
+
+- #94: added ability to set custom renderer (unclead, bokodi-dev)
+- #97: Respect `addButtonPosition` when rendering the button (unclead)
1.3.1
-----
diff --git a/README.md b/README.md
index 1a52fca..61b815b 100644
--- a/README.md
+++ b/README.md
@@ -1,66 +1,60 @@
-#Yii2 Multiple input widget.
+# Yii2 Multiple input widget.
Yii2 widget for handle multiple inputs for an attribute of model and tabular input for batch of models.
[](https://packagist.org/packages/unclead/yii2-multiple-input)
[](https://packagist.org/packages/unclead/yii2-multiple-input)
[](https://packagist.org/packages/unclead/yii2-multiple-input)
-[](https://packagist.org/packages/unclead/yii2-multiple-input)
+[](https://packagist.org/packages/unclead/yii2-multiple-input)
[](https://packagist.org/packages/unclead/yii2-multiple-input)
-##Latest release
-The latest stable version of the extension is v1.3.1. Follow the [instruction](./UPGRADE.md) for upgrading from previous versions
+## Latest release
+The latest stable version of the extension is v2.27.0 Follow the [instruction](./UPGRADE.md) for upgrading from previous versions
-##Installation
+## Installation
The preferred way to install this extension is through [composer](http://getcomposer.org/download/).
Either run
```
-php composer.phar require unclead/yii2-multiple-input "~1.0"
+php composer.phar require unclead/yii2-multiple-input "~2.0"
```
or add
```
-"unclead/yii2-multiple-input": "~1.0"
+"unclead/yii2-multiple-input": "~2.0"
```
to the require section of your `composer.json` file.
-##Basic usage
+## Basic usage
-
+
For example you want to have an ability of entering several emails of user on profile page.
In this case you can use yii2-multiple-input widget like in the following code
```php
-use unclead\widgets\MultipleInput;
+use unclead\multipleinput\MultipleInput;
...
field($model, 'emails')->widget(MultipleInput::className(), [
- 'limit' => 6,
+ 'max' => 6,
+ 'min' => 2, // should be at least 2 rows
'allowEmptyList' => false,
'enableGuessTitle' => true,
- 'min' => 2, // should be at least 2 rows
- 'addButtonPosition' => MultipleInput::POS_HEADER // show add button in the header
+ 'addButtonPosition' => MultipleInput::POS_HEADER, // show add button in the header
])
->label(false);
?>
```
-You can find more examples of usage [here](./docs/usage.md)
-
-##Documentation
+## Documentation
-- [Configuration](./docs/configuration.md)
-- [Usage](./docs/usage.md)
-- [Tips and tricks](./docs/tips.md)
-- [Javascript Events and Operations](./docs/javascript.md)
-- [Renderers](./docs/renderers.md)
+You can find a full version of documentation [here](https://unclead.github.io/yii2-multiple-input/)
-##License
+## License
**yii2-multiple-input** is released under the BSD 3-Clause License. See the bundled [LICENSE.md](./LICENSE.md) for details.
diff --git a/UPGRADE.md b/UPGRADE.md
index 0566f67..db7f21e 100644
--- a/UPGRADE.md
+++ b/UPGRADE.md
@@ -8,6 +8,32 @@ if you want to upgrade from version A to version C and there is
version B between A and C, you need to following the instructions
for both A and B.
+Upgrade 2.12.0
+--------------
+- Ensure you use yii2 2.0.13 and higher, otherwise you have to use previous version of the widget
+
+Upgrade from 2.2.0 tp 2.3.0
+---------------------------
+
+- Ensure that you set `id` option in case you are using js actions, otherwise your old code won't work.
+
+Upgrade from 2.0.0 tp 2.0.1
+---------------------------
+
+- Change namespace prefix `yii\multipleinput\` to `unclead\multipleinput\`.
+
+Upgrade from 1.4 to 2.0
+-----------------------
+
+- Rename option `limit` to `max`
+- Change namespace prefix `unclead\widgets\` to `yii\multipleinput\`.
+
+Upgrade from 1.3 to 1.4
+-----------------------
+- In scope of #97 was changed a behavior of rendering add button. The button renders now depends on option `addButtonPosition` and now this
+option is not set by default.
+
+
Upgrade from 1.2 to 1.3
-----------------------
@@ -23,4 +49,4 @@ After installing version 1.1.0 you have to rename js events following the next s
- Event `init` rename to `afterInit`
- Event `addNewRow` rename to `afterAddRow`
-- Event `removeRow` rename to `afterDeleteRow`
\ No newline at end of file
+- Event `removeRow` rename to `afterDeleteRow`
diff --git a/composer.json b/composer.json
index 02967ec..f5e557e 100644
--- a/composer.json
+++ b/composer.json
@@ -2,14 +2,13 @@
"name": "unclead/yii2-multiple-input",
"description": "Widget for handle multiple inputs for an attribute of Yii2 framework model",
"keywords": [
- "yii2",
- "yii2 multiple input",
+ "yii2",
+ "yii2 multiple input",
"yii2 array input",
"yii2 multiple field",
"yii2 tabular input"
],
"type": "yii2-extension",
- "version": "1.3.1",
"license": "BSD-3-Clause",
"support": {
"issues": "https://github.com/unclead/yii2-multiple-input/issues?state=open",
@@ -23,12 +22,16 @@
],
"require": {
"php": ">=5.4.0",
- "yiisoft/yii2": "*"
+ "yiisoft/yii2": ">=2.0.38"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "5.7.*"
},
"autoload": {
"psr-4": {
- "unclead\\widgets\\examples\\": "examples/",
- "unclead\\widgets\\": "src/"
+ "unclead\\multipleinput\\examples\\": "examples/",
+ "unclead\\multipleinput\\": "src/",
+ "unclead\\multipleinput\\tests\\": "tests/"
}
}
}
diff --git a/docs/README.md b/docs/README.md
deleted file mode 100644
index a59deb0..0000000
--- a/docs/README.md
+++ /dev/null
@@ -1,7 +0,0 @@
-#Documentation
-
-- [Configuration](./configuration.md)
-- [Usage](./usage.md)
-- [Tips and tricks](./tips.md)
-- [Javascript Events and Operations](./javascript.md)
-- [Renderers](./renderers.md)
diff --git a/docs/clonning.md b/docs/clonning.md
new file mode 100644
index 0000000..0171e82
--- /dev/null
+++ b/docs/clonning.md
@@ -0,0 +1,48 @@
+# Clonning
+
+
+
+```text
+use unclead\multipleinput\MultipleInput;
+
+...
+
+$form->field($model, 'products')->widget(MultipleInput::className(), [
+ 'max' => 10,
+ 'cloneButton' => true,
+ 'columns' => [
+ [
+ 'name' => 'product_id',
+ 'type' => 'dropDownList',
+ 'title' => 'Special Products',
+ 'defaultValue' => 1,
+ 'items' => [
+ 1 => 'id: 1, price: $19.99, title: product1',
+ 2 => 'id: 2, price: $29.99, title: product2',
+ 3 => 'id: 3, price: $39.99, title: product3',
+ 4 => 'id: 4, price: $49.99, title: product4',
+ 5 => 'id: 5, price: $59.99, title: product5',
+ ],
+ ],
+ [
+ 'name' => 'time',
+ 'type' => DateTimePicker::className(),
+ 'title' => 'due date',
+ 'defaultValue' => date('d-m-Y h:i')
+ ],
+ [
+ 'name' => 'count',
+ 'title' => 'Count',
+ 'defaultValue' => 1,
+ 'enableError' => true,
+ 'options' => [
+ 'type' => 'number',
+ 'class' => 'input-priority',
+ ]
+ ]
+ ]
+])->label(false);
+```
+
+
+
diff --git a/docs/configuration.md b/docs/configuration.md
index f9e67fd..42d7df6 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -1,106 +1,169 @@
-#Configuration
+# Configuration
Widget support the following options that are additionally recognized over and above the configuration options in the InputWidget.
-##Base options
+## Base options
-**limit** *integer*: rows limit. If not set will defaul to unlimited
+**theme** _string_: specify the theme of the widget. Available 2 themes:
-**min** *integer*: minimum number of rows. Set to `0` if you need the empty list in case you don't have any data
+* `default` with only widget css classes
+* `bs` \(twitter bootstrap\) theme with additional BS ccs classes\).
-**attributeOptions** *array*: client-side attribute options, e.g. enableAjaxValidation. You may use this property in case when
-you use widget without a model, since in this case widget is not able to detect client-side options automatically
+Default value is `bs`
-**addButtonPosition** *integer|array*: the position(s) of `add` button.
-This can be `MultipleInput::POS_HEADER`, `MultipleInput::POS_ROW` or `MultipleInput:PO_FOOTER`
+**max** _integer_: maximum number of rows. If not set will default to unlimited
-**addButtonOptions** *array*: the HTML options for `add` button. Can contains `class` and `label` keys
+**min** _integer_: minimum number of rows. Set to `0` if you need the empty list in case you don't have any data
-**removeButtonOptions** *array*: the HTML options for `add` button. Can contains `class` and `label` keys
+**prepend** _boolean_: add a new row to the beginning of the list, not to the end
-**data** *array*: array of values in case you use widget without model
+**attributeOptions** _array_: client-side attribute options, e.g. enableAjaxValidation. You may use this property in case when you use widget without a model, since in this case widget is not able to detect client-side options automatically
-**models** *array*: the list of models. Required in case you use `TabularInput` widget
+**addButtonPosition** _integer\|array_: the position\(s\) of `add` button. This can be `MultipleInput::POS_HEADER`, `MultipleInput::POS_ROW`, `MultipleInput::POS_ROW_BEGIN` or `MultipleInput::POS_FOOTER`.
-**allowEmptyList** *boolean*: whether to allow the empty list
+**addButtonOptions** _array_: the HTML options for `add` button. Can contains `class` and `label` keys
-**columnClass** *string*: the name of column class. You can specify your own class to extend base functionality.
-Defaults to `unclead\widgets\MultipleInputColumn` for `MultipleInput` and `unclead\widgets\TabularColumn` for `TabularInput`.
+**removeButtonOptions** _array_: the HTML options for `remove` button. Can contains `class` and `label` keys
-**columns** *array*: the row columns configuration where you can set the properties which is described below
+**cloneButton** _bool_: whether need to enable clone buttons or not
-**rowOptions** *array|\Closure*: the HTML attributes for the table body rows. This can be either an array
-specifying the common HTML attributes for all body rows, or an anonymous function that returns an array of the HTML attributes.
-It should have the following signature:
+**cloneButtonOptions** _array_: the HTML options for `remove` button. Can contains `class` and `label` keys
+
+**data** _array_: array of values in case you use widget without model
+
+**models** _array_: the list of models. Required in case you use `TabularInput` widget
+
+**allowEmptyList** _boolean_: whether to allow the empty list. **Deprecateed** use the `min` option instead
+
+**columnClass** _string_: the name of column class. You can specify your own class to extend base functionality. Defaults to `unclead\multipleinput\MultipleInputColumn` for `MultipleInput` and `unclead\multipleinput\TabularColumn` for `TabularInput`.
+
+**rendererClass** _string_: the name of renderer class. You can specify your own class to extend base functionality. Defaults to `unclead\multipleinput\renderers\TableRenderer`.
+
+**columns** _array_: the row columns configuration where you can set the properties which is described below
+
+**rowOptions** _array\|\Closure_: the HTML attributes for the table body rows. This can be either an array specifying the common HTML attributes for all body rows, or an anonymous function that returns an array of the HTML attributes. It should have the following signature:
```php
function ($model, $index, $context)
```
-- `$model`: the current data model being rendered
-- `$index`: the zero-based index of the data model in the model array
-- `$context`: the widget object
+* `$model`: the current data model being rendered
+* `$index`: the zero-based index of the data model in the model array
+* `$context`: the widget object
+
+**sortable** _bool_: whether need to enable sorting or not
+
+**modelClass** _string_: a class of model which is used to render `TabularInput`. You must specify this property when a list of `models` is empty. If this property is not specified the widget will detect it based on a class of `models`
+
+**extraButtons** _string\|\Closure_: the HTML content that will be rendered after the buttons. It can be either string or an anonymous function that returns a string which will be treated as HTML content. It should have the following signature:
+
+```php
+function ($model, $index, $context)
+```
+
+* `$model`: the current data model being rendered
+* `$index`: the zero-based index of the data model in the model array
+* `$context`: the MultipleInput widget object
+
+**layoutConfig** _array_: CSS grid classes for horizontal layout \(only supported for `ListRenderer` class\). This must be an array with these keys:
-##Column options
+* `'offsetClass'`: the offset grid class to append to the wrapper if no label is rendered
+* `'labelClass'`: the label grid class
+* `'wrapperClass'`: the wrapper grid class
+* `'errorClass'`: the error grid class
-**name** *string*: input name. *Required options*
+**showGeneralError** _bool_: whether need to show error message for main attribute, when you don't want to validate particular input and want to validate a filed in general.
-**type** *string*: type of the input. If not set will default to `textInput`. Read more about the types described below
+## Column options
-**title** *string*: the column title
+**name** _string_: input name. _Required options_
-**value** *Closure*: you can set it to an anonymous function with the following signature:
+**type** _string_: type of the input. If not set will default to `textInput`. Read more about the types described below
+
+**title** _string_: the column title
+
+**value** _Closure_: you can set it to an anonymous function with the following signature:
```php
function($data) {}
```
-**defaultValue** *string*: default value of input
+**defaultValue** _string_: default value of input
-**items** *array*|*Closure*: the items for input with type dropDownList, listBox, checkboxList, radioList
-or anonymous function which return array of items and has the following signature:
+**items** _array_\|_Closure_: the items for input with type dropDownList, listBox, checkboxList, radioList or anonymous function which return array of items and has the following signature:
```php
function($data) {}
```
-**options** *array*|*Closure*: the HTML attributes for the input, you can set it as array
-or an anonymous function with the following signature:
+**options** _array_\|_Closure_: the HTML attributes for the input, you can set it as array or an anonymous function with the following signature:
```php
function($data) {}
```
-**headerOptions** *array*: the HTML attributes for the header cell
+**headerOptions** _array_: the HTML attributes for the header cell
+
+**enableError** _boolean_: whether to render inline error for the input. Default to `false`
+
+**errorOptions** _array_: the HTMl attributes for the error tag
+
+**nameSuffix** _string_: the unique prefix for attribute's name to avoid id duplication e.g. in case of using several copies of the widget on a page and one column is a Select2 widget
-**enableError** *boolean*: whether to render inline error for the input. Default to `false`
+**tabindex** _integer_: use it to customize a form element `tabindex`
-**errorOptions** *array*: the HTMl attributes for the error tag
+**attributeOptions** _array_: client-side options of the attribute, e.g. enableAjaxValidation. You can use this property for custom configuration of the column (attribute). By default, the column will use options which are defined on widget level.
+_Supported versions >= 2.1.0
-##Input types
+**columnOptions** _array|\Closure_: the HTML attributes for the indivdual table body column. This can be either an array specifying the common HTML attributes for indivdual body column, or an anonymous function that returns an array of the HTML attributes.
+
+It should have the following signature:
+```php
+function ($model, $index, $context)
+```
+* `$model`: the current data model being rendered
+* `$index`: the zero-based index of the data model in the model array
+* `$context`: the widget object
+
+_Supported versions >= 2.18.0_
+
+**inputTemplate** _string_: the template of input for customize view. Default is `{input}`.
+
+**Example**
+
+`
{input}
`
+
+## Input types
Each column in a row can has their own type. Widget supports:
-- all yii2 html input types:
- - `textInput`
- - `dropDownList`
- - `radioList`
- - `textarea`
- - For more detail look at [Html helper class](http://www.yiiframework.com/doc-2.0/yii-helpers-html.html)
-- input widget (widget that extends from `InputWidget` class). For example, `yii\widgets\MaskedInput`
-- `static` to output a static HTML content
+* all yii2 html input types:
+ * `textInput`
+ * `dropDownList`
+ * `radioList`
+ * `textarea`
+ * For more detail look at [Html helper class](http://www.yiiframework.com/doc-2.0/yii-helpers-html.html)
+* input widget \(widget that extends from `InputWidget` class\). For example, `yii\widgets\MaskedInput`
+* `static` to output a static HTML content
For using widget as column input you may use the following code:
```php
-[
- 'name' => 'phone',
- 'title' => 'Phone number',
- 'type' => \yii\widgets\MaskedInput::className(),
- 'options' => [
- 'class' => 'input-phone',
- 'mask' => '999-999-99-99'
- ]
-]
-```
\ No newline at end of file
+echo $form->field($model, 'phones')->widget(MultipleInput::className(), [
+...
+ 'columns' => [
+ ...
+ [
+ 'name' => 'phones',
+ 'title' => $model->getAttributeLabel('phones'),
+ 'type' => \yii\widgets\MaskedInput::className(),
+ 'options' => [
+ 'class' => 'input-phone',
+ 'mask' => '999-999-99-99',
+ ],
+ ],
+ ],
+])->label(false);
+```
+
diff --git a/docs/getting-started.md b/docs/getting-started.md
new file mode 100644
index 0000000..2e1daa9
--- /dev/null
+++ b/docs/getting-started.md
@@ -0,0 +1,133 @@
+# Getting started
+
+I found this small guide here [https://stackoverflow.com/a/51849747](https://stackoverflow.com/a/51849747) and I think it is a good example of basic usage of the widget
+
+## Question
+
+I want to generate a different number of rows with values from my database. How can I do this?
+
+I can design my columns in view and edit data manually after a page was generated. But miss how to program the number of rows and their values in the view.
+
+My code is as follows:
+
+```text
+ = $form->field($User, 'User')->widget(MultipleInput::className(), [
+ 'min' => 0,
+ 'max' => 4,
+ 'columns' => [
+ [
+ 'name' => 'name',
+ 'title' => 'Name',
+ 'type' => 'textInput',
+ 'options' => [
+ 'onchange' => $onchange,
+ ],
+ ],
+ [
+ 'name' => 'birth',
+ 'type' => \kartik\date\DatePicker::className(),
+ 'title' => 'Birth',
+ 'value' => function($data) {
+ return $data['day'];
+ },
+
+ 'options' => [
+ 'pluginOptions' => [
+ 'format' => 'dd.mm.yyyy',
+ 'todayHighlight' => true
+ ]
+ ]
+ ],
+
+ ]
+ ])->label(false);
+```
+
+How can I make \(for example\) 8 rows with different values, and also have the ability to edit/remove/update some of them?
+
+## Answer
+
+You need to look into the documentation as it says that you need to assign a separate field into the model which will store all the schedule in form of JSON and then provide it back to the field when editing/updating the model.
+
+You have not added the appropriate model to verify how are you creating the field User in your given case above. so, I will try to create a simple example that will help you implement it in your scenario.
+
+For Example.
+
+You have to store a user in the database along with his favorite books.
+
+```text
+User
+id, name, email
+
+Books
+id, name
+```
+
+Create a field/column in your User table with the name schedule of type text, you can write a migration or add manually. Add it to the rules in the User model as safe.
+
+like below
+
+```text
+public function rules() {
+ return [
+ ....//other rules
+ [ [ 'schedule'] , 'safe' ]
+ ];
+}
+```
+
+Add the widget to the newly created column in ActiveForm
+
+```text
+echo $form->field($model,'schedule')->widget(MultipleInput::class,[
+ 'max' => 4,
+ 'columns' => [
+ [
+ 'name' => 'book_id',
+ 'type' => 'dropDownList',
+ 'title' => 'Book',
+ 'items' => ArrayHelper::map( Books::find()->asArray()->all (),'id','name'),
+ ],
+ ]
+
+]);
+```
+
+When saving the User model convert the array to JSON string
+
+```text
+if( Yii::$app->request->isPost && $model->load(Yii::$app->request->post()) ){
+ $model->schedule = \yii\helpers\Json::encode($model->schedule);
+ $model->save();
+}
+```
+
+Override the afterFind\(\) of the User model to covert the JSON back to the array before loading the form
+
+```text
+public function afterFind() {
+ parent::afterFind();
+ $this->schedule = \yii\helpers\Json::decode($this->schedule);
+}
+```
+
+Now when saved the schedule field against the current user will have the JSON for the selected rows for the books, as many selected, for example, if I saved three books having ids\(1,2,3\) then it will have JSON
+
+```text
+{
+ "0": {
+ "book_id": "1"
+ },
+ "2": {
+ "book_id": "2"
+ },
+ "3": {
+ "book_id": "3"
+ }
+}
+```
+
+The above JSON will be converted to an array in the afterFind\(\) so that the widget loads the saved schedule when you EDIT the record.
+
+Now go to your update page or edit the newly saved model you will see the books loaded automatically.
+
diff --git a/docs/icons.md b/docs/icons.md
new file mode 100644
index 0000000..c805877
--- /dev/null
+++ b/docs/icons.md
@@ -0,0 +1,40 @@
+# Using other icon libraries
+
+Multiple input and Tabular input widgets now support FontAwesome and indeed any other icon library you chose to integrate into your project.
+
+To take advantage of this, please proceed as follows:
+
+1. Include the preferred icon library in your project. If you wish to use **font awesome**, you can use the included FontAwesomeAsset which will integrate the free fa from their CDN;
+2. Add a mapping for your preferred icon library if it is not in the `iconMap` array of the widget, like the following;
+
+```text
+public $iconMap = [
+ 'glyphicons' => [
+ 'drag-handle' => 'glyphicon glyphicon-menu-hamburger',
+ 'remove' => 'glyphicon glyphicon-remove',
+ 'add' => 'glyphicon glyphicon-plus',
+ 'clone' => 'glyphicon glyphicon-duplicate',
+ ],
+ 'fa' => [
+ 'drag-handle' => 'fa fa-bars',
+ 'remove' => 'fa fa-times',
+ 'add' => 'fa fa-plus',
+ 'clone' => 'fa fa-files-o',
+ ],
+ 'my-amazing-icons' => [
+ 'drag-handle' => 'my my-bars',
+ 'remove' => 'my my-times',
+ 'add' => 'my my-plus',
+ 'clone' => 'my my-files',
+ ]
+];
+```
+
+3. Set the preferred icon source
+
+```text
+ public $iconSource = 'my-amazing-icons';
+```
+
+If you do none of the above, the default behavior which assumes you are using `glyphicons` is retained.
+
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000..e8dbbcf
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,11 @@
+# Yii2 Multiple input widget.
+Yii2 widget for handle multiple inputs for an attribute of model and tabular input for batch of models.
+
+[](https://packagist.org/packages/unclead/yii2-multiple-input)
+[](https://packagist.org/packages/unclead/yii2-multiple-input)
+[](https://packagist.org/packages/unclead/yii2-multiple-input)
+[](https://packagist.org/packages/unclead/yii2-multiple-input)
+[](https://packagist.org/packages/unclead/yii2-multiple-input)
+
+## Latest release
+The latest stable version of the extension is v2.25.0 Follow the [instruction](./UPGRADE.md) for upgrading from previous versions
diff --git a/docs/installation.md b/docs/installation.md
new file mode 100644
index 0000000..8a9b853
--- /dev/null
+++ b/docs/installation.md
@@ -0,0 +1,18 @@
+# Installation
+
+The preferred way to install this extension is through [composer](http://getcomposer.org/download/).
+
+Either run
+
+```text
+php composer.phar require unclead/yii2-multiple-input "~2.0"
+```
+
+or add
+
+```text
+"unclead/yii2-multiple-input": "~2.0"
+```
+
+to the `require`section of your `composer.json` file.
+
diff --git a/docs/javascript-events.md b/docs/javascript-events.md
new file mode 100644
index 0000000..5a31c25
--- /dev/null
+++ b/docs/javascript-events.md
@@ -0,0 +1,86 @@
+# Javascript events
+
+This widget has following events:
+
+* `afterInit`: triggered after initialization
+* `afterAddRow`: triggered after new row insertion
+* `beforeDeleteRow`: triggered before the row removal
+* `afterDeleteRow`: triggered after the row removal
+* `afterDropRow`: triggered after drop the row when sortable mode is on
+
+**Example**
+
+```javascript
+jQuery('#multiple-input').on('afterInit', function(){
+ console.log('calls on after initialization event');
+}).on('beforeAddRow', function(e, row, currentIndex) {
+ console.log('calls on before add row event');
+}).on('afterAddRow', function(e, row, currentIndex) {
+ console.log('calls on after add row event');
+}).on('beforeDeleteRow', function(e, row, currentIndex){
+ // row - HTML container of the current row for removal.
+ // For TableRenderer it is tr.multiple-input-list__item
+ console.log('calls on before remove row event.');
+ return confirm('Are you sure you want to delete row?')
+}).on('afterDeleteRow', function(e, row, currentIndex){
+ console.log('calls on after remove row event');
+ console.log(row);
+}).on('afterDropRow', function(e, item){
+ console.log('calls on after drop row', item);
+});
+```
+
+## JavaScript operations
+
+### add
+
+Adding new row with specified settings.
+
+Input arguments:
+
+* _object_ - values for inputs, can be filled with tags for dynamically added options for select \(for ajax select\).
+
+Example:
+
+```javascript
+$('#multiple-input').multipleInput('add', {first: 10, second: 'second '});
+```
+
+### remove
+
+Remove row with specified index.
+
+Input arguments:
+
+* _integer_ - row number for removing, if not specified then removes last row.
+
+Example:
+
+```javascript
+$('#multiple-input').multipleInput('remove', 2);
+```
+
+### clear
+
+Remove all rows
+
+```javascript
+$('#multiple-input').multipleInput('clear');
+```
+
+### option
+
+Get or set a particular option
+
+Input arguments:
+
+* _string_ - a name of an option
+* _mixed_ - a value of an option \(optional\). If specified will be used as a new value of an option;
+
+Example:
+
+```javascript
+$('#multiple-input').multipleInput('option', 'max');
+$('#multiple-input').multipleInput('option', 'max', 10);
+```
+
diff --git a/docs/javascript.md b/docs/javascript.md
deleted file mode 100644
index 203872e..0000000
--- a/docs/javascript.md
+++ /dev/null
@@ -1,41 +0,0 @@
-#JavaScript events
-
-This widget has following events:
- - `afterInit`: triggered after initialization
- - `afterAddRow`: triggered after new row insertion
- - `beforeDeleteRow`: triggered before the row removal
- - `afterDeleteRow`: triggered after the row removal
-
-**Example**
-
-```js
-jQuery('#multiple-input').on('afterInit', function(){
- console.log('calls on after initialization event');
-}).on('beforeAddRow', function(e) {
- console.log('calls on before add row event');
-}).on('afterAddRow', function(e) {
- console.log('calls on after add row event');
-}).on('beforeDeleteRow', function(e, row){
- // row - HTML container of the current row for removal.
- // For TableRenderer it is tr.multiple-input-list__item
- console.log('calls on before remove row event.');
- return confirm('Are you sure you want to delete row?')
-}).on('afterDeleteRow', function(){
- console.log('calls on after remove row event');
-});
-```
-
-#JavaScript operations
-
-Dynamically operations in widget:
- - `add`: adding new row, **param** *object*: object with values for inputs, can be filled with tags for dynamically added options for select (for ajax select).
- - `remove`: remove row, **param** *integer*: row number for removing, if not specified then removes last row.
- - `clear`: remove all rows
-
-**Examples**
-
-```js
-$('#multiple-input').multipleInput('add', {first: 10, second: ' second '});
-$('#multiple-input').multipleInput('remove', 2);
-$('#multiple-input').multipleInput('clear');
-```
\ No newline at end of file
diff --git a/docs/multiple_input_embedded.md b/docs/multiple_input_embedded.md
deleted file mode 100644
index e69de29..0000000
diff --git a/docs/multiple_input_multiple.md b/docs/multiple_input_multiple.md
deleted file mode 100644
index b04d267..0000000
--- a/docs/multiple_input_multiple.md
+++ /dev/null
@@ -1,119 +0,0 @@
-#Multiple columns example
-
-
-
-For example you want to have an interface for manage user schedule. For simplicity we will store the schedule in json string.
-
-In this case you can use `yii2-multiple-input` widget for supporting multiple inputs how to describe below.
-
-Our test model can looks like as the following snippet
-
-```php
-class ExampleModel extends Model
-{
- public $schedule;
-
- public function init()
- {
- parent::init();
-
- $this->schedule = [
- [
- 'day' => '27.02.2015',
- 'user_id' => 1,
- 'priority' => 1
- ],
- [
- 'day' => '27.02.2015',
- 'user_id' => 2,
- 'priority' => 2
- ],
- ];
- }
-```
-
-Then we have to use `MultipleInput` widget for rendering form field in the view file
-
-```php
-use yii\bootstrap\ActiveForm;
-use unclead\widgets\MultipleInput;
-use unclead\widgets\examples\models\ExampleModel;
-use yii\helpers\Html;
-
-/* @var $this \yii\base\View */
-/* @var $model ExampleModel */
-?>
-
- true,
- 'enableClientValidation' => false,
- 'validateOnChange' => false,
- 'validateOnSubmit' => true,
- 'validateOnBlur' => false,
-]);?>
-
-= $form->field($model, 'schedule')->widget(MultipleInput::className(), [
- 'limit' => 4,
- 'columns' => [
- [
- 'name' => 'user_id',
- 'type' => 'dropDownList',
- 'title' => 'User',
- 'defaultValue' => 1,
- 'items' => [
- 1 => 'User 1',
- 2 => 'User 2'
- ]
- ],
- [
- 'name' => 'day',
- 'type' => \kartik\date\DatePicker::className(),
- 'title' => 'Day',
- 'value' => function($data) {
- return $data['day'];
- },
- 'items' => [
- '0' => 'Saturday',
- '1' => 'Monday'
- ],
- 'options' => [
- 'pluginOptions' => [
- 'format' => 'dd.mm.yyyy',
- 'todayHighlight' => true
- ]
- ]
- ],
- [
- 'name' => 'priority',
- 'title' => 'Priority',
- 'enableError' => true,
- 'options' => [
- 'class' => 'input-priority'
- ]
- ]
- ]
- ]);
-?>
-= Html::submitButton('Update', ['class' => 'btn btn-success']);?>
-
-```
-
-
-For validation the schedule you can use the following code
-
-```php
-
- public function validateSchedule($attribute)
- {
- $requiredValidator = new RequiredValidator();
-
- foreach($this->$attribute as $index => $row) {
- $error = null;
- $requiredValidator->validate($row['priority'], $error);
- if (!empty($error)) {
- $key = $attribute . '[' . $index . '][priority]';
- $this->addError($key, $error);
- }
- }
- }
-```
diff --git a/docs/multiple_input_single.md b/docs/multiple_input_single.md
deleted file mode 100644
index f39f193..0000000
--- a/docs/multiple_input_single.md
+++ /dev/null
@@ -1,77 +0,0 @@
-#Single column example
-
-
-
-For example your application contains the model `User` that has the related model `UserEmail`
-You can add virtual attribute `emails` for collect emails from form and then you can save them to database.
-
-In this case you can use `yii2-multiple-input` widget for supporting multiple inputs how to describe below.
-
-First of all we have to declare virtual attribute in model
-
-```php
-class ExampleModel extends Model
-{
- /**
- * @var array virtual attribute for keeping emails
- */
- public $emails;
-```
-
-Then we have to use `MultipleInput` widget for rendering form field in the view file
-
-```php
-use yii\bootstrap\ActiveForm;
-use unclead\widgets\MultipleInput;
-use unclead\widgets\examples\models\ExampleModel;
-use yii\helpers\Html;
-
-/* @var $this \yii\base\View */
-/* @var $model ExampleModel */
-?>
-
- true,
- 'enableClientValidation' => false,
- 'validateOnChange' => false,
- 'validateOnSubmit' => true,
- 'validateOnBlur' => false,
-]);?>
-
-= $form->field($model, 'emails')->widget(MultipleInput::className(), [
- 'limit' => 4,
- ]);
-?>
-= Html::submitButton('Update', ['class' => 'btn btn-success']);?>
-
-```
-
-Options `limit` means that user able to input only 4 emails
-
-For validation emails you can use the following code
-
-```php
- /**
- * Email validation.
- *
- * @param $attribute
- */
- public function validateEmails($attribute)
- {
- $items = $this->$attribute;
-
- if (!is_array($items)) {
- $items = [];
- }
-
- foreach ($items as $index => $item) {
- $validator = new EmailValidator();
- $error = null;
- $validator->validate($item, $error);
- if (!empty($error)) {
- $key = $attribute . '[' . $index . ']';
- $this->addError($key, $error);
- }
- }
- }
-```
diff --git a/docs/renderers.md b/docs/renderers.md
index 201d857..67d33bb 100644
--- a/docs/renderers.md
+++ b/docs/renderers.md
@@ -1,5 +1,60 @@
-##Renderers
+# Renderers
-> Section is under development
+Currently widget supports three type of renderers
+
+## TableRenderer
+
+
+
+This renderer is enabled by default.
+
+## ListRenderer
+
+
+
+To enable this renderer you have to use an option `rendererClass`
+
+```php
+field($model, 'schedule')->widget(MultipleInput::className(), [
+ 'rendererClass' => \unclead\multipleinput\renderers\ListRenderer::className(),
+ 'max' => 4,
+ 'allowEmptyList' => true,
+ 'rowOptions' => function($model) {
+ $options = [];
+
+ if ($model['priority'] > 1) {
+ $options['class'] = 'danger';
+ }
+ return $options;
+ },
+```
+
+## DivRenderer
+
+
+
+To enable this renderer you have to use an option `rendererClass`
+
+```php
+field($model, 'schedule')->widget(MultipleInput::className(), [
+ 'rendererClass' => \unclead\multipleinput\renderers\ListRenderer::class,
+ 'addButtonPosition' => MultipleInput::POS_ROW, // show add button inside of the row
+ 'extraButtons' => function ($model, $index, $context) {
+ if ($index === 0) {
+ return Html::tag('div', Yii::t('object', 'Add object'), ['class' => 'mi-after-add']);
+ }
+
+ return Html::tag('div', Yii::t('object', 'Remove object'), ['class' => 'mi-after-remove']);
+ },
+ 'layoutConfig' => [
+ 'offsetClass' => 'col-md-offset-2',
+ 'labelClass' => 'col-md-2',
+ 'wrapperClass' => 'col-md-6',
+ 'errorClass' => 'col-md-offset-2 col-md-6',
+ 'buttonActionClass' => 'col-md-offset-1 col-md-2',
+ ],
+...
+```
-Currently widget supports only `TableRenderer` which renders content in table format.
diff --git a/docs/tabular_input.md b/docs/tabular_input.md
deleted file mode 100644
index 621ea7d..0000000
--- a/docs/tabular_input.md
+++ /dev/null
@@ -1,167 +0,0 @@
-# Tabular input
-
-For example you want to have an interface for manage some abstract items via tabular input.
-
-In this case you can use `yii2-multiple-input` widget for supporting tabular input how to describe below.
-
-Our test model can looks like as the following snippet
-
-```php
-namespace unclead\widgets\examples\models;
-
-use Yii;
-use yii\base\Model;
-// you have to install https://github.com/vova07/yii2-fileapi-widget
-use vova07\fileapi\behaviors\UploadBehavior;
-
-/**
- * Class Item
- * @package unclead\widgets\examples\models
- */
-class Item extends Model
-{
- public $title;
- public $description;
- public $file;
- public $date;
-
- public function behaviors()
- {
- return [
- 'uploadBehavior' => [
- 'class' => UploadBehavior::className(),
- 'attributes' => [
- 'file' => [
- 'path' => Yii::getAlias('@webroot') . '/images/',
- 'tempPath' => Yii::getAlias('@webroot') . '/images/tmp/',
- 'url' => '/images/'
- ],
- ]
- ]
- ];
- }
-
- public function rules()
- {
- return [
- [['title', 'description'], 'required'],
- ['file', 'safe']
- ];
- }
-}
-```
-
-Then we have to use `TabularInput` widget for rendering form field in the view file
-
-```php
-
-
- 'tabular-form',
- 'enableAjaxValidation' => true,
- 'enableClientValidation' => false,
- 'validateOnChange' => false,
- 'validateOnSubmit' => true,
- 'validateOnBlur' => false,
- 'options' => [
- 'enctype' => 'multipart/form-data'
- ]
-]) ?>
-
-= TabularInput::widget([
- 'models' => $models,
- 'attributeOptions' => [
- 'enableAjaxValidation' => true,
- 'enableClientValidation' => false,
- 'validateOnChange' => false,
- 'validateOnSubmit' => true,
- 'validateOnBlur' => false,
- ],
- 'columns' => [
- [
- 'name' => 'title',
- 'title' => 'Title',
- 'type' => \unclead\widgets\MultipleInputColumn::TYPE_TEXT_INPUT,
- ],
- [
- 'name' => 'description',
- 'title' => 'Description',
- ],
- [
- 'name' => 'file',
- 'title' => 'File',
- 'type' => \vova07\fileapi\Widget::className(),
- 'options' => [
- 'settings' => [
- 'url' => ['site/fileapi-upload']
- ]
- ]
- ],
- [
- 'name' => 'date',
- 'type' => \kartik\date\DatePicker::className(),
- 'title' => 'Day',
- 'options' => [
- 'pluginOptions' => [
- 'format' => 'dd.mm.yyyy',
- 'todayHighlight' => true
- ]
- ],
- 'headerOptions' => [
- 'style' => 'width: 250px;',
- 'class' => 'day-css-class'
- ]
- ],
- ],
-]) ?>
-
-
-= Html::submitButton('Update', ['class' => 'btn btn-success']);?>
-
-```
-
-
-Your action can looks like the following code
-
-```php
-/**
- * Class TabularInputAction
- * @package unclead\widgets\examples\actions
- */
-class TabularInputAction extends Action
-{
- public function run()
- {
- Yii::setAlias('@unclead-examples', realpath(__DIR__ . '/../'));
-
- $models = [new Item()];
- $request = Yii::$app->getRequest();
- if ($request->isPost && $request->post('ajax') !== null) {
- $data = Yii::$app->request->post('Item', []);
- foreach (array_keys($data) as $index) {
- $models[$index] = new Item();
- }
- Model::loadMultiple($models, Yii::$app->request->post());
- Yii::$app->response->format = Response::FORMAT_JSON;
- $result = ActiveForm::validateMultiple($models);
- return $result;
- }
-
- if (Model::loadMultiple($models, Yii::$app->request->post())) {
- // your magic
- }
-
-
- return $this->controller->render('@unclead-examples/views/tabular-input.php', ['models' => $models]);
- }
-}
-```
diff --git a/docs/tips.md b/docs/tips-and-tricks.md
similarity index 52%
rename from docs/tips.md
rename to docs/tips-and-tricks.md
index 6d2d51d..caa449c 100644
--- a/docs/tips.md
+++ b/docs/tips-and-tricks.md
@@ -1,22 +1,12 @@
-#Tips and tricks
+# Tips and tricks
- - [How to customize buttons](#how-to-customize-buttons)
- - [Work with empty list](#work-with-empty-list)
- - [Guess column title](#guess-column-title)
- - [Ajax loading of a widget](#ajax-loading)
- - [Use of a widget's placeholder](#using-placeholder)
- - [Custom index of the row](#custom-index)
- - [Embedded MultipleInput widget](#embedded)
+## How to customize buttons
-##How to customize buttons
-
-You can customize `add` and `remove` buttons via `addButtonOptions` and `removeButtonOptions`. Here is the simple example
-how you can use those options:
+You can customize `add` and `remove` buttons via `addButtonOptions` and `removeButtonOptions`. Here is a simple example of how you can use those options:
```php
-
echo $form->field($model, 'emails')->widget(MultipleInput::className(), [
- 'limit' => 5,
+ 'max' => 5,
'addButtonOptions' => [
'class' => 'btn btn-success',
'label' => 'add' // also you can use html code
@@ -26,53 +16,59 @@ how you can use those options:
]
])
->label(false);
-
```
-##Work with an empty list
+## How to add content after the buttons
-In some cases you need to have the ability to delete all rows in the list. For this purpose you can use option `allowEmptyList` like in the example below:
+You can add html content after `add` and `remove` buttons via `extraButtons`.
```php
+ echo $form->field($model, 'field')->widget(MultipleInput::className(), [
+ 'rendererClass' => \unclead\multipleinput\renderers\ListRenderer::class,
+ 'extraButtons' => function ($model, $index, $context) {
+ return Html::tag('span', '', ['class' => "btn-show-hide-{$index} glyphicon glyphicon-eye-open btn btn-info"]);
+ },
+ ])
+ ->label(false);
+```
+
+## Work with an empty list
+In some cases, you need to have the ability to delete all rows in the list. For this purpose, you can use option `allowEmptyList` like in the example below:
+
+```php
echo $form->field($model, 'emails')->widget(MultipleInput::className(), [
- 'limit' => 5,
+ 'max' => 5,
'allowEmptyList' => true
])
->label(false);
-
```
-Also you can set `0` in `min` option if you don't need first blank row when data is empty.
+Also, you can set `0` in `min` option if you don't need the first blank row when data is empty.
-##Guess column title
+## Guess column title
-Sometimes you can use the widget without defining columns but you want to have the column header of the table.
-In this case you can use `enableGuessTitle` option like in the example below:
+Sometimes you can use the widget without defining columns but you want to have the column header of the table. In this case, you can use the option `enableGuessTitle` like in the example below:
```php
-
echo $form->field($model, 'emails')->widget(MultipleInput::className(), [
- 'limit' => 5,
+ 'max' => 5,
'allowEmptyList' => true,
'enableGuessTitle' => true
])
->label(false);
-
```
-##Ajax loading of a widget
-
-Assume you want to load a widget via ajax and then show it inside modal window. In this case you MUST:
+## Ajax loading of a widget
-- Ensure that you specified ID of widget otherwise the widget will get random ID and it can be the same as id of others elements on the page.
-- Ensure that you use the widget inside ActiveForm because it works incorrectly in this case.
+Assume you want to load a widget via ajax and then show it inside the modal window. In this case, you MUST:
-You can fina an example of usage in a discussion of [issue](https://github.com/unclead/yii2-multiple-input/issues/58)
+* Ensure that you specified the ID of the widget otherwise the widget will get a random ID and it can be the same as the ID of others elements on the page.
+* Ensure that you use the widget inside ActiveForm because it works incorrectly in this case.
-##Use of a widget's placeholder
+## Use of a widget's placeholder
-You can use a placeholder `{multiple_index}` in a widget configuration, e.g. for implementation of dependent drop down lists.
+You can use a placeholder `{multiple_index}` in a widget configuration, e.g. for implementation of dependent drop-down lists.
```php
= $form->field($model, 'field')->widget(MultipleInput::className(), [
@@ -118,10 +114,9 @@ JS
**Important** Ensure that you added ID of widget to a base placeholder `multiple_index`
-##Custom index of the row
+## Custom index of the row
-Assume that you want to set specific index for each row. In this case you can pass the `data` attribute as associative array
-as in the example below:
+Assume that you want to set a specific index for each row. In this case, you can pass the `data` attribute as an associative array as in the example below:
```php
= $form->field($model, 'field')->widget(MultipleInput::className(), [
@@ -143,15 +138,13 @@ as in the example below:
]
...
-
```
-
-##Embedded MultipleInput widget
+## Embedded MultipleInput widget
You can use nested `MultipleInput` as in the example below:
-```
+```php
echo MultipleInput::widget([
'model' => $model,
'attribute' => 'questions',
@@ -181,4 +174,45 @@ echo MultipleInput::widget([
]);
```
-But in this case you have to pass `attributeOptions` to the widget otherwise you will not be able to use ajax or client side validation of data.
+But in this case, you have to pass `attributeOptions` to the widget otherwise, you will not be able to use ajax or client-side validation of data.
+
+## Client validation
+
+Apart from ajax validation, you can use client validation but in this case, you MUST set property `form`. Also, ensure that you set `enableClientValidation` to `true` value in property `attributeOptions`. If you want to use client validation for a particular column you can use the property `attributeOptions`. An example of using client validation is listed below:
+
+```php
+= TabularInput::widget([
+ 'models' => $models,
+ 'form' => $form,
+ 'attributeOptions' => [
+ 'enableAjaxValidation' => true,
+ 'enableClientValidation' => false,
+ 'validateOnChange' => false,
+ 'validateOnSubmit' => true,
+ 'validateOnBlur' => false,
+ ],
+ 'columns' => [
+ [
+ 'name' => 'id',
+ 'type' => TabularColumn::TYPE_HIDDEN_INPUT
+ ],
+ [
+ 'name' => 'title',
+ 'title' => 'Title',
+ 'type' => TabularColumn::TYPE_TEXT_INPUT,
+ 'attributeOptions' => [
+ 'enableClientValidation' => true,
+ 'validateOnChange' => true,
+ ],
+ 'enableError' => true
+ ],
+ [
+ 'name' => 'description',
+ 'title' => 'Description',
+ ],
+ ],
+]) ?>
+```
+
+In the example above we use client validation for column `title` and ajax validation for column `description`. As you can seee we also enabled `validateOnChange` for column `title` thus you can use all client-side options from the `ActiveField` class.
+
diff --git a/docs/usage.md b/docs/usage.md
index 96a4962..654c8a3 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -1,52 +1,213 @@
-##Usage
+# Usage
-> You can find source code of examples [here](./examples/)
+You can find the source code of examples [here](https://github.com/unclead/yii2-multiple-input/tree/master/examples)
-- [Input with one column](#one-column)
-- [Input with multiple column in each row](#multiple-columns)
-- [Tabular input](#tabular)
+## One column
-##Input with one column
+
-
+For example, your application contains the model `User` that has the related model `UserEmail` You can add virtual attribute `emails` for collect emails from a form and then you can save them to the database.
-For example you want to have an ability of entering several emails of user on profile page.
-In this case you can use yii2-multiple-input widget like in the following code
+In this case, you can use `yii2-multiple-input` widget for supporting multiple inputs how to describe below.
+
+First of all, we have to declare a virtual attribute in the model
```php
-use unclead\widgets\MultipleInput;
+class ExampleModel extends Model
+{
+ /**
+ * @var array virtual attribute for keeping emails
+ */
+ public $emails;
+```
-...
+Then we have to use `MultipleInput` widget for rendering form field in the view file
-field($model, 'emails')->widget(MultipleInput::className(), [
- 'limit' => 6,
- 'allowEmptyList' => false,
- 'enableGuessTitle' => true,
- 'min' => 2, // should be at least 2 rows
- 'addButtonPosition' => MultipleInput::POS_HEADER // show add button in the header
- ])
- ->label(false);
+```php
+use yii\bootstrap\ActiveForm;
+use unclead\multipleinput\MultipleInput;
+use unclead\multipleinput\examples\models\ExampleModel;
+use yii\helpers\Html;
+
+/* @var $this \yii\base\View */
+/* @var $model ExampleModel */
+?>
+
+ true,
+ 'enableClientValidation' => false,
+ 'validateOnChange' => false,
+ 'validateOnSubmit' => true,
+ 'validateOnBlur' => false,
+]);?>
+
+= $form->field($model, 'emails')->widget(MultipleInput::className(), [
+ 'max' => 4,
+ ]);
+?>
+= Html::submitButton('Update', ['class' => 'btn btn-success']);?>
+
+```
+
+Options `max` means that a user is able to input only 4 emails
+
+For validation emails, you can use the following code
+
+```php
+ /**
+ * Email validation.
+ *
+ * @param $attribute
+ */
+ public function validateEmails($attribute)
+ {
+ $items = $this->$attribute;
+
+ if (!is_array($items)) {
+ $items = [];
+ }
+
+ foreach ($items as $index => $item) {
+ $validator = new EmailValidator();
+ $error = null;
+ $validator->validate($item, $error);
+ if (!empty($error)) {
+ $key = $attribute . '[' . $index . ']';
+ $this->addError($key, $error);
+ }
+ }
+ }
+```
+
+## Multiple columns
+
+
+
+For example, you want to have an interface for manage a user schedule. For simplicity, we will store the schedule in json string.
+
+In this case, you can use `yii2-multiple-input` widget for supporting multiple inputs how to describe below.
+
+Our test model can look like as the following snippet
+
+```php
+class ExampleModel extends Model
+{
+ public $schedule;
+
+ public function init()
+ {
+ parent::init();
+
+ $this->schedule = [
+ [
+ 'day' => '27.02.2015',
+ 'user_id' => 1,
+ 'priority' => 1
+ ],
+ [
+ 'day' => '27.02.2015',
+ 'user_id' => 2,
+ 'priority' => 2
+ ],
+ ];
+ }
+```
+
+Then we have to use `MultipleInput` widget for rendering form field in the view file
+
+```php
+use yii\bootstrap\ActiveForm;
+use unclead\multipleinput\MultipleInput;
+use unclead\multipleinput\examples\models\ExampleModel;
+use yii\helpers\Html;
+
+/* @var $this \yii\base\View */
+/* @var $model ExampleModel */
+?>
+
+ true,
+ 'enableClientValidation' => false,
+ 'validateOnChange' => false,
+ 'validateOnSubmit' => true,
+ 'validateOnBlur' => false,
+]);?>
+
+= $form->field($model, 'schedule')->widget(MultipleInput::className(), [
+ 'max' => 4,
+ 'columns' => [
+ [
+ 'name' => 'user_id',
+ 'type' => 'dropDownList',
+ 'title' => 'User',
+ 'defaultValue' => 1,
+ 'items' => [
+ 1 => 'User 1',
+ 2 => 'User 2'
+ ]
+ ],
+ [
+ 'name' => 'day',
+ 'type' => \kartik\date\DatePicker::className(),
+ 'title' => 'Day',
+ 'value' => function($data) {
+ return $data['day'];
+ },
+ 'items' => [
+ '0' => 'Saturday',
+ '1' => 'Monday'
+ ],
+ 'options' => [
+ 'pluginOptions' => [
+ 'format' => 'dd.mm.yyyy',
+ 'todayHighlight' => true
+ ]
+ ]
+ ],
+ [
+ 'name' => 'priority',
+ 'title' => 'Priority',
+ 'enableError' => true,
+ 'options' => [
+ 'class' => 'input-priority'
+ ]
+ ]
+ ]
+ ]);
?>
+= Html::submitButton('Update', ['class' => 'btn btn-success']);?>
+
```
-You can find more detail about this use case [here](multiple_input_single.md)
+For validation of the schedule you can use the following code
-##Input with multiple column in each row
+```php
+ public function validateSchedule($attribute)
+ {
+ $requiredValidator = new RequiredValidator();
-
+ foreach($this->$attribute as $index => $row) {
+ $error = null;
+ $requiredValidator->validate($row['priority'], $error);
+ if (!empty($error)) {
+ $key = $attribute . '[' . $index . '][priority]';
+ $this->addError($key, $error);
+ }
+ }
+ }
+```
-For example you keep some data in json format in attribute of model. Imagine that it is an abstract user schedule with keys: user_id, day, priority
+For example, you keep some data in json format in an attribute of a model. Imagine that it is an abstract user schedule with keys: user\_id, day, priority
-On the edit page you want to be able to manage this schedule and you can you yii2-multiple-input widget like in the following code
+On the edit page, you want to be able to manage this schedule and you can you yii2-multiple-input widget like in the following code
```php
-use unclead\widgets\MultipleInput;
+use unclead\multipleinput\MultipleInput;
...
= $form->field($model, 'schedule')->widget(MultipleInput::className(), [
- 'limit' => 4,
+ 'max' => 4,
'columns' => [
[
'name' => 'user_id',
@@ -103,14 +264,87 @@ use unclead\widgets\MultipleInput;
?>
```
-You can find more detail about this use case [here](multiple_input_multiple.md)
+## Tabular input
+
+For example, you want to have an interface for manage some abstract items via tabular input.
+
+In this case, you can use `yii2-multiple-input` widget for supporting tabular input how to describe below.
+
+Our test model can look like as the following snippet
+
+```php
+namespace unclead\multipleinput\examples\models;
+
+use Yii;
+use yii\base\Model;
+// you have to install https://github.com/vova07/yii2-fileapi-widget
+use vova07\fileapi\behaviors\UploadBehavior;
+
+/**
+ * Class Item
+ * @package unclead\multipleinput\examples\models
+ */
+class Item extends Model
+{
+ public $title;
+ public $description;
+ public $file;
+ public $date;
+
+ public function behaviors()
+ {
+ return [
+ 'uploadBehavior' => [
+ 'class' => UploadBehavior::className(),
+ 'attributes' => [
+ 'file' => [
+ 'path' => Yii::getAlias('@webroot') . '/images/',
+ 'tempPath' => Yii::getAlias('@webroot') . '/images/tmp/',
+ 'url' => '/images/'
+ ],
+ ]
+ ]
+ ];
+ }
+
+ public function rules()
+ {
+ return [
+ [['title', 'description'], 'required'],
+ ['file', 'safe']
+ ];
+ }
+}
+```
-##Tabular input
+Then we have to use `TabularInput` widget for rendering form field in the view file
-For example you want to manage some models via tabular input. In this case you can use `TabularInput` widget which is based on `MultipleInput` widget.
-Use the following code for this purpose:
+Since version **2.18.0** you can configure `columnOptions` also.
```php
+
+
+ 'tabular-form',
+ 'enableAjaxValidation' => true,
+ 'enableClientValidation' => false,
+ 'validateOnChange' => false,
+ 'validateOnSubmit' => true,
+ 'validateOnBlur' => false,
+ 'options' => [
+ 'enctype' => 'multipart/form-data'
+ ]
+]) ?>
+
= TabularInput::widget([
'models' => $models,
'attributeOptions' => [
@@ -124,7 +358,7 @@ Use the following code for this purpose:
[
'name' => 'title',
'title' => 'Title',
- 'type' => TabularInputColumn::TYPE_TEXT_INPUT,
+ 'type' => \unclead\multipleinput\MultipleInputColumn::TYPE_TEXT_INPUT,
],
[
'name' => 'description',
@@ -138,6 +372,10 @@ Use the following code for this purpose:
'settings' => [
'url' => ['site/fileapi-upload']
]
+ ],
+ 'columnOptions' => [
+ 'style' => 'width: 250px;',
+ 'class' => 'custom-css-class'
]
],
[
@@ -157,6 +395,45 @@ Use the following code for this purpose:
],
],
]) ?>
+
+
+= Html::submitButton('Update', ['class' => 'btn btn-success']);?>
+
+```
+
+Your action can look like the following code
+
+```php
+/**
+ * Class TabularInputAction
+ * @package unclead\multipleinput\examples\actions
+ */
+class TabularInputAction extends Action
+{
+ public function run()
+ {
+ Yii::setAlias('@unclead-examples', realpath(__DIR__ . '/../'));
+
+ $models = [new Item()];
+ $request = Yii::$app->getRequest();
+ if ($request->isPost && $request->post('ajax') !== null) {
+ $data = Yii::$app->request->post('Item', []);
+ foreach (array_keys($data) as $index) {
+ $models[$index] = new Item();
+ }
+ Model::loadMultiple($models, Yii::$app->request->post());
+ Yii::$app->response->format = Response::FORMAT_JSON;
+ $result = ActiveForm::validateMultiple($models);
+ return $result;
+ }
+
+ if (Model::loadMultiple($models, Yii::$app->request->post())) {
+ // your magic
+ }
+
+
+ return $this->controller->render('@unclead-examples/views/tabular-input.php', ['models' => $models]);
+ }
+}
```
-You can find more detail about this use case [here](tabular_input.md)
\ No newline at end of file
diff --git a/examples/actions/EmbeddedInputAction.php b/examples/actions/EmbeddedInputAction.php
index caf5b07..58bfb3b 100644
--- a/examples/actions/EmbeddedInputAction.php
+++ b/examples/actions/EmbeddedInputAction.php
@@ -1,16 +1,16 @@
getItems();
diff --git a/examples/models/ExampleModel.php b/examples/models/ExampleModel.php
index 4ed990b..b05218d 100644
--- a/examples/models/ExampleModel.php
+++ b/examples/models/ExampleModel.php
@@ -1,6 +1,6 @@
5],
['emails', 'validateEmails'],
['phones', 'validatePhones'],
- ['schedule', 'validateSchedule'],
+ ['schedule', 'validateSchedule', 'skipOnEmpty' => false],
['questions', 'validateQuestions']
];
}
diff --git a/examples/models/Item.php b/examples/models/Item.php
index 61e870c..2a32feb 100644
--- a/examples/models/Item.php
+++ b/examples/models/Item.php
@@ -6,14 +6,14 @@
* @license https://github.com/unclead/yii2-multiple-input/blob/master/LICENSE.md
*/
-namespace unclead\widgets\examples\models;
+namespace unclead\multipleinput\examples\models;
use Yii;
use yii\base\Model;
/**
* Class Item
- * @package unclead\widgets\examples\models
+ * @package unclead\multipleinput\examples\models
*/
class Item extends Model
{
diff --git a/examples/views/embedded-input.php b/examples/views/embedded-input.php
index 306b91d..ba33087 100644
--- a/examples/views/embedded-input.php
+++ b/examples/views/embedded-input.php
@@ -1,24 +1,24 @@
false,
+ 'enableAjaxValidation' => true,
'enableClientValidation' => false,
'validateOnChange' => false,
'validateOnSubmit' => true,
'validateOnBlur' => false,
];
-$enableActiveForm = false;
+$enableActiveForm = true;
?>
false,
]);?>
+
Single column
field($model, 'emails')->widget(MultipleInput::className(), [
- 'limit' => 6,
+ 'max' => 6,
'allowEmptyList' => false,
+ 'sortable' => true,
'columns' => [
[
'name' => 'emails',
@@ -46,9 +48,12 @@
Multiple columns
field($model, 'schedule')->widget(MultipleInput::className(), [
- 'limit' => 4,
+echo $form->field($model, 'schedule')->label(false)->widget(MultipleInput::className(), [
+ 'id' => 'examplemodel-schedule',
+ 'max' => 4,
+ 'sortable' => true,
'allowEmptyList' => true,
+ 'showGeneralError' => true,
'rowOptions' => function($model) {
$options = [];
@@ -57,6 +62,8 @@
}
return $options;
},
+ 'cloneButton' => true,
+
'columns' => [
[
'name' => 'user_id',
@@ -105,7 +112,7 @@
'headerOptions' => [
'style' => 'width: 250px;',
'class' => 'day-css-class'
- ]
+ ],
],
[
'name' => 'priority',
@@ -117,7 +124,7 @@
]
],
[
- 'name' => 'comment',
+ 'name' => 'comment', // can be ommited in case of static column
'type' => MultipleInputColumn::TYPE_STATIC,
'value' => function($data) {
return Html::tag('span', 'static content', ['class' => 'label label-info']);
@@ -158,15 +165,19 @@
console.log('calls on after initialization event');
}).on('beforeAddRow', function(e) {
console.log('calls on before add row event');
- }).on('afterAddRow', function(e) {
- console.log('calls on after add row event');
+ return confirm('Are you sure you want to add row?')
+ }).on('afterAddRow', function(e, row) {
+ console.log('calls on after add row event', $(row));
}).on('beforeDeleteRow', function(e, item){
console.log(item);
console.log('calls on before remove row event');
return confirm('Are you sure you want to delete row?')
- }).on('afterDeleteRow', function(){
+ }).on('afterDeleteRow', function(e, item){
console.log('calls on after remove row event');
+ console.log('User_id:' + item.find('.list-cell__user_id').find('select').first().val());
+ }).on('afterDropRow', function(e, item){
+ console.log('calls on after drop row', item);
});
JS;
-$this->registerJs($js);
\ No newline at end of file
+$this->registerJs($js);
diff --git a/examples/views/tabular-input.php b/examples/views/tabular-input.php
index 4c6fdc4..bba351e 100644
--- a/examples/views/tabular-input.php
+++ b/examples/views/tabular-input.php
@@ -1,10 +1,10 @@
$models,
+ 'modelClass' => Item::class,
+ 'cloneButton' => true,
+ 'sortable' => true,
+ 'min' => 0,
+ 'addButtonPosition' => [
+ TabularInput::POS_HEADER,
+ TabularInput::POS_FOOTER,
+ TabularInput::POS_ROW
+ ],
+ 'layoutConfig' => [
+ 'offsetClass' => 'col-sm-offset-4',
+ 'labelClass' => 'col-sm-2',
+ 'wrapperClass' => 'col-sm-10',
+ 'errorClass' => 'col-sm-4'
+ ],
'attributeOptions' => [
- 'enableAjaxValidation' => true,
+ 'enableAjaxValidation' => true,
'enableClientValidation' => false,
- 'validateOnChange' => false,
- 'validateOnSubmit' => true,
- 'validateOnBlur' => false,
+ 'validateOnChange' => false,
+ 'validateOnSubmit' => true,
+ 'validateOnBlur' => false,
],
+ 'form' => $form,
'columns' => [
[
'name' => 'id',
@@ -36,31 +52,29 @@
'name' => 'title',
'title' => 'Title',
'type' => TabularColumn::TYPE_TEXT_INPUT,
+ 'attributeOptions' => [
+ 'enableClientValidation' => true,
+ 'validateOnChange' => true,
+ ],
+ 'defaultValue' => 'Test',
'enableError' => true
],
[
'name' => 'description',
'title' => 'Description',
],
-// [
-// 'name' => 'file',
-// 'title' => 'File',
-// 'type' => \vova07\fileapi\Widget::className(),
-// 'options' => [
-// 'settings' => [
-// 'url' => ['site/fileapi-upload']
-// ]
-// ]
-// ],
[
'name' => 'date',
- 'type' => \kartik\date\DatePicker::className(),
+ 'type' => '\kartik\date\DatePicker',
'title' => 'Day',
+ 'defaultValue' => '1970/01/01',
'options' => [
'pluginOptions' => [
- 'format' => 'dd.mm.yyyy',
- 'todayHighlight' => true
- ]
+ 'autoclose' => true,
+ 'format' => 'dd/mm/yyyy',
+ 'todayHighlight' => true,
+ ],
+
],
'headerOptions' => [
'style' => 'width: 250px;',
@@ -72,4 +86,4 @@
= Html::submitButton('Update', ['class' => 'btn btn-success']); ?>
-
\ No newline at end of file
+
diff --git a/gulpfile.js b/gulpfile.js
index 79206fc..5e2a310 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -1,18 +1,18 @@
-var gulp = require('gulp'),
- uglify = require('gulp-uglify'),
- concat = require('gulp-concat'),
- rename = require('gulp-rename');
+const {gulp, src, dest} = require('gulp');
+const uglify = require('gulp-uglify-es').default;
+const concat = require('gulp-concat');
+const rename = require('gulp-rename');
-gulp.task('js', function () {
+function build () {
var path = './src/assets/src/js/';
-
- return gulp.src([
+
+ return src([
path + 'jquery.multipleInput.js'
])
.pipe(concat('jquery.multipleInput.js'))
.pipe(uglify())
.pipe(rename({suffix: '.min'}))
- .pipe(gulp.dest(path));
-});
-
-gulp.task('default', ['js']);
\ No newline at end of file
+ .pipe(dest(path));
+};
+
+exports.default = build;
diff --git a/mkdocs.yml b/mkdocs.yml
new file mode 100644
index 0000000..e006c20
--- /dev/null
+++ b/mkdocs.yml
@@ -0,0 +1,19 @@
+site_name: Yii2 multiple input
+site_description: 'Yii2 widget to handle multiple inputs for an attribute of a model'
+site_author: 'Eugene Tupikov'
+docs_dir: docs/
+repo_name: 'unclead/yii2-multiple-input'
+repo_url: 'https://github.com/unclead/yii2-multiple-input'
+nav:
+ - About: index.md
+ - Installation: installation.md
+ - Getting started: getting-started.md
+ - Configuration: configuration.md
+ - Renderers: renderers.md
+ - JS events: javascript-events.md
+ - Clonning: clonning.md
+ - Tips and Tricks: tips-and-tricks.md
+ - Custom icons: icons.md
+ - Usage: usage.md
+theme:
+ name: 'material'
diff --git a/package.json b/package.json
index 693f6cb..f566264 100644
--- a/package.json
+++ b/package.json
@@ -1,9 +1,9 @@
{
"name": "jquery.multipleInput",
- "version": "1.3.1",
+ "version": "2.27.0",
"description": "jQuery multipleInput",
"scripts": {
- "build": "npm install && (gulp || node node_modules/gulp/bin/gulp.js)"
+ "build": "npm install && (gulp || node node_modules/gulp/bin/gulp.js)"
},
"repository": {
"type": "git",
@@ -14,7 +14,7 @@
"email": "unclead.nsk@gmail.com"
},
"keywords": [
- "jquery"
+ "jquery"
],
"license": "BSD-3-Clause",
"bugs": {
@@ -22,9 +22,9 @@
},
"homepage": "https://github.com/unclead/yii2-multiple-input",
"devDependencies": {
- "gulp": "^3.8.8",
- "gulp-uglify": "^1.0.1",
+ "gulp": "^4.0.2",
"gulp-concat": "^2.4.1",
- "gulp-rename": "^1.2.0"
+ "gulp-rename": "^1.4.0",
+ "gulp-uglify-es": "3.0.0"
}
}
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
new file mode 100644
index 0000000..fd3fa65
--- /dev/null
+++ b/phpunit.xml.dist
@@ -0,0 +1,22 @@
+
+
+
+
+ ./tests
+ ./vendor
+
+
+
+
+ ./tests/unit/
+
+
+
+
+
+
\ No newline at end of file
diff --git a/resources/images/clone-button.gif b/resources/images/clone-button.gif
new file mode 100644
index 0000000..f3718d0
Binary files /dev/null and b/resources/images/clone-button.gif differ
diff --git a/resources/images/list-renderer.jpg b/resources/images/list-renderer.jpg
new file mode 100644
index 0000000..5480716
Binary files /dev/null and b/resources/images/list-renderer.jpg differ
diff --git a/docs/images/multiple-column.gif b/resources/images/multiple-column.gif
similarity index 100%
rename from docs/images/multiple-column.gif
rename to resources/images/multiple-column.gif
diff --git a/docs/images/single-column.gif b/resources/images/single-column.gif
similarity index 100%
rename from docs/images/single-column.gif
rename to resources/images/single-column.gif
diff --git a/resources/images/table-renderer.jpg b/resources/images/table-renderer.jpg
new file mode 100644
index 0000000..0ea01df
Binary files /dev/null and b/resources/images/table-renderer.jpg differ
diff --git a/src/MultipleInput.php b/src/MultipleInput.php
index 0962453..dcad5eb 100644
--- a/src/MultipleInput.php
+++ b/src/MultipleInput.php
@@ -6,13 +6,18 @@
* @license https://github.com/unclead/yii2-multiple-input/blob/master/LICENSE.md
*/
-namespace unclead\widgets;
+namespace unclead\multipleinput;
use Yii;
+use yii\base\InvalidConfigException;
use yii\base\Model;
+use yii\helpers\ArrayHelper;
+use yii\helpers\Html;
+use yii\widgets\ActiveForm;
use yii\widgets\InputWidget;
use yii\db\ActiveRecordInterface;
-use unclead\widgets\renderers\TableRenderer;
+use unclead\multipleinput\renderers\TableRenderer;
+use unclead\multipleinput\renderers\RendererInterface;
/**
@@ -22,14 +27,21 @@
*/
class MultipleInput extends InputWidget
{
- const POS_HEADER = TableRenderer::POS_HEADER;
- const POS_ROW = TableRenderer::POS_ROW;
- const POS_FOOTER = TableRenderer::POS_FOOTER;
+ const POS_HEADER = RendererInterface::POS_HEADER;
+ const POS_ROW = RendererInterface::POS_ROW;
+ const POS_ROW_BEGIN = RendererInterface::POS_ROW_BEGIN;
+ const POS_FOOTER = RendererInterface::POS_FOOTER;
+
+ const THEME_DEFAULT = 'default';
+ const THEME_BS = 'bootstrap';
+
+ const ICONS_SOURCE_GLYPHICONS = 'glyphicons';
+ const ICONS_SOURCE_FONTAWESOME = 'fa';
/**
* @var ActiveRecordInterface[]|array[] input data
*/
- public $data = null;
+ public $data;
/**
* @var array columns configuration
@@ -37,9 +49,9 @@ class MultipleInput extends InputWidget
public $columns = [];
/**
- * @var integer inputs limit
+ * @var integer maximum number of rows
*/
- public $limit;
+ public $max;
/**
* @var array client-side attribute options, e.g. enableAjaxValidation. You may use this property in case when
@@ -58,6 +70,11 @@ class MultipleInput extends InputWidget
*/
public $addButtonOptions;
+ /**
+ * @var array the HTML options for the `clone` button
+ */
+ public $cloneButtonOptions;
+
/**
* @var bool whether to allow the empty list
*/
@@ -74,9 +91,9 @@ class MultipleInput extends InputWidget
public $min;
/**
- * @var string|array position of add button. By default button is rendered in the row.
+ * @var string|array position of add button.
*/
- public $addButtonPosition = self::POS_ROW;
+ public $addButtonPosition;
/**
* @var array|\Closure the HTML attributes for the table body rows. This can be either an array
@@ -96,10 +113,108 @@ class MultipleInput extends InputWidget
/**
* @var string the name of column class. You can specify your own class to extend base functionality.
- * Defaults to `unclead\widgets\MultipleInputColumn`
+ * Defaults to `unclead\multipleinput\MultipleInputColumn`
*/
public $columnClass;
+ /**
+ * @var string the name of renderer class. Defaults to `unclead\multipleinput\renderers\TableRenderer`.
+ * @since 1.4
+ */
+ public $rendererClass;
+
+ /**
+ * @var bool whether the widget is embedded or not.
+ * @internal this property is used for internal purposes. Do not use it in your code.
+ */
+ public $isEmbedded = false;
+
+ /**
+ * @var ActiveForm an instance of ActiveForm which you have to pass in case of using client validation
+ * @since 2.1
+ */
+ public $form;
+
+ /**
+ * @var bool allow sorting.
+ * @internal this property is used when need to allow sorting rows.
+ */
+ public $sortable = false;
+
+ /**
+ * @var bool whether to render inline error for all input. Default to `false`. Can be override in `columns`
+ * @since 2.10
+ */
+ public $enableError = false;
+
+ /**
+ * @var bool whether to render clone button. Default to `false`.
+ */
+ public $cloneButton = false;
+
+ /**
+ * @var string|\Closure the HTML content that will be rendered after the buttons.
+ *
+ * ```php
+ * function ($model, $index, $context)
+ * ```
+ *
+ * - `$model`: the current data model being rendered
+ * - `$index`: the zero-based index of the data model in the model array
+ * - `$context`: the MultipleInput widget object
+ *
+ */
+ public $extraButtons;
+
+ /**
+ * @var array CSS grid classes for horizontal layout. This must be an array with these keys:
+ * - 'offsetClass' the offset grid class to append to the wrapper if no label is rendered
+ * - 'labelClass' the label grid class
+ * - 'wrapperClass' the wrapper grid class
+ * - 'errorClass' the error grid class
+ */
+ public $layoutConfig = [];
+
+ /**
+ * @var array
+ * --icon library classes mapped for various controls
+ */
+ public $iconMap = [
+ self::ICONS_SOURCE_GLYPHICONS => [
+ 'drag-handle' => 'glyphicon glyphicon-menu-hamburger',
+ 'remove' => 'glyphicon glyphicon-remove',
+ 'add' => 'glyphicon glyphicon-plus',
+ 'clone' => 'glyphicon glyphicon-duplicate',
+ ],
+ self::ICONS_SOURCE_FONTAWESOME => [
+ 'drag-handle' => 'fa fa-bars',
+ 'remove' => 'fa fa-times',
+ 'add' => 'fa fa-plus',
+ 'clone' => 'fa fa-files-o',
+ ],
+ ];
+ /**
+ * @var string the name of default icon library
+ */
+ public $iconSource = self::ICONS_SOURCE_GLYPHICONS;
+
+ /**
+ * @var string the CSS theme of the widget
+ *
+ * @todo Use bootstrap theme for BC. We can switch to default theme in major release
+ */
+ public $theme = self::THEME_BS;
+
+ /**
+ * @var bool
+ */
+ public $showGeneralError = false;
+
+ /**
+ * @var bool add a new line to the beginning of the list, not to the end
+ */
+ public $prepend = false;
+
/**
* Initialization.
*
@@ -107,8 +222,17 @@ class MultipleInput extends InputWidget
*/
public function init()
{
+ if ($this->form !== null && !$this->form instanceof ActiveForm) {
+ throw new InvalidConfigException('Property "form" must be an instance of yii\widgets\ActiveForm');
+ }
+
+ if ($this->showGeneralError && $this->field === null) {
+ $this->showGeneralError = false;
+ }
+
$this->guessColumns();
$this->initData();
+
parent::init();
}
@@ -127,7 +251,19 @@ protected function initData()
}
if ($this->model instanceof Model) {
- foreach ((array)$this->model->{$this->attribute} as $index => $value) {
+ $data = ($this->model->hasProperty($this->attribute) || isset($this->model->{$this->attribute}))
+ ? ArrayHelper::getValue($this->model, $this->attribute, [])
+ : [];
+
+ if (!is_array($data) && empty($data)) {
+ return;
+ }
+
+ if (!($data instanceof \Traversable)) {
+ $data = (array) $data;
+ }
+
+ foreach ($data as $index => $value) {
$this->data[$index] = $value;
}
}
@@ -157,36 +293,92 @@ protected function guessColumns()
*/
public function run()
{
- return $this->createRenderer()->render();
+ $content = '';
+ if ($this->isEmbedded === false && $this->hasModel()) {
+ $content .= Html::hiddenInput(Html::getInputName($this->model, $this->attribute), null);
+ }
+
+ $content .= $this->createRenderer()->render();
+
+ return $content;
}
/**
* @return TableRenderer
*/
- private function createRenderer()
+ protected function createRenderer()
{
+ if($this->sortable) {
+ $drag = [
+ 'name' => 'drag',
+ 'type' => MultipleInputColumn::TYPE_DRAGCOLUMN,
+ 'headerOptions' => [
+ 'style' => 'width: 20px;',
+ ]
+ ];
+
+ array_unshift($this->columns, $drag);
+ }
+
+ $available_themes = [
+ self::THEME_BS,
+ self::THEME_DEFAULT
+ ];
+
+ if (!in_array($this->theme, $available_themes, true)) {
+ $this->theme = self::THEME_BS;
+ }
+
+ /**
+ * set default icon map
+ */
+ $iconMap = array_key_exists($this->iconSource, $this->iconMap)
+ ? $this->iconMap[$this->iconSource]
+ : $this->iconMap[self::ICONS_SOURCE_GLYPHICONS];
+
$config = [
- 'id' => $this->options['id'],
+ 'id' => $this->getId(),
'columns' => $this->columns,
- 'limit' => $this->limit,
+ 'min' => $this->min,
+ 'max' => $this->max,
'attributeOptions' => $this->attributeOptions,
'data' => $this->data,
'columnClass' => $this->columnClass !== null ? $this->columnClass : MultipleInputColumn::className(),
'allowEmptyList' => $this->allowEmptyList,
- 'min' => $this->min,
'addButtonPosition' => $this->addButtonPosition,
'rowOptions' => $this->rowOptions,
'context' => $this,
+ 'form' => $this->form,
+ 'sortable' => $this->sortable,
+ 'enableError' => $this->enableError,
+ 'cloneButton' => $this->cloneButton,
+ 'extraButtons' => $this->extraButtons,
+ 'layoutConfig' => $this->layoutConfig,
+ 'iconMap' => $iconMap,
+ 'theme' => $this->theme,
+ 'prepend' => $this->prepend
];
- if (!is_null($this->removeButtonOptions)) {
+ if ($this->showGeneralError) {
+ $config['jsExtraSettings'] = [
+ 'showGeneralError' => true
+ ];
+ }
+
+ if ($this->removeButtonOptions !== null) {
$config['removeButtonOptions'] = $this->removeButtonOptions;
}
- if (!is_null($this->addButtonOptions)) {
+ if ($this->addButtonOptions !== null) {
$config['addButtonOptions'] = $this->addButtonOptions;
}
- return new TableRenderer($config);
+ if ($this->cloneButtonOptions !== null) {
+ $config['cloneButtonOptions'] = $this->cloneButtonOptions;
+ }
+
+ $config['class'] = $this->rendererClass ?: TableRenderer::className();
+
+ return Yii::createObject($config);
}
-}
\ No newline at end of file
+}
diff --git a/src/MultipleInputColumn.php b/src/MultipleInputColumn.php
index c821ef6..e92c20c 100644
--- a/src/MultipleInputColumn.php
+++ b/src/MultipleInputColumn.php
@@ -6,25 +6,23 @@
* @license https://github.com/unclead/yii2-multiple-input/blob/master/LICENSE.md
*/
-namespace unclead\widgets;
+namespace unclead\multipleinput;
use yii\base\InvalidConfigException;
use yii\base\Model;
+use yii\base\DynamicModel;
use yii\db\ActiveRecordInterface;
use yii\helpers\Html;
-use unclead\widgets\components\BaseColumn;
+use unclead\multipleinput\components\BaseColumn;
/**
* Class MultipleInputColumn
- * @package unclead\widgets
+ * @package unclead\multipleinput
+ *
+ * @property MultipleInput $context
*/
class MultipleInputColumn extends BaseColumn
{
- /**
- * @var MultipleInput
- */
- public $context;
-
/**
* @throws InvalidConfigException
*/
@@ -40,23 +38,31 @@ public function init()
/**
* Returns element's name.
*
- * @param int|null $index current row index
+ * @param int|null|string $index current row index
* @param bool $withPrefix whether to add prefix.
+ *
* @return string
*/
public function getElementName($index, $withPrefix = true)
{
- if (is_null($index)) {
+ if ($index === null) {
$index = '{' . $this->renderer->getIndexPlaceholder() . '}';
}
-
+
$elementName = $this->isRendererHasOneColumn()
? '[' . $this->name . '][' . $index . ']'
: '[' . $index . '][' . $this->name . ']';
- $prefix = $withPrefix ? $this->getInputNamePrefix() : '';
-
- return $prefix . $elementName;
+ if (!$withPrefix) {
+ return $elementName;
+ }
+
+ $prefix = $this->getInputNamePrefix();
+ if ($this->context->isEmbedded && strpos($prefix, $this->context->name) === false) {
+ $prefix = $this->context->name;
+ }
+
+ return $prefix . $elementName . (empty($this->nameSuffix) ? '' : ('_' . $this->nameSuffix));
}
/**
@@ -64,7 +70,11 @@ public function getElementName($index, $withPrefix = true)
*/
private function isRendererHasOneColumn()
{
- return count($this->renderer->columns) === 1;
+ $columns = \array_filter($this->renderer->columns, function(self $column) {
+ return $column->type !== self::TYPE_DRAGCOLUMN;
+ });
+
+ return count($columns) === 1;
}
/**
@@ -79,10 +89,10 @@ protected function getInputNamePrefix()
if (empty($this->renderer->columns) || ($this->isRendererHasOneColumn() && $this->hasModelAttribute($this->name))) {
return $model->formName();
}
-
+
return Html::getInputName($this->context->model, $this->context->attribute);
}
-
+
return $this->context->name;
}
@@ -92,11 +102,17 @@ protected function hasModelAttribute($name)
if ($model->hasProperty($name)) {
return true;
- } elseif ($model instanceof ActiveRecordInterface && $model->hasAttribute($name)) {
+ }
+
+ if ($model instanceof ActiveRecordInterface && $model->hasAttribute($name)) {
return true;
- } else {
- return false;
}
+
+ if ($model instanceof DynamicModel && isset($model->{$name})) {
+ return true;
+ }
+
+ return false;
}
/**
@@ -108,7 +124,7 @@ public function getFirstError($index)
if ($index === null) {
return null;
}
-
+
if ($this->isRendererHasOneColumn()) {
$attribute = $this->name . '[' . $index . ']';
} else {
@@ -131,7 +147,7 @@ protected function renderWidget($type, $name, $value, $options)
// Extend options in case of rendering embedded MultipleInput
// We have to pass to the widget an original model and an attribute to be able get a first error from model
// for embedded widget.
- if ($type === MultipleInput::className() && strpos($name, $this->renderer->getIndexPlaceholder()) === false) {
+ if ($type === MultipleInput::className()) {
$model = $this->context->model;
// in case of embedding level 2 and more
@@ -147,8 +163,14 @@ protected function renderWidget($type, $name, $value, $options)
$options['model'] = $model;
$options['attribute'] = $attribute;
+
+ // Remember current name and mark the widget as embedded to prevent
+ // generation of wrong prefix in case the column is associated with AR relation
+ // @see https://github.com/unclead/yii2-multiple-input/issues/92
+ $options['name'] = $name;
+ $options['isEmbedded'] = true;
}
return parent::renderWidget($type, $name, $value, $options);
}
-}
\ No newline at end of file
+}
diff --git a/src/TabularColumn.php b/src/TabularColumn.php
index b829636..e5dbf8e 100644
--- a/src/TabularColumn.php
+++ b/src/TabularColumn.php
@@ -6,34 +6,36 @@
* @license https://github.com/unclead/yii2-multiple-input/blob/master/LICENSE.md
*/
-namespace unclead\widgets;
+namespace unclead\multipleinput;
-use unclead\widgets\components\BaseColumn;
+use unclead\multipleinput\components\BaseColumn;
use yii\base\Model;
/**
* Class TabularColumn
- * @package unclead\widgets
+ * @package unclead\multipleinput
+ *
+ * @property TabularInput $context
*/
class TabularColumn extends BaseColumn
-{
+{
/**
* Returns element's name.
*
- * @param int|null $index current row index
+ * @param int|null|string $index current row index
* @param bool $withPrefix whether to add prefix.
* @return string
*/
public function getElementName($index, $withPrefix = true)
{
- if (is_null($index)) {
+ if ($index === null) {
$index = '{' . $this->renderer->getIndexPlaceholder() . '}';
}
$elementName = '[' . $index . '][' . $this->name . ']';
$prefix = $withPrefix ? $this->getModel()->formName() : '';
- return $prefix . $elementName;
+ return $prefix . $elementName . (empty($this->nameSuffix) ? '' : ('_' . $this->nameSuffix));
}
/**
@@ -63,16 +65,10 @@ protected function ensureModel($model)
*/
public function setModel($model)
{
- $currentModel = $this->getModel();
-
- // If model is null and current model is not empty it means that widget renders a template
- // In this case we have to unset all model attributes
- if ($model === null && $currentModel !== null) {
- foreach ($currentModel->attributes() as $attribute) {
- $currentModel->$attribute = null;
- }
- } else {
- parent::setModel($model);
+ if ($model === null) {
+ $model = \Yii::createObject(['class' => $this->context->modelClass]);
}
+
+ parent::setModel($model);
}
-}
\ No newline at end of file
+}
diff --git a/src/TabularInput.php b/src/TabularInput.php
index 5b95373..95e2f89 100644
--- a/src/TabularInput.php
+++ b/src/TabularInput.php
@@ -6,24 +6,33 @@
* @license https://github.com/unclead/yii2-multiple-input/blob/master/LICENSE.md
*/
-namespace unclead\widgets;
+namespace unclead\multipleinput;
use Yii;
use yii\base\InvalidConfigException;
use yii\base\Model;
use yii\db\ActiveRecordInterface;
use yii\bootstrap\Widget;
-use unclead\widgets\renderers\TableRenderer;
+use yii\widgets\ActiveForm;
+use unclead\multipleinput\renderers\TableRenderer;
+use unclead\multipleinput\renderers\RendererInterface;
/**
* Class TabularInput
- * @package unclead\widgets
+ * @package unclead\multipleinput
*/
class TabularInput extends Widget
{
- const POS_HEADER = TableRenderer::POS_HEADER;
- const POS_ROW = TableRenderer::POS_ROW;
- const POS_FOOTER = TableRenderer::POS_FOOTER;
+ const POS_HEADER = RendererInterface::POS_HEADER;
+ const POS_ROW = RendererInterface::POS_ROW;
+ const POS_FOOTER = RendererInterface::POS_FOOTER;
+ const POS_ROW_BEGIN = RendererInterface::POS_ROW_BEGIN;
+
+ const THEME_DEFAULT = 'default';
+ const THEME_BS = 'bootstrap';
+
+ const ICONS_SOURCE_GLYPHICONS = 'glyphicons';
+ const ICONS_SOURCE_FONTAWESOME = 'fa';
/**
* @var array
@@ -31,9 +40,9 @@ class TabularInput extends Widget
public $columns = [];
/**
- * @var integer inputs limit
+ * @var integer maximum number of rows
*/
- public $limit;
+ public $max;
/**
* @var int minimum number of rows
@@ -57,6 +66,11 @@ class TabularInput extends Widget
*/
public $addButtonOptions;
+ /**
+ * @var array the HTML options for the `clone` button
+ */
+ public $cloneButtonOptions;
+
/**
* @var bool whether to allow the empty list
*/
@@ -65,12 +79,12 @@ class TabularInput extends Widget
/**
* @var Model[]|ActiveRecordInterface[]
*/
- public $models;
+ public $models = [];
/**
- * @var string|array position of add button. By default button is rendered in the row.
+ * @var string|array position of add button.
*/
- public $addButtonPosition = self::POS_ROW;
+ public $addButtonPosition;
/**
* @var array|\Closure the HTML attributes for the table body rows. This can be either an array
@@ -91,10 +105,105 @@ class TabularInput extends Widget
/**
* @var string the name of column class. You can specify your own class to extend base functionality.
- * Defaults to `unclead\widgets\TabularColumn`
+ * Defaults to `unclead\multipleinput\TabularColumn`
*/
public $columnClass;
+ /**
+ * @var string the name of renderer class. Defaults to `unclead\multipleinput\renderers\TableRenderer`.
+ * @since 1.4
+ */
+ public $rendererClass;
+
+ /**
+ * @var ActiveForm an instance of ActiveForm which you have to pass in case of using client validation
+ * @since 2.1
+ */
+ public $form;
+
+ /**
+ * @var bool allow sorting.
+ * @internal this property is used when need to allow sorting rows.
+ */
+ public $sortable = false;
+
+ /**
+ * @var bool whether to render inline error for all input. Default to `false`. Can be override in `columns`
+ * @since 2.10
+ */
+ public $enableError = false;
+
+ /**
+ * @var bool whether to render clone button. Default to `false`.
+ */
+ public $cloneButton = false;
+
+ /**
+ * @var string|\Closure the HTML content that will be rendered after the buttons.
+ *
+ * ```php
+ * function ($model, $index, $context)
+ * ```
+ *
+ * - `$model`: the current data model being rendered
+ * - `$index`: the zero-based index of the data model in the model array
+ * - `$context`: the MultipleInput widget object
+ *
+ */
+ public $extraButtons;
+
+ /**
+ * @var string a class of model which is used to render the widget.
+ * You have to specify this property in case you set `min` property to 0 (when you want to allow an empty list)
+ * @since 2.13
+ */
+ public $modelClass;
+
+ /**
+ * @var array CSS grid classes for horizontal layout. This must be an array with these keys:
+ * - 'offsetClass' the offset grid class to append to the wrapper if no label is rendered
+ * - 'labelClass' the label grid class
+ * - 'wrapperClass' the wrapper grid class
+ * - 'errorClass' the error grid class
+ */
+ public $layoutConfig = [];
+
+ /**
+ * @var array
+ * --icon library classes mapped for various controls
+ */
+ public $iconMap = [
+ self::ICONS_SOURCE_GLYPHICONS => [
+ 'drag-handle' => 'glyphicon glyphicon-menu-hamburger',
+ 'remove' => 'glyphicon glyphicon-remove',
+ 'add' => 'glyphicon glyphicon-plus',
+ 'clone' => 'glyphicon glyphicon-duplicate',
+ ],
+ self::ICONS_SOURCE_FONTAWESOME => [
+ 'drag-handle' => 'fa fa-bars',
+ 'remove' => 'fa fa-times',
+ 'add' => 'fa fa-plus',
+ 'clone' => 'fa fa-files-o',
+ ],
+ ];
+
+ /**
+ * @var string the CSS theme of the widget
+ *
+ * @todo Use bootstrap theme for BC. We can switch to default theme in major release
+ */
+ public $theme = self::THEME_BS;
+
+ /**
+ * @var string the name of default icon library
+ */
+ public $iconSource = self::ICONS_SOURCE_GLYPHICONS;
+
+ /**
+ * @var bool add a new line to the beginning of the list, not to the end
+ */
+ public $prepend = false;
+
/**
* Initialization.
*
@@ -102,14 +211,33 @@ class TabularInput extends Widget
*/
public function init()
{
- if (empty($this->models)) {
- throw new InvalidConfigException('You must specify "models"');
+ if (empty($this->models) && !$this->modelClass) {
+ throw new InvalidConfigException('You must at least specify "models" or "modelClass"');
}
- foreach ($this->models as $model) {
- if (!$model instanceof Model) {
- throw new InvalidConfigException('Model has to be an instance of yii\base\Model');
+ if ($this->form !== null && !$this->form instanceof ActiveForm) {
+ throw new InvalidConfigException('Property "form" must be an instance of yii\widgets\ActiveForm');
+ }
+
+ if (!is_array($this->models)) {
+ throw new InvalidConfigException('Property "models" must be an array');
+ }
+
+ if ($this->models) {
+ $modelClasses = [];
+ foreach ($this->models as $model) {
+ if (!$model instanceof Model) {
+ throw new InvalidConfigException('Model has to be an instance of yii\base\Model');
+ }
+
+ $modelClasses[get_class($model)] = true;
}
+
+ if (count($modelClasses) > 1) {
+ throw new InvalidConfigException("You cannot use models of different classes");
+ }
+
+ $this->modelClass = key($modelClasses);
}
parent::init();
@@ -126,30 +254,77 @@ public function run()
/**
* @return TableRenderer
*/
- private function createRenderer()
+ protected function createRenderer()
{
+ if($this->sortable) {
+ $drag = [
+ 'name' => 'drag',
+ 'type' => TabularColumn::TYPE_DRAGCOLUMN,
+ 'headerOptions' => [
+ 'style' => 'width: 20px;',
+ ]
+ ];
+
+ array_unshift($this->columns, $drag);
+ }
+
+ $available_themes = [
+ self::THEME_BS,
+ self::THEME_DEFAULT
+ ];
+
+ if (!in_array($this->theme, $available_themes, true)) {
+ $this->theme = self::THEME_BS;
+ }
+
+ /**
+ * set default icon map
+ */
+ $iconMap = array_key_exists($this->iconSource, $this->iconMap)
+ ? $this->iconMap[$this->iconSource]
+ : $this->iconMap[self::ICONS_SOURCE_GLYPHICONS];
+
$config = [
- 'id' => $this->options['id'],
+ 'id' => $this->getId(),
'columns' => $this->columns,
- 'limit' => $this->limit,
+ 'min' => $this->min,
+ 'max' => $this->max,
'attributeOptions' => $this->attributeOptions,
'data' => $this->models,
'columnClass' => $this->columnClass !== null ? $this->columnClass : TabularColumn::className(),
'allowEmptyList' => $this->allowEmptyList,
- 'min' => $this->min,
'rowOptions' => $this->rowOptions,
'addButtonPosition' => $this->addButtonPosition,
'context' => $this,
+ 'form' => $this->form,
+ 'sortable' => $this->sortable,
+ 'enableError' => $this->enableError,
+ 'cloneButton' => $this->cloneButton,
+ 'extraButtons' => $this->extraButtons,
+ 'layoutConfig' => $this->layoutConfig,
+ 'iconMap' => $iconMap,
+ 'theme' => $this->theme,
+ 'prepend' => $this->prepend
];
- if (!is_null($this->removeButtonOptions)) {
+ if ($this->removeButtonOptions !== null) {
$config['removeButtonOptions'] = $this->removeButtonOptions;
}
- if (!is_null($this->addButtonOptions)) {
+ if ($this->addButtonOptions !== null) {
$config['addButtonOptions'] = $this->addButtonOptions;
}
- return new TableRenderer($config);
+ if ($this->cloneButtonOptions !== null) {
+ $config['cloneButtonOptions'] = $this->cloneButtonOptions;
+ }
+
+ if (!$this->rendererClass) {
+ $this->rendererClass = TableRenderer::className();
+ }
+
+ $config['class'] = $this->rendererClass ?: TableRenderer::className();
+
+ return Yii::createObject($config);
}
-}
\ No newline at end of file
+}
diff --git a/src/assets/FontAwesomeAsset.php b/src/assets/FontAwesomeAsset.php
new file mode 100644
index 0000000..47061dc
--- /dev/null
+++ b/src/assets/FontAwesomeAsset.php
@@ -0,0 +1,26 @@
+'text/css', 'integrity'=>'sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ', 'crossorigin'=>'anonymous', 'media'=>'all', 'id'=>'font-awesome', 'rel'=>'stylesheet'],
+ ];
+
+}
\ No newline at end of file
diff --git a/src/assets/MultipleInputAsset.php b/src/assets/MultipleInputAsset.php
index 131d24c..df3f426 100644
--- a/src/assets/MultipleInputAsset.php
+++ b/src/assets/MultipleInputAsset.php
@@ -6,34 +6,34 @@
* @license https://github.com/unclead/yii2-multiple-input/blob/master/LICENSE.md
*/
-namespace unclead\widgets\assets;
+namespace unclead\multipleinput\assets;
use yii\web\AssetBundle;
/**
* Class MultipleInputAsset
- * @package unclead\widgets\assets
+ * @package unclead\multipleinput\assets
*/
class MultipleInputAsset extends AssetBundle
{
- public $css = [
- 'css/multiple-input.css'
- ];
-
- public $js = [];
-
public $depends = [
'yii\web\JqueryAsset'
];
- public function init()
+ public function __construct($config = [])
{
- $this->sourcePath = __DIR__ . '/src/';
- $this->js = [
- YII_DEBUG ? 'js/jquery.multipleInput.js' : 'js/jquery.multipleInput.min.js'
- ];
- parent::init();
+ $config = array_merge([
+ 'sourcePath' => __DIR__ . '/src/',
+ 'js' => [
+ YII_DEBUG ? 'js/jquery.multipleInput.js' : 'js/jquery.multipleInput.min.js'
+ ],
+ 'css' => [
+ YII_DEBUG ? 'css/multiple-input.css' : 'css/multiple-input.min.css'
+ ],
+ ], $config);
+
+ parent::__construct($config);
}
-}
\ No newline at end of file
+}
diff --git a/src/assets/MultipleInputSortableAsset.php b/src/assets/MultipleInputSortableAsset.php
new file mode 100644
index 0000000..152d558
--- /dev/null
+++ b/src/assets/MultipleInputSortableAsset.php
@@ -0,0 +1,37 @@
+sourcePath = __DIR__ . '/src/';
+
+ $this->js = [
+ YII_DEBUG ? 'js/sortable.js' : 'js/sortable.min.js'
+ ];
+
+ $this->css = [
+ YII_DEBUG ? 'css/sorting.css' : 'css/sorting.min.css'
+ ];
+
+ parent::init();
+ }
+}
\ No newline at end of file
diff --git a/src/assets/src/css/multiple-input.css b/src/assets/src/css/multiple-input.css
index 9640449..a7361cb 100644
--- a/src/assets/src/css/multiple-input.css
+++ b/src/assets/src/css/multiple-input.css
@@ -1,7 +1,10 @@
-.multiple-input-list {}
+.multiple-input-list {
+}
+
.multiple-input-list__item {
margin-bottom: 5px;
}
+
.multiple-input-list__input {
display: inline-block;
width: 80%;
@@ -11,39 +14,76 @@
display: block;
width: 100%;
}
+
table.multiple-input-list {
margin: 0;
}
-table.multiple-input-list tbody tr > td {
+
+table.multiple-input-list.table-renderer tbody tr > td {
border: 0 !important;
}
-table.multiple-input-list tr > td:first-child {
+
+table.multiple-input-list.table-renderer tr > td:first-child {
padding-left: 0;
}
-table.multiple-input-list tr > td:last-child {
+
+table.multiple-input-list.table-renderer tr > td:last-child {
padding-right: 0;
}
+
table.multiple-input-list tr > th {
border-bottom: 1px solid #dddddd;
}
-.multiple-input-list .form-group {
+
+.multiple-input-list.table-renderer .form-group {
margin: 0 !important;
}
-.multiple-input-list__item .label {
+
+.multiple-input-list.list-renderer .form-group {
+ margin-bottom: 10px !important;
+}
+
+.multiple-input-list.table-renderer .multiple-input-list__item .label {
display: block;
font-size: 13px;
}
-.multiple-input-list .list-cell__button {
+
+.multiple-input-list.table-renderer .list-cell__button {
width: 40px;
}
+
+.multiple-input-list.list-renderer .list-cell__button {
+ width: 40px;
+ text-align: right;
+ padding-right: 0;
+ padding-left: 5px;
+}
+
+.multiple-input-list.list-renderer .list-cell__button:last-child {
+ padding-right: 15px;
+}
+
+.multiple-input-list.list-renderer tbody .list-cell__button .btn{
+ margin-top: 25px;
+}
+
.multiple-input-list__item .radio,
.multiple-input-list__item .checkbox {
margin: 7px 0 7px 0;
}
+
.multiple-input-list__item .radio-list .radio,
.multiple-input-list__item .checkbox-list .checkbox {
margin: 0;
}
+
.multiple-input-list .multiple-input-list {
margin-top: -5px;
+}
+
+@media (min-width: 768px) {
+ .multiple-input-list.list-renderer tbody .list-cell__button .btn {
+ margin-top: 0;
+ }
+
}
\ No newline at end of file
diff --git a/src/assets/src/css/multiple-input.min.css b/src/assets/src/css/multiple-input.min.css
new file mode 100644
index 0000000..50a3834
--- /dev/null
+++ b/src/assets/src/css/multiple-input.min.css
@@ -0,0 +1 @@
+.multiple-input-list__item{margin-bottom:5px}.multiple-input-list__input{display:inline-block;width:80%}.multiple-input-list.no-buttons .multiple-input-list__input{display:block;width:100%}table.multiple-input-list{margin:0}table.multiple-input-list.table-renderer tbody tr>td{border:0!important}table.multiple-input-list.table-renderer tr>td:first-child{padding-left:0}table.multiple-input-list.table-renderer tr>td:last-child{padding-right:0}table.multiple-input-list tr>th{border-bottom:1px solid #ddd}.multiple-input-list.table-renderer .form-group{margin:0!important}.multiple-input-list.list-renderer .form-group{margin-bottom:10px!important}.multiple-input-list.table-renderer .multiple-input-list__item .label{display:block;font-size:13px}.multiple-input-list.table-renderer .list-cell__button{width:40px}.multiple-input-list.list-renderer .list-cell__button{width:70px;text-align:right;padding-right:15px}.multiple-input-list__item .checkbox,.multiple-input-list__item .radio{margin:7px 0}.multiple-input-list__item .checkbox-list .checkbox,.multiple-input-list__item .radio-list .radio{margin:0}.multiple-input-list .multiple-input-list{margin-top:-5px}
\ No newline at end of file
diff --git a/src/assets/src/css/sorting.css b/src/assets/src/css/sorting.css
new file mode 100644
index 0000000..829393a
--- /dev/null
+++ b/src/assets/src/css/sorting.css
@@ -0,0 +1,46 @@
+.drag-handle,
+.dragging,
+.dragging * {
+ cursor: move !important;
+}
+
+.dragged {
+ position: absolute;
+ top: 0;
+ opacity: .5;
+ z-index: 2000;
+}
+
+.drag-handle {
+ opacity: .5;
+ padding: 7.5px;
+}
+
+.drag-handle:hover {
+ opacity: 1;
+}
+
+tr.placeholder {
+ display: block;
+ background: red;
+ position: relative;
+ margin: 0;
+ padding: 0;
+ border: none;
+}
+
+tr.placeholder:before {
+ content: "";
+ position: absolute;
+ width: 0;
+ height: 0;
+ border: 5px solid transparent;
+ border-left-color: red;
+ margin-top: -5px;
+ left: -5px;
+ border-right: none;
+}
+
+table.multiple-input-list.table-renderer tr > td.list-cell__drag {
+ width: 35px;
+}
\ No newline at end of file
diff --git a/src/assets/src/css/sorting.min.css b/src/assets/src/css/sorting.min.css
new file mode 100644
index 0000000..37ad594
--- /dev/null
+++ b/src/assets/src/css/sorting.min.css
@@ -0,0 +1 @@
+.drag-handle,.dragging,.dragging *{cursor:move!important}.dragged{position:absolute;top:0;opacity:.5;z-index:2000}.drag-handle{opacity:.5;padding:7.5px}.drag-handle:hover{opacity:1}tr.placeholder{display:block;background:red;position:relative;margin:0;padding:0;border:none}tr.placeholder:before{content:"";position:absolute;width:0;height:0;border:5px solid transparent;border-left-color:red;margin-top:-5px;left:-5px;border-right:none}table.multiple-input-list.table-renderer tr>td.list-cell__drag{width:35px}
\ No newline at end of file
diff --git a/src/assets/src/js/jquery.multipleInput.js b/src/assets/src/js/jquery.multipleInput.js
index 95a1927..596d3ec 100644
--- a/src/assets/src/js/jquery.multipleInput.js
+++ b/src/assets/src/js/jquery.multipleInput.js
@@ -1,4 +1,6 @@
(function ($) {
+ 'use strict';
+
$.fn.multipleInput = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
@@ -22,7 +24,15 @@
/**
* afterAddRow event is triggered after successful adding new row.
* The signature of the event handler should be:
- * function (event)
+ * function (event, row)
+ * where event is an Event object.
+ *
+ */
+ beforeAddRow: 'beforeAddRow',
+ /**
+ * afterAddRow event is triggered after successful adding new row.
+ * The signature of the event handler should be:
+ * function (event, row)
* where event is an Event object.
*
*/
@@ -44,46 +54,97 @@
* where event is an Event object.
*
*/
- afterDeleteRow: 'afterDeleteRow'
+ afterDeleteRow: 'afterDeleteRow',
+
+ /**
+ * afterDropRow event is triggered after drop the row in sortable mode.
+ * The signature of the event handler should be:
+ * function (event, row)
+ * where event is an Event object and row is html container of dragged row
+ */
+ afterDropRow: 'afterDropRow'
};
var defaultOptions = {
+ /**
+ * the ID of widget
+ */
id: null,
- // the template of row
+
+ /**
+ * the ID of related input in case of using widget for an active field
+ */
+ inputId: null,
+
+ /**
+ * the template of row
+ */
template: null,
- // string that collect js templates of widgets which uses in the columns
+
+ /**
+ * array that collect js templates of widgets which uses in the columns
+ */
jsTemplates: [],
- // how many row has to renders
- limit: 1,
- // minimum number of rows
+
+ /**
+ * array of scripts which need to execute before initialization
+ */
+ jsInit: [],
+
+ /**
+ * how many row are allowed to render
+ */
+ max: 1,
+
+ /**
+ * a minimum number of rows
+ */
min: 1,
- attributeOptions: {},
+
+ /**
+ * active form options of attributes
+ */
+ attributes: {},
+
+ /**
+ * default prefix of a widget's placeholder
+ */
indexPlaceholder: 'multiple_index',
- };
- var defaultAttributeOptions = {
- enableAjaxValidation: false,
- validateOnBlur: false,
- validateOnChange: false,
- validateOnType: false
+ /**
+ * whether need to show general error message or no
+ */
+ showGeneralError: false,
+
+ /**
+ * if need to prepend new row, not append
+ */
+ prepend: false
};
var isActiveFormEnabled = false;
var methods = {
init: function (options) {
+ if (typeof options !== 'object') {
+ console.error('Options must be an object');
+ return;
+ }
+
var settings = $.extend(true, {}, defaultOptions, options || {}),
$wrapper = $('#' + settings.id),
form = $wrapper.closest('form'),
- id = this.selector.replace('#', '');
+ inputId = settings.inputId;
+
+ for (i in settings.jsInit) {
+ window.eval(settings.jsInit[i]);
+ }
$wrapper.data('multipleInput', {
settings: settings,
- currentIndex: 0,
- attributeDefaults: {}
+ currentIndex: 0
});
-
$wrapper.on('click.multipleInput', '.js-input-remove', function (e) {
e.stopPropagation();
removeInput($(this));
@@ -94,39 +155,51 @@
addInput($(this));
});
+ $wrapper.on('click.multipleInput', '.js-input-clone', function (e) {
+ e.stopPropagation();
+ cloneInput($(this));
+ });
+
var i = 0,
event = $.Event(events.afterInit);
var intervalID = setInterval(function () {
if (typeof form.data('yiiActiveForm') === 'object') {
- var attribute = form.yiiActiveForm('find', id),
- attributeDefaults = [];
-
+ var attribute = form.yiiActiveForm('find', inputId),
+ defaultAttributeOptions = {
+ enableAjaxValidation: false,
+ validateOnBlur: false,
+ validateOnChange: false,
+ validateOnType: false,
+ validationDelay: 500
+ };
+
+ // fetch default attribute options from active from attribute
if (typeof attribute === 'object') {
$.each(attribute, function (key, value) {
- if (['id', 'input', 'container'].indexOf(key) == -1) {
- attributeDefaults[key] = value;
+ if (['id', 'input', 'container'].indexOf(key) === -1) {
+ defaultAttributeOptions[key] = value;
}
});
- form.yiiActiveForm('remove', id);
+ if (!settings.showGeneralError) {
+ form.yiiActiveForm('remove', inputId);
+ }
}
- var attributeOptions = $.extend({}, defaultAttributeOptions, settings.attributeOptions);
-
- $.each(attributeOptions, function (key, value) {
- if (typeof attributeDefaults[key] === 'undefined') {
- attributeDefaults[key] = value;
- }
+ // append default options to option from settings
+ $.each(settings.attributes, function (attribute, attributeOptions) {
+ attributeOptions = $.extend({}, defaultAttributeOptions, attributeOptions);
+ settings.attributes[attribute] = attributeOptions;
});
- $wrapper.data('multipleInput').attributeDefaults = attributeDefaults;
+ $wrapper.data('multipleInput').settings = settings;
$wrapper.find('.multiple-input-list').find('input, select, textarea').each(function () {
- addAttribute($(this));
+ addActiveFormAttribute($(this));
});
- $wrapper.data('multipleInput').currentIndex = getCurrentIndex($wrapper);
+ $wrapper.data('multipleInput').currentIndex = findMaxRowIndex($wrapper);
isActiveFormEnabled = true;
clearInterval(intervalID);
@@ -138,11 +211,14 @@
// wait for initialization of ActiveForm a second
// If after a second system could not detect ActiveForm it means
// that widget is used without ActiveForm and we should just complete initialization of the widget
- if (i > 10) {
- $wrapper.data('multipleInput').currentIndex = getCurrentIndex($wrapper);
+ if (form.length === 0 || i > 10) {
+ clearInterval(intervalID);
isActiveFormEnabled = false;
- clearInterval(intervalID);
+ if (typeof $wrapper.data('multipleInput') !== 'undefined') {
+ $wrapper.data('multipleInput').currentIndex = findMaxRowIndex($wrapper);
+ }
+
$wrapper.trigger(event);
}
}, 100);
@@ -154,7 +230,7 @@
remove: function (index) {
var row = null;
- if (index) {
+ if (index !== undefined) {
row = $(this).find('.js-input-remove:eq(' + index + ')');
} else {
row = $(this).find('.js-input-remove').last();
@@ -164,103 +240,179 @@
},
clear: function () {
- $('.js-input-remove').each(function () {
+ $(this).find('.js-input-remove').each(function () {
removeInput($(this));
});
+ },
+
+ option: function(name, value) {
+ value = value || null;
+
+ var data = $(this).data('multipleInput'),
+ settings = data.settings;
+ if (value === null) {
+ if (!settings.hasOwnProperty(name)) {
+ throw new Error('Option "' + name + '" does not exist');
+ }
+ return settings[name];
+ } else if (settings.hasOwnProperty(name)) {
+ settings[name] = value;
+ data.settings = settings;
+ $(this).data('multipleInput', data);
+ }
}
};
- var addInput = function (btn, values) {
- var $wrapper = $(btn).closest('.multiple-input').first(),
- data = $wrapper.data('multipleInput'),
- settings = data.settings,
- template = settings.template,
- inputList = $wrapper.children('.multiple-input-list').first();
+ var cloneInput = function (btn) {
+ let $wrapper = $(btn).closest('.multiple-input').first();
+ let data = $wrapper.data('multipleInput');
+ let settings = data.settings;
- if (settings.limit != null && getCurrentIndex($wrapper) >= settings.limit) {
- return;
- }
+ let values = {};
- template = template.replaceAll('{' + settings.indexPlaceholder + '}', data.currentIndex);
+ btn.closest('.multiple-input-list__item').find('input, select, textarea').each(function (k, v) {
+ let $element = $(v);
- $(template).hide().appendTo(inputList).fadeIn(300);
+ let id = getInputId($element);
+ if (id) {
+ // todo still doesn't work for sinlge column
+ let columnName = id.replace(settings.inputId, '').replace(/-\d+-/, '');
+ if ($element.is(':checkbox')) {
+ if (!values.hasOwnProperty(columnName)) {
+ values[columnName] = [];
+ }
- if (values instanceof Object) {
- var tmp = [];
- for (var key in values) {
- if (values.hasOwnProperty(key)) {
- tmp.push(values[key]);
+ if ($element.is(':checked')) {
+ values[columnName].push($element.val());
+ }
+ } else {
+ values[columnName] = $element.val();
}
}
+ });
- values = tmp;
- }
+ addInput(btn, values);
+ }
- var jsTemplate;
+ var addInput = function (btn, rowValues) {
+ rowValues = rowValues || {};
- for (var i in settings.jsTemplates) {
- jsTemplate = settings.jsTemplates[i]
- .replaceAll('{' + settings.indexPlaceholder + '}', data.currentIndex)
- .replaceAll('%7B' + settings.indexPlaceholder + '%7D', data.currentIndex);
-
- window.eval(jsTemplate);
+ let $wrapper = $(btn).closest('.multiple-input').first();
+ let data = $wrapper.data('multipleInput');
+ let settings = data.settings;
+ let inputList = $wrapper.children('.multiple-input-list').first();
+
+ if (settings.max !== null && getRowsCount($wrapper) >= settings.max) {
+ return;
}
- var index = 0;
-
- $(template).find('input, select, textarea').each(function () {
- var that = $(this),
- tag = that.get(0).tagName,
- id = getInputId(that),
- obj = $('#' + id);
-
- if (values) {
- var val = values[index];
-
- if (tag == 'INPUT' || tag == 'TEXTAREA') {
- obj.val(val);
- } else if (tag == 'SELECT') {
- if (val && val.indexOf('option') != -1) {
- obj.append(val);
- } else {
- var option = obj.find('option[value="' + val + '"]');
- if (option.length) {
- obj.val(val);
- }
+ let newRowIndex = data.currentIndex + 1;
+
+ let template = replaceAll('{' + settings.indexPlaceholder + '}', newRowIndex, settings.template);
+ let $newRow = $(template);
+
+ var beforeAddEvent = $.Event(events.beforeAddRow);
+
+ $wrapper.trigger(beforeAddEvent, [$newRow, newRowIndex]);
+ if (beforeAddEvent.result === false) {
+ return;
+ }
+
+ $newRow.find('input, select, textarea').each(function (index, element) {
+ let $element = $(element);
+
+ let id = getInputId($element);
+ if (id) {
+ let columnName = id.replace(settings.inputId, '').replace(/-\d+-?/, '');
+
+ if (rowValues.hasOwnProperty(columnName)) {
+ let tag = $element.get(0).tagName;
+
+ let inputValue = rowValues[columnName];
+
+ switch (tag) {
+ case 'INPUT':
+ if ($element.is(':checkbox')) {
+ if (inputValue.indexOf($element.val()) !== -1) {
+ $element.prop('checked', true);
+ }
+ } else {
+ $element.val(inputValue);
+ }
+
+ break;
+
+ case 'TEXTAREA':
+ $element.val(inputValue);
+ break;
+
+ case 'SELECT':
+ if (inputValue && inputValue.indexOf('option') !== -1) {
+ $element.append(inputValue);
+ } else {
+ var option = $element.find('option[value="' + inputValue + '"]');
+ if (option.length) {
+ $element.val(inputValue);
+ }
+ }
+
+ break;
+
+ default:
+ break;
}
}
}
+ });
- if (isActiveFormEnabled) {
- addAttribute(that);
- }
+ if (settings.prepend) {
+ $newRow.hide().prependTo(inputList).fadeIn(300);
+ } else {
+ $newRow.hide().appendTo(inputList).fadeIn(300);
+ }
- index++;
- });
+ let jsTemplate = null;
+ for (var i in settings.jsTemplates) {
+ jsTemplate = settings.jsTemplates[i];
+ jsTemplate = replaceAll('{' + settings.indexPlaceholder + '}', newRowIndex, jsTemplate);
+ jsTemplate = replaceAll('%7B' + settings.indexPlaceholder + '%7D', newRowIndex, jsTemplate);
+
+ window.eval(jsTemplate);
+ }
+
+ // in order to initialize an active form attribute we need to find an input wrapper and we can do it
+ // only after adding a new rows to dom tree
+ if (isActiveFormEnabled) {
+ $newRow.find('input, select, textarea').each(function (index, element) {
+ let $element = $(element);
+ addActiveFormAttribute($element);
+ });
+ }
- $wrapper.data('multipleInput').currentIndex++;
+ $wrapper.data('multipleInput').currentIndex = newRowIndex;
- var event = $.Event(events.afterAddRow);
- $wrapper.trigger(event);
+ var afterAddEvent = $.Event(events.afterAddRow);
+ $wrapper.trigger(afterAddEvent, [$newRow, newRowIndex]);
};
var removeInput = function ($btn) {
- var $wrapper = $btn.closest('.multiple-input').first(),
+ var $wrapper = $btn.closest('.multiple-input').first(),
$toDelete = $btn.closest('.multiple-input-list__item'),
- data = $wrapper.data('multipleInput'),
- settings = data.settings;
+ data = $wrapper.data('multipleInput'),
+ settings = data.settings;
- if (getCurrentIndex($wrapper) > settings.min) {
+ var rowsCount = getRowsCount($wrapper);
+ if (rowsCount > settings.min) {
var event = $.Event(events.beforeDeleteRow);
- $wrapper.trigger(event, [$toDelete]);
+ $wrapper.trigger(event, [$toDelete, data.currentIndex]);
if (event.result === false) {
return;
}
if (isActiveFormEnabled) {
- $toDelete.find('input, select, textarea').each(function () {
- removeAttribute($(this));
+ $toDelete.find('input, select, textarea').each(function (index, ele) {
+ removeActiveFormAttribute($(ele));
});
}
@@ -268,7 +420,7 @@
$(this).remove();
event = $.Event(events.afterDeleteRow);
- $wrapper.trigger(event);
+ $wrapper.trigger(event, [$toDelete, rowsCount]);
});
}
};
@@ -278,7 +430,7 @@
*
* @param input
*/
- var addAttribute = function (input) {
+ var addActiveFormAttribute = function (input) {
var id = getInputId(input);
// skip if we could not get an ID of input
@@ -290,9 +442,8 @@
wrapper = ele.closest('.multiple-input').first(),
form = ele.closest('form');
-
// do not add attribute which are not the part of widget
- if (wrapper.length == 0) {
+ if (wrapper.length === 0) {
return;
}
@@ -301,9 +452,26 @@
return;
}
+ var data = wrapper.data('multipleInput'),
+ attributeOptions = {};
+
+ // try to find options for embedded attribute at first.
+ // For example the id of new input is example-1-field-0.
+ // We remove last index and check whether attribute with such id exists or not.
+ var bareId = id.replace(/-\d+-([^\d]+)$/, '-$1');
+ if (data.settings.attributes.hasOwnProperty(bareId)) {
+ attributeOptions = data.settings.attributes[bareId];
+ } else {
+ // fallback in case of using flatten widget - just remove all digital indexes
+ // and check whether attribute exists or not.
+ bareId = replaceAll(/-\d+-/, '-', bareId);
+ bareId = replaceAll(/-\d+/, '', bareId);
+ if (data.settings.attributes.hasOwnProperty(bareId)) {
+ attributeOptions = data.settings.attributes[bareId];
+ }
+ }
- var data = wrapper.data('multipleInput');
- form.yiiActiveForm('add', $.extend({}, data.attributeDefaults, {
+ form.yiiActiveForm('add', $.extend({}, attributeOptions, {
'id': id,
'input': '#' + id,
'container': '.field-' + id
@@ -313,8 +481,8 @@
/**
* Removes an attribute from ActiveForm.
*/
- var removeAttribute = function () {
- var id = getInputId($(this));
+ var removeActiveFormAttribute = function (ele) {
+ var id = getInputId(ele);
if (id === null) {
return;
@@ -341,15 +509,37 @@
return id;
};
- var getCurrentIndex = function($wrapper) {
+ var getRowsCount = function($wrapper) {
+ return findRows($wrapper).length;
+ };
+
+ var findRows = function($wrapper) {
return $wrapper
- .children('.multiple-input-list')
- .children('tbody')
- .children('.multiple-input-list__item')
- .length;
+ .find('.multiple-input-list .multiple-input-list__item')
+ .filter(function(){
+ return $(this).parents('.multiple-input').first().attr('id') === $wrapper.attr('id');
+ });
+ }
+
+ var findMaxRowIndex = function($wrapper) {
+ let maxIndex = 0;
+
+ findRows($wrapper).each(function(key, element) {
+ let index = $(element).data('index');
+ if (index > maxIndex) {
+ maxIndex = index;
+ }
+ });
+
+ return maxIndex;
};
- String.prototype.replaceAll = function (search, replace) {
- return this.split(search).join(replace);
+ var replaceAll = function (search, replace, subject) {
+ if (!(subject instanceof String) && typeof subject !== 'string') {
+ console.warn('Call replaceAll for non-string value: ' + subject);
+ return subject;
+ }
+
+ return subject.split(search).join(replace);
};
-})(window.jQuery);
\ No newline at end of file
+})(window.jQuery);
diff --git a/src/assets/src/js/jquery.multipleInput.min.js b/src/assets/src/js/jquery.multipleInput.min.js
index c4c192f..636f288 100644
--- a/src/assets/src/js/jquery.multipleInput.min.js
+++ b/src/assets/src/js/jquery.multipleInput.min.js
@@ -1 +1 @@
-!function(t){t.fn.multipleInput=function(e){return r[e]?r[e].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof e&&e?(t.error("Method "+e+" does not exist on jQuery.multipleInput"),!1):r.init.apply(this,arguments)};var e={afterInit:"afterInit",afterAddRow:"afterAddRow",beforeDeleteRow:"beforeDeleteRow",afterDeleteRow:"afterDeleteRow"},i={id:null,template:null,jsTemplates:[],limit:1,min:1,attributeOptions:{},indexPlaceholder:"multiple_index"},n={enableAjaxValidation:!1,validateOnBlur:!1,validateOnChange:!1,validateOnType:!1},l=!1,r={init:function(r){var p=t.extend(!0,{},i,r||{}),f=t("#"+p.id),c=f.closest("form"),s=this.selector.replace("#","");f.data("multipleInput",{settings:p,currentIndex:0,attributeDefaults:{}}),f.on("click.multipleInput",".js-input-remove",function(e){e.stopPropagation(),u(t(this))}),f.on("click.multipleInput",".js-input-plus",function(e){e.stopPropagation(),a(t(this))});var v=0,m=t.Event(e.afterInit),h=setInterval(function(){if("object"==typeof c.data("yiiActiveForm")){var e=c.yiiActiveForm("find",s),i=[];"object"==typeof e&&(t.each(e,function(t,e){-1==["id","input","container"].indexOf(t)&&(i[t]=e)}),c.yiiActiveForm("remove",s));var r=t.extend({},n,p.attributeOptions);t.each(r,function(t,e){"undefined"==typeof i[t]&&(i[t]=e)}),f.data("multipleInput").attributeDefaults=i,f.find(".multiple-input-list").find("input, select, textarea").each(function(){o(t(this))}),f.data("multipleInput").currentIndex=d(f),l=!0,clearInterval(h),f.trigger(m)}else v++;v>10&&(f.data("multipleInput").currentIndex=d(f),l=!1,clearInterval(h),f.trigger(m))},100)},add:function(e){a(t(this),e)},remove:function(e){var i=null;i=e?t(this).find(".js-input-remove:eq("+e+")"):t(this).find(".js-input-remove").last(),u(i)},clear:function(){t(".js-input-remove").each(function(){u(t(this))})}},a=function(i,n){var r=t(i).closest(".multiple-input").first(),a=r.data("multipleInput"),u=a.settings,p=u.template,c=r.children(".multiple-input-list").first();if(!(null!=u.limit&&d(r)>=u.limit)){if(p=p.replaceAll("{"+u.indexPlaceholder+"}",a.currentIndex),t(p).hide().appendTo(c).fadeIn(300),n instanceof Object){var s=[];for(var v in n)n.hasOwnProperty(v)&&s.push(n[v]);n=s}var m;for(var h in u.jsTemplates)m=u.jsTemplates[h].replaceAll("{"+u.indexPlaceholder+"}",a.currentIndex).replaceAll("%7B"+u.indexPlaceholder+"%7D",a.currentIndex),window.eval(m);var I=0;t(p).find("input, select, textarea").each(function(){var e=t(this),i=e.get(0).tagName,r=f(e),a=t("#"+r);if(n){var u=n[I];if("INPUT"==i||"TEXTAREA"==i)a.val(u);else if("SELECT"==i)if(u&&-1!=u.indexOf("option"))a.append(u);else{var p=a.find('option[value="'+u+'"]');p.length&&a.val(u)}}l&&o(e),I++}),r.data("multipleInput").currentIndex++;var g=t.Event(e.afterAddRow);r.trigger(g)}},u=function(i){var n=i.closest(".multiple-input").first(),r=i.closest(".multiple-input-list__item"),a=n.data("multipleInput"),u=a.settings;if(d(n)>u.min){var o=t.Event(e.beforeDeleteRow);if(n.trigger(o,[r]),o.result===!1)return;l&&r.find("input, select, textarea").each(function(){p(t(this))}),r.fadeOut(300,function(){t(this).remove(),o=t.Event(e.afterDeleteRow),n.trigger(o)})}},o=function(e){var i=f(e);if(null!==i){var n=t("#"+i),l=n.closest(".multiple-input").first(),r=n.closest("form");if(0!=l.length&&"undefined"==typeof r.yiiActiveForm("find",i)){var a=l.data("multipleInput");r.yiiActiveForm("add",t.extend({},a.attributeDefaults,{id:i,input:"#"+i,container:".field-"+i}))}}},p=function(){var e=f(t(this));if(null!==e){var i=t("#"+e).closest("form");0!==i.length&&i.yiiActiveForm("remove",e)}},f=function(t){var e=t.attr("id");return"undefined"==typeof e&&(e=t.data("id")),"undefined"==typeof e?null:e},d=function(t){return t.children(".multiple-input-list").children("tbody").children(".multiple-input-list__item").length};String.prototype.replaceAll=function(t,e){return this.split(t).join(e)}}(window.jQuery);
\ No newline at end of file
+!function(t){"use strict";t.fn.multipleInput=function(e){return o[e]?o[e].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof e&&e?(t.error("Method "+e+" does not exist on jQuery.multipleInput"),!1):o.init.apply(this,arguments)};var e="afterInit",i="beforeAddRow",n="afterAddRow",l="beforeDeleteRow",r="afterDeleteRow",a={id:null,inputId:null,template:null,jsTemplates:[],jsInit:[],max:1,min:1,attributes:{},indexPlaceholder:"multiple_index",showGeneralError:!1,prepend:!1},u=!1,o={init:function(i){if("object"==typeof i){var n=t.extend(!0,{},a,i||{}),l=t("#"+n.id),r=l.closest("form"),o=n.inputId;for(f in n.jsInit)window.eval(n.jsInit[f]);l.data("multipleInput",{settings:n,currentIndex:0}),l.on("click.multipleInput",".js-input-remove",(function(e){e.stopPropagation(),c(t(this))})),l.on("click.multipleInput",".js-input-plus",(function(e){e.stopPropagation(),p(t(this))})),l.on("click.multipleInput",".js-input-clone",(function(e){e.stopPropagation(),s(t(this))}));var f=0,m=t.Event(e),v=setInterval((function(){if("object"==typeof r.data("yiiActiveForm")){var e=r.yiiActiveForm("find",o),i={enableAjaxValidation:!1,validateOnBlur:!1,validateOnChange:!1,validateOnType:!1,validationDelay:500};"object"==typeof e&&(t.each(e,(function(t,e){-1===["id","input","container"].indexOf(t)&&(i[t]=e)})),n.showGeneralError||r.yiiActiveForm("remove",o)),t.each(n.attributes,(function(e,l){l=t.extend({},i,l),n.attributes[e]=l})),l.data("multipleInput").settings=n,l.find(".multiple-input-list").find("input, select, textarea").each((function(){d(t(this))})),l.data("multipleInput").currentIndex=g(l),u=!0,clearInterval(v),l.trigger(m)}else f++;(0===r.length||f>10)&&(clearInterval(v),u=!1,void 0!==l.data("multipleInput")&&(l.data("multipleInput").currentIndex=g(l)),l.trigger(m))}),100)}else console.error("Options must be an object")},add:function(e){p(t(this),e)},remove:function(e){var i=null;i=void 0!==e?t(this).find(".js-input-remove:eq("+e+")"):t(this).find(".js-input-remove").last(),c(i)},clear:function(){t(this).find(".js-input-remove").each((function(){c(t(this))}))},option:function(e,i){i=i||null;var n=t(this).data("multipleInput"),l=n.settings;if(null===i){if(!l.hasOwnProperty(e))throw new Error('Option "'+e+'" does not exist');return l[e]}l.hasOwnProperty(e)&&(l[e]=i,n.settings=l,t(this).data("multipleInput",n))}},s=function(e){let i=t(e).closest(".multiple-input").first().data("multipleInput").settings,n={};e.closest(".multiple-input-list__item").find("input, select, textarea").each((function(e,l){let r=t(l),a=m(r);if(a){let t=a.replace(i.inputId,"").replace(/-\d+-/,"");r.is(":checkbox")?(n.hasOwnProperty(t)||(n[t]=[]),r.is(":checked")&&n[t].push(r.val())):n[t]=r.val()}})),p(e,n)},p=function(e,l){l=l||{};let r=t(e).closest(".multiple-input").first(),a=r.data("multipleInput"),o=a.settings,s=r.children(".multiple-input-list").first();if(null!==o.max&&v(r)>=o.max)return;let p=a.currentIndex+1,c=I("{"+o.indexPlaceholder+"}",p,o.template),f=t(c);var h=t.Event(i);if(r.trigger(h,[f,p]),!1===h.result)return;f.find("input, select, textarea").each((function(e,i){let n=t(i),r=m(n);if(r){let t=r.replace(o.inputId,"").replace(/-\d+-?/,"");if(l.hasOwnProperty(t)){let e=n.get(0).tagName,i=l[t];switch(e){case"INPUT":n.is(":checkbox")?-1!==i.indexOf(n.val())&&n.prop("checked",!0):n.val(i);break;case"TEXTAREA":n.val(i);break;case"SELECT":if(i&&-1!==i.indexOf("option"))n.append(i);else n.find('option[value="'+i+'"]').length&&n.val(i)}}}})),o.prepend?f.hide().prependTo(s).fadeIn(300):f.hide().appendTo(s).fadeIn(300);let g=null;for(var x in o.jsTemplates)g=o.jsTemplates[x],g=I("{"+o.indexPlaceholder+"}",p,g),g=I("%7B"+o.indexPlaceholder+"%7D",p,g),window.eval(g);u&&f.find("input, select, textarea").each((function(e,i){let n=t(i);d(n)})),r.data("multipleInput").currentIndex=p;var y=t.Event(n);r.trigger(y,[f,p])},c=function(e){var i=e.closest(".multiple-input").first(),n=e.closest(".multiple-input-list__item"),a=i.data("multipleInput"),o=a.settings,s=v(i);if(s>o.min){var p=t.Event(l);if(i.trigger(p,[n,a.currentIndex]),!1===p.result)return;u&&n.find("input, select, textarea").each((function(e,i){f(t(i))})),n.fadeOut(300,(function(){t(this).remove(),p=t.Event(r),i.trigger(p,[n,s])}))}},d=function(e){var i=m(e);if(null!==i){var n=t("#"+i),l=n.closest(".multiple-input").first(),r=n.closest("form");if(0!==l.length&&void 0===r.yiiActiveForm("find",i)){var a=l.data("multipleInput"),u={},o=i.replace(/-\d+-([^\d]+)$/,"-$1");a.settings.attributes.hasOwnProperty(o)?u=a.settings.attributes[o]:(o=I(/-\d+-/,"-",o),o=I(/-\d+/,"",o),a.settings.attributes.hasOwnProperty(o)&&(u=a.settings.attributes[o])),r.yiiActiveForm("add",t.extend({},u,{id:i,input:"#"+i,container:".field-"+i}))}}},f=function(e){var i=m(e);if(null!==i){var n=t("#"+i).closest("form");0!==n.length&&n.yiiActiveForm("remove",i)}},m=function(t){var e=t.attr("id");return void 0===e&&(e=t.data("id")),void 0===e?null:e},v=function(t){return h(t).length},h=function(e){return e.find(".multiple-input-list .multiple-input-list__item").filter((function(){return t(this).parents(".multiple-input").first().attr("id")===e.attr("id")}))},g=function(e){let i=0;return h(e).each((function(e,n){let l=t(n).data("index");l>i&&(i=l)})),i},I=function(t,e,i){return i instanceof String||"string"==typeof i?i.split(t).join(e):(console.warn("Call replaceAll for non-string value: "+i),i)}}(window.jQuery);
\ No newline at end of file
diff --git a/src/assets/src/js/sortable.js b/src/assets/src/js/sortable.js
new file mode 100644
index 0000000..98c90ab
--- /dev/null
+++ b/src/assets/src/js/sortable.js
@@ -0,0 +1,3362 @@
+/**!
+ * Sortable 1.15.2
+ * @author RubaXa
+ * @author owenm
+ * @license MIT
+ */
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global = global || self, global.Sortable = factory());
+}(this, (function () { 'use strict';
+
+ function ownKeys(object, enumerableOnly) {
+ var keys = Object.keys(object);
+ if (Object.getOwnPropertySymbols) {
+ var symbols = Object.getOwnPropertySymbols(object);
+ if (enumerableOnly) {
+ symbols = symbols.filter(function (sym) {
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
+ });
+ }
+ keys.push.apply(keys, symbols);
+ }
+ return keys;
+ }
+ function _objectSpread2(target) {
+ for (var i = 1; i < arguments.length; i++) {
+ var source = arguments[i] != null ? arguments[i] : {};
+ if (i % 2) {
+ ownKeys(Object(source), true).forEach(function (key) {
+ _defineProperty(target, key, source[key]);
+ });
+ } else if (Object.getOwnPropertyDescriptors) {
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
+ } else {
+ ownKeys(Object(source)).forEach(function (key) {
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
+ });
+ }
+ }
+ return target;
+ }
+ function _typeof(obj) {
+ "@babel/helpers - typeof";
+
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
+ _typeof = function (obj) {
+ return typeof obj;
+ };
+ } else {
+ _typeof = function (obj) {
+ return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
+ };
+ }
+ return _typeof(obj);
+ }
+ function _defineProperty(obj, key, value) {
+ if (key in obj) {
+ Object.defineProperty(obj, key, {
+ value: value,
+ enumerable: true,
+ configurable: true,
+ writable: true
+ });
+ } else {
+ obj[key] = value;
+ }
+ return obj;
+ }
+ function _extends() {
+ _extends = Object.assign || function (target) {
+ for (var i = 1; i < arguments.length; i++) {
+ var source = arguments[i];
+ for (var key in source) {
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
+ target[key] = source[key];
+ }
+ }
+ }
+ return target;
+ };
+ return _extends.apply(this, arguments);
+ }
+ function _objectWithoutPropertiesLoose(source, excluded) {
+ if (source == null) return {};
+ var target = {};
+ var sourceKeys = Object.keys(source);
+ var key, i;
+ for (i = 0; i < sourceKeys.length; i++) {
+ key = sourceKeys[i];
+ if (excluded.indexOf(key) >= 0) continue;
+ target[key] = source[key];
+ }
+ return target;
+ }
+ function _objectWithoutProperties(source, excluded) {
+ if (source == null) return {};
+ var target = _objectWithoutPropertiesLoose(source, excluded);
+ var key, i;
+ if (Object.getOwnPropertySymbols) {
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
+ for (i = 0; i < sourceSymbolKeys.length; i++) {
+ key = sourceSymbolKeys[i];
+ if (excluded.indexOf(key) >= 0) continue;
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
+ target[key] = source[key];
+ }
+ }
+ return target;
+ }
+ function _toConsumableArray(arr) {
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
+ }
+ function _arrayWithoutHoles(arr) {
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
+ }
+ function _iterableToArray(iter) {
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
+ }
+ function _unsupportedIterableToArray(o, minLen) {
+ if (!o) return;
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
+ var n = Object.prototype.toString.call(o).slice(8, -1);
+ if (n === "Object" && o.constructor) n = o.constructor.name;
+ if (n === "Map" || n === "Set") return Array.from(o);
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
+ }
+ function _arrayLikeToArray(arr, len) {
+ if (len == null || len > arr.length) len = arr.length;
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
+ return arr2;
+ }
+ function _nonIterableSpread() {
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
+ }
+
+ var version = "1.15.2";
+
+ function userAgent(pattern) {
+ if (typeof window !== 'undefined' && window.navigator) {
+ return !! /*@__PURE__*/navigator.userAgent.match(pattern);
+ }
+ }
+ var IE11OrLess = userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i);
+ var Edge = userAgent(/Edge/i);
+ var FireFox = userAgent(/firefox/i);
+ var Safari = userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i);
+ var IOS = userAgent(/iP(ad|od|hone)/i);
+ var ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i);
+
+ var captureMode = {
+ capture: false,
+ passive: false
+ };
+ function on(el, event, fn) {
+ el.addEventListener(event, fn, !IE11OrLess && captureMode);
+ }
+ function off(el, event, fn) {
+ el.removeEventListener(event, fn, !IE11OrLess && captureMode);
+ }
+ function matches( /**HTMLElement*/el, /**String*/selector) {
+ if (!selector) return;
+ selector[0] === '>' && (selector = selector.substring(1));
+ if (el) {
+ try {
+ if (el.matches) {
+ return el.matches(selector);
+ } else if (el.msMatchesSelector) {
+ return el.msMatchesSelector(selector);
+ } else if (el.webkitMatchesSelector) {
+ return el.webkitMatchesSelector(selector);
+ }
+ } catch (_) {
+ return false;
+ }
+ }
+ return false;
+ }
+ function getParentOrHost(el) {
+ return el.host && el !== document && el.host.nodeType ? el.host : el.parentNode;
+ }
+ function closest( /**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) {
+ if (el) {
+ ctx = ctx || document;
+ do {
+ if (selector != null && (selector[0] === '>' ? el.parentNode === ctx && matches(el, selector) : matches(el, selector)) || includeCTX && el === ctx) {
+ return el;
+ }
+ if (el === ctx) break;
+ /* jshint boss:true */
+ } while (el = getParentOrHost(el));
+ }
+ return null;
+ }
+ var R_SPACE = /\s+/g;
+ function toggleClass(el, name, state) {
+ if (el && name) {
+ if (el.classList) {
+ el.classList[state ? 'add' : 'remove'](name);
+ } else {
+ var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');
+ el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');
+ }
+ }
+ }
+ function css(el, prop, val) {
+ var style = el && el.style;
+ if (style) {
+ if (val === void 0) {
+ if (document.defaultView && document.defaultView.getComputedStyle) {
+ val = document.defaultView.getComputedStyle(el, '');
+ } else if (el.currentStyle) {
+ val = el.currentStyle;
+ }
+ return prop === void 0 ? val : val[prop];
+ } else {
+ if (!(prop in style) && prop.indexOf('webkit') === -1) {
+ prop = '-webkit-' + prop;
+ }
+ style[prop] = val + (typeof val === 'string' ? '' : 'px');
+ }
+ }
+ }
+ function matrix(el, selfOnly) {
+ var appliedTransforms = '';
+ if (typeof el === 'string') {
+ appliedTransforms = el;
+ } else {
+ do {
+ var transform = css(el, 'transform');
+ if (transform && transform !== 'none') {
+ appliedTransforms = transform + ' ' + appliedTransforms;
+ }
+ /* jshint boss:true */
+ } while (!selfOnly && (el = el.parentNode));
+ }
+ var matrixFn = window.DOMMatrix || window.WebKitCSSMatrix || window.CSSMatrix || window.MSCSSMatrix;
+ /*jshint -W056 */
+ return matrixFn && new matrixFn(appliedTransforms);
+ }
+ function find(ctx, tagName, iterator) {
+ if (ctx) {
+ var list = ctx.getElementsByTagName(tagName),
+ i = 0,
+ n = list.length;
+ if (iterator) {
+ for (; i < n; i++) {
+ iterator(list[i], i);
+ }
+ }
+ return list;
+ }
+ return [];
+ }
+ function getWindowScrollingElement() {
+ var scrollingElement = document.scrollingElement;
+ if (scrollingElement) {
+ return scrollingElement;
+ } else {
+ return document.documentElement;
+ }
+ }
+
+ /**
+ * Returns the "bounding client rect" of given element
+ * @param {HTMLElement} el The element whose boundingClientRect is wanted
+ * @param {[Boolean]} relativeToContainingBlock Whether the rect should be relative to the containing block of (including) the container
+ * @param {[Boolean]} relativeToNonStaticParent Whether the rect should be relative to the relative parent of (including) the contaienr
+ * @param {[Boolean]} undoScale Whether the container's scale() should be undone
+ * @param {[HTMLElement]} container The parent the element will be placed in
+ * @return {Object} The boundingClientRect of el, with specified adjustments
+ */
+ function getRect(el, relativeToContainingBlock, relativeToNonStaticParent, undoScale, container) {
+ if (!el.getBoundingClientRect && el !== window) return;
+ var elRect, top, left, bottom, right, height, width;
+ if (el !== window && el.parentNode && el !== getWindowScrollingElement()) {
+ elRect = el.getBoundingClientRect();
+ top = elRect.top;
+ left = elRect.left;
+ bottom = elRect.bottom;
+ right = elRect.right;
+ height = elRect.height;
+ width = elRect.width;
+ } else {
+ top = 0;
+ left = 0;
+ bottom = window.innerHeight;
+ right = window.innerWidth;
+ height = window.innerHeight;
+ width = window.innerWidth;
+ }
+ if ((relativeToContainingBlock || relativeToNonStaticParent) && el !== window) {
+ // Adjust for translate()
+ container = container || el.parentNode;
+
+ // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312)
+ // Not needed on <= IE11
+ if (!IE11OrLess) {
+ do {
+ if (container && container.getBoundingClientRect && (css(container, 'transform') !== 'none' || relativeToNonStaticParent && css(container, 'position') !== 'static')) {
+ var containerRect = container.getBoundingClientRect();
+
+ // Set relative to edges of padding box of container
+ top -= containerRect.top + parseInt(css(container, 'border-top-width'));
+ left -= containerRect.left + parseInt(css(container, 'border-left-width'));
+ bottom = top + elRect.height;
+ right = left + elRect.width;
+ break;
+ }
+ /* jshint boss:true */
+ } while (container = container.parentNode);
+ }
+ }
+ if (undoScale && el !== window) {
+ // Adjust for scale()
+ var elMatrix = matrix(container || el),
+ scaleX = elMatrix && elMatrix.a,
+ scaleY = elMatrix && elMatrix.d;
+ if (elMatrix) {
+ top /= scaleY;
+ left /= scaleX;
+ width /= scaleX;
+ height /= scaleY;
+ bottom = top + height;
+ right = left + width;
+ }
+ }
+ return {
+ top: top,
+ left: left,
+ bottom: bottom,
+ right: right,
+ width: width,
+ height: height
+ };
+ }
+
+ /**
+ * Checks if a side of an element is scrolled past a side of its parents
+ * @param {HTMLElement} el The element who's side being scrolled out of view is in question
+ * @param {String} elSide Side of the element in question ('top', 'left', 'right', 'bottom')
+ * @param {String} parentSide Side of the parent in question ('top', 'left', 'right', 'bottom')
+ * @return {HTMLElement} The parent scroll element that the el's side is scrolled past, or null if there is no such element
+ */
+ function isScrolledPast(el, elSide, parentSide) {
+ var parent = getParentAutoScrollElement(el, true),
+ elSideVal = getRect(el)[elSide];
+
+ /* jshint boss:true */
+ while (parent) {
+ var parentSideVal = getRect(parent)[parentSide],
+ visible = void 0;
+ if (parentSide === 'top' || parentSide === 'left') {
+ visible = elSideVal >= parentSideVal;
+ } else {
+ visible = elSideVal <= parentSideVal;
+ }
+ if (!visible) return parent;
+ if (parent === getWindowScrollingElement()) break;
+ parent = getParentAutoScrollElement(parent, false);
+ }
+ return false;
+ }
+
+ /**
+ * Gets nth child of el, ignoring hidden children, sortable's elements (does not ignore clone if it's visible)
+ * and non-draggable elements
+ * @param {HTMLElement} el The parent element
+ * @param {Number} childNum The index of the child
+ * @param {Object} options Parent Sortable's options
+ * @return {HTMLElement} The child at index childNum, or null if not found
+ */
+ function getChild(el, childNum, options, includeDragEl) {
+ var currentChild = 0,
+ i = 0,
+ children = el.children;
+ while (i < children.length) {
+ if (children[i].style.display !== 'none' && children[i] !== Sortable.ghost && (includeDragEl || children[i] !== Sortable.dragged) && closest(children[i], options.draggable, el, false)) {
+ if (currentChild === childNum) {
+ return children[i];
+ }
+ currentChild++;
+ }
+ i++;
+ }
+ return null;
+ }
+
+ /**
+ * Gets the last child in the el, ignoring ghostEl or invisible elements (clones)
+ * @param {HTMLElement} el Parent element
+ * @param {selector} selector Any other elements that should be ignored
+ * @return {HTMLElement} The last child, ignoring ghostEl
+ */
+ function lastChild(el, selector) {
+ var last = el.lastElementChild;
+ while (last && (last === Sortable.ghost || css(last, 'display') === 'none' || selector && !matches(last, selector))) {
+ last = last.previousElementSibling;
+ }
+ return last || null;
+ }
+
+ /**
+ * Returns the index of an element within its parent for a selected set of
+ * elements
+ * @param {HTMLElement} el
+ * @param {selector} selector
+ * @return {number}
+ */
+ function index(el, selector) {
+ var index = 0;
+ if (!el || !el.parentNode) {
+ return -1;
+ }
+
+ /* jshint boss:true */
+ while (el = el.previousElementSibling) {
+ if (el.nodeName.toUpperCase() !== 'TEMPLATE' && el !== Sortable.clone && (!selector || matches(el, selector))) {
+ index++;
+ }
+ }
+ return index;
+ }
+
+ /**
+ * Returns the scroll offset of the given element, added with all the scroll offsets of parent elements.
+ * The value is returned in real pixels.
+ * @param {HTMLElement} el
+ * @return {Array} Offsets in the format of [left, top]
+ */
+ function getRelativeScrollOffset(el) {
+ var offsetLeft = 0,
+ offsetTop = 0,
+ winScroller = getWindowScrollingElement();
+ if (el) {
+ do {
+ var elMatrix = matrix(el),
+ scaleX = elMatrix.a,
+ scaleY = elMatrix.d;
+ offsetLeft += el.scrollLeft * scaleX;
+ offsetTop += el.scrollTop * scaleY;
+ } while (el !== winScroller && (el = el.parentNode));
+ }
+ return [offsetLeft, offsetTop];
+ }
+
+ /**
+ * Returns the index of the object within the given array
+ * @param {Array} arr Array that may or may not hold the object
+ * @param {Object} obj An object that has a key-value pair unique to and identical to a key-value pair in the object you want to find
+ * @return {Number} The index of the object in the array, or -1
+ */
+ function indexOfObject(arr, obj) {
+ for (var i in arr) {
+ if (!arr.hasOwnProperty(i)) continue;
+ for (var key in obj) {
+ if (obj.hasOwnProperty(key) && obj[key] === arr[i][key]) return Number(i);
+ }
+ }
+ return -1;
+ }
+ function getParentAutoScrollElement(el, includeSelf) {
+ // skip to window
+ if (!el || !el.getBoundingClientRect) return getWindowScrollingElement();
+ var elem = el;
+ var gotSelf = false;
+ do {
+ // we don't need to get elem css if it isn't even overflowing in the first place (performance)
+ if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) {
+ var elemCSS = css(elem);
+ if (elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll')) {
+ if (!elem.getBoundingClientRect || elem === document.body) return getWindowScrollingElement();
+ if (gotSelf || includeSelf) return elem;
+ gotSelf = true;
+ }
+ }
+ /* jshint boss:true */
+ } while (elem = elem.parentNode);
+ return getWindowScrollingElement();
+ }
+ function extend(dst, src) {
+ if (dst && src) {
+ for (var key in src) {
+ if (src.hasOwnProperty(key)) {
+ dst[key] = src[key];
+ }
+ }
+ }
+ return dst;
+ }
+ function isRectEqual(rect1, rect2) {
+ return Math.round(rect1.top) === Math.round(rect2.top) && Math.round(rect1.left) === Math.round(rect2.left) && Math.round(rect1.height) === Math.round(rect2.height) && Math.round(rect1.width) === Math.round(rect2.width);
+ }
+ var _throttleTimeout;
+ function throttle(callback, ms) {
+ return function () {
+ if (!_throttleTimeout) {
+ var args = arguments,
+ _this = this;
+ if (args.length === 1) {
+ callback.call(_this, args[0]);
+ } else {
+ callback.apply(_this, args);
+ }
+ _throttleTimeout = setTimeout(function () {
+ _throttleTimeout = void 0;
+ }, ms);
+ }
+ };
+ }
+ function cancelThrottle() {
+ clearTimeout(_throttleTimeout);
+ _throttleTimeout = void 0;
+ }
+ function scrollBy(el, x, y) {
+ el.scrollLeft += x;
+ el.scrollTop += y;
+ }
+ function clone(el) {
+ var Polymer = window.Polymer;
+ var $ = window.jQuery || window.Zepto;
+ if (Polymer && Polymer.dom) {
+ return Polymer.dom(el).cloneNode(true);
+ } else if ($) {
+ return $(el).clone(true)[0];
+ } else {
+ return el.cloneNode(true);
+ }
+ }
+ function setRect(el, rect) {
+ css(el, 'position', 'absolute');
+ css(el, 'top', rect.top);
+ css(el, 'left', rect.left);
+ css(el, 'width', rect.width);
+ css(el, 'height', rect.height);
+ }
+ function unsetRect(el) {
+ css(el, 'position', '');
+ css(el, 'top', '');
+ css(el, 'left', '');
+ css(el, 'width', '');
+ css(el, 'height', '');
+ }
+ function getChildContainingRectFromElement(container, options, ghostEl) {
+ var rect = {};
+ Array.from(container.children).forEach(function (child) {
+ var _rect$left, _rect$top, _rect$right, _rect$bottom;
+ if (!closest(child, options.draggable, container, false) || child.animated || child === ghostEl) return;
+ var childRect = getRect(child);
+ rect.left = Math.min((_rect$left = rect.left) !== null && _rect$left !== void 0 ? _rect$left : Infinity, childRect.left);
+ rect.top = Math.min((_rect$top = rect.top) !== null && _rect$top !== void 0 ? _rect$top : Infinity, childRect.top);
+ rect.right = Math.max((_rect$right = rect.right) !== null && _rect$right !== void 0 ? _rect$right : -Infinity, childRect.right);
+ rect.bottom = Math.max((_rect$bottom = rect.bottom) !== null && _rect$bottom !== void 0 ? _rect$bottom : -Infinity, childRect.bottom);
+ });
+ rect.width = rect.right - rect.left;
+ rect.height = rect.bottom - rect.top;
+ rect.x = rect.left;
+ rect.y = rect.top;
+ return rect;
+ }
+ var expando = 'Sortable' + new Date().getTime();
+
+ function AnimationStateManager() {
+ var animationStates = [],
+ animationCallbackId;
+ return {
+ captureAnimationState: function captureAnimationState() {
+ animationStates = [];
+ if (!this.options.animation) return;
+ var children = [].slice.call(this.el.children);
+ children.forEach(function (child) {
+ if (css(child, 'display') === 'none' || child === Sortable.ghost) return;
+ animationStates.push({
+ target: child,
+ rect: getRect(child)
+ });
+ var fromRect = _objectSpread2({}, animationStates[animationStates.length - 1].rect);
+
+ // If animating: compensate for current animation
+ if (child.thisAnimationDuration) {
+ var childMatrix = matrix(child, true);
+ if (childMatrix) {
+ fromRect.top -= childMatrix.f;
+ fromRect.left -= childMatrix.e;
+ }
+ }
+ child.fromRect = fromRect;
+ });
+ },
+ addAnimationState: function addAnimationState(state) {
+ animationStates.push(state);
+ },
+ removeAnimationState: function removeAnimationState(target) {
+ animationStates.splice(indexOfObject(animationStates, {
+ target: target
+ }), 1);
+ },
+ animateAll: function animateAll(callback) {
+ var _this = this;
+ if (!this.options.animation) {
+ clearTimeout(animationCallbackId);
+ if (typeof callback === 'function') callback();
+ return;
+ }
+ var animating = false,
+ animationTime = 0;
+ animationStates.forEach(function (state) {
+ var time = 0,
+ target = state.target,
+ fromRect = target.fromRect,
+ toRect = getRect(target),
+ prevFromRect = target.prevFromRect,
+ prevToRect = target.prevToRect,
+ animatingRect = state.rect,
+ targetMatrix = matrix(target, true);
+ if (targetMatrix) {
+ // Compensate for current animation
+ toRect.top -= targetMatrix.f;
+ toRect.left -= targetMatrix.e;
+ }
+ target.toRect = toRect;
+ if (target.thisAnimationDuration) {
+ // Could also check if animatingRect is between fromRect and toRect
+ if (isRectEqual(prevFromRect, toRect) && !isRectEqual(fromRect, toRect) &&
+ // Make sure animatingRect is on line between toRect & fromRect
+ (animatingRect.top - toRect.top) / (animatingRect.left - toRect.left) === (fromRect.top - toRect.top) / (fromRect.left - toRect.left)) {
+ // If returning to same place as started from animation and on same axis
+ time = calculateRealTime(animatingRect, prevFromRect, prevToRect, _this.options);
+ }
+ }
+
+ // if fromRect != toRect: animate
+ if (!isRectEqual(toRect, fromRect)) {
+ target.prevFromRect = fromRect;
+ target.prevToRect = toRect;
+ if (!time) {
+ time = _this.options.animation;
+ }
+ _this.animate(target, animatingRect, toRect, time);
+ }
+ if (time) {
+ animating = true;
+ animationTime = Math.max(animationTime, time);
+ clearTimeout(target.animationResetTimer);
+ target.animationResetTimer = setTimeout(function () {
+ target.animationTime = 0;
+ target.prevFromRect = null;
+ target.fromRect = null;
+ target.prevToRect = null;
+ target.thisAnimationDuration = null;
+ }, time);
+ target.thisAnimationDuration = time;
+ }
+ });
+ clearTimeout(animationCallbackId);
+ if (!animating) {
+ if (typeof callback === 'function') callback();
+ } else {
+ animationCallbackId = setTimeout(function () {
+ if (typeof callback === 'function') callback();
+ }, animationTime);
+ }
+ animationStates = [];
+ },
+ animate: function animate(target, currentRect, toRect, duration) {
+ if (duration) {
+ css(target, 'transition', '');
+ css(target, 'transform', '');
+ var elMatrix = matrix(this.el),
+ scaleX = elMatrix && elMatrix.a,
+ scaleY = elMatrix && elMatrix.d,
+ translateX = (currentRect.left - toRect.left) / (scaleX || 1),
+ translateY = (currentRect.top - toRect.top) / (scaleY || 1);
+ target.animatingX = !!translateX;
+ target.animatingY = !!translateY;
+ css(target, 'transform', 'translate3d(' + translateX + 'px,' + translateY + 'px,0)');
+ this.forRepaintDummy = repaint(target); // repaint
+
+ css(target, 'transition', 'transform ' + duration + 'ms' + (this.options.easing ? ' ' + this.options.easing : ''));
+ css(target, 'transform', 'translate3d(0,0,0)');
+ typeof target.animated === 'number' && clearTimeout(target.animated);
+ target.animated = setTimeout(function () {
+ css(target, 'transition', '');
+ css(target, 'transform', '');
+ target.animated = false;
+ target.animatingX = false;
+ target.animatingY = false;
+ }, duration);
+ }
+ }
+ };
+ }
+ function repaint(target) {
+ return target.offsetWidth;
+ }
+ function calculateRealTime(animatingRect, fromRect, toRect, options) {
+ return Math.sqrt(Math.pow(fromRect.top - animatingRect.top, 2) + Math.pow(fromRect.left - animatingRect.left, 2)) / Math.sqrt(Math.pow(fromRect.top - toRect.top, 2) + Math.pow(fromRect.left - toRect.left, 2)) * options.animation;
+ }
+
+ var plugins = [];
+ var defaults = {
+ initializeByDefault: true
+ };
+ var PluginManager = {
+ mount: function mount(plugin) {
+ // Set default static properties
+ for (var option in defaults) {
+ if (defaults.hasOwnProperty(option) && !(option in plugin)) {
+ plugin[option] = defaults[option];
+ }
+ }
+ plugins.forEach(function (p) {
+ if (p.pluginName === plugin.pluginName) {
+ throw "Sortable: Cannot mount plugin ".concat(plugin.pluginName, " more than once");
+ }
+ });
+ plugins.push(plugin);
+ },
+ pluginEvent: function pluginEvent(eventName, sortable, evt) {
+ var _this = this;
+ this.eventCanceled = false;
+ evt.cancel = function () {
+ _this.eventCanceled = true;
+ };
+ var eventNameGlobal = eventName + 'Global';
+ plugins.forEach(function (plugin) {
+ if (!sortable[plugin.pluginName]) return;
+ // Fire global events if it exists in this sortable
+ if (sortable[plugin.pluginName][eventNameGlobal]) {
+ sortable[plugin.pluginName][eventNameGlobal](_objectSpread2({
+ sortable: sortable
+ }, evt));
+ }
+
+ // Only fire plugin event if plugin is enabled in this sortable,
+ // and plugin has event defined
+ if (sortable.options[plugin.pluginName] && sortable[plugin.pluginName][eventName]) {
+ sortable[plugin.pluginName][eventName](_objectSpread2({
+ sortable: sortable
+ }, evt));
+ }
+ });
+ },
+ initializePlugins: function initializePlugins(sortable, el, defaults, options) {
+ plugins.forEach(function (plugin) {
+ var pluginName = plugin.pluginName;
+ if (!sortable.options[pluginName] && !plugin.initializeByDefault) return;
+ var initialized = new plugin(sortable, el, sortable.options);
+ initialized.sortable = sortable;
+ initialized.options = sortable.options;
+ sortable[pluginName] = initialized;
+
+ // Add default options from plugin
+ _extends(defaults, initialized.defaults);
+ });
+ for (var option in sortable.options) {
+ if (!sortable.options.hasOwnProperty(option)) continue;
+ var modified = this.modifyOption(sortable, option, sortable.options[option]);
+ if (typeof modified !== 'undefined') {
+ sortable.options[option] = modified;
+ }
+ }
+ },
+ getEventProperties: function getEventProperties(name, sortable) {
+ var eventProperties = {};
+ plugins.forEach(function (plugin) {
+ if (typeof plugin.eventProperties !== 'function') return;
+ _extends(eventProperties, plugin.eventProperties.call(sortable[plugin.pluginName], name));
+ });
+ return eventProperties;
+ },
+ modifyOption: function modifyOption(sortable, name, value) {
+ var modifiedValue;
+ plugins.forEach(function (plugin) {
+ // Plugin must exist on the Sortable
+ if (!sortable[plugin.pluginName]) return;
+
+ // If static option listener exists for this option, call in the context of the Sortable's instance of this plugin
+ if (plugin.optionListeners && typeof plugin.optionListeners[name] === 'function') {
+ modifiedValue = plugin.optionListeners[name].call(sortable[plugin.pluginName], value);
+ }
+ });
+ return modifiedValue;
+ }
+ };
+
+ function dispatchEvent(_ref) {
+ var sortable = _ref.sortable,
+ rootEl = _ref.rootEl,
+ name = _ref.name,
+ targetEl = _ref.targetEl,
+ cloneEl = _ref.cloneEl,
+ toEl = _ref.toEl,
+ fromEl = _ref.fromEl,
+ oldIndex = _ref.oldIndex,
+ newIndex = _ref.newIndex,
+ oldDraggableIndex = _ref.oldDraggableIndex,
+ newDraggableIndex = _ref.newDraggableIndex,
+ originalEvent = _ref.originalEvent,
+ putSortable = _ref.putSortable,
+ extraEventProperties = _ref.extraEventProperties;
+ sortable = sortable || rootEl && rootEl[expando];
+ if (!sortable) return;
+ var evt,
+ options = sortable.options,
+ onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);
+ // Support for new CustomEvent feature
+ if (window.CustomEvent && !IE11OrLess && !Edge) {
+ evt = new CustomEvent(name, {
+ bubbles: true,
+ cancelable: true
+ });
+ } else {
+ evt = document.createEvent('Event');
+ evt.initEvent(name, true, true);
+ }
+ evt.to = toEl || rootEl;
+ evt.from = fromEl || rootEl;
+ evt.item = targetEl || rootEl;
+ evt.clone = cloneEl;
+ evt.oldIndex = oldIndex;
+ evt.newIndex = newIndex;
+ evt.oldDraggableIndex = oldDraggableIndex;
+ evt.newDraggableIndex = newDraggableIndex;
+ evt.originalEvent = originalEvent;
+ evt.pullMode = putSortable ? putSortable.lastPutMode : undefined;
+ var allEventProperties = _objectSpread2(_objectSpread2({}, extraEventProperties), PluginManager.getEventProperties(name, sortable));
+ for (var option in allEventProperties) {
+ evt[option] = allEventProperties[option];
+ }
+ if (rootEl) {
+ rootEl.dispatchEvent(evt);
+ }
+ if (options[onName]) {
+ options[onName].call(sortable, evt);
+ }
+ }
+
+ var _excluded = ["evt"];
+ var pluginEvent = function pluginEvent(eventName, sortable) {
+ var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
+ originalEvent = _ref.evt,
+ data = _objectWithoutProperties(_ref, _excluded);
+ PluginManager.pluginEvent.bind(Sortable)(eventName, sortable, _objectSpread2({
+ dragEl: dragEl,
+ parentEl: parentEl,
+ ghostEl: ghostEl,
+ rootEl: rootEl,
+ nextEl: nextEl,
+ lastDownEl: lastDownEl,
+ cloneEl: cloneEl,
+ cloneHidden: cloneHidden,
+ dragStarted: moved,
+ putSortable: putSortable,
+ activeSortable: Sortable.active,
+ originalEvent: originalEvent,
+ oldIndex: oldIndex,
+ oldDraggableIndex: oldDraggableIndex,
+ newIndex: newIndex,
+ newDraggableIndex: newDraggableIndex,
+ hideGhostForTarget: _hideGhostForTarget,
+ unhideGhostForTarget: _unhideGhostForTarget,
+ cloneNowHidden: function cloneNowHidden() {
+ cloneHidden = true;
+ },
+ cloneNowShown: function cloneNowShown() {
+ cloneHidden = false;
+ },
+ dispatchSortableEvent: function dispatchSortableEvent(name) {
+ _dispatchEvent({
+ sortable: sortable,
+ name: name,
+ originalEvent: originalEvent
+ });
+ }
+ }, data));
+ };
+ function _dispatchEvent(info) {
+ dispatchEvent(_objectSpread2({
+ putSortable: putSortable,
+ cloneEl: cloneEl,
+ targetEl: dragEl,
+ rootEl: rootEl,
+ oldIndex: oldIndex,
+ oldDraggableIndex: oldDraggableIndex,
+ newIndex: newIndex,
+ newDraggableIndex: newDraggableIndex
+ }, info));
+ }
+ var dragEl,
+ parentEl,
+ ghostEl,
+ rootEl,
+ nextEl,
+ lastDownEl,
+ cloneEl,
+ cloneHidden,
+ oldIndex,
+ newIndex,
+ oldDraggableIndex,
+ newDraggableIndex,
+ activeGroup,
+ putSortable,
+ awaitingDragStarted = false,
+ ignoreNextClick = false,
+ sortables = [],
+ tapEvt,
+ touchEvt,
+ lastDx,
+ lastDy,
+ tapDistanceLeft,
+ tapDistanceTop,
+ moved,
+ lastTarget,
+ lastDirection,
+ pastFirstInvertThresh = false,
+ isCircumstantialInvert = false,
+ targetMoveDistance,
+ // For positioning ghost absolutely
+ ghostRelativeParent,
+ ghostRelativeParentInitialScroll = [],
+ // (left, top)
+
+ _silent = false,
+ savedInputChecked = [];
+
+ /** @const */
+ var documentExists = typeof document !== 'undefined',
+ PositionGhostAbsolutely = IOS,
+ CSSFloatProperty = Edge || IE11OrLess ? 'cssFloat' : 'float',
+ // This will not pass for IE9, because IE9 DnD only works on anchors
+ supportDraggable = documentExists && !ChromeForAndroid && !IOS && 'draggable' in document.createElement('div'),
+ supportCssPointerEvents = function () {
+ if (!documentExists) return;
+ // false when <= IE11
+ if (IE11OrLess) {
+ return false;
+ }
+ var el = document.createElement('x');
+ el.style.cssText = 'pointer-events:auto';
+ return el.style.pointerEvents === 'auto';
+ }(),
+ _detectDirection = function _detectDirection(el, options) {
+ var elCSS = css(el),
+ elWidth = parseInt(elCSS.width) - parseInt(elCSS.paddingLeft) - parseInt(elCSS.paddingRight) - parseInt(elCSS.borderLeftWidth) - parseInt(elCSS.borderRightWidth),
+ child1 = getChild(el, 0, options),
+ child2 = getChild(el, 1, options),
+ firstChildCSS = child1 && css(child1),
+ secondChildCSS = child2 && css(child2),
+ firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + getRect(child1).width,
+ secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + getRect(child2).width;
+ if (elCSS.display === 'flex') {
+ return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal';
+ }
+ if (elCSS.display === 'grid') {
+ return elCSS.gridTemplateColumns.split(' ').length <= 1 ? 'vertical' : 'horizontal';
+ }
+ if (child1 && firstChildCSS["float"] && firstChildCSS["float"] !== 'none') {
+ var touchingSideChild2 = firstChildCSS["float"] === 'left' ? 'left' : 'right';
+ return child2 && (secondChildCSS.clear === 'both' || secondChildCSS.clear === touchingSideChild2) ? 'vertical' : 'horizontal';
+ }
+ return child1 && (firstChildCSS.display === 'block' || firstChildCSS.display === 'flex' || firstChildCSS.display === 'table' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS[CSSFloatProperty] === 'none' || child2 && elCSS[CSSFloatProperty] === 'none' && firstChildWidth + secondChildWidth > elWidth) ? 'vertical' : 'horizontal';
+ },
+ _dragElInRowColumn = function _dragElInRowColumn(dragRect, targetRect, vertical) {
+ var dragElS1Opp = vertical ? dragRect.left : dragRect.top,
+ dragElS2Opp = vertical ? dragRect.right : dragRect.bottom,
+ dragElOppLength = vertical ? dragRect.width : dragRect.height,
+ targetS1Opp = vertical ? targetRect.left : targetRect.top,
+ targetS2Opp = vertical ? targetRect.right : targetRect.bottom,
+ targetOppLength = vertical ? targetRect.width : targetRect.height;
+ return dragElS1Opp === targetS1Opp || dragElS2Opp === targetS2Opp || dragElS1Opp + dragElOppLength / 2 === targetS1Opp + targetOppLength / 2;
+ },
+ /**
+ * Detects first nearest empty sortable to X and Y position using emptyInsertThreshold.
+ * @param {Number} x X position
+ * @param {Number} y Y position
+ * @return {HTMLElement} Element of the first found nearest Sortable
+ */
+ _detectNearestEmptySortable = function _detectNearestEmptySortable(x, y) {
+ var ret;
+ sortables.some(function (sortable) {
+ var threshold = sortable[expando].options.emptyInsertThreshold;
+ if (!threshold || lastChild(sortable)) return;
+ var rect = getRect(sortable),
+ insideHorizontally = x >= rect.left - threshold && x <= rect.right + threshold,
+ insideVertically = y >= rect.top - threshold && y <= rect.bottom + threshold;
+ if (insideHorizontally && insideVertically) {
+ return ret = sortable;
+ }
+ });
+ return ret;
+ },
+ _prepareGroup = function _prepareGroup(options) {
+ function toFn(value, pull) {
+ return function (to, from, dragEl, evt) {
+ var sameGroup = to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name;
+ if (value == null && (pull || sameGroup)) {
+ // Default pull value
+ // Default pull and put value if same group
+ return true;
+ } else if (value == null || value === false) {
+ return false;
+ } else if (pull && value === 'clone') {
+ return value;
+ } else if (typeof value === 'function') {
+ return toFn(value(to, from, dragEl, evt), pull)(to, from, dragEl, evt);
+ } else {
+ var otherGroup = (pull ? to : from).options.group.name;
+ return value === true || typeof value === 'string' && value === otherGroup || value.join && value.indexOf(otherGroup) > -1;
+ }
+ };
+ }
+ var group = {};
+ var originalGroup = options.group;
+ if (!originalGroup || _typeof(originalGroup) != 'object') {
+ originalGroup = {
+ name: originalGroup
+ };
+ }
+ group.name = originalGroup.name;
+ group.checkPull = toFn(originalGroup.pull, true);
+ group.checkPut = toFn(originalGroup.put);
+ group.revertClone = originalGroup.revertClone;
+ options.group = group;
+ },
+ _hideGhostForTarget = function _hideGhostForTarget() {
+ if (!supportCssPointerEvents && ghostEl) {
+ css(ghostEl, 'display', 'none');
+ }
+ },
+ _unhideGhostForTarget = function _unhideGhostForTarget() {
+ if (!supportCssPointerEvents && ghostEl) {
+ css(ghostEl, 'display', '');
+ }
+ };
+
+ // #1184 fix - Prevent click event on fallback if dragged but item not changed position
+ if (documentExists && !ChromeForAndroid) {
+ document.addEventListener('click', function (evt) {
+ if (ignoreNextClick) {
+ evt.preventDefault();
+ evt.stopPropagation && evt.stopPropagation();
+ evt.stopImmediatePropagation && evt.stopImmediatePropagation();
+ ignoreNextClick = false;
+ return false;
+ }
+ }, true);
+ }
+ var nearestEmptyInsertDetectEvent = function nearestEmptyInsertDetectEvent(evt) {
+ if (dragEl) {
+ evt = evt.touches ? evt.touches[0] : evt;
+ var nearest = _detectNearestEmptySortable(evt.clientX, evt.clientY);
+ if (nearest) {
+ // Create imitation event
+ var event = {};
+ for (var i in evt) {
+ if (evt.hasOwnProperty(i)) {
+ event[i] = evt[i];
+ }
+ }
+ event.target = event.rootEl = nearest;
+ event.preventDefault = void 0;
+ event.stopPropagation = void 0;
+ nearest[expando]._onDragOver(event);
+ }
+ }
+ };
+ var _checkOutsideTargetEl = function _checkOutsideTargetEl(evt) {
+ if (dragEl) {
+ dragEl.parentNode[expando]._isOutsideThisEl(evt.target);
+ }
+ };
+
+ /**
+ * @class Sortable
+ * @param {HTMLElement} el
+ * @param {Object} [options]
+ */
+ function Sortable(el, options) {
+ if (!(el && el.nodeType && el.nodeType === 1)) {
+ throw "Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(el));
+ }
+ this.el = el; // root element
+ this.options = options = _extends({}, options);
+
+ // Export instance
+ el[expando] = this;
+ var defaults = {
+ group: null,
+ sort: true,
+ disabled: false,
+ store: null,
+ handle: null,
+ draggable: /^[uo]l$/i.test(el.nodeName) ? '>li' : '>*',
+ swapThreshold: 1,
+ // percentage; 0 <= x <= 1
+ invertSwap: false,
+ // invert always
+ invertedSwapThreshold: null,
+ // will be set to same as swapThreshold if default
+ removeCloneOnHide: true,
+ direction: function direction() {
+ return _detectDirection(el, this.options);
+ },
+ ghostClass: 'sortable-ghost',
+ chosenClass: 'sortable-chosen',
+ dragClass: 'sortable-drag',
+ ignore: 'a, img',
+ filter: null,
+ preventOnFilter: true,
+ animation: 0,
+ easing: null,
+ setData: function setData(dataTransfer, dragEl) {
+ dataTransfer.setData('Text', dragEl.textContent);
+ },
+ dropBubble: false,
+ dragoverBubble: false,
+ dataIdAttr: 'data-id',
+ delay: 0,
+ delayOnTouchOnly: false,
+ touchStartThreshold: (Number.parseInt ? Number : window).parseInt(window.devicePixelRatio, 10) || 1,
+ forceFallback: false,
+ fallbackClass: 'sortable-fallback',
+ fallbackOnBody: false,
+ fallbackTolerance: 0,
+ fallbackOffset: {
+ x: 0,
+ y: 0
+ },
+ supportPointer: Sortable.supportPointer !== false && 'PointerEvent' in window && !Safari,
+ emptyInsertThreshold: 5
+ };
+ PluginManager.initializePlugins(this, el, defaults);
+
+ // Set default options
+ for (var name in defaults) {
+ !(name in options) && (options[name] = defaults[name]);
+ }
+ _prepareGroup(options);
+
+ // Bind all private methods
+ for (var fn in this) {
+ if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
+ this[fn] = this[fn].bind(this);
+ }
+ }
+
+ // Setup drag mode
+ this.nativeDraggable = options.forceFallback ? false : supportDraggable;
+ if (this.nativeDraggable) {
+ // Touch start threshold cannot be greater than the native dragstart threshold
+ this.options.touchStartThreshold = 1;
+ }
+
+ // Bind events
+ if (options.supportPointer) {
+ on(el, 'pointerdown', this._onTapStart);
+ } else {
+ on(el, 'mousedown', this._onTapStart);
+ on(el, 'touchstart', this._onTapStart);
+ }
+ if (this.nativeDraggable) {
+ on(el, 'dragover', this);
+ on(el, 'dragenter', this);
+ }
+ sortables.push(this.el);
+
+ // Restore sorting
+ options.store && options.store.get && this.sort(options.store.get(this) || []);
+
+ // Add animation state manager
+ _extends(this, AnimationStateManager());
+ }
+ Sortable.prototype = /** @lends Sortable.prototype */{
+ constructor: Sortable,
+ _isOutsideThisEl: function _isOutsideThisEl(target) {
+ if (!this.el.contains(target) && target !== this.el) {
+ lastTarget = null;
+ }
+ },
+ _getDirection: function _getDirection(evt, target) {
+ return typeof this.options.direction === 'function' ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction;
+ },
+ _onTapStart: function _onTapStart( /** Event|TouchEvent */evt) {
+ if (!evt.cancelable) return;
+ var _this = this,
+ el = this.el,
+ options = this.options,
+ preventOnFilter = options.preventOnFilter,
+ type = evt.type,
+ touch = evt.touches && evt.touches[0] || evt.pointerType && evt.pointerType === 'touch' && evt,
+ target = (touch || evt).target,
+ originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0] || evt.composedPath && evt.composedPath()[0]) || target,
+ filter = options.filter;
+ _saveInputCheckedState(el);
+
+ // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.
+ if (dragEl) {
+ return;
+ }
+ if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {
+ return; // only left button and enabled
+ }
+
+ // cancel dnd if original target is content editable
+ if (originalTarget.isContentEditable) {
+ return;
+ }
+
+ // Safari ignores further event handling after mousedown
+ if (!this.nativeDraggable && Safari && target && target.tagName.toUpperCase() === 'SELECT') {
+ return;
+ }
+ target = closest(target, options.draggable, el, false);
+ if (target && target.animated) {
+ return;
+ }
+ if (lastDownEl === target) {
+ // Ignoring duplicate `down`
+ return;
+ }
+
+ // Get the index of the dragged element within its parent
+ oldIndex = index(target);
+ oldDraggableIndex = index(target, options.draggable);
+
+ // Check filter
+ if (typeof filter === 'function') {
+ if (filter.call(this, evt, target, this)) {
+ _dispatchEvent({
+ sortable: _this,
+ rootEl: originalTarget,
+ name: 'filter',
+ targetEl: target,
+ toEl: el,
+ fromEl: el
+ });
+ pluginEvent('filter', _this, {
+ evt: evt
+ });
+ preventOnFilter && evt.cancelable && evt.preventDefault();
+ return; // cancel dnd
+ }
+ } else if (filter) {
+ filter = filter.split(',').some(function (criteria) {
+ criteria = closest(originalTarget, criteria.trim(), el, false);
+ if (criteria) {
+ _dispatchEvent({
+ sortable: _this,
+ rootEl: criteria,
+ name: 'filter',
+ targetEl: target,
+ fromEl: el,
+ toEl: el
+ });
+ pluginEvent('filter', _this, {
+ evt: evt
+ });
+ return true;
+ }
+ });
+ if (filter) {
+ preventOnFilter && evt.cancelable && evt.preventDefault();
+ return; // cancel dnd
+ }
+ }
+ if (options.handle && !closest(originalTarget, options.handle, el, false)) {
+ return;
+ }
+
+ // Prepare `dragstart`
+ this._prepareDragStart(evt, touch, target);
+ },
+ _prepareDragStart: function _prepareDragStart( /** Event */evt, /** Touch */touch, /** HTMLElement */target) {
+ var _this = this,
+ el = _this.el,
+ options = _this.options,
+ ownerDocument = el.ownerDocument,
+ dragStartFn;
+ if (target && !dragEl && target.parentNode === el) {
+ var dragRect = getRect(target);
+ rootEl = el;
+ dragEl = target;
+ parentEl = dragEl.parentNode;
+ nextEl = dragEl.nextSibling;
+ lastDownEl = target;
+ activeGroup = options.group;
+ Sortable.dragged = dragEl;
+ tapEvt = {
+ target: dragEl,
+ clientX: (touch || evt).clientX,
+ clientY: (touch || evt).clientY
+ };
+ tapDistanceLeft = tapEvt.clientX - dragRect.left;
+ tapDistanceTop = tapEvt.clientY - dragRect.top;
+ this._lastX = (touch || evt).clientX;
+ this._lastY = (touch || evt).clientY;
+ dragEl.style['will-change'] = 'all';
+ dragStartFn = function dragStartFn() {
+ pluginEvent('delayEnded', _this, {
+ evt: evt
+ });
+ if (Sortable.eventCanceled) {
+ _this._onDrop();
+ return;
+ }
+ // Delayed drag has been triggered
+ // we can re-enable the events: touchmove/mousemove
+ _this._disableDelayedDragEvents();
+ if (!FireFox && _this.nativeDraggable) {
+ dragEl.draggable = true;
+ }
+
+ // Bind the events: dragstart/dragend
+ _this._triggerDragStart(evt, touch);
+
+ // Drag start event
+ _dispatchEvent({
+ sortable: _this,
+ name: 'choose',
+ originalEvent: evt
+ });
+
+ // Chosen item
+ toggleClass(dragEl, options.chosenClass, true);
+ };
+
+ // Disable "draggable"
+ options.ignore.split(',').forEach(function (criteria) {
+ find(dragEl, criteria.trim(), _disableDraggable);
+ });
+ on(ownerDocument, 'dragover', nearestEmptyInsertDetectEvent);
+ on(ownerDocument, 'mousemove', nearestEmptyInsertDetectEvent);
+ on(ownerDocument, 'touchmove', nearestEmptyInsertDetectEvent);
+ on(ownerDocument, 'mouseup', _this._onDrop);
+ on(ownerDocument, 'touchend', _this._onDrop);
+ on(ownerDocument, 'touchcancel', _this._onDrop);
+
+ // Make dragEl draggable (must be before delay for FireFox)
+ if (FireFox && this.nativeDraggable) {
+ this.options.touchStartThreshold = 4;
+ dragEl.draggable = true;
+ }
+ pluginEvent('delayStart', this, {
+ evt: evt
+ });
+
+ // Delay is impossible for native DnD in Edge or IE
+ if (options.delay && (!options.delayOnTouchOnly || touch) && (!this.nativeDraggable || !(Edge || IE11OrLess))) {
+ if (Sortable.eventCanceled) {
+ this._onDrop();
+ return;
+ }
+ // If the user moves the pointer or let go the click or touch
+ // before the delay has been reached:
+ // disable the delayed drag
+ on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
+ on(ownerDocument, 'touchend', _this._disableDelayedDrag);
+ on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
+ on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler);
+ on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler);
+ options.supportPointer && on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler);
+ _this._dragStartTimer = setTimeout(dragStartFn, options.delay);
+ } else {
+ dragStartFn();
+ }
+ }
+ },
+ _delayedDragTouchMoveHandler: function _delayedDragTouchMoveHandler( /** TouchEvent|PointerEvent **/e) {
+ var touch = e.touches ? e.touches[0] : e;
+ if (Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) >= Math.floor(this.options.touchStartThreshold / (this.nativeDraggable && window.devicePixelRatio || 1))) {
+ this._disableDelayedDrag();
+ }
+ },
+ _disableDelayedDrag: function _disableDelayedDrag() {
+ dragEl && _disableDraggable(dragEl);
+ clearTimeout(this._dragStartTimer);
+ this._disableDelayedDragEvents();
+ },
+ _disableDelayedDragEvents: function _disableDelayedDragEvents() {
+ var ownerDocument = this.el.ownerDocument;
+ off(ownerDocument, 'mouseup', this._disableDelayedDrag);
+ off(ownerDocument, 'touchend', this._disableDelayedDrag);
+ off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
+ off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler);
+ off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler);
+ off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler);
+ },
+ _triggerDragStart: function _triggerDragStart( /** Event */evt, /** Touch */touch) {
+ touch = touch || evt.pointerType == 'touch' && evt;
+ if (!this.nativeDraggable || touch) {
+ if (this.options.supportPointer) {
+ on(document, 'pointermove', this._onTouchMove);
+ } else if (touch) {
+ on(document, 'touchmove', this._onTouchMove);
+ } else {
+ on(document, 'mousemove', this._onTouchMove);
+ }
+ } else {
+ on(dragEl, 'dragend', this);
+ on(rootEl, 'dragstart', this._onDragStart);
+ }
+ try {
+ if (document.selection) {
+ // Timeout neccessary for IE9
+ _nextTick(function () {
+ document.selection.empty();
+ });
+ } else {
+ window.getSelection().removeAllRanges();
+ }
+ } catch (err) {}
+ },
+ _dragStarted: function _dragStarted(fallback, evt) {
+ awaitingDragStarted = false;
+ if (rootEl && dragEl) {
+ pluginEvent('dragStarted', this, {
+ evt: evt
+ });
+ if (this.nativeDraggable) {
+ on(document, 'dragover', _checkOutsideTargetEl);
+ }
+ var options = this.options;
+
+ // Apply effect
+ !fallback && toggleClass(dragEl, options.dragClass, false);
+ toggleClass(dragEl, options.ghostClass, true);
+ Sortable.active = this;
+ fallback && this._appendGhost();
+
+ // Drag start event
+ _dispatchEvent({
+ sortable: this,
+ name: 'start',
+ originalEvent: evt
+ });
+ } else {
+ this._nulling();
+ }
+ },
+ _emulateDragOver: function _emulateDragOver() {
+ if (touchEvt) {
+ this._lastX = touchEvt.clientX;
+ this._lastY = touchEvt.clientY;
+ _hideGhostForTarget();
+ var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
+ var parent = target;
+ while (target && target.shadowRoot) {
+ target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
+ if (target === parent) break;
+ parent = target;
+ }
+ dragEl.parentNode[expando]._isOutsideThisEl(target);
+ if (parent) {
+ do {
+ if (parent[expando]) {
+ var inserted = void 0;
+ inserted = parent[expando]._onDragOver({
+ clientX: touchEvt.clientX,
+ clientY: touchEvt.clientY,
+ target: target,
+ rootEl: parent
+ });
+ if (inserted && !this.options.dragoverBubble) {
+ break;
+ }
+ }
+ target = parent; // store last element
+ }
+ /* jshint boss:true */ while (parent = parent.parentNode);
+ }
+ _unhideGhostForTarget();
+ }
+ },
+ _onTouchMove: function _onTouchMove( /**TouchEvent*/evt) {
+ if (tapEvt) {
+ var options = this.options,
+ fallbackTolerance = options.fallbackTolerance,
+ fallbackOffset = options.fallbackOffset,
+ touch = evt.touches ? evt.touches[0] : evt,
+ ghostMatrix = ghostEl && matrix(ghostEl, true),
+ scaleX = ghostEl && ghostMatrix && ghostMatrix.a,
+ scaleY = ghostEl && ghostMatrix && ghostMatrix.d,
+ relativeScrollOffset = PositionGhostAbsolutely && ghostRelativeParent && getRelativeScrollOffset(ghostRelativeParent),
+ dx = (touch.clientX - tapEvt.clientX + fallbackOffset.x) / (scaleX || 1) + (relativeScrollOffset ? relativeScrollOffset[0] - ghostRelativeParentInitialScroll[0] : 0) / (scaleX || 1),
+ dy = (touch.clientY - tapEvt.clientY + fallbackOffset.y) / (scaleY || 1) + (relativeScrollOffset ? relativeScrollOffset[1] - ghostRelativeParentInitialScroll[1] : 0) / (scaleY || 1);
+
+ // only set the status to dragging, when we are actually dragging
+ if (!Sortable.active && !awaitingDragStarted) {
+ if (fallbackTolerance && Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) < fallbackTolerance) {
+ return;
+ }
+ this._onDragStart(evt, true);
+ }
+ if (ghostEl) {
+ if (ghostMatrix) {
+ ghostMatrix.e += dx - (lastDx || 0);
+ ghostMatrix.f += dy - (lastDy || 0);
+ } else {
+ ghostMatrix = {
+ a: 1,
+ b: 0,
+ c: 0,
+ d: 1,
+ e: dx,
+ f: dy
+ };
+ }
+ var cssMatrix = "matrix(".concat(ghostMatrix.a, ",").concat(ghostMatrix.b, ",").concat(ghostMatrix.c, ",").concat(ghostMatrix.d, ",").concat(ghostMatrix.e, ",").concat(ghostMatrix.f, ")");
+ css(ghostEl, 'webkitTransform', cssMatrix);
+ css(ghostEl, 'mozTransform', cssMatrix);
+ css(ghostEl, 'msTransform', cssMatrix);
+ css(ghostEl, 'transform', cssMatrix);
+ lastDx = dx;
+ lastDy = dy;
+ touchEvt = touch;
+ }
+ evt.cancelable && evt.preventDefault();
+ }
+ },
+ _appendGhost: function _appendGhost() {
+ // Bug if using scale(): https://stackoverflow.com/questions/2637058
+ // Not being adjusted for
+ if (!ghostEl) {
+ var container = this.options.fallbackOnBody ? document.body : rootEl,
+ rect = getRect(dragEl, true, PositionGhostAbsolutely, true, container),
+ options = this.options;
+
+ // Position absolutely
+ if (PositionGhostAbsolutely) {
+ // Get relatively positioned parent
+ ghostRelativeParent = container;
+ while (css(ghostRelativeParent, 'position') === 'static' && css(ghostRelativeParent, 'transform') === 'none' && ghostRelativeParent !== document) {
+ ghostRelativeParent = ghostRelativeParent.parentNode;
+ }
+ if (ghostRelativeParent !== document.body && ghostRelativeParent !== document.documentElement) {
+ if (ghostRelativeParent === document) ghostRelativeParent = getWindowScrollingElement();
+ rect.top += ghostRelativeParent.scrollTop;
+ rect.left += ghostRelativeParent.scrollLeft;
+ } else {
+ ghostRelativeParent = getWindowScrollingElement();
+ }
+ ghostRelativeParentInitialScroll = getRelativeScrollOffset(ghostRelativeParent);
+ }
+ ghostEl = dragEl.cloneNode(true);
+ toggleClass(ghostEl, options.ghostClass, false);
+ toggleClass(ghostEl, options.fallbackClass, true);
+ toggleClass(ghostEl, options.dragClass, true);
+ css(ghostEl, 'transition', '');
+ css(ghostEl, 'transform', '');
+ css(ghostEl, 'box-sizing', 'border-box');
+ css(ghostEl, 'margin', 0);
+ css(ghostEl, 'top', rect.top);
+ css(ghostEl, 'left', rect.left);
+ css(ghostEl, 'width', rect.width);
+ css(ghostEl, 'height', rect.height);
+ css(ghostEl, 'opacity', '0.8');
+ css(ghostEl, 'position', PositionGhostAbsolutely ? 'absolute' : 'fixed');
+ css(ghostEl, 'zIndex', '100000');
+ css(ghostEl, 'pointerEvents', 'none');
+ Sortable.ghost = ghostEl;
+ container.appendChild(ghostEl);
+
+ // Set transform-origin
+ css(ghostEl, 'transform-origin', tapDistanceLeft / parseInt(ghostEl.style.width) * 100 + '% ' + tapDistanceTop / parseInt(ghostEl.style.height) * 100 + '%');
+ }
+ },
+ _onDragStart: function _onDragStart( /**Event*/evt, /**boolean*/fallback) {
+ var _this = this;
+ var dataTransfer = evt.dataTransfer;
+ var options = _this.options;
+ pluginEvent('dragStart', this, {
+ evt: evt
+ });
+ if (Sortable.eventCanceled) {
+ this._onDrop();
+ return;
+ }
+ pluginEvent('setupClone', this);
+ if (!Sortable.eventCanceled) {
+ cloneEl = clone(dragEl);
+ cloneEl.removeAttribute("id");
+ cloneEl.draggable = false;
+ cloneEl.style['will-change'] = '';
+ this._hideClone();
+ toggleClass(cloneEl, this.options.chosenClass, false);
+ Sortable.clone = cloneEl;
+ }
+
+ // #1143: IFrame support workaround
+ _this.cloneId = _nextTick(function () {
+ pluginEvent('clone', _this);
+ if (Sortable.eventCanceled) return;
+ if (!_this.options.removeCloneOnHide) {
+ rootEl.insertBefore(cloneEl, dragEl);
+ }
+ _this._hideClone();
+ _dispatchEvent({
+ sortable: _this,
+ name: 'clone'
+ });
+ });
+ !fallback && toggleClass(dragEl, options.dragClass, true);
+
+ // Set proper drop events
+ if (fallback) {
+ ignoreNextClick = true;
+ _this._loopId = setInterval(_this._emulateDragOver, 50);
+ } else {
+ // Undo what was set in _prepareDragStart before drag started
+ off(document, 'mouseup', _this._onDrop);
+ off(document, 'touchend', _this._onDrop);
+ off(document, 'touchcancel', _this._onDrop);
+ if (dataTransfer) {
+ dataTransfer.effectAllowed = 'move';
+ options.setData && options.setData.call(_this, dataTransfer, dragEl);
+ }
+ on(document, 'drop', _this);
+
+ // #1276 fix:
+ css(dragEl, 'transform', 'translateZ(0)');
+ }
+ awaitingDragStarted = true;
+ _this._dragStartId = _nextTick(_this._dragStarted.bind(_this, fallback, evt));
+ on(document, 'selectstart', _this);
+ moved = true;
+ if (Safari) {
+ css(document.body, 'user-select', 'none');
+ }
+ },
+ // Returns true - if no further action is needed (either inserted or another condition)
+ _onDragOver: function _onDragOver( /**Event*/evt) {
+ var el = this.el,
+ target = evt.target,
+ dragRect,
+ targetRect,
+ revert,
+ options = this.options,
+ group = options.group,
+ activeSortable = Sortable.active,
+ isOwner = activeGroup === group,
+ canSort = options.sort,
+ fromSortable = putSortable || activeSortable,
+ vertical,
+ _this = this,
+ completedFired = false;
+ if (_silent) return;
+ function dragOverEvent(name, extra) {
+ pluginEvent(name, _this, _objectSpread2({
+ evt: evt,
+ isOwner: isOwner,
+ axis: vertical ? 'vertical' : 'horizontal',
+ revert: revert,
+ dragRect: dragRect,
+ targetRect: targetRect,
+ canSort: canSort,
+ fromSortable: fromSortable,
+ target: target,
+ completed: completed,
+ onMove: function onMove(target, after) {
+ return _onMove(rootEl, el, dragEl, dragRect, target, getRect(target), evt, after);
+ },
+ changed: changed
+ }, extra));
+ }
+
+ // Capture animation state
+ function capture() {
+ dragOverEvent('dragOverAnimationCapture');
+ _this.captureAnimationState();
+ if (_this !== fromSortable) {
+ fromSortable.captureAnimationState();
+ }
+ }
+
+ // Return invocation when dragEl is inserted (or completed)
+ function completed(insertion) {
+ dragOverEvent('dragOverCompleted', {
+ insertion: insertion
+ });
+ if (insertion) {
+ // Clones must be hidden before folding animation to capture dragRectAbsolute properly
+ if (isOwner) {
+ activeSortable._hideClone();
+ } else {
+ activeSortable._showClone(_this);
+ }
+ if (_this !== fromSortable) {
+ // Set ghost class to new sortable's ghost class
+ toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : activeSortable.options.ghostClass, false);
+ toggleClass(dragEl, options.ghostClass, true);
+ }
+ if (putSortable !== _this && _this !== Sortable.active) {
+ putSortable = _this;
+ } else if (_this === Sortable.active && putSortable) {
+ putSortable = null;
+ }
+
+ // Animation
+ if (fromSortable === _this) {
+ _this._ignoreWhileAnimating = target;
+ }
+ _this.animateAll(function () {
+ dragOverEvent('dragOverAnimationComplete');
+ _this._ignoreWhileAnimating = null;
+ });
+ if (_this !== fromSortable) {
+ fromSortable.animateAll();
+ fromSortable._ignoreWhileAnimating = null;
+ }
+ }
+
+ // Null lastTarget if it is not inside a previously swapped element
+ if (target === dragEl && !dragEl.animated || target === el && !target.animated) {
+ lastTarget = null;
+ }
+
+ // no bubbling and not fallback
+ if (!options.dragoverBubble && !evt.rootEl && target !== document) {
+ dragEl.parentNode[expando]._isOutsideThisEl(evt.target);
+
+ // Do not detect for empty insert if already inserted
+ !insertion && nearestEmptyInsertDetectEvent(evt);
+ }
+ !options.dragoverBubble && evt.stopPropagation && evt.stopPropagation();
+ return completedFired = true;
+ }
+
+ // Call when dragEl has been inserted
+ function changed() {
+ newIndex = index(dragEl);
+ newDraggableIndex = index(dragEl, options.draggable);
+ _dispatchEvent({
+ sortable: _this,
+ name: 'change',
+ toEl: el,
+ newIndex: newIndex,
+ newDraggableIndex: newDraggableIndex,
+ originalEvent: evt
+ });
+ }
+ if (evt.preventDefault !== void 0) {
+ evt.cancelable && evt.preventDefault();
+ }
+ target = closest(target, options.draggable, el, true);
+ dragOverEvent('dragOver');
+ if (Sortable.eventCanceled) return completedFired;
+ if (dragEl.contains(evt.target) || target.animated && target.animatingX && target.animatingY || _this._ignoreWhileAnimating === target) {
+ return completed(false);
+ }
+ ignoreNextClick = false;
+ if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = parentEl !== rootEl) // Reverting item into the original list
+ : putSortable === this || (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt))) {
+ vertical = this._getDirection(evt, target) === 'vertical';
+ dragRect = getRect(dragEl);
+ dragOverEvent('dragOverValid');
+ if (Sortable.eventCanceled) return completedFired;
+ if (revert) {
+ parentEl = rootEl; // actualization
+ capture();
+ this._hideClone();
+ dragOverEvent('revert');
+ if (!Sortable.eventCanceled) {
+ if (nextEl) {
+ rootEl.insertBefore(dragEl, nextEl);
+ } else {
+ rootEl.appendChild(dragEl);
+ }
+ }
+ return completed(true);
+ }
+ var elLastChild = lastChild(el, options.draggable);
+ if (!elLastChild || _ghostIsLast(evt, vertical, this) && !elLastChild.animated) {
+ // Insert to end of list
+
+ // If already at end of list: Do not insert
+ if (elLastChild === dragEl) {
+ return completed(false);
+ }
+
+ // if there is a last element, it is the target
+ if (elLastChild && el === evt.target) {
+ target = elLastChild;
+ }
+ if (target) {
+ targetRect = getRect(target);
+ }
+ if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) {
+ capture();
+ if (elLastChild && elLastChild.nextSibling) {
+ // the last draggable element is not the last node
+ el.insertBefore(dragEl, elLastChild.nextSibling);
+ } else {
+ el.appendChild(dragEl);
+ }
+ parentEl = el; // actualization
+
+ changed();
+ return completed(true);
+ }
+ } else if (elLastChild && _ghostIsFirst(evt, vertical, this)) {
+ // Insert to start of list
+ var firstChild = getChild(el, 0, options, true);
+ if (firstChild === dragEl) {
+ return completed(false);
+ }
+ target = firstChild;
+ targetRect = getRect(target);
+ if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, false) !== false) {
+ capture();
+ el.insertBefore(dragEl, firstChild);
+ parentEl = el; // actualization
+
+ changed();
+ return completed(true);
+ }
+ } else if (target.parentNode === el) {
+ targetRect = getRect(target);
+ var direction = 0,
+ targetBeforeFirstSwap,
+ differentLevel = dragEl.parentNode !== el,
+ differentRowCol = !_dragElInRowColumn(dragEl.animated && dragEl.toRect || dragRect, target.animated && target.toRect || targetRect, vertical),
+ side1 = vertical ? 'top' : 'left',
+ scrolledPastTop = isScrolledPast(target, 'top', 'top') || isScrolledPast(dragEl, 'top', 'top'),
+ scrollBefore = scrolledPastTop ? scrolledPastTop.scrollTop : void 0;
+ if (lastTarget !== target) {
+ targetBeforeFirstSwap = targetRect[side1];
+ pastFirstInvertThresh = false;
+ isCircumstantialInvert = !differentRowCol && options.invertSwap || differentLevel;
+ }
+ direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target);
+ var sibling;
+ if (direction !== 0) {
+ // Check if target is beside dragEl in respective direction (ignoring hidden elements)
+ var dragIndex = index(dragEl);
+ do {
+ dragIndex -= direction;
+ sibling = parentEl.children[dragIndex];
+ } while (sibling && (css(sibling, 'display') === 'none' || sibling === ghostEl));
+ }
+ // If dragEl is already beside target: Do not insert
+ if (direction === 0 || sibling === target) {
+ return completed(false);
+ }
+ lastTarget = target;
+ lastDirection = direction;
+ var nextSibling = target.nextElementSibling,
+ after = false;
+ after = direction === 1;
+ var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);
+ if (moveVector !== false) {
+ if (moveVector === 1 || moveVector === -1) {
+ after = moveVector === 1;
+ }
+ _silent = true;
+ setTimeout(_unsilent, 30);
+ capture();
+ if (after && !nextSibling) {
+ el.appendChild(dragEl);
+ } else {
+ target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
+ }
+
+ // Undo chrome's scroll adjustment (has no effect on other browsers)
+ if (scrolledPastTop) {
+ scrollBy(scrolledPastTop, 0, scrollBefore - scrolledPastTop.scrollTop);
+ }
+ parentEl = dragEl.parentNode; // actualization
+
+ // must be done before animation
+ if (targetBeforeFirstSwap !== undefined && !isCircumstantialInvert) {
+ targetMoveDistance = Math.abs(targetBeforeFirstSwap - getRect(target)[side1]);
+ }
+ changed();
+ return completed(true);
+ }
+ }
+ if (el.contains(dragEl)) {
+ return completed(false);
+ }
+ }
+ return false;
+ },
+ _ignoreWhileAnimating: null,
+ _offMoveEvents: function _offMoveEvents() {
+ off(document, 'mousemove', this._onTouchMove);
+ off(document, 'touchmove', this._onTouchMove);
+ off(document, 'pointermove', this._onTouchMove);
+ off(document, 'dragover', nearestEmptyInsertDetectEvent);
+ off(document, 'mousemove', nearestEmptyInsertDetectEvent);
+ off(document, 'touchmove', nearestEmptyInsertDetectEvent);
+ },
+ _offUpEvents: function _offUpEvents() {
+ var ownerDocument = this.el.ownerDocument;
+ off(ownerDocument, 'mouseup', this._onDrop);
+ off(ownerDocument, 'touchend', this._onDrop);
+ off(ownerDocument, 'pointerup', this._onDrop);
+ off(ownerDocument, 'touchcancel', this._onDrop);
+ off(document, 'selectstart', this);
+ },
+ _onDrop: function _onDrop( /**Event*/evt) {
+ var el = this.el,
+ options = this.options;
+
+ // Get the index of the dragged element within its parent
+ newIndex = index(dragEl);
+ newDraggableIndex = index(dragEl, options.draggable);
+ pluginEvent('drop', this, {
+ evt: evt
+ });
+ parentEl = dragEl && dragEl.parentNode;
+
+ // Get again after plugin event
+ newIndex = index(dragEl);
+ newDraggableIndex = index(dragEl, options.draggable);
+ if (Sortable.eventCanceled) {
+ this._nulling();
+ return;
+ }
+ awaitingDragStarted = false;
+ isCircumstantialInvert = false;
+ pastFirstInvertThresh = false;
+ clearInterval(this._loopId);
+ clearTimeout(this._dragStartTimer);
+ _cancelNextTick(this.cloneId);
+ _cancelNextTick(this._dragStartId);
+
+ // Unbind events
+ if (this.nativeDraggable) {
+ off(document, 'drop', this);
+ off(el, 'dragstart', this._onDragStart);
+ }
+ this._offMoveEvents();
+ this._offUpEvents();
+ if (Safari) {
+ css(document.body, 'user-select', '');
+ }
+ css(dragEl, 'transform', '');
+ if (evt) {
+ if (moved) {
+ evt.cancelable && evt.preventDefault();
+ !options.dropBubble && evt.stopPropagation();
+ }
+ ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);
+ if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {
+ // Remove clone(s)
+ cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);
+ }
+ if (dragEl) {
+ if (this.nativeDraggable) {
+ off(dragEl, 'dragend', this);
+ }
+ _disableDraggable(dragEl);
+ dragEl.style['will-change'] = '';
+
+ // Remove classes
+ // ghostClass is added in dragStarted
+ if (moved && !awaitingDragStarted) {
+ toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : this.options.ghostClass, false);
+ }
+ toggleClass(dragEl, this.options.chosenClass, false);
+
+ // Drag stop event
+ _dispatchEvent({
+ sortable: this,
+ name: 'unchoose',
+ toEl: parentEl,
+ newIndex: null,
+ newDraggableIndex: null,
+ originalEvent: evt
+ });
+ if (rootEl !== parentEl) {
+ if (newIndex >= 0) {
+ // Add event
+ _dispatchEvent({
+ rootEl: parentEl,
+ name: 'add',
+ toEl: parentEl,
+ fromEl: rootEl,
+ originalEvent: evt
+ });
+
+ // Remove event
+ _dispatchEvent({
+ sortable: this,
+ name: 'remove',
+ toEl: parentEl,
+ originalEvent: evt
+ });
+
+ // drag from one list and drop into another
+ _dispatchEvent({
+ rootEl: parentEl,
+ name: 'sort',
+ toEl: parentEl,
+ fromEl: rootEl,
+ originalEvent: evt
+ });
+ _dispatchEvent({
+ sortable: this,
+ name: 'sort',
+ toEl: parentEl,
+ originalEvent: evt
+ });
+ }
+ putSortable && putSortable.save();
+ } else {
+ if (newIndex !== oldIndex) {
+ if (newIndex >= 0) {
+ // drag & drop within the same list
+ _dispatchEvent({
+ sortable: this,
+ name: 'update',
+ toEl: parentEl,
+ originalEvent: evt
+ });
+ _dispatchEvent({
+ sortable: this,
+ name: 'sort',
+ toEl: parentEl,
+ originalEvent: evt
+ });
+ }
+ }
+ }
+ if (Sortable.active) {
+ /* jshint eqnull:true */
+ if (newIndex == null || newIndex === -1) {
+ newIndex = oldIndex;
+ newDraggableIndex = oldDraggableIndex;
+ }
+ _dispatchEvent({
+ sortable: this,
+ name: 'end',
+ toEl: parentEl,
+ originalEvent: evt
+ });
+
+ // Save sorting
+ this.save();
+ }
+ }
+ }
+ this._nulling();
+ },
+ _nulling: function _nulling() {
+ pluginEvent('nulling', this);
+ rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = cloneHidden = tapEvt = touchEvt = moved = newIndex = newDraggableIndex = oldIndex = oldDraggableIndex = lastTarget = lastDirection = putSortable = activeGroup = Sortable.dragged = Sortable.ghost = Sortable.clone = Sortable.active = null;
+ savedInputChecked.forEach(function (el) {
+ el.checked = true;
+ });
+ savedInputChecked.length = lastDx = lastDy = 0;
+ },
+ handleEvent: function handleEvent( /**Event*/evt) {
+ switch (evt.type) {
+ case 'drop':
+ case 'dragend':
+ this._onDrop(evt);
+ break;
+ case 'dragenter':
+ case 'dragover':
+ if (dragEl) {
+ this._onDragOver(evt);
+ _globalDragOver(evt);
+ }
+ break;
+ case 'selectstart':
+ evt.preventDefault();
+ break;
+ }
+ },
+ /**
+ * Serializes the item into an array of string.
+ * @returns {String[]}
+ */
+ toArray: function toArray() {
+ var order = [],
+ el,
+ children = this.el.children,
+ i = 0,
+ n = children.length,
+ options = this.options;
+ for (; i < n; i++) {
+ el = children[i];
+ if (closest(el, options.draggable, this.el, false)) {
+ order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
+ }
+ }
+ return order;
+ },
+ /**
+ * Sorts the elements according to the array.
+ * @param {String[]} order order of the items
+ */
+ sort: function sort(order, useAnimation) {
+ var items = {},
+ rootEl = this.el;
+ this.toArray().forEach(function (id, i) {
+ var el = rootEl.children[i];
+ if (closest(el, this.options.draggable, rootEl, false)) {
+ items[id] = el;
+ }
+ }, this);
+ useAnimation && this.captureAnimationState();
+ order.forEach(function (id) {
+ if (items[id]) {
+ rootEl.removeChild(items[id]);
+ rootEl.appendChild(items[id]);
+ }
+ });
+ useAnimation && this.animateAll();
+ },
+ /**
+ * Save the current sorting
+ */
+ save: function save() {
+ var store = this.options.store;
+ store && store.set && store.set(this);
+ },
+ /**
+ * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
+ * @param {HTMLElement} el
+ * @param {String} [selector] default: `options.draggable`
+ * @returns {HTMLElement|null}
+ */
+ closest: function closest$1(el, selector) {
+ return closest(el, selector || this.options.draggable, this.el, false);
+ },
+ /**
+ * Set/get option
+ * @param {string} name
+ * @param {*} [value]
+ * @returns {*}
+ */
+ option: function option(name, value) {
+ var options = this.options;
+ if (value === void 0) {
+ return options[name];
+ } else {
+ var modifiedValue = PluginManager.modifyOption(this, name, value);
+ if (typeof modifiedValue !== 'undefined') {
+ options[name] = modifiedValue;
+ } else {
+ options[name] = value;
+ }
+ if (name === 'group') {
+ _prepareGroup(options);
+ }
+ }
+ },
+ /**
+ * Destroy
+ */
+ destroy: function destroy() {
+ pluginEvent('destroy', this);
+ var el = this.el;
+ el[expando] = null;
+ off(el, 'mousedown', this._onTapStart);
+ off(el, 'touchstart', this._onTapStart);
+ off(el, 'pointerdown', this._onTapStart);
+ if (this.nativeDraggable) {
+ off(el, 'dragover', this);
+ off(el, 'dragenter', this);
+ }
+ // Remove draggable attributes
+ Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
+ el.removeAttribute('draggable');
+ });
+ this._onDrop();
+ this._disableDelayedDragEvents();
+ sortables.splice(sortables.indexOf(this.el), 1);
+ this.el = el = null;
+ },
+ _hideClone: function _hideClone() {
+ if (!cloneHidden) {
+ pluginEvent('hideClone', this);
+ if (Sortable.eventCanceled) return;
+ css(cloneEl, 'display', 'none');
+ if (this.options.removeCloneOnHide && cloneEl.parentNode) {
+ cloneEl.parentNode.removeChild(cloneEl);
+ }
+ cloneHidden = true;
+ }
+ },
+ _showClone: function _showClone(putSortable) {
+ if (putSortable.lastPutMode !== 'clone') {
+ this._hideClone();
+ return;
+ }
+ if (cloneHidden) {
+ pluginEvent('showClone', this);
+ if (Sortable.eventCanceled) return;
+
+ // show clone at dragEl or original position
+ if (dragEl.parentNode == rootEl && !this.options.group.revertClone) {
+ rootEl.insertBefore(cloneEl, dragEl);
+ } else if (nextEl) {
+ rootEl.insertBefore(cloneEl, nextEl);
+ } else {
+ rootEl.appendChild(cloneEl);
+ }
+ if (this.options.group.revertClone) {
+ this.animate(dragEl, cloneEl);
+ }
+ css(cloneEl, 'display', '');
+ cloneHidden = false;
+ }
+ }
+ };
+ function _globalDragOver( /**Event*/evt) {
+ if (evt.dataTransfer) {
+ evt.dataTransfer.dropEffect = 'move';
+ }
+ evt.cancelable && evt.preventDefault();
+ }
+ function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvent, willInsertAfter) {
+ var evt,
+ sortable = fromEl[expando],
+ onMoveFn = sortable.options.onMove,
+ retVal;
+ // Support for new CustomEvent feature
+ if (window.CustomEvent && !IE11OrLess && !Edge) {
+ evt = new CustomEvent('move', {
+ bubbles: true,
+ cancelable: true
+ });
+ } else {
+ evt = document.createEvent('Event');
+ evt.initEvent('move', true, true);
+ }
+ evt.to = toEl;
+ evt.from = fromEl;
+ evt.dragged = dragEl;
+ evt.draggedRect = dragRect;
+ evt.related = targetEl || toEl;
+ evt.relatedRect = targetRect || getRect(toEl);
+ evt.willInsertAfter = willInsertAfter;
+ evt.originalEvent = originalEvent;
+ fromEl.dispatchEvent(evt);
+ if (onMoveFn) {
+ retVal = onMoveFn.call(sortable, evt, originalEvent);
+ }
+ return retVal;
+ }
+ function _disableDraggable(el) {
+ el.draggable = false;
+ }
+ function _unsilent() {
+ _silent = false;
+ }
+ function _ghostIsFirst(evt, vertical, sortable) {
+ var firstElRect = getRect(getChild(sortable.el, 0, sortable.options, true));
+ var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);
+ var spacer = 10;
+ return vertical ? evt.clientX < childContainingRect.left - spacer || evt.clientY < firstElRect.top && evt.clientX < firstElRect.right : evt.clientY < childContainingRect.top - spacer || evt.clientY < firstElRect.bottom && evt.clientX < firstElRect.left;
+ }
+ function _ghostIsLast(evt, vertical, sortable) {
+ var lastElRect = getRect(lastChild(sortable.el, sortable.options.draggable));
+ var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);
+ var spacer = 10;
+ return vertical ? evt.clientX > childContainingRect.right + spacer || evt.clientY > lastElRect.bottom && evt.clientX > lastElRect.left : evt.clientY > childContainingRect.bottom + spacer || evt.clientX > lastElRect.right && evt.clientY > lastElRect.top;
+ }
+ function _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) {
+ var mouseOnAxis = vertical ? evt.clientY : evt.clientX,
+ targetLength = vertical ? targetRect.height : targetRect.width,
+ targetS1 = vertical ? targetRect.top : targetRect.left,
+ targetS2 = vertical ? targetRect.bottom : targetRect.right,
+ invert = false;
+ if (!invertSwap) {
+ // Never invert or create dragEl shadow when target movemenet causes mouse to move past the end of regular swapThreshold
+ if (isLastTarget && targetMoveDistance < targetLength * swapThreshold) {
+ // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2
+ // check if past first invert threshold on side opposite of lastDirection
+ if (!pastFirstInvertThresh && (lastDirection === 1 ? mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 : mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2)) {
+ // past first invert threshold, do not restrict inverted threshold to dragEl shadow
+ pastFirstInvertThresh = true;
+ }
+ if (!pastFirstInvertThresh) {
+ // dragEl shadow (target move distance shadow)
+ if (lastDirection === 1 ? mouseOnAxis < targetS1 + targetMoveDistance // over dragEl shadow
+ : mouseOnAxis > targetS2 - targetMoveDistance) {
+ return -lastDirection;
+ }
+ } else {
+ invert = true;
+ }
+ } else {
+ // Regular
+ if (mouseOnAxis > targetS1 + targetLength * (1 - swapThreshold) / 2 && mouseOnAxis < targetS2 - targetLength * (1 - swapThreshold) / 2) {
+ return _getInsertDirection(target);
+ }
+ }
+ }
+ invert = invert || invertSwap;
+ if (invert) {
+ // Invert of regular
+ if (mouseOnAxis < targetS1 + targetLength * invertedSwapThreshold / 2 || mouseOnAxis > targetS2 - targetLength * invertedSwapThreshold / 2) {
+ return mouseOnAxis > targetS1 + targetLength / 2 ? 1 : -1;
+ }
+ }
+ return 0;
+ }
+
+ /**
+ * Gets the direction dragEl must be swapped relative to target in order to make it
+ * seem that dragEl has been "inserted" into that element's position
+ * @param {HTMLElement} target The target whose position dragEl is being inserted at
+ * @return {Number} Direction dragEl must be swapped
+ */
+ function _getInsertDirection(target) {
+ if (index(dragEl) < index(target)) {
+ return 1;
+ } else {
+ return -1;
+ }
+ }
+
+ /**
+ * Generate id
+ * @param {HTMLElement} el
+ * @returns {String}
+ * @private
+ */
+ function _generateId(el) {
+ var str = el.tagName + el.className + el.src + el.href + el.textContent,
+ i = str.length,
+ sum = 0;
+ while (i--) {
+ sum += str.charCodeAt(i);
+ }
+ return sum.toString(36);
+ }
+ function _saveInputCheckedState(root) {
+ savedInputChecked.length = 0;
+ var inputs = root.getElementsByTagName('input');
+ var idx = inputs.length;
+ while (idx--) {
+ var el = inputs[idx];
+ el.checked && savedInputChecked.push(el);
+ }
+ }
+ function _nextTick(fn) {
+ return setTimeout(fn, 0);
+ }
+ function _cancelNextTick(id) {
+ return clearTimeout(id);
+ }
+
+ // Fixed #973:
+ if (documentExists) {
+ on(document, 'touchmove', function (evt) {
+ if ((Sortable.active || awaitingDragStarted) && evt.cancelable) {
+ evt.preventDefault();
+ }
+ });
+ }
+
+ // Export utils
+ Sortable.utils = {
+ on: on,
+ off: off,
+ css: css,
+ find: find,
+ is: function is(el, selector) {
+ return !!closest(el, selector, el, false);
+ },
+ extend: extend,
+ throttle: throttle,
+ closest: closest,
+ toggleClass: toggleClass,
+ clone: clone,
+ index: index,
+ nextTick: _nextTick,
+ cancelNextTick: _cancelNextTick,
+ detectDirection: _detectDirection,
+ getChild: getChild
+ };
+
+ /**
+ * Get the Sortable instance of an element
+ * @param {HTMLElement} element The element
+ * @return {Sortable|undefined} The instance of Sortable
+ */
+ Sortable.get = function (element) {
+ return element[expando];
+ };
+
+ /**
+ * Mount a plugin to Sortable
+ * @param {...SortablePlugin|SortablePlugin[]} plugins Plugins being mounted
+ */
+ Sortable.mount = function () {
+ for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {
+ plugins[_key] = arguments[_key];
+ }
+ if (plugins[0].constructor === Array) plugins = plugins[0];
+ plugins.forEach(function (plugin) {
+ if (!plugin.prototype || !plugin.prototype.constructor) {
+ throw "Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(plugin));
+ }
+ if (plugin.utils) Sortable.utils = _objectSpread2(_objectSpread2({}, Sortable.utils), plugin.utils);
+ PluginManager.mount(plugin);
+ });
+ };
+
+ /**
+ * Create sortable instance
+ * @param {HTMLElement} el
+ * @param {Object} [options]
+ */
+ Sortable.create = function (el, options) {
+ return new Sortable(el, options);
+ };
+
+ // Export
+ Sortable.version = version;
+
+ var autoScrolls = [],
+ scrollEl,
+ scrollRootEl,
+ scrolling = false,
+ lastAutoScrollX,
+ lastAutoScrollY,
+ touchEvt$1,
+ pointerElemChangedInterval;
+ function AutoScrollPlugin() {
+ function AutoScroll() {
+ this.defaults = {
+ scroll: true,
+ forceAutoScrollFallback: false,
+ scrollSensitivity: 30,
+ scrollSpeed: 10,
+ bubbleScroll: true
+ };
+
+ // Bind all private methods
+ for (var fn in this) {
+ if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
+ this[fn] = this[fn].bind(this);
+ }
+ }
+ }
+ AutoScroll.prototype = {
+ dragStarted: function dragStarted(_ref) {
+ var originalEvent = _ref.originalEvent;
+ if (this.sortable.nativeDraggable) {
+ on(document, 'dragover', this._handleAutoScroll);
+ } else {
+ if (this.options.supportPointer) {
+ on(document, 'pointermove', this._handleFallbackAutoScroll);
+ } else if (originalEvent.touches) {
+ on(document, 'touchmove', this._handleFallbackAutoScroll);
+ } else {
+ on(document, 'mousemove', this._handleFallbackAutoScroll);
+ }
+ }
+ },
+ dragOverCompleted: function dragOverCompleted(_ref2) {
+ var originalEvent = _ref2.originalEvent;
+ // For when bubbling is canceled and using fallback (fallback 'touchmove' always reached)
+ if (!this.options.dragOverBubble && !originalEvent.rootEl) {
+ this._handleAutoScroll(originalEvent);
+ }
+ },
+ drop: function drop() {
+ if (this.sortable.nativeDraggable) {
+ off(document, 'dragover', this._handleAutoScroll);
+ } else {
+ off(document, 'pointermove', this._handleFallbackAutoScroll);
+ off(document, 'touchmove', this._handleFallbackAutoScroll);
+ off(document, 'mousemove', this._handleFallbackAutoScroll);
+ }
+ clearPointerElemChangedInterval();
+ clearAutoScrolls();
+ cancelThrottle();
+ },
+ nulling: function nulling() {
+ touchEvt$1 = scrollRootEl = scrollEl = scrolling = pointerElemChangedInterval = lastAutoScrollX = lastAutoScrollY = null;
+ autoScrolls.length = 0;
+ },
+ _handleFallbackAutoScroll: function _handleFallbackAutoScroll(evt) {
+ this._handleAutoScroll(evt, true);
+ },
+ _handleAutoScroll: function _handleAutoScroll(evt, fallback) {
+ var _this = this;
+ var x = (evt.touches ? evt.touches[0] : evt).clientX,
+ y = (evt.touches ? evt.touches[0] : evt).clientY,
+ elem = document.elementFromPoint(x, y);
+ touchEvt$1 = evt;
+
+ // IE does not seem to have native autoscroll,
+ // Edge's autoscroll seems too conditional,
+ // MACOS Safari does not have autoscroll,
+ // Firefox and Chrome are good
+ if (fallback || this.options.forceAutoScrollFallback || Edge || IE11OrLess || Safari) {
+ autoScroll(evt, this.options, elem, fallback);
+
+ // Listener for pointer element change
+ var ogElemScroller = getParentAutoScrollElement(elem, true);
+ if (scrolling && (!pointerElemChangedInterval || x !== lastAutoScrollX || y !== lastAutoScrollY)) {
+ pointerElemChangedInterval && clearPointerElemChangedInterval();
+ // Detect for pointer elem change, emulating native DnD behaviour
+ pointerElemChangedInterval = setInterval(function () {
+ var newElem = getParentAutoScrollElement(document.elementFromPoint(x, y), true);
+ if (newElem !== ogElemScroller) {
+ ogElemScroller = newElem;
+ clearAutoScrolls();
+ }
+ autoScroll(evt, _this.options, newElem, fallback);
+ }, 10);
+ lastAutoScrollX = x;
+ lastAutoScrollY = y;
+ }
+ } else {
+ // if DnD is enabled (and browser has good autoscrolling), first autoscroll will already scroll, so get parent autoscroll of first autoscroll
+ if (!this.options.bubbleScroll || getParentAutoScrollElement(elem, true) === getWindowScrollingElement()) {
+ clearAutoScrolls();
+ return;
+ }
+ autoScroll(evt, this.options, getParentAutoScrollElement(elem, false), false);
+ }
+ }
+ };
+ return _extends(AutoScroll, {
+ pluginName: 'scroll',
+ initializeByDefault: true
+ });
+ }
+ function clearAutoScrolls() {
+ autoScrolls.forEach(function (autoScroll) {
+ clearInterval(autoScroll.pid);
+ });
+ autoScrolls = [];
+ }
+ function clearPointerElemChangedInterval() {
+ clearInterval(pointerElemChangedInterval);
+ }
+ var autoScroll = throttle(function (evt, options, rootEl, isFallback) {
+ // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
+ if (!options.scroll) return;
+ var x = (evt.touches ? evt.touches[0] : evt).clientX,
+ y = (evt.touches ? evt.touches[0] : evt).clientY,
+ sens = options.scrollSensitivity,
+ speed = options.scrollSpeed,
+ winScroller = getWindowScrollingElement();
+ var scrollThisInstance = false,
+ scrollCustomFn;
+
+ // New scroll root, set scrollEl
+ if (scrollRootEl !== rootEl) {
+ scrollRootEl = rootEl;
+ clearAutoScrolls();
+ scrollEl = options.scroll;
+ scrollCustomFn = options.scrollFn;
+ if (scrollEl === true) {
+ scrollEl = getParentAutoScrollElement(rootEl, true);
+ }
+ }
+ var layersOut = 0;
+ var currentParent = scrollEl;
+ do {
+ var el = currentParent,
+ rect = getRect(el),
+ top = rect.top,
+ bottom = rect.bottom,
+ left = rect.left,
+ right = rect.right,
+ width = rect.width,
+ height = rect.height,
+ canScrollX = void 0,
+ canScrollY = void 0,
+ scrollWidth = el.scrollWidth,
+ scrollHeight = el.scrollHeight,
+ elCSS = css(el),
+ scrollPosX = el.scrollLeft,
+ scrollPosY = el.scrollTop;
+ if (el === winScroller) {
+ canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll' || elCSS.overflowX === 'visible');
+ canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll' || elCSS.overflowY === 'visible');
+ } else {
+ canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll');
+ canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll');
+ }
+ var vx = canScrollX && (Math.abs(right - x) <= sens && scrollPosX + width < scrollWidth) - (Math.abs(left - x) <= sens && !!scrollPosX);
+ var vy = canScrollY && (Math.abs(bottom - y) <= sens && scrollPosY + height < scrollHeight) - (Math.abs(top - y) <= sens && !!scrollPosY);
+ if (!autoScrolls[layersOut]) {
+ for (var i = 0; i <= layersOut; i++) {
+ if (!autoScrolls[i]) {
+ autoScrolls[i] = {};
+ }
+ }
+ }
+ if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) {
+ autoScrolls[layersOut].el = el;
+ autoScrolls[layersOut].vx = vx;
+ autoScrolls[layersOut].vy = vy;
+ clearInterval(autoScrolls[layersOut].pid);
+ if (vx != 0 || vy != 0) {
+ scrollThisInstance = true;
+ /* jshint loopfunc:true */
+ autoScrolls[layersOut].pid = setInterval(function () {
+ // emulate drag over during autoscroll (fallback), emulating native DnD behaviour
+ if (isFallback && this.layer === 0) {
+ Sortable.active._onTouchMove(touchEvt$1); // To move ghost if it is positioned absolutely
+ }
+ var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0;
+ var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0;
+ if (typeof scrollCustomFn === 'function') {
+ if (scrollCustomFn.call(Sortable.dragged.parentNode[expando], scrollOffsetX, scrollOffsetY, evt, touchEvt$1, autoScrolls[this.layer].el) !== 'continue') {
+ return;
+ }
+ }
+ scrollBy(autoScrolls[this.layer].el, scrollOffsetX, scrollOffsetY);
+ }.bind({
+ layer: layersOut
+ }), 24);
+ }
+ }
+ layersOut++;
+ } while (options.bubbleScroll && currentParent !== winScroller && (currentParent = getParentAutoScrollElement(currentParent, false)));
+ scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not
+ }, 30);
+
+ var drop = function drop(_ref) {
+ var originalEvent = _ref.originalEvent,
+ putSortable = _ref.putSortable,
+ dragEl = _ref.dragEl,
+ activeSortable = _ref.activeSortable,
+ dispatchSortableEvent = _ref.dispatchSortableEvent,
+ hideGhostForTarget = _ref.hideGhostForTarget,
+ unhideGhostForTarget = _ref.unhideGhostForTarget;
+ if (!originalEvent) return;
+ var toSortable = putSortable || activeSortable;
+ hideGhostForTarget();
+ var touch = originalEvent.changedTouches && originalEvent.changedTouches.length ? originalEvent.changedTouches[0] : originalEvent;
+ var target = document.elementFromPoint(touch.clientX, touch.clientY);
+ unhideGhostForTarget();
+ if (toSortable && !toSortable.el.contains(target)) {
+ dispatchSortableEvent('spill');
+ this.onSpill({
+ dragEl: dragEl,
+ putSortable: putSortable
+ });
+ }
+ };
+ function Revert() {}
+ Revert.prototype = {
+ startIndex: null,
+ dragStart: function dragStart(_ref2) {
+ var oldDraggableIndex = _ref2.oldDraggableIndex;
+ this.startIndex = oldDraggableIndex;
+ },
+ onSpill: function onSpill(_ref3) {
+ var dragEl = _ref3.dragEl,
+ putSortable = _ref3.putSortable;
+ this.sortable.captureAnimationState();
+ if (putSortable) {
+ putSortable.captureAnimationState();
+ }
+ var nextSibling = getChild(this.sortable.el, this.startIndex, this.options);
+ if (nextSibling) {
+ this.sortable.el.insertBefore(dragEl, nextSibling);
+ } else {
+ this.sortable.el.appendChild(dragEl);
+ }
+ this.sortable.animateAll();
+ if (putSortable) {
+ putSortable.animateAll();
+ }
+ },
+ drop: drop
+ };
+ _extends(Revert, {
+ pluginName: 'revertOnSpill'
+ });
+ function Remove() {}
+ Remove.prototype = {
+ onSpill: function onSpill(_ref4) {
+ var dragEl = _ref4.dragEl,
+ putSortable = _ref4.putSortable;
+ var parentSortable = putSortable || this.sortable;
+ parentSortable.captureAnimationState();
+ dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);
+ parentSortable.animateAll();
+ },
+ drop: drop
+ };
+ _extends(Remove, {
+ pluginName: 'removeOnSpill'
+ });
+
+ var lastSwapEl;
+ function SwapPlugin() {
+ function Swap() {
+ this.defaults = {
+ swapClass: 'sortable-swap-highlight'
+ };
+ }
+ Swap.prototype = {
+ dragStart: function dragStart(_ref) {
+ var dragEl = _ref.dragEl;
+ lastSwapEl = dragEl;
+ },
+ dragOverValid: function dragOverValid(_ref2) {
+ var completed = _ref2.completed,
+ target = _ref2.target,
+ onMove = _ref2.onMove,
+ activeSortable = _ref2.activeSortable,
+ changed = _ref2.changed,
+ cancel = _ref2.cancel;
+ if (!activeSortable.options.swap) return;
+ var el = this.sortable.el,
+ options = this.options;
+ if (target && target !== el) {
+ var prevSwapEl = lastSwapEl;
+ if (onMove(target) !== false) {
+ toggleClass(target, options.swapClass, true);
+ lastSwapEl = target;
+ } else {
+ lastSwapEl = null;
+ }
+ if (prevSwapEl && prevSwapEl !== lastSwapEl) {
+ toggleClass(prevSwapEl, options.swapClass, false);
+ }
+ }
+ changed();
+ completed(true);
+ cancel();
+ },
+ drop: function drop(_ref3) {
+ var activeSortable = _ref3.activeSortable,
+ putSortable = _ref3.putSortable,
+ dragEl = _ref3.dragEl;
+ var toSortable = putSortable || this.sortable;
+ var options = this.options;
+ lastSwapEl && toggleClass(lastSwapEl, options.swapClass, false);
+ if (lastSwapEl && (options.swap || putSortable && putSortable.options.swap)) {
+ if (dragEl !== lastSwapEl) {
+ toSortable.captureAnimationState();
+ if (toSortable !== activeSortable) activeSortable.captureAnimationState();
+ swapNodes(dragEl, lastSwapEl);
+ toSortable.animateAll();
+ if (toSortable !== activeSortable) activeSortable.animateAll();
+ }
+ }
+ },
+ nulling: function nulling() {
+ lastSwapEl = null;
+ }
+ };
+ return _extends(Swap, {
+ pluginName: 'swap',
+ eventProperties: function eventProperties() {
+ return {
+ swapItem: lastSwapEl
+ };
+ }
+ });
+ }
+ function swapNodes(n1, n2) {
+ var p1 = n1.parentNode,
+ p2 = n2.parentNode,
+ i1,
+ i2;
+ if (!p1 || !p2 || p1.isEqualNode(n2) || p2.isEqualNode(n1)) return;
+ i1 = index(n1);
+ i2 = index(n2);
+ if (p1.isEqualNode(p2) && i1 < i2) {
+ i2++;
+ }
+ p1.insertBefore(n2, p1.children[i1]);
+ p2.insertBefore(n1, p2.children[i2]);
+ }
+
+ var multiDragElements = [],
+ multiDragClones = [],
+ lastMultiDragSelect,
+ // for selection with modifier key down (SHIFT)
+ multiDragSortable,
+ initialFolding = false,
+ // Initial multi-drag fold when drag started
+ folding = false,
+ // Folding any other time
+ dragStarted = false,
+ dragEl$1,
+ clonesFromRect,
+ clonesHidden;
+ function MultiDragPlugin() {
+ function MultiDrag(sortable) {
+ // Bind all private methods
+ for (var fn in this) {
+ if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
+ this[fn] = this[fn].bind(this);
+ }
+ }
+ if (!sortable.options.avoidImplicitDeselect) {
+ if (sortable.options.supportPointer) {
+ on(document, 'pointerup', this._deselectMultiDrag);
+ } else {
+ on(document, 'mouseup', this._deselectMultiDrag);
+ on(document, 'touchend', this._deselectMultiDrag);
+ }
+ }
+ on(document, 'keydown', this._checkKeyDown);
+ on(document, 'keyup', this._checkKeyUp);
+ this.defaults = {
+ selectedClass: 'sortable-selected',
+ multiDragKey: null,
+ avoidImplicitDeselect: false,
+ setData: function setData(dataTransfer, dragEl) {
+ var data = '';
+ if (multiDragElements.length && multiDragSortable === sortable) {
+ multiDragElements.forEach(function (multiDragElement, i) {
+ data += (!i ? '' : ', ') + multiDragElement.textContent;
+ });
+ } else {
+ data = dragEl.textContent;
+ }
+ dataTransfer.setData('Text', data);
+ }
+ };
+ }
+ MultiDrag.prototype = {
+ multiDragKeyDown: false,
+ isMultiDrag: false,
+ delayStartGlobal: function delayStartGlobal(_ref) {
+ var dragged = _ref.dragEl;
+ dragEl$1 = dragged;
+ },
+ delayEnded: function delayEnded() {
+ this.isMultiDrag = ~multiDragElements.indexOf(dragEl$1);
+ },
+ setupClone: function setupClone(_ref2) {
+ var sortable = _ref2.sortable,
+ cancel = _ref2.cancel;
+ if (!this.isMultiDrag) return;
+ for (var i = 0; i < multiDragElements.length; i++) {
+ multiDragClones.push(clone(multiDragElements[i]));
+ multiDragClones[i].sortableIndex = multiDragElements[i].sortableIndex;
+ multiDragClones[i].draggable = false;
+ multiDragClones[i].style['will-change'] = '';
+ toggleClass(multiDragClones[i], this.options.selectedClass, false);
+ multiDragElements[i] === dragEl$1 && toggleClass(multiDragClones[i], this.options.chosenClass, false);
+ }
+ sortable._hideClone();
+ cancel();
+ },
+ clone: function clone(_ref3) {
+ var sortable = _ref3.sortable,
+ rootEl = _ref3.rootEl,
+ dispatchSortableEvent = _ref3.dispatchSortableEvent,
+ cancel = _ref3.cancel;
+ if (!this.isMultiDrag) return;
+ if (!this.options.removeCloneOnHide) {
+ if (multiDragElements.length && multiDragSortable === sortable) {
+ insertMultiDragClones(true, rootEl);
+ dispatchSortableEvent('clone');
+ cancel();
+ }
+ }
+ },
+ showClone: function showClone(_ref4) {
+ var cloneNowShown = _ref4.cloneNowShown,
+ rootEl = _ref4.rootEl,
+ cancel = _ref4.cancel;
+ if (!this.isMultiDrag) return;
+ insertMultiDragClones(false, rootEl);
+ multiDragClones.forEach(function (clone) {
+ css(clone, 'display', '');
+ });
+ cloneNowShown();
+ clonesHidden = false;
+ cancel();
+ },
+ hideClone: function hideClone(_ref5) {
+ var _this = this;
+ var sortable = _ref5.sortable,
+ cloneNowHidden = _ref5.cloneNowHidden,
+ cancel = _ref5.cancel;
+ if (!this.isMultiDrag) return;
+ multiDragClones.forEach(function (clone) {
+ css(clone, 'display', 'none');
+ if (_this.options.removeCloneOnHide && clone.parentNode) {
+ clone.parentNode.removeChild(clone);
+ }
+ });
+ cloneNowHidden();
+ clonesHidden = true;
+ cancel();
+ },
+ dragStartGlobal: function dragStartGlobal(_ref6) {
+ var sortable = _ref6.sortable;
+ if (!this.isMultiDrag && multiDragSortable) {
+ multiDragSortable.multiDrag._deselectMultiDrag();
+ }
+ multiDragElements.forEach(function (multiDragElement) {
+ multiDragElement.sortableIndex = index(multiDragElement);
+ });
+
+ // Sort multi-drag elements
+ multiDragElements = multiDragElements.sort(function (a, b) {
+ return a.sortableIndex - b.sortableIndex;
+ });
+ dragStarted = true;
+ },
+ dragStarted: function dragStarted(_ref7) {
+ var _this2 = this;
+ var sortable = _ref7.sortable;
+ if (!this.isMultiDrag) return;
+ if (this.options.sort) {
+ // Capture rects,
+ // hide multi drag elements (by positioning them absolute),
+ // set multi drag elements rects to dragRect,
+ // show multi drag elements,
+ // animate to rects,
+ // unset rects & remove from DOM
+
+ sortable.captureAnimationState();
+ if (this.options.animation) {
+ multiDragElements.forEach(function (multiDragElement) {
+ if (multiDragElement === dragEl$1) return;
+ css(multiDragElement, 'position', 'absolute');
+ });
+ var dragRect = getRect(dragEl$1, false, true, true);
+ multiDragElements.forEach(function (multiDragElement) {
+ if (multiDragElement === dragEl$1) return;
+ setRect(multiDragElement, dragRect);
+ });
+ folding = true;
+ initialFolding = true;
+ }
+ }
+ sortable.animateAll(function () {
+ folding = false;
+ initialFolding = false;
+ if (_this2.options.animation) {
+ multiDragElements.forEach(function (multiDragElement) {
+ unsetRect(multiDragElement);
+ });
+ }
+
+ // Remove all auxiliary multidrag items from el, if sorting enabled
+ if (_this2.options.sort) {
+ removeMultiDragElements();
+ }
+ });
+ },
+ dragOver: function dragOver(_ref8) {
+ var target = _ref8.target,
+ completed = _ref8.completed,
+ cancel = _ref8.cancel;
+ if (folding && ~multiDragElements.indexOf(target)) {
+ completed(false);
+ cancel();
+ }
+ },
+ revert: function revert(_ref9) {
+ var fromSortable = _ref9.fromSortable,
+ rootEl = _ref9.rootEl,
+ sortable = _ref9.sortable,
+ dragRect = _ref9.dragRect;
+ if (multiDragElements.length > 1) {
+ // Setup unfold animation
+ multiDragElements.forEach(function (multiDragElement) {
+ sortable.addAnimationState({
+ target: multiDragElement,
+ rect: folding ? getRect(multiDragElement) : dragRect
+ });
+ unsetRect(multiDragElement);
+ multiDragElement.fromRect = dragRect;
+ fromSortable.removeAnimationState(multiDragElement);
+ });
+ folding = false;
+ insertMultiDragElements(!this.options.removeCloneOnHide, rootEl);
+ }
+ },
+ dragOverCompleted: function dragOverCompleted(_ref10) {
+ var sortable = _ref10.sortable,
+ isOwner = _ref10.isOwner,
+ insertion = _ref10.insertion,
+ activeSortable = _ref10.activeSortable,
+ parentEl = _ref10.parentEl,
+ putSortable = _ref10.putSortable;
+ var options = this.options;
+ if (insertion) {
+ // Clones must be hidden before folding animation to capture dragRectAbsolute properly
+ if (isOwner) {
+ activeSortable._hideClone();
+ }
+ initialFolding = false;
+ // If leaving sort:false root, or already folding - Fold to new location
+ if (options.animation && multiDragElements.length > 1 && (folding || !isOwner && !activeSortable.options.sort && !putSortable)) {
+ // Fold: Set all multi drag elements's rects to dragEl's rect when multi-drag elements are invisible
+ var dragRectAbsolute = getRect(dragEl$1, false, true, true);
+ multiDragElements.forEach(function (multiDragElement) {
+ if (multiDragElement === dragEl$1) return;
+ setRect(multiDragElement, dragRectAbsolute);
+
+ // Move element(s) to end of parentEl so that it does not interfere with multi-drag clones insertion if they are inserted
+ // while folding, and so that we can capture them again because old sortable will no longer be fromSortable
+ parentEl.appendChild(multiDragElement);
+ });
+ folding = true;
+ }
+
+ // Clones must be shown (and check to remove multi drags) after folding when interfering multiDragElements are moved out
+ if (!isOwner) {
+ // Only remove if not folding (folding will remove them anyways)
+ if (!folding) {
+ removeMultiDragElements();
+ }
+ if (multiDragElements.length > 1) {
+ var clonesHiddenBefore = clonesHidden;
+ activeSortable._showClone(sortable);
+
+ // Unfold animation for clones if showing from hidden
+ if (activeSortable.options.animation && !clonesHidden && clonesHiddenBefore) {
+ multiDragClones.forEach(function (clone) {
+ activeSortable.addAnimationState({
+ target: clone,
+ rect: clonesFromRect
+ });
+ clone.fromRect = clonesFromRect;
+ clone.thisAnimationDuration = null;
+ });
+ }
+ } else {
+ activeSortable._showClone(sortable);
+ }
+ }
+ }
+ },
+ dragOverAnimationCapture: function dragOverAnimationCapture(_ref11) {
+ var dragRect = _ref11.dragRect,
+ isOwner = _ref11.isOwner,
+ activeSortable = _ref11.activeSortable;
+ multiDragElements.forEach(function (multiDragElement) {
+ multiDragElement.thisAnimationDuration = null;
+ });
+ if (activeSortable.options.animation && !isOwner && activeSortable.multiDrag.isMultiDrag) {
+ clonesFromRect = _extends({}, dragRect);
+ var dragMatrix = matrix(dragEl$1, true);
+ clonesFromRect.top -= dragMatrix.f;
+ clonesFromRect.left -= dragMatrix.e;
+ }
+ },
+ dragOverAnimationComplete: function dragOverAnimationComplete() {
+ if (folding) {
+ folding = false;
+ removeMultiDragElements();
+ }
+ },
+ drop: function drop(_ref12) {
+ var evt = _ref12.originalEvent,
+ rootEl = _ref12.rootEl,
+ parentEl = _ref12.parentEl,
+ sortable = _ref12.sortable,
+ dispatchSortableEvent = _ref12.dispatchSortableEvent,
+ oldIndex = _ref12.oldIndex,
+ putSortable = _ref12.putSortable;
+ var toSortable = putSortable || this.sortable;
+ if (!evt) return;
+ var options = this.options,
+ children = parentEl.children;
+
+ // Multi-drag selection
+ if (!dragStarted) {
+ if (options.multiDragKey && !this.multiDragKeyDown) {
+ this._deselectMultiDrag();
+ }
+ toggleClass(dragEl$1, options.selectedClass, !~multiDragElements.indexOf(dragEl$1));
+ if (!~multiDragElements.indexOf(dragEl$1)) {
+ multiDragElements.push(dragEl$1);
+ dispatchEvent({
+ sortable: sortable,
+ rootEl: rootEl,
+ name: 'select',
+ targetEl: dragEl$1,
+ originalEvent: evt
+ });
+
+ // Modifier activated, select from last to dragEl
+ if (evt.shiftKey && lastMultiDragSelect && sortable.el.contains(lastMultiDragSelect)) {
+ var lastIndex = index(lastMultiDragSelect),
+ currentIndex = index(dragEl$1);
+ if (~lastIndex && ~currentIndex && lastIndex !== currentIndex) {
+ // Must include lastMultiDragSelect (select it), in case modified selection from no selection
+ // (but previous selection existed)
+ var n, i;
+ if (currentIndex > lastIndex) {
+ i = lastIndex;
+ n = currentIndex;
+ } else {
+ i = currentIndex;
+ n = lastIndex + 1;
+ }
+ for (; i < n; i++) {
+ if (~multiDragElements.indexOf(children[i])) continue;
+ toggleClass(children[i], options.selectedClass, true);
+ multiDragElements.push(children[i]);
+ dispatchEvent({
+ sortable: sortable,
+ rootEl: rootEl,
+ name: 'select',
+ targetEl: children[i],
+ originalEvent: evt
+ });
+ }
+ }
+ } else {
+ lastMultiDragSelect = dragEl$1;
+ }
+ multiDragSortable = toSortable;
+ } else {
+ multiDragElements.splice(multiDragElements.indexOf(dragEl$1), 1);
+ lastMultiDragSelect = null;
+ dispatchEvent({
+ sortable: sortable,
+ rootEl: rootEl,
+ name: 'deselect',
+ targetEl: dragEl$1,
+ originalEvent: evt
+ });
+ }
+ }
+
+ // Multi-drag drop
+ if (dragStarted && this.isMultiDrag) {
+ folding = false;
+ // Do not "unfold" after around dragEl if reverted
+ if ((parentEl[expando].options.sort || parentEl !== rootEl) && multiDragElements.length > 1) {
+ var dragRect = getRect(dragEl$1),
+ multiDragIndex = index(dragEl$1, ':not(.' + this.options.selectedClass + ')');
+ if (!initialFolding && options.animation) dragEl$1.thisAnimationDuration = null;
+ toSortable.captureAnimationState();
+ if (!initialFolding) {
+ if (options.animation) {
+ dragEl$1.fromRect = dragRect;
+ multiDragElements.forEach(function (multiDragElement) {
+ multiDragElement.thisAnimationDuration = null;
+ if (multiDragElement !== dragEl$1) {
+ var rect = folding ? getRect(multiDragElement) : dragRect;
+ multiDragElement.fromRect = rect;
+
+ // Prepare unfold animation
+ toSortable.addAnimationState({
+ target: multiDragElement,
+ rect: rect
+ });
+ }
+ });
+ }
+
+ // Multi drag elements are not necessarily removed from the DOM on drop, so to reinsert
+ // properly they must all be removed
+ removeMultiDragElements();
+ multiDragElements.forEach(function (multiDragElement) {
+ if (children[multiDragIndex]) {
+ parentEl.insertBefore(multiDragElement, children[multiDragIndex]);
+ } else {
+ parentEl.appendChild(multiDragElement);
+ }
+ multiDragIndex++;
+ });
+
+ // If initial folding is done, the elements may have changed position because they are now
+ // unfolding around dragEl, even though dragEl may not have his index changed, so update event
+ // must be fired here as Sortable will not.
+ if (oldIndex === index(dragEl$1)) {
+ var update = false;
+ multiDragElements.forEach(function (multiDragElement) {
+ if (multiDragElement.sortableIndex !== index(multiDragElement)) {
+ update = true;
+ return;
+ }
+ });
+ if (update) {
+ dispatchSortableEvent('update');
+ dispatchSortableEvent('sort');
+ }
+ }
+ }
+
+ // Must be done after capturing individual rects (scroll bar)
+ multiDragElements.forEach(function (multiDragElement) {
+ unsetRect(multiDragElement);
+ });
+ toSortable.animateAll();
+ }
+ multiDragSortable = toSortable;
+ }
+
+ // Remove clones if necessary
+ if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {
+ multiDragClones.forEach(function (clone) {
+ clone.parentNode && clone.parentNode.removeChild(clone);
+ });
+ }
+ },
+ nullingGlobal: function nullingGlobal() {
+ this.isMultiDrag = dragStarted = false;
+ multiDragClones.length = 0;
+ },
+ destroyGlobal: function destroyGlobal() {
+ this._deselectMultiDrag();
+ off(document, 'pointerup', this._deselectMultiDrag);
+ off(document, 'mouseup', this._deselectMultiDrag);
+ off(document, 'touchend', this._deselectMultiDrag);
+ off(document, 'keydown', this._checkKeyDown);
+ off(document, 'keyup', this._checkKeyUp);
+ },
+ _deselectMultiDrag: function _deselectMultiDrag(evt) {
+ if (typeof dragStarted !== "undefined" && dragStarted) return;
+
+ // Only deselect if selection is in this sortable
+ if (multiDragSortable !== this.sortable) return;
+
+ // Only deselect if target is not item in this sortable
+ if (evt && closest(evt.target, this.options.draggable, this.sortable.el, false)) return;
+
+ // Only deselect if left click
+ if (evt && evt.button !== 0) return;
+ while (multiDragElements.length) {
+ var el = multiDragElements[0];
+ toggleClass(el, this.options.selectedClass, false);
+ multiDragElements.shift();
+ dispatchEvent({
+ sortable: this.sortable,
+ rootEl: this.sortable.el,
+ name: 'deselect',
+ targetEl: el,
+ originalEvent: evt
+ });
+ }
+ },
+ _checkKeyDown: function _checkKeyDown(evt) {
+ if (evt.key === this.options.multiDragKey) {
+ this.multiDragKeyDown = true;
+ }
+ },
+ _checkKeyUp: function _checkKeyUp(evt) {
+ if (evt.key === this.options.multiDragKey) {
+ this.multiDragKeyDown = false;
+ }
+ }
+ };
+ return _extends(MultiDrag, {
+ // Static methods & properties
+ pluginName: 'multiDrag',
+ utils: {
+ /**
+ * Selects the provided multi-drag item
+ * @param {HTMLElement} el The element to be selected
+ */
+ select: function select(el) {
+ var sortable = el.parentNode[expando];
+ if (!sortable || !sortable.options.multiDrag || ~multiDragElements.indexOf(el)) return;
+ if (multiDragSortable && multiDragSortable !== sortable) {
+ multiDragSortable.multiDrag._deselectMultiDrag();
+ multiDragSortable = sortable;
+ }
+ toggleClass(el, sortable.options.selectedClass, true);
+ multiDragElements.push(el);
+ },
+ /**
+ * Deselects the provided multi-drag item
+ * @param {HTMLElement} el The element to be deselected
+ */
+ deselect: function deselect(el) {
+ var sortable = el.parentNode[expando],
+ index = multiDragElements.indexOf(el);
+ if (!sortable || !sortable.options.multiDrag || !~index) return;
+ toggleClass(el, sortable.options.selectedClass, false);
+ multiDragElements.splice(index, 1);
+ }
+ },
+ eventProperties: function eventProperties() {
+ var _this3 = this;
+ var oldIndicies = [],
+ newIndicies = [];
+ multiDragElements.forEach(function (multiDragElement) {
+ oldIndicies.push({
+ multiDragElement: multiDragElement,
+ index: multiDragElement.sortableIndex
+ });
+
+ // multiDragElements will already be sorted if folding
+ var newIndex;
+ if (folding && multiDragElement !== dragEl$1) {
+ newIndex = -1;
+ } else if (folding) {
+ newIndex = index(multiDragElement, ':not(.' + _this3.options.selectedClass + ')');
+ } else {
+ newIndex = index(multiDragElement);
+ }
+ newIndicies.push({
+ multiDragElement: multiDragElement,
+ index: newIndex
+ });
+ });
+ return {
+ items: _toConsumableArray(multiDragElements),
+ clones: [].concat(multiDragClones),
+ oldIndicies: oldIndicies,
+ newIndicies: newIndicies
+ };
+ },
+ optionListeners: {
+ multiDragKey: function multiDragKey(key) {
+ key = key.toLowerCase();
+ if (key === 'ctrl') {
+ key = 'Control';
+ } else if (key.length > 1) {
+ key = key.charAt(0).toUpperCase() + key.substr(1);
+ }
+ return key;
+ }
+ }
+ });
+ }
+ function insertMultiDragElements(clonesInserted, rootEl) {
+ multiDragElements.forEach(function (multiDragElement, i) {
+ var target = rootEl.children[multiDragElement.sortableIndex + (clonesInserted ? Number(i) : 0)];
+ if (target) {
+ rootEl.insertBefore(multiDragElement, target);
+ } else {
+ rootEl.appendChild(multiDragElement);
+ }
+ });
+ }
+
+ /**
+ * Insert multi-drag clones
+ * @param {[Boolean]} elementsInserted Whether the multi-drag elements are inserted
+ * @param {HTMLElement} rootEl
+ */
+ function insertMultiDragClones(elementsInserted, rootEl) {
+ multiDragClones.forEach(function (clone, i) {
+ var target = rootEl.children[clone.sortableIndex + (elementsInserted ? Number(i) : 0)];
+ if (target) {
+ rootEl.insertBefore(clone, target);
+ } else {
+ rootEl.appendChild(clone);
+ }
+ });
+ }
+ function removeMultiDragElements() {
+ multiDragElements.forEach(function (multiDragElement) {
+ if (multiDragElement === dragEl$1) return;
+ multiDragElement.parentNode && multiDragElement.parentNode.removeChild(multiDragElement);
+ });
+ }
+
+ Sortable.mount(new AutoScrollPlugin());
+ Sortable.mount(Remove, Revert);
+
+ Sortable.mount(new SwapPlugin());
+ Sortable.mount(new MultiDragPlugin());
+
+ return Sortable;
+
+})));
\ No newline at end of file
diff --git a/src/assets/src/js/sortable.min.js b/src/assets/src/js/sortable.min.js
new file mode 100644
index 0000000..bb99533
--- /dev/null
+++ b/src/assets/src/js/sortable.min.js
@@ -0,0 +1,2 @@
+/*! Sortable 1.15.2 - MIT | git://github.com/SortableJS/Sortable.git */
+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Sortable=e()}(this,function(){"use strict";function e(e,t){var n,o=Object.keys(e);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(e),t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),o.push.apply(o,n)),o}function I(o){for(var t=1;tt.length)&&(e=t.length);for(var n=0,o=new Array(e);n"===e[0]&&(e=e.substring(1)),t))try{if(t.matches)return t.matches(e);if(t.msMatchesSelector)return t.msMatchesSelector(e);if(t.webkitMatchesSelector)return t.webkitMatchesSelector(e)}catch(t){return}}function P(t,e,n,o){if(t){n=n||document;do{if(null!=e&&(">"!==e[0]||t.parentNode===n)&&p(t,e)||o&&t===n)return t}while(t!==n&&(t=(i=t).host&&i!==document&&i.host.nodeType?i.host:i.parentNode))}var i;return null}var g,m=/\s+/g;function k(t,e,n){var o;t&&e&&(t.classList?t.classList[n?"add":"remove"](e):(o=(" "+t.className+" ").replace(m," ").replace(" "+e+" "," "),t.className=(o+(n?" "+e:"")).replace(m," ")))}function R(t,e,n){var o=t&&t.style;if(o){if(void 0===n)return document.defaultView&&document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(t,""):t.currentStyle&&(n=t.currentStyle),void 0===e?n:n[e];o[e=!(e in o||-1!==e.indexOf("webkit"))?"-webkit-"+e:e]=n+("string"==typeof n?"":"px")}}function v(t,e){var n="";if("string"==typeof t)n=t;else do{var o=R(t,"transform")}while(o&&"none"!==o&&(n=o+" "+n),!e&&(t=t.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&&new i(n)}function b(t,e,n){if(t){var o=t.getElementsByTagName(e),i=0,r=o.length;if(n)for(;i=n.left-e&&i<=n.right+e,e=r>=n.top-e&&r<=n.bottom+e;return o&&e?a=t:void 0}}),a);if(e){var n,o={};for(n in t)t.hasOwnProperty(n)&&(o[n]=t[n]);o.target=o.rootEl=e,o.preventDefault=void 0,o.stopPropagation=void 0,e[K]._onDragOver(o)}}var i,r,a}function Bt(t){V&&V.parentNode[K]._isOutsideThisEl(t.target)}function Ft(t,e){if(!t||!t.nodeType||1!==t.nodeType)throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(t));this.el=t,this.options=e=a({},e),t[K]=this;var n,o,i={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(t.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return Pt(t,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(t,e){t.setData("Text",e.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:!1!==Ft.supportPointer&&"PointerEvent"in window&&!u,emptyInsertThreshold:5};for(n in W.initializePlugins(this,t,i),i)n in e||(e[n]=i[n]);for(o in kt(e),this)"_"===o.charAt(0)&&"function"==typeof this[o]&&(this[o]=this[o].bind(this));this.nativeDraggable=!e.forceFallback&&Nt,this.nativeDraggable&&(this.options.touchStartThreshold=1),e.supportPointer?h(t,"pointerdown",this._onTapStart):(h(t,"mousedown",this._onTapStart),h(t,"touchstart",this._onTapStart)),this.nativeDraggable&&(h(t,"dragover",this),h(t,"dragenter",this)),Dt.push(this.el),e.store&&e.store.get&&this.sort(e.store.get(this)||[]),a(this,x())}function jt(t,e,n,o,i,r,a,l){var s,c,u=t[K],d=u.options.onMove;return!window.CustomEvent||y||w?(s=document.createEvent("Event")).initEvent("move",!0,!0):s=new CustomEvent("move",{bubbles:!0,cancelable:!0}),s.to=e,s.from=t,s.dragged=n,s.draggedRect=o,s.related=i||e,s.relatedRect=r||X(e),s.willInsertAfter=l,s.originalEvent=a,t.dispatchEvent(s),c=d?d.call(u,s,a):c}function Ht(t){t.draggable=!1}function Lt(){Tt=!1}function Kt(t){return setTimeout(t,0)}function Wt(t){return clearTimeout(t)}Ft.prototype={constructor:Ft,_isOutsideThisEl:function(t){this.el.contains(t)||t===this.el||(mt=null)},_getDirection:function(t,e){return"function"==typeof this.options.direction?this.options.direction.call(this,t,e,V):this.options.direction},_onTapStart:function(e){if(e.cancelable){var n=this,o=this.el,t=this.options,i=t.preventOnFilter,r=e.type,a=e.touches&&e.touches[0]||e.pointerType&&"touch"===e.pointerType&&e,l=(a||e).target,s=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||l,c=t.filter;if(!function(t){xt.length=0;var e=t.getElementsByTagName("input"),n=e.length;for(;n--;){var o=e[n];o.checked&&xt.push(o)}}(o),!V&&!(/mousedown|pointerdown/.test(r)&&0!==e.button||t.disabled)&&!s.isContentEditable&&(this.nativeDraggable||!u||!l||"SELECT"!==l.tagName.toUpperCase())&&!((l=P(l,t.draggable,o,!1))&&l.animated||tt===l)){if(ot=j(l),rt=j(l,t.draggable),"function"==typeof c){if(c.call(this,e,l,this))return q({sortable:n,rootEl:s,name:"filter",targetEl:l,toEl:o,fromEl:o}),G("filter",n,{evt:e}),void(i&&e.cancelable&&e.preventDefault())}else if(c=c&&c.split(",").some(function(t){if(t=P(s,t.trim(),o,!1))return q({sortable:n,rootEl:t,name:"filter",targetEl:l,fromEl:o,toEl:o}),G("filter",n,{evt:e}),!0}))return void(i&&e.cancelable&&e.preventDefault());t.handle&&!P(s,t.handle,o,!1)||this._prepareDragStart(e,a,l)}}},_prepareDragStart:function(t,e,n){var o,i=this,r=i.el,a=i.options,l=r.ownerDocument;n&&!V&&n.parentNode===r&&(o=X(n),Q=r,Z=(V=n).parentNode,J=V.nextSibling,tt=n,lt=a.group,ct={target:Ft.dragged=V,clientX:(e||t).clientX,clientY:(e||t).clientY},ft=ct.clientX-o.left,pt=ct.clientY-o.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,V.style["will-change"]="all",o=function(){G("delayEnded",i,{evt:t}),Ft.eventCanceled?i._onDrop():(i._disableDelayedDragEvents(),!s&&i.nativeDraggable&&(V.draggable=!0),i._triggerDragStart(t,e),q({sortable:i,name:"choose",originalEvent:t}),k(V,a.chosenClass,!0))},a.ignore.split(",").forEach(function(t){b(V,t.trim(),Ht)}),h(l,"dragover",Yt),h(l,"mousemove",Yt),h(l,"touchmove",Yt),h(l,"mouseup",i._onDrop),h(l,"touchend",i._onDrop),h(l,"touchcancel",i._onDrop),s&&this.nativeDraggable&&(this.options.touchStartThreshold=4,V.draggable=!0),G("delayStart",this,{evt:t}),!a.delay||a.delayOnTouchOnly&&!e||this.nativeDraggable&&(w||y)?o():Ft.eventCanceled?this._onDrop():(h(l,"mouseup",i._disableDelayedDrag),h(l,"touchend",i._disableDelayedDrag),h(l,"touchcancel",i._disableDelayedDrag),h(l,"mousemove",i._delayedDragTouchMoveHandler),h(l,"touchmove",i._delayedDragTouchMoveHandler),a.supportPointer&&h(l,"pointermove",i._delayedDragTouchMoveHandler),i._dragStartTimer=setTimeout(o,a.delay)))},_delayedDragTouchMoveHandler:function(t){t=t.touches?t.touches[0]:t;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){V&&Ht(V),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;f(t,"mouseup",this._disableDelayedDrag),f(t,"touchend",this._disableDelayedDrag),f(t,"touchcancel",this._disableDelayedDrag),f(t,"mousemove",this._delayedDragTouchMoveHandler),f(t,"touchmove",this._delayedDragTouchMoveHandler),f(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||"touch"==t.pointerType&&t,!this.nativeDraggable||e?this.options.supportPointer?h(document,"pointermove",this._onTouchMove):h(document,e?"touchmove":"mousemove",this._onTouchMove):(h(V,"dragend",this),h(Q,"dragstart",this._onDragStart));try{document.selection?Kt(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch(t){}},_dragStarted:function(t,e){var n;wt=!1,Q&&V?(G("dragStarted",this,{evt:e}),this.nativeDraggable&&h(document,"dragover",Bt),n=this.options,t||k(V,n.dragClass,!1),k(V,n.ghostClass,!0),Ft.active=this,t&&this._appendGhost(),q({sortable:this,name:"start",originalEvent:e})):this._nulling()},_emulateDragOver:function(){if(ut){this._lastX=ut.clientX,this._lastY=ut.clientY,Rt();for(var t=document.elementFromPoint(ut.clientX,ut.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(ut.clientX,ut.clientY))!==e;)e=t;if(V.parentNode[K]._isOutsideThisEl(t),e)do{if(e[K])if(e[K]._onDragOver({clientX:ut.clientX,clientY:ut.clientY,target:t,rootEl:e})&&!this.options.dragoverBubble)break}while(e=(t=e).parentNode);Xt()}},_onTouchMove:function(t){if(ct){var e=this.options,n=e.fallbackTolerance,o=e.fallbackOffset,i=t.touches?t.touches[0]:t,r=$&&v($,!0),a=$&&r&&r.a,l=$&&r&&r.d,e=Mt&&yt&&E(yt),a=(i.clientX-ct.clientX+o.x)/(a||1)+(e?e[0]-Ct[0]:0)/(a||1),l=(i.clientY-ct.clientY+o.y)/(l||1)+(e?e[1]-Ct[1]:0)/(l||1);if(!Ft.active&&!wt){if(n&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))D.right+10||S.clientY>x.bottom&&S.clientX>x.left:S.clientY>D.bottom+10||S.clientX>x.right&&S.clientY>x.top)||m.animated)){if(m&&(t=n,e=r,C=X(B((_=this).el,0,_.options,!0)),_=L(_.el,_.options,$),e?t.clientX<_.left-10||t.clientY {input}'
+ */
+ public $inputTemplate = '{input}';
+
/**
* @var Model|ActiveRecordInterface|array
*/
@@ -146,12 +191,16 @@ public function init()
{
parent::init();
- if (empty($this->name)) {
- throw new InvalidConfigException("The 'name' option is required.");
+ if ($this->type === null) {
+ $this->type = self::TYPE_TEXT_INPUT;
}
- if (is_null($this->type)) {
- $this->type = self::TYPE_TEXT_INPUT;
+ if ($this->type === self::TYPE_STATIC && empty($this->name)) {
+ $this->name = self::DEFAULT_STATIC_COLUMN_NAME;
+ }
+
+ if ($this->isNameEmpty()) {
+ throw new InvalidConfigException("The 'name' option is required.");
}
if (empty($this->options)) {
@@ -159,6 +208,19 @@ public function init()
}
}
+ private function isNameEmpty()
+ {
+ if (empty($this->name)) {
+ if ($this->name === 0 || $this->name === '0') {
+ return false;
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
/**
* @return bool whether the type of column is hidden input.
*/
@@ -170,27 +232,24 @@ public function isHiddenInput()
/**
* Prepares the value of column.
- *
+ * @param array $contextParams the params who passed to closure:
+ * string $id the id of input element
+ * string $name the name of input element
+ * string $indexPlaceholder The index placeholder of multiple input. The {$indexPlaceholder} template will be replace by $index
+ * int $index The index of multiple input
+ * int $columnIndex The index of current model attributes
* @return mixed
*/
- protected function prepareValue()
+ protected function prepareValue($contextParams = [])
{
$data = $this->getModel();
if ($this->value instanceof \Closure) {
- $value = call_user_func($this->value, $data);
+ $value = call_user_func($this->value, $data, $contextParams);
} else {
- if ($data instanceof ActiveRecordInterface ) {
- $value = $data->getAttribute($this->name);
- } elseif ($data instanceof Model) {
- $value = $data->{$this->name};
- } elseif (is_array($data)) {
- $value = ArrayHelper::getValue($data, $this->name, null);
- } elseif(is_string($data) || is_numeric($data)) {
- $value = $data;
- }else {
- $value = $this->defaultValue;
- }
+ $valuePreparer = new ValuePreparer($this->name, $this->defaultValue);
+ $value = $valuePreparer->prepare($data);
}
+
return $value;
}
@@ -227,35 +286,70 @@ private function normalize($name) {
/**
* Renders the input.
*
- * @param string $name the name of the input
- * @param array $options the HTML options of input
+ * @param string $name the name of the input
+ * @param array $options the HTML options of input
+ * @param array $contextParams the params who passed to closure:
+ * string $id the id of input element
+ * string $name the name of input element
+ * string $indexPlaceholder The index placeholder of multiple input. The {$indexPlaceholder} template will be replace by $index
+ * int $index The index of multiple input
+ * int $columnIndex The index of current model attributes
* @return string
+ * @throws InvalidConfigException
*/
- public function renderInput($name, $options)
+ public function renderInput($name, $options, $contextParams = [])
{
if ($this->options instanceof \Closure) {
$optionsExt = call_user_func($this->options, $this->getModel());
} else {
$optionsExt = $this->options;
}
-
+
$options = ArrayHelper::merge($options, $optionsExt);
$method = 'render' . Inflector::camelize($this->type);
- $value = $this->prepareValue();
+
+ // @see https://github.com/unclead/yii2-multiple-input/issues/261
+ if (isset($contextParams['index']) && isset($contextParams['indexPlaceholder'])) {
+ $options = $this->replaceIndexPlaceholderInOptions($options, $contextParams['indexPlaceholder'], $contextParams['index']);
+ }
+
+ $value = null;
+ if ($this->type !== self::TYPE_DRAGCOLUMN) {
+ $value = $this->prepareValue($contextParams);
+ }
if (isset($options['items'])) {
$options['items'] = $this->prepareItems($options['items']);
}
if (method_exists($this, $method)) {
- $input = call_user_func_array([$this, $method], [$name, $value, $options]);
+ $input = $this->$method($name, $value, $options);
} else {
$input = $this->renderDefault($name, $value, $options);
}
- return $input;
+ return strtr($this->inputTemplate, ['{input}' => $input]);
}
+ private function replaceIndexPlaceholderInOptions($options, $indexPlaceholder, $index)
+ {
+ $result = [];
+ foreach ($options as $key => $value) {
+ if (is_array($value)) {
+ $result[$key] = $this->replaceIndexPlaceholderInOptions($value, $indexPlaceholder, $index);
+ } elseif (is_string($value)) {
+ $result[$key] = str_replace('{' . $indexPlaceholder . '}', $index, $value);
+ } else {
+ if ($value instanceof JsExpression) {
+ $value->expression = str_replace('{' . $indexPlaceholder . '}', $index, $value->expression);
+ }
+
+ $result[$key] = $value;
+ }
+ }
+
+ return $result;
+ }
/**
* Renders drop down list.
@@ -267,7 +361,9 @@ public function renderInput($name, $options)
*/
protected function renderDropDownList($name, $value, $options)
{
- Html::addCssClass($options, 'form-control');
+ if ($this->renderer->isBootstrapTheme()) {
+ Html::addCssClass($options, 'form-control');
+ }
return Html::dropDownList($name, $value, $this->prepareItems($this->items), $options);
}
@@ -281,10 +377,10 @@ protected function renderDropDownList($name, $value, $options)
private function prepareItems($items)
{
if ($items instanceof \Closure) {
- return call_user_func($items, $this->getModel());
- } else {
- return $items;
+ return $items($this->getModel());
}
+
+ return $items;
}
/**
@@ -297,7 +393,9 @@ private function prepareItems($items)
*/
protected function renderListBox($name, $value, $options)
{
- Html::addCssClass($options, 'form-control');
+ if ($this->renderer->isBootstrapTheme()) {
+ Html::addCssClass($options, 'form-control');
+ }
return Html::listBox($name, $value, $this->prepareItems($this->items), $options);
}
@@ -354,9 +452,9 @@ protected function renderRadioList($name, $value, $options)
$options['item'] = function ($index, $label, $name, $checked, $value) use ($options) {
$content = Html::radio($name, $checked, [
- 'label' => $label,
- 'value' => $value,
- 'data-id' => ArrayHelper::getValue($options, 'id')
+ 'label' => $label,
+ 'value' => $value,
+ 'data-id' => ArrayHelper::getValue($options, 'id'),
]);
return Html::tag('div', $content, ['class' => 'radio']);
@@ -406,9 +504,9 @@ protected function renderCheckboxList($name, $value, $options)
$options['item'] = function ($index, $label, $name, $checked, $value) use ($options) {
$content = Html::checkbox($name, $checked, [
- 'label' => $label,
- 'value' => $value,
- 'data-id' => ArrayHelper::getValue($options, 'id')
+ 'label' => $label,
+ 'value' => $value,
+ 'data-id' => ArrayHelper::getValue($options, 'id'),
]);
return Html::tag('div', $content, ['class' => 'checkbox']);
@@ -420,22 +518,52 @@ protected function renderCheckboxList($name, $value, $options)
}
/**
- * @param $name
- * @param $value
- * @param $options
+ * Renders a text.
+ *
+ * @param string $name the name of input
+ * @param mixed $value the value of input
+ * @param array $options the HTMl options of input
* @return string
*/
protected function renderStatic($name, $value, $options)
{
- return Html::tag('p', $value, ['class' => 'form-control-static']);
+ if ($this->renderer->isBootstrapTheme()) {
+ Html::addCssClass($options, 'form-control-static');
+ }
+
+ return Html::tag('p', $value, $options);
+ }
+
+ /**
+ * Renders a drag&drop column.
+ *
+ * @param string $name the name of input
+ * @param mixed $value the value of input
+ * @param array $options the HTMl options of input
+ * @return string
+ */
+ protected function renderDragColumn($name, $value, $options)
+ {
+ /**
+ * Class was passed into options by TableRenderer->renderCellContent(),
+ * we can extract it here
+ */
+ $class = '';
+ if (array_key_exists('class', $options)) {
+ $class = ArrayHelper::remove($options, 'class');
+ }
+
+ $dragClass = implode(' ', [$class, 'drag-handle']);
+
+ return Html::tag('span', null, ['class' => $dragClass]);
}
/**
* Renders an input.
*
- * @param $name
- * @param $value
- * @param $options
+ * @param string $name the name of input
+ * @param mixed $value the value of input
+ * @param array $options the HTMl options of input
* @return string
* @throws InvalidConfigException
*/
@@ -444,7 +572,10 @@ protected function renderDefault($name, $value, $options)
$type = $this->type;
if (method_exists('yii\helpers\Html', $type)) {
- Html::addCssClass($options, 'form-control');
+ if ($this->renderer->isBootstrapTheme()) {
+ Html::addCssClass($options, 'form-control');
+ }
+
$input = Html::$type($name, $value, $options);
} elseif (class_exists($type) && method_exists($type, 'widget')) {
$input = $this->renderWidget($type, $name, $value, $options);
@@ -458,14 +589,24 @@ protected function renderDefault($name, $value, $options)
/**
* Renders a widget.
*
- * @param $type
- * @param $name
- * @param $value
- * @param $options
+ * @param string $type
+ * @param string $name the name of input
+ * @param mixed $value the value of input
+ * @param array $options the HTMl options of input
* @return mixed
*/
protected function renderWidget($type, $name, $value, $options)
{
+ if (isset($options['options']['tabindex'])) {
+ $tabindex = $options['options']['tabindex'];
+ } elseif (isset($options['tabindex'])) {
+ $tabindex = $options['tabindex'];
+ unset($options['tabindex']);
+ } else {
+ $tabindex = null;
+ }
+
+ $id = isset($options['id']) ? $options['id'] : $this->normalize($name);
$model = $this->getModel();
if ($model instanceof Model) {
$widgetOptions = [
@@ -473,14 +614,22 @@ protected function renderWidget($type, $name, $value, $options)
'attribute' => $this->name,
'value' => $value,
'options' => [
- 'id' => $this->normalize($name),
- 'name' => $name
+ 'id' => $id,
+ 'name' => $name,
+ 'tabindex' => $tabindex,
+ 'value' => $value
]
];
} else {
$widgetOptions = [
- 'name' => $name,
- 'value' => $value
+ 'name' => $name,
+ 'value' => $value,
+ 'options' => [
+ 'id' => $id,
+ 'name' => $name,
+ 'tabindex' => $tabindex,
+ 'value' => $value
+ ]
];
}
@@ -511,4 +660,4 @@ public function renderError($error)
* @return mixed
*/
abstract public function getFirstError($index);
-}
\ No newline at end of file
+}
diff --git a/src/components/BaseRenderer.php b/src/components/BaseRenderer.php
deleted file mode 100644
index 087c0da..0000000
--- a/src/components/BaseRenderer.php
+++ /dev/null
@@ -1,330 +0,0 @@
-context = $context;
- }
-
- public function init()
- {
- parent::init();
-
- $this->prepareMinOption();
- $this->prepareLimit();
- $this->prepareColumnClass();
- $this->prepareButtons();
- $this->prepareIndexPlaceholder();
- }
-
- private function prepareColumnClass()
- {
- if (!$this->columnClass) {
- throw new InvalidConfigException('You must specify "columnClass"');
- }
-
- if (!class_exists($this->columnClass)) {
- throw new InvalidConfigException('Column class "' . $this->columnClass. '" does not exist');
- }
- }
-
- private function prepareMinOption()
- {
- // Set value of min option based on value of allowEmptyList for BC
- if ($this->min === null) {
- $this->min = $this->allowEmptyList ? 0 : 1;
- } else {
- if ($this->min < 0) {
- throw new InvalidConfigException('Option "min" cannot be less 0');
- }
-
- // Allow empty list in case when minimum number of rows equal 0.
- if ($this->min === 0 && !$this->allowEmptyList) {
- $this->allowEmptyList = true;
- }
-
- // Deny empty list in case when min number of rows greater then 0
- if ($this->min > 0 && $this->allowEmptyList) {
- $this->allowEmptyList = false;
- }
- }
- }
-
- private function prepareLimit()
- {
- if ($this->limit === null) {
- $this->limit = PHP_INT_MAX;
- }
-
- if ($this->limit < 1) {
- $this->limit = 1;
- }
-
- // Maximum number of rows cannot be less then minimum number.
- if ($this->limit < $this->min) {
- $this->limit = $this->min;
- }
- }
-
- private function prepareButtons()
- {
- if (!is_array($this->addButtonPosition)) {
- $this->addButtonPosition = (array) $this->addButtonPosition;
- }
-
- if (!array_key_exists('class', $this->removeButtonOptions)) {
- $this->removeButtonOptions['class'] = 'btn btn-danger';
- }
-
- if (!array_key_exists('label', $this->removeButtonOptions)) {
- $this->removeButtonOptions['label'] = Html::tag('i', null, ['class' => 'glyphicon glyphicon-remove']);
- }
-
- if (!array_key_exists('class', $this->addButtonOptions)) {
- $this->addButtonOptions['class'] = 'btn btn-default';
- }
-
- if (!array_key_exists('label', $this->addButtonOptions)) {
- $this->addButtonOptions['label'] = Html::tag('i', null, ['class' => 'glyphicon glyphicon-plus']);
- }
- }
-
-
- /**
- * Creates column objects and initializes them.
- *
- * @throws \yii\base\InvalidConfigException
- */
- protected function initColumns()
- {
- foreach ($this->columns as $i => $column) {
- $definition = array_merge([
- 'class' => $this->columnClass,
- 'renderer' => $this,
- 'context' => $this->context
- ], $column);
-
- $this->columns[$i] = Yii::createObject($definition);
- }
- }
-
- public function render()
- {
- $this->initColumns();
- $content = $this->internalRender();
- $this->registerAssets();
- return $content;
- }
-
- /**
- * @return mixed
- * @throws NotSupportedException
- */
- abstract protected function internalRender();
-
- /**
- * Register script.
- *
- * @throws \yii\base\InvalidParamException
- */
- protected function registerAssets()
- {
- $view = $this->context->getView();
- MultipleInputAsset::register($view);
-
- $jsBefore = $this->collectJsTemplates();
- $template = $this->prepareTemplate();
- $jsTemplates = $this->collectJsTemplates($jsBefore);
-
- $options = Json::encode([
- 'id' => $this->id,
- 'template' => $template,
- 'jsTemplates' => $jsTemplates,
- 'limit' => $this->limit,
- 'min' => $this->min,
- 'attributeOptions' => $this->attributeOptions,
- 'indexPlaceholder' => $this->getIndexPlaceholder()
- ]);
-
- $js = "jQuery('#{$this->id}').multipleInput($options);";
- $view->registerJs($js);
- }
-
- /**
- * @return string
- */
- abstract protected function prepareTemplate();
-
-
- protected function collectJsTemplates($except = [])
- {
- $view = $this->context->getView();
- $output = [];
- if (is_array($view->js) && array_key_exists(View::POS_READY, $view->js)) {
- foreach ($view->js[View::POS_READY] as $key => $js) {
- if (array_key_exists($key, $except)) {
- continue;
- }
- if (preg_match('/^[^{]+{' . $this->getIndexPlaceholder() . '}.*$/m', $js) === 1) {
- $output[$key] = $js;
- unset($view->js[View::POS_READY][$key]);
- }
- }
- }
- return $output;
- }
-
- /**
- * @return mixed
- */
- public function getIndexPlaceholder()
- {
- return $this->indexPlaceholder;
- }
-
- /**
- * @return bool
- */
- protected function isAddButtonPositionHeader()
- {
- return in_array(self::POS_HEADER, $this->addButtonPosition);
- }
-
- /**
- * @return bool
- */
- protected function isAddButtonPositionFooter()
- {
- return in_array(self::POS_FOOTER, $this->addButtonPosition);
- }
-
- /**
- * @return bool
- */
- protected function isAddButtonPositionRow()
- {
- return in_array(self::POS_ROW, $this->addButtonPosition);
- }
-
- private function prepareIndexPlaceholder()
- {
- $this->indexPlaceholder = 'multiple_index_' . $this->id;
- }
-}
diff --git a/src/components/ValuePreparer.php b/src/components/ValuePreparer.php
new file mode 100644
index 0000000..91e01fb
--- /dev/null
+++ b/src/components/ValuePreparer.php
@@ -0,0 +1,82 @@
+name = $name;
+ $this->defaultValue = $defaultValue;
+ }
+
+ /**
+ * @param $data Prepared data
+ *
+ * @return int|mixed|null|string
+ */
+ public function prepare($data)
+ {
+ $value = null;
+ if ($data instanceof ActiveRecordInterface) {
+ if ($data->canGetProperty($this->name)) {
+ $value = $data->{$this->name};
+ } else {
+ $relation = $data->getRelation($this->name, false);
+ if ($relation !== null) {
+ $value = $relation->findFor($this->name, $data);
+ } else {
+ $value = $data->{$this->name};
+ }
+ }
+ } elseif ($data instanceof Model) {
+ $value = $data->{$this->name};
+ } elseif (is_array($data)) {
+ $value = ArrayHelper::getValue($data, $this->name, null);
+ } elseif(is_string($data) || is_numeric($data)) {
+ $value = $data;
+ }
+
+ if ($this->defaultValue !== null && $this->isEmpty($value)) {
+ $value = $this->defaultValue;
+ }
+
+ return $value;
+ }
+
+ protected function isEmpty($value)
+ {
+ return $value === null || $value === [] || $value === '';
+ }
+}
\ No newline at end of file
diff --git a/src/renderers/BaseRenderer.php b/src/renderers/BaseRenderer.php
new file mode 100644
index 0000000..5a701a1
--- /dev/null
+++ b/src/renderers/BaseRenderer.php
@@ -0,0 +1,614 @@
+context = $context;
+ }
+
+ public function init()
+ {
+ parent::init();
+
+ $this->prepareMinOption();
+ $this->prepareMaxOption();
+ $this->prepareColumnClass();
+ $this->prepareButtons();
+ $this->prepareIndexPlaceholder();
+ }
+
+ private function prepareColumnClass()
+ {
+ if (!$this->columnClass) {
+ throw new InvalidConfigException('You must specify "columnClass"');
+ }
+
+ if (!class_exists($this->columnClass)) {
+ throw new InvalidConfigException('Column class "' . $this->columnClass. '" does not exist');
+ }
+ }
+
+ private function prepareMinOption()
+ {
+ // Set value of min option based on value of allowEmptyList for BC
+ if ($this->min === null) {
+ $this->min = $this->allowEmptyList ? 0 : 1;
+ } else {
+ if ($this->min < 0) {
+ throw new InvalidConfigException('Option "min" cannot be less 0');
+ }
+
+ // Allow empty list in case when minimum number of rows equal 0.
+ if ($this->min === 0 && !$this->allowEmptyList) {
+ $this->allowEmptyList = true;
+ }
+
+ // Deny empty list in case when min number of rows greater then 0
+ if ($this->min > 0 && $this->allowEmptyList) {
+ $this->allowEmptyList = false;
+ }
+ }
+ }
+
+ private function prepareMaxOption()
+ {
+ if ($this->max === null) {
+ $this->max = PHP_INT_MAX;
+ }
+
+ if ($this->max < 1) {
+ $this->max = 1;
+ }
+
+ // Maximum number of rows cannot be less then minimum number.
+ if ($this->max < $this->min) {
+ $this->max = $this->min;
+ }
+ }
+
+ /**
+ * @throws InvalidConfigException
+ */
+ private function prepareButtons()
+ {
+ if ($this->addButtonPosition === null || $this->addButtonPosition === []) {
+ $this->addButtonPosition = $this->min === 0 ? self::POS_HEADER : self::POS_ROW;
+ }
+
+ if (!is_array($this->addButtonPosition)) {
+ $this->addButtonPosition = (array) $this->addButtonPosition;
+ }
+
+ if (!array_key_exists('class', $this->removeButtonOptions)) {
+ $this->removeButtonOptions['class'] = $this->isBootstrapTheme() ? 'btn btn-danger' : '';
+ }
+
+ if (!array_key_exists('label', $this->removeButtonOptions)) {
+ $this->removeButtonOptions['label'] = Html::tag('i', null, ['class' => $this->getIconClass('remove')]);
+ }
+
+ if (!array_key_exists('class', $this->addButtonOptions)) {
+ $this->addButtonOptions['class'] = $this->isBootstrapTheme() ? 'btn btn-default' : '';
+ }
+
+ if (!array_key_exists('label', $this->addButtonOptions)) {
+ $this->addButtonOptions['label'] = Html::tag('i', null, ['class' => $this->getIconClass('add')]);
+ }
+
+ if (!array_key_exists('class', $this->cloneButtonOptions)) {
+ $this->cloneButtonOptions['class'] = $this->isBootstrapTheme() ? 'btn btn-info' : '';
+ }
+
+ if (!array_key_exists('label', $this->cloneButtonOptions)) {
+ $this->cloneButtonOptions['label'] = Html::tag('i', null, ['class' => $this->getIconClass('clone')]);
+ }
+ }
+
+
+ /**
+ * Creates column objects and initializes them.
+ *
+ * @throws \yii\base\InvalidConfigException
+ */
+ protected function initColumns()
+ {
+ foreach ($this->columns as $i => $column) {
+ $definition = array_merge([
+ 'class' => $this->columnClass,
+ 'renderer' => $this,
+ 'context' => $this->context,
+ ], $column);
+
+ $this->addButtonOptions = (array)$this->addButtonOptions;
+
+ if (!isset($definition['attributeOptions'])) {
+ $definition['attributeOptions'] = $this->attributeOptions;
+ }
+
+ if (!isset($definition['enableError'])) {
+ $definition['enableError'] = $this->enableError;
+ }
+
+ $this->columns[$i] = Yii::createObject($definition);
+ }
+ }
+
+ /**
+ * Render extra content in action column.
+ *
+ * @param $index
+ * @param $item
+ *
+ * @return string
+ */
+ protected function getExtraButtons($index, $item)
+ {
+ if (!$this->extraButtons) {
+ return '';
+ }
+
+ if (is_callable($this->extraButtons)) {
+ $content = call_user_func($this->extraButtons, $item, $index, $this->context);
+ } else {
+ $content = $this->extraButtons;
+ }
+
+ if (!is_string($content)) {
+ throw new InvalidParamException('Property "extraButtons" must return string.');
+ }
+
+ return $content;
+ }
+
+ public function render()
+ {
+ $this->initColumns();
+
+ $view = $this->context->getView();
+ MultipleInputAsset::register($view);
+
+ // Collect all js scripts which were added before rendering of our widget
+ $jsBefore= [];
+ if (is_array($view->js)) {
+ foreach ($view->js as $position => $scripts) {
+ foreach ((array)$scripts as $key => $js) {
+ if (!isset($jsBefore[$position])) {
+ $jsBefore[$position] = [];
+ }
+ $jsBefore[$position][$key] = $js;
+ }
+ }
+ }
+
+ $content = $this->internalRender();
+
+ // Collect all js scripts which has to be appended to page before initialization widget
+ $jsInit = [];
+ if (is_array($view->js)) {
+ foreach ($this->jsPositions as $position) {
+ foreach (ArrayHelper::getValue($view->js, $position, []) as $key => $js) {
+ if (isset($jsBefore[$position][$key])) {
+ continue;
+ }
+ $jsInit[$key] = $js;
+ $jsBefore[$position][$key] = $js;
+ unset($view->js[$position][$key]);
+ }
+ }
+ }
+
+ $template = $this->prepareTemplate();
+
+ $jsTemplates = [];
+ if (is_array($view->js)) {
+ foreach ($this->jsPositions as $position) {
+ foreach (ArrayHelper::getValue($view->js, $position, []) as $key => $js) {
+ if (isset($jsBefore[$position][$key])) {
+ continue;
+ }
+ $jsTemplates[$key] = $js;
+ unset($view->js[$position][$key]);
+ }
+ }
+ }
+
+ $options = Json::encode(array_merge([
+ 'id' => $this->id,
+ 'inputId' => $this->context->options['id'],
+ 'template' => $template,
+ 'jsInit' => $jsInit,
+ 'jsTemplates' => $jsTemplates,
+ 'max' => $this->max,
+ 'min' => $this->min,
+ 'attributes' => $this->prepareJsAttributes(),
+ 'indexPlaceholder' => $this->getIndexPlaceholder(),
+ 'prepend' => $this->prepend
+ ], $this->jsExtraSettings));
+
+ $js = "jQuery('#{$this->id}').multipleInput($options);";
+ $view->registerJs($js);
+
+ if ($this->sortable) {
+ $this->registerJsSortable();
+ }
+
+ return $content;
+ }
+
+ private function registerJsSortable()
+ {
+ $view = $this->context->getView();
+ MultipleInputSortableAsset::register($view);
+
+ // todo override when ListRenderer will use div markup
+ $options = Json::encode($this->getJsSortableOptions());
+ $js = "new Sortable(document.getElementById('{$this->id}').querySelector('.multiple-input-list tbody'), {$options});";
+ $view->registerJs($js);
+ }
+
+ /**
+ * Returns an array of JQuery sortable plugin options.
+ * You can override this method extend plugin behaviour.
+ *
+ * @return array
+ */
+ protected function getJsSortableOptions()
+ {
+ return [
+ 'handle' => '.drag-handle',
+ 'draggable' => '.multiple-input-list__item',
+ 'onEnd' => new \yii\web\JsExpression("
+ function(event) {
+ var item = $(event.item),
+ wrapper = item.closest('.multiple-input').first(),
+ trigeredEvent = $.Event('afterDropRow');
+ wrapper.trigger(trigeredEvent, [item]);
+ }
+ ")
+ ];
+ }
+
+ /**
+ * @return mixed
+ * @throws NotSupportedException
+ */
+ abstract protected function internalRender();
+
+ /**
+ * @return string
+ */
+ abstract protected function prepareTemplate();
+
+ /**
+ * @return mixed
+ */
+ public function getIndexPlaceholder()
+ {
+ return $this->indexPlaceholder;
+ }
+
+ /**
+ * @return bool
+ */
+ protected function isAddButtonPositionHeader()
+ {
+ return in_array(self::POS_HEADER, $this->addButtonPosition);
+ }
+
+ /**
+ * @return bool
+ */
+ protected function isAddButtonPositionFooter()
+ {
+ return in_array(self::POS_FOOTER, $this->addButtonPosition);
+ }
+
+ /**
+ * @return bool
+ */
+ protected function isAddButtonPositionRow()
+ {
+ return in_array(self::POS_ROW, $this->addButtonPosition);
+ }
+
+ /**
+ * @return bool
+ */
+ protected function isAddButtonPositionRowBegin()
+ {
+ return in_array(self::POS_ROW_BEGIN, $this->addButtonPosition);
+ }
+
+ protected function isFixedNumberOfRows()
+ {
+ return $this->max === $this->min;
+ }
+
+ private function prepareIndexPlaceholder()
+ {
+ $this->indexPlaceholder = 'multiple_index_' . $this->id;
+ }
+
+ /**
+ * Prepares attributes options for client side.
+ *
+ * @return array
+ */
+ protected function prepareJsAttributes()
+ {
+ $attributes = [];
+ foreach ($this->columns as $column) {
+ $model = $column->getModel();
+ $inputID = str_replace(['-0', '-0-'], '', $column->getElementId(0));
+ if ($this->form instanceof ActiveForm && $model instanceof Model) {
+ $field = $this->form->field($model, $column->name);
+ foreach ($column->attributeOptions as $name => $value) {
+ if ($field->hasProperty($name)) {
+ $field->$name = $value;
+ }
+ }
+ $field->render('');
+ $attributeOptions = array_pop($this->form->attributes);
+ if (isset($attributeOptions['name']) && $attributeOptions['name'] === $column->name) {
+ $attributes[$inputID] = ArrayHelper::merge($attributeOptions, $column->attributeOptions);
+ } else {
+ $this->form->attributes[] = $attributeOptions;
+ }
+ } else {
+ $attributes[$inputID] = $column->attributeOptions;
+ }
+ }
+
+ return $attributes;
+ }
+
+ /**
+ * @param $action - the control parameter, used as key into allowed types
+ * @return string - the relevant icon class
+ *
+ * @throws InvalidConfigException
+ */
+ protected function getIconClass($action) {
+ if (in_array($action, ['add', 'remove', 'clone', 'drag-handle'])) {
+ return $this->iconMap[$action];
+ }
+
+ if (YII_DEBUG) {
+ throw new InvalidConfigException('Out of bounds, "' . $action . '" not found in your iconMap');
+ }
+ return '';
+ }
+
+ public function isDefaultTheme()
+ {
+ return $this->theme === self::THEME_DEFAULT;
+ }
+
+ public function isBootstrapTheme()
+ {
+ return $this->theme === self::THEME_BS;
+ }
+
+ protected function renderRows()
+ {
+ $rows = [];
+
+ $rowIndex = 0;
+ if ($this->data) {
+ foreach ($this->data as $index => $item) {
+ if ($rowIndex <= $this->max) {
+ $rows[] = $this->renderRowContent($index, $item, $rowIndex);
+ } else {
+ break;
+ }
+ $rowIndex++;
+ }
+ for (; $rowIndex < $this->min; $rowIndex++) {
+ $rows[] = $this->renderRowContent($rowIndex, null, $rowIndex);
+ }
+ } elseif ($this->min > 0) {
+ for (; $rowIndex < $this->min; $rowIndex++) {
+ $rows[] = $this->renderRowContent($rowIndex, null, $rowIndex);
+ }
+ }
+
+ return $rows;
+ }
+
+ abstract protected function renderRowContent($index = null, $item = null, $rowIndex = null);
+}
diff --git a/src/renderers/DivRenderer.php b/src/renderers/DivRenderer.php
new file mode 100644
index 0000000..80e3056
--- /dev/null
+++ b/src/renderers/DivRenderer.php
@@ -0,0 +1,390 @@
+renderHeader();
+ $content[] = $this->renderBody();
+ $content[] = $this->renderFooter();
+
+ $options = [];
+ Html::addCssClass($options, 'multiple-input-list list-renderer');
+
+ if ($this->isBootstrapTheme()) {
+ Html::addCssClass($options, 'form-horizontal');
+ }
+
+ $content = Html::tag('div', implode("\n", $content), $options);
+
+ return Html::tag('div', $content, [
+ 'id' => $this->id,
+ 'class' => 'multiple-input'
+ ]);
+ }
+
+ /**
+ * Renders the header.
+ *
+ * @return string
+ */
+ public function renderHeader()
+ {
+ if (!$this->isAddButtonPositionHeader()) {
+ return '';
+ }
+
+ $options = ['class' => 'list-cell__button'];
+ $layoutConfig = array_merge([
+ 'buttonAddClass' => $this->isBootstrapTheme() ? 'col-sm-offset-9 col-sm-3' : '',
+ ], $this->layoutConfig);
+ Html::addCssClass($options, $layoutConfig['buttonAddClass']);
+
+ return Html::tag('div', $this->renderAddButton(), $options);
+ }
+
+ /**
+ * Renders the footer.
+ *
+ * @return string
+ */
+ public function renderFooter()
+ {
+ if (!$this->isAddButtonPositionFooter()) {
+ return '';
+ }
+
+ $options = ['class' => 'list-cell__button'];
+ $layoutConfig = array_merge([
+ 'buttonAddClass' => $this->isBootstrapTheme() ? 'col-sm-offset-9 col-sm-3' : '',
+ ], $this->layoutConfig);
+ Html::addCssClass($options, $layoutConfig['buttonAddClass']);
+
+ return Html::tag('div', $this->renderAddButton(), $options);
+ }
+
+ /**
+ * Renders the body.
+ *
+ * @return string
+ * @throws \yii\base\InvalidConfigException
+ * @throws \yii\base\InvalidParamException
+ */
+ protected function renderBody()
+ {
+ return implode("\n", $this->renderRows());
+ }
+
+ /**
+ * Renders the row content.
+ *
+ * @param int $index
+ * @param ActiveRecordInterface|array $item
+ * @return mixed
+ */
+ protected function renderRowContent($index = null, $item = null, $rowIndex = null)
+ {
+ $elements = [];
+
+ $columnIndex = 0;
+ foreach ($this->columns as $column) {
+ /* @var $column BaseColumn */
+ $column->setModel($item);
+ $elements[] = $this->renderCellContent($column, $index, $columnIndex, $rowIndex);
+ $columnIndex++;
+ }
+
+ $content = Html::tag('div', implode("\n", $elements), $this->prepareRowOptions($index, $item));
+ if ($index !== null) {
+ $content = str_replace('{' . $this->getIndexPlaceholder() . '}', $index, $content);
+ }
+
+ return $content;
+ }
+
+ /**
+ * Prepares the row options.
+ *
+ * @param int $index
+ * @param ActiveRecordInterface|array $item
+ * @return array
+ */
+ protected function prepareRowOptions($index, $item)
+ {
+ if (is_callable($this->rowOptions)) {
+ $options = call_user_func($this->rowOptions, $item, $index, $this->context);
+ } else {
+ $options = $this->rowOptions;
+ }
+
+ $options['data-index'] = '{' . $this->getIndexPlaceholder() . '}';
+
+ Html::addCssClass($options, 'multiple-input-list__item');
+
+ return $options;
+ }
+
+ /**
+ * Renders the cell content.
+ *
+ * @param BaseColumn $column
+ * @param int|null $index
+ * @param int|null $columnIndex
+ * @param int|null $rowIndex
+ * @return string
+ * @throws \Exception
+ */
+ public function renderCellContent($column, $index = null, $columnIndex = null, $rowIndex = null)
+ {
+ $id = $column->getElementId($index);
+ $name = $column->getElementName($index);
+
+ /**
+ * This class inherits iconMap from BaseRenderer
+ * If the input to be rendered is a drag column, we give it the appropriate icon class
+ * via the $options array
+ */
+ $options = ['id' => $id];
+ if ($column->type === BaseColumn::TYPE_DRAGCOLUMN) {
+ $options = ArrayHelper::merge($options, ['class' => $this->iconMap['drag-handle']]);
+ }
+
+ $input = $column->renderInput($name, $options, [
+ 'id' => $id,
+ 'name' => $name,
+ 'indexPlaceholder' => $this->getIndexPlaceholder(),
+ 'index' => $index,
+ 'columnIndex' => $columnIndex,
+ 'context' => $this->context,
+ ]);
+
+ if ($column->isHiddenInput()) {
+ return $input;
+ }
+
+ $layoutConfig = array_merge([
+ 'offsetClass' => $this->isBootstrapTheme() ? 'col-sm-offset-3' : '',
+ 'labelClass' => $this->isBootstrapTheme() ? 'col-sm-3' : '',
+ 'wrapperClass' => $this->isBootstrapTheme() ? 'col-sm-6' : '',
+ 'errorClass' => $this->isBootstrapTheme() ? 'col-sm-offset-3 col-sm-6' : '',
+ ], $this->layoutConfig);
+
+ Html::addCssClass($column->errorOptions, $layoutConfig['errorClass']);
+
+ $hasError = false;
+ $error = '';
+
+ if ($index !== null) {
+ $error = $column->getFirstError($index);
+ $hasError = !empty($error);
+ }
+
+ $wrapperOptions = [];
+
+ if ($hasError) {
+ Html::addCssClass($wrapperOptions, 'has-error');
+ }
+
+ Html::addCssClass($wrapperOptions, $layoutConfig['wrapperClass']);
+
+ $options = [
+ 'class' => "field-$id list-cell__$column->name" . ($hasError ? ' has-error' : '')
+ ];
+
+ if ($this->isBootstrapTheme()) {
+ Html::addCssClass($options, 'form-group');
+ }
+
+ if (is_callable($column->columnOptions)) {
+ $columnOptions = call_user_func($column->columnOptions, $column->getModel(), $index, $this->context);
+ } else {
+ $columnOptions = $column->columnOptions;
+ }
+
+ $options = array_merge_recursive($options, $columnOptions);
+
+ $content = Html::beginTag('div', $options);
+
+ if (empty($column->title)) {
+ Html::addCssClass($wrapperOptions, $layoutConfig['offsetClass']);
+ } else {
+ $labelOptions = ['class' => $layoutConfig['labelClass']];
+ if ($this->isBootstrapTheme()) {
+ Html::addCssClass($labelOptions, 'control-label');
+ }
+
+ $content .= Html::label($column->title, $id, $labelOptions);
+ }
+
+ $content .= Html::tag('div', $input, $wrapperOptions);
+
+ // first line
+ if ($columnIndex == 0) {
+ if (!$this->isFixedNumberOfRows()) {
+ $content .= $this->renderActionColumn($index, $column->getModel(), $rowIndex);
+ }
+
+ if ($this->cloneButton) {
+ $content .= $this->renderCloneColumn();
+ }
+ }
+
+ if ($column->enableError) {
+ $content .= "\n" . $column->renderError($error);
+ }
+
+ $content .= Html::endTag('div');
+
+ return $content;
+ }
+
+ /**
+ * Renders the action column.
+ *
+ * @param null|int $index
+ * @param null|ActiveRecordInterface|array $item
+ * @return string
+ */
+ private function renderActionColumn($index = null, $item = null, $rowIndex = null)
+ {
+ $content = $this->getActionButton($index, $rowIndex) . $this->getExtraButtons($index, $item);
+
+ $options = ['class' => 'list-cell__button'];
+ $layoutConfig = array_merge([
+ 'buttonActionClass' => $this->isBootstrapTheme() ? 'col-sm-offset-0 col-sm-2' : '',
+ ], $this->layoutConfig);
+
+ Html::addCssClass($options, $layoutConfig['buttonActionClass']);
+
+ return Html::tag('div', $content, $options);
+ }
+
+ /**
+ * Renders the clone column.
+ *
+ * @return string
+ */
+ private function renderCloneColumn()
+ {
+
+ $options = ['class' => 'list-cell__button'];
+ $layoutConfig = array_merge([
+ 'buttonCloneClass' => $this->isBootstrapTheme() ? 'col-sm-offset-0 col-sm-1' : '',
+ ], $this->layoutConfig);
+ Html::addCssClass($options, $layoutConfig['buttonCloneClass']);
+
+ return Html::tag('div', $this->renderCloneButton(), $options);
+ }
+
+ private function getActionButton($index, $rowIndex)
+ {
+ if ($index === null || $this->min === 0) {
+ return $this->renderRemoveButton();
+ }
+
+ // rowIndex is zero-based, so we have to increment it to properly cpmpare it with min number of rows
+ $rowIndex++;
+
+ if ($rowIndex < $this->min) {
+ return '';
+ }
+
+ if ($rowIndex === $this->min) {
+ return $this->isAddButtonPositionRow() ? $this->renderAddButton() : '';
+ }
+
+ return $this->renderRemoveButton();
+ }
+
+ private function renderAddButton()
+ {
+ $options = [
+ 'class' => 'multiple-input-list__btn js-input-plus',
+ ];
+ Html::addCssClass($options, $this->addButtonOptions['class']);
+
+ return Html::tag('div', $this->addButtonOptions['label'], $options);
+ }
+
+ /**
+ * Renders remove button.
+ *
+ * @return string
+ */
+ private function renderRemoveButton()
+ {
+ $options = [
+ 'class' => 'multiple-input-list__btn js-input-remove',
+ ];
+ Html::addCssClass($options, $this->removeButtonOptions['class']);
+
+ return Html::tag('div', $this->removeButtonOptions['label'], $options);
+ }
+
+ /**
+ * Renders clone button.
+ *
+ * @return string
+ */
+ private function renderCloneButton()
+ {
+ $options = [
+ 'class' => 'multiple-input-list__btn js-input-clone',
+ ];
+ Html::addCssClass($options, $this->cloneButtonOptions['class']);
+
+ return Html::tag('div', $this->cloneButtonOptions['label'], $options);
+ }
+
+ /**
+ * Returns template for using in js.
+ *
+ * @return string
+ *
+ * @throws \yii\base\InvalidConfigException
+ */
+ protected function prepareTemplate()
+ {
+ return $this->renderRowContent();
+ }
+
+ /**
+ * Returns an array of JQuery sortable plugin options for DivRenderer
+ * @return array
+ */
+ protected function getJsSortableOptions()
+ {
+ return ArrayHelper::merge(parent::getJsSortableOptions(),
+ [
+ 'containerSelector' => '.list-renderer',
+ 'itemPath' => new UnsetArrayValue,
+ 'itemSelector' => '.multiple-input-list__item',
+ ]);
+ }
+}
diff --git a/src/renderers/ListRenderer.php b/src/renderers/ListRenderer.php
new file mode 100644
index 0000000..7661a41
--- /dev/null
+++ b/src/renderers/ListRenderer.php
@@ -0,0 +1,370 @@
+renderHeader();
+ $content[] = $this->renderBody();
+ $content[] = $this->renderFooter();
+
+ $options = [];
+ Html::addCssClass($options, 'multiple-input-list list-renderer');
+
+ if ($this->isBootstrapTheme()) {
+ Html::addCssClass($options, 'table form-horizontal');
+ }
+
+ $content = Html::tag('table', implode("\n", $content), $options);
+
+ return Html::tag('div', $content, [
+ 'id' => $this->id,
+ 'class' => 'multiple-input'
+ ]);
+ }
+
+ /**
+ * Renders the header.
+ *
+ * @return string
+ */
+ public function renderHeader()
+ {
+ if ($this->min !== 0 || !$this->isAddButtonPositionHeader()) {
+ return '';
+ }
+
+ $button = $this->isAddButtonPositionHeader() ? $this->renderAddButton() : '';
+
+ $content = [];
+ $content[] = Html::tag('td', ' ');
+
+ if ($this->cloneButton) {
+ $content[] = Html::tag('td', ' ');
+ }
+
+ $content[] = Html::tag('td', $button, [
+ 'class' => 'list-cell__button',
+ ]);
+
+ return Html::tag('thead', Html::tag('tr', implode("\n", $content)));
+ }
+
+ /**
+ * Renders the footer.
+ *
+ * @return string
+ */
+ public function renderFooter()
+ {
+ if (!$this->isAddButtonPositionFooter()) {
+ return '';
+ }
+
+ $cells = [];
+ $cells[] = Html::tag('td', ' ');
+ $cells[] = Html::tag('td', $this->renderAddButton(), [
+ 'class' => 'list-cell__button'
+ ]);
+
+ return Html::tag('tfoot', Html::tag('tr', implode("\n", $cells)));
+ }
+
+ /**
+ * Renders the body.
+ *
+ * @return string
+ * @throws \yii\base\InvalidConfigException
+ * @throws \yii\base\InvalidParamException
+ */
+ protected function renderBody()
+ {
+ return Html::tag('tbody', implode("\n", $this->renderRows()));
+ }
+
+ /**
+ * Renders the row content.
+ *
+ * @param int $index
+ * @param ActiveRecordInterface|array $item
+ * @return mixed
+ * @throws InvalidConfigException
+ */
+ protected function renderRowContent($index = null, $item = null, $rowIndex = null)
+ {
+ $elements = [];
+
+ $columnIndex = 0;
+ foreach ($this->columns as $column) {
+ /* @var $column BaseColumn */
+ $column->setModel($item);
+ $elements[] = $this->renderCellContent($column, $index, $columnIndex++);
+ }
+
+ $content = [];
+ $content[] = Html::tag('td', implode("\n", $elements));
+ if (!$this->isFixedNumberOfRows()) {
+ $content[] = $this->renderActionColumn($index, $item, $rowIndex);
+ }
+
+ if ($this->cloneButton) {
+ $content[] = $this->renderCloneColumn();
+ }
+
+ $content = Html::tag('tr', implode("\n", $content), $this->prepareRowOptions($index, $item));
+
+ if ($index !== null) {
+ $content = str_replace('{' . $this->getIndexPlaceholder() . '}', $index, $content);
+ }
+
+ return $content;
+ }
+
+ /**
+ * Prepares the row options.
+ *
+ * @param int $index
+ * @param ActiveRecordInterface|array $item
+ * @return array
+ */
+ protected function prepareRowOptions($index, $item)
+ {
+ if (is_callable($this->rowOptions)) {
+ $options = call_user_func($this->rowOptions, $item, $index, $this->context);
+ } else {
+ $options = $this->rowOptions;
+ }
+
+ $options['data-index'] = '{' . $this->getIndexPlaceholder() . '}';
+
+ Html::addCssClass($options, 'multiple-input-list__item');
+
+ return $options;
+ }
+
+ /**
+ * Renders the cell content.
+ *
+ * @param BaseColumn $column
+ * @param int|null $index
+ * @return string
+ */
+ public function renderCellContent($column, $index, $columnIndex = null)
+ {
+ $id = $column->getElementId($index);
+ $name = $column->getElementName($index);
+
+ /**
+ * This class inherits iconMap from BaseRenderer
+ * If the input to be rendered is a drag column, we give it the appropriate icon class
+ * via the $options array
+ */
+ $options = ['id' => $id];
+ if ($column->type === BaseColumn::TYPE_DRAGCOLUMN) {
+ $options = ArrayHelper::merge($options, ['class' => $this->iconMap['drag-handle']]);
+ }
+
+ $input = $column->renderInput($name, $options, [
+ 'id' => $id,
+ 'name' => $name,
+ 'indexPlaceholder' => $this->getIndexPlaceholder(),
+ 'index' => $index,
+ 'columnIndex' => $columnIndex,
+ 'context' => $this->context,
+ ]);
+
+ if ($column->isHiddenInput()) {
+ return $input;
+ }
+
+ $layoutConfig = array_merge([
+ 'offsetClass' => $this->isBootstrapTheme() ? 'col-sm-offset-3' : '',
+ 'labelClass' => $this->isBootstrapTheme() ? 'col-sm-3' : '',
+ 'wrapperClass' => $this->isBootstrapTheme() ? 'col-sm-6' : '',
+ 'errorClass' => $this->isBootstrapTheme() ? 'col-sm-offset-3 col-sm-6' : '',
+ ], $this->layoutConfig);
+
+ Html::addCssClass($column->errorOptions, $layoutConfig['errorClass']);
+
+ $hasError = false;
+ $error = '';
+
+ if ($index !== null) {
+ $error = $column->getFirstError($index);
+ $hasError = !empty($error);
+ }
+
+ $wrapperOptions = [];
+
+ if ($hasError) {
+ Html::addCssClass($wrapperOptions, 'has-error');
+ }
+
+ Html::addCssClass($wrapperOptions, $layoutConfig['wrapperClass']);
+
+ $options = [
+ 'class' => "field-$id list-cell__$column->name" . ($hasError ? ' has-error' : '')
+ ];
+
+ if ($this->isBootstrapTheme()) {
+ Html::addCssClass($options, 'form-group');
+ }
+
+ if (is_callable($column->columnOptions)) {
+ $columnOptions = call_user_func($column->columnOptions, $column->getModel(), $index, $this->context);
+ } else {
+ $columnOptions = $column->columnOptions;
+ }
+
+ $options = array_merge_recursive($options, $columnOptions);
+
+ $content = Html::beginTag('div', $options);
+
+ if (empty($column->title)) {
+ Html::addCssClass($wrapperOptions, $layoutConfig['offsetClass']);
+ } else {
+ $labelOptions = ['class' => $layoutConfig['labelClass']];
+ if ($this->isBootstrapTheme()) {
+ Html::addCssClass($labelOptions, 'control-label');
+ }
+
+ $content .= Html::label($column->title, $id, $labelOptions);
+ }
+
+ $content .= Html::tag('div', $input, $wrapperOptions);
+
+ if ($column->enableError) {
+ $content .= "\n" . $column->renderError($error);
+ }
+
+ $content .= Html::endTag('div');
+
+ return $content;
+ }
+
+ /**
+ * Renders the action column.
+ *
+ * @param null|int $index
+ * @param null|ActiveRecordInterface|array $item
+ * @param null|int $rowIndex
+ * @return string
+ * @throws \Exception
+ */
+ private function renderActionColumn($index = null, $item = null, $rowIndex = null)
+ {
+ $content = $this->getActionButton($index, $rowIndex) . $this->getExtraButtons($index, $item);
+
+ return Html::tag('td', $content, [
+ 'class' => 'list-cell__button',
+ ]);
+ }
+
+ /**
+ * Renders the clone column.
+ *
+ * @return string
+ * @throws \Exception
+ */
+ private function renderCloneColumn()
+ {
+ return Html::tag('td', $this->renderCloneButton(), [
+ 'class' => 'list-cell__button',
+ ]);
+ }
+
+ private function getActionButton($index, $rowIndex)
+ {
+ if ($index === null || $this->min === 0) {
+ return $this->renderRemoveButton();
+ }
+
+ // rowIndex is zero-based, so we have to increment it to properly cpmpare it with min number of rows
+ $rowIndex++;
+
+ if ($rowIndex < $this->min) {
+ return '';
+ }
+
+ if ($rowIndex === $this->min) {
+ return $this->isAddButtonPositionRow() ? $this->renderAddButton() : '';
+ }
+
+ return $this->renderRemoveButton();
+ }
+
+ private function renderAddButton()
+ {
+ $options = [
+ 'class' => 'multiple-input-list__btn js-input-plus',
+ ];
+ Html::addCssClass($options, $this->addButtonOptions['class']);
+
+ return Html::tag('div', $this->addButtonOptions['label'], $options);
+ }
+
+ /**
+ * Renders remove button.
+ *
+ * @return string
+ */
+ private function renderRemoveButton()
+ {
+ $options = [
+ 'class' => 'multiple-input-list__btn js-input-remove',
+ ];
+ Html::addCssClass($options, $this->removeButtonOptions['class']);
+
+ return Html::tag('div', $this->removeButtonOptions['label'], $options);
+ }
+
+ /**
+ * Renders clone button.
+ *
+ * @return string
+ */
+ private function renderCloneButton()
+ {
+ $options = [
+ 'class' => 'multiple-input-list__btn js-input-clone',
+ ];
+ Html::addCssClass($options, $this->cloneButtonOptions['class']);
+
+ return Html::tag('div', $this->cloneButtonOptions['label'], $options);
+ }
+
+ /**
+ * Returns template for using in js.
+ *
+ * @return string
+ *
+ * @throws \yii\base\InvalidConfigException
+ */
+ protected function prepareTemplate()
+ {
+ return $this->renderRowContent();
+ }
+}
diff --git a/src/renderers/RendererInterface.php b/src/renderers/RendererInterface.php
new file mode 100644
index 0000000..395ef3e
--- /dev/null
+++ b/src/renderers/RendererInterface.php
@@ -0,0 +1,47 @@
+renderFooter();
$options = [];
- Html::addCssClass($options, 'multiple-input-list table table-condensed');
+ Html::addCssClass($options, 'multiple-input-list');
+
+ if ($this->isBootstrapTheme()) {
+ Html::addCssClass($options, 'table table-condensed table-renderer');
+ }
$content = Html::tag('table', implode("\n", $content), $options);
- return Html::tag( 'div', $content, [
+ return Html::tag('div', $content, [
'id' => $this->id,
'class' => 'multiple-input'
]);
@@ -54,17 +57,23 @@ protected function internalRender()
public function renderHeader()
{
$cells = [];
+ if ($this->isAddButtonPositionRowBegin()) {
+ $cells[] = $this->renderButtonHeaderCell();
+ }
+
foreach ($this->columns as $column) {
/* @var $column BaseColumn */
$cells[] = $this->renderHeaderCell($column);
}
- if ($this->limit === null || ($this->limit >= 1 && $this->limit !== $this->min)) {
- $button = $this->min === 0 || $this->isAddButtonPositionHeader() ? $this->renderAddButton() : '';
+ if ($this->max === null || ($this->max >= 1 && $this->max !== $this->min)) {
+ $button = $this->isAddButtonPositionHeader() ? $this->renderAddButton() : '';
+
+ if ($this->cloneButton) {
+ $cells[] = $this->renderButtonHeaderCell();
+ }
- $cells[] = Html::tag('th', $button, [
- 'class' => 'list-cell__button'
- ]);
+ $cells[] = $this->renderButtonHeaderCell($button);
}
return Html::tag('thead', Html::tag('tr', implode("\n", $cells)));
@@ -81,8 +90,23 @@ public function renderFooter()
return '';
}
+ $columnsCount = 0;
+ foreach ($this->columns as $column) {
+ if (!$column->isHiddenInput()) {
+ $columnsCount++;
+ }
+ }
+
+ if ($this->cloneButton) {
+ $columnsCount++;
+ }
+
+ if ($this->isAddButtonPositionRowBegin()) {
+ $columnsCount++;
+ }
+
$cells = [];
- $cells[] = Html::tag('td', ' ', ['colspan' => count($this->columns)]);
+ $cells[] = Html::tag('td', ' ', ['colspan' => $columnsCount]);
$cells[] = Html::tag('td', $this->renderAddButton(), [
'class' => 'list-cell__button'
]);
@@ -101,14 +125,14 @@ private function hasHeader()
if ($this->min === 0 || $this->isAddButtonPositionHeader()) {
return true;
}
-
+
foreach ($this->columns as $column) {
/* @var $column BaseColumn */
if ($column->title) {
return true;
}
}
-
+
return false;
}
@@ -122,43 +146,36 @@ private function renderHeaderCell($column)
if ($column->isHiddenInput()) {
return null;
}
+
$options = $column->headerOptions;
Html::addCssClass($options, 'list-cell__' . $column->name);
-
+
return Html::tag('th', $column->title, $options);
}
+ /**
+ * Renders the button header cell.
+ * @param string
+ * @return string
+ */
+ private function renderButtonHeaderCell($button = '')
+ {
+ return Html::tag('th', $button, [
+ 'class' => 'list-cell__button'
+ ]);
+ }
+
/**
* Renders the body.
*
* @return string
+ *
* @throws \yii\base\InvalidConfigException
* @throws \yii\base\InvalidParamException
*/
protected function renderBody()
{
- $rows = [];
-
- if ($this->data) {
- $cnt = count($this->data);
- if ($this->min === $this->limit && $cnt < $this->limit) {
- $cnt = $this->limit;
- }
-
- $indices = array_keys($this->data);
-
- for ($i = 0; $i < $cnt; $i++) {
- $index = ArrayHelper::getValue($indices, $i, $i);
- $item = ArrayHelper::getValue($this->data, $index, null);
- $rows[] = $this->renderRowContent($index, $item);
- }
- } elseif ($this->min > 0) {
- for ($i = 0; $i < $this->min; $i++) {
- $rows[] = $this->renderRowContent($i);
- }
- }
-
- return Html::tag('tbody', implode("\n", $rows));
+ return Html::tag('tbody', implode("\n", $this->renderRows()));
}
/**
@@ -169,30 +186,39 @@ protected function renderBody()
* @return mixed
* @throws InvalidConfigException
*/
- private function renderRowContent($index = null, $item = null)
+ protected function renderRowContent($index = null, $item = null, $rowIndex = null)
{
$cells = [];
$hiddenInputs = [];
+ if (!$this->isFixedNumberOfRows() && $this->isAddButtonPositionRowBegin()) {
+ $cells[] = $this->renderActionColumn($index, $item, $rowIndex, true);
+ }
+
+ $columnIndex = 0;
foreach ($this->columns as $column) {
/* @var $column BaseColumn */
$column->setModel($item);
if ($column->isHiddenInput()) {
- $hiddenInputs[] = $this->renderCellContent($column, $index);
+ $hiddenInputs[] = $this->renderCellContent($column, $index, $columnIndex++);
} else {
- $cells[] = $this->renderCellContent($column, $index);
+ $cells[] = $this->renderCellContent($column, $index, $columnIndex++);
}
}
- if ($this->limit !== $this->min) {
- $cells[] = $this->renderActionColumn($index);
+ if ($this->cloneButton) {
+ $cells[] = $this->renderCloneColumn();
+ }
+
+ if (!$this->isFixedNumberOfRows()) {
+ $cells[] = $this->renderActionColumn($index, $item, $rowIndex);
}
if ($hiddenInputs) {
$hiddenInputs = implode("\n", $hiddenInputs);
$cells[0] = preg_replace('/^(]+>)(.*)(<\/td>)$/s', '${1}' . $hiddenInputs . '$2$3', $cells[0]);
}
-
+
$content = Html::tag('tr', implode("\n", $cells), $this->prepareRowOptions($index, $item));
if ($index !== null) {
@@ -217,6 +243,8 @@ protected function prepareRowOptions($index, $item)
$options = $this->rowOptions;
}
+ $options['data-index'] = '{' . $this->getIndexPlaceholder() . '}';
+
Html::addCssClass($options, 'multiple-input-list__item');
return $options;
@@ -227,14 +255,33 @@ protected function prepareRowOptions($index, $item)
*
* @param BaseColumn $column
* @param int|null $index
+ * @param int|null $columnIndex
* @return string
+ *
+ * @todo rethink visibility level (make it private)
*/
- public function renderCellContent($column, $index)
+ public function renderCellContent($column, $index, $columnIndex = null)
{
$id = $column->getElementId($index);
$name = $column->getElementName($index);
- $input = $column->renderInput($name, [
- 'id' => $id
+
+ /**
+ * This class inherits iconMap from BaseRenderer
+ * If the input to be rendered is a drag column, we give it the appropriate icon class
+ * via the $options array
+ */
+ $options = ['id' => $id];
+ if ($column->type === BaseColumn::TYPE_DRAGCOLUMN) {
+ $options = ArrayHelper::merge($options, ['class' => $this->iconMap['drag-handle']]);
+ }
+
+ $input = $column->renderInput($name, $options, [
+ 'id' => $id,
+ 'name' => $name,
+ 'indexPlaceholder' => $this->getIndexPlaceholder(),
+ 'index' => $index,
+ 'columnIndex' => $columnIndex,
+ 'context' => $this->context,
]);
if ($column->isHiddenInput()) {
@@ -253,59 +300,109 @@ public function renderCellContent($column, $index)
$input .= "\n" . $column->renderError($error);
}
- $wrapperOptions = [
- 'class' => 'form-group field-' . $id
- ];
+ $wrapperOptions = ['class' => 'field-' . $id];
+ if ($this->isBootstrapTheme()) {
+ Html::addCssClass($wrapperOptions, 'form-group');
+ }
if ($hasError) {
Html::addCssClass($wrapperOptions, 'has-error');
}
-
+
+ if (is_callable($column->columnOptions)) {
+ $columnOptions = call_user_func($column->columnOptions, $column->getModel(), $index, $this->context);
+ } else {
+ $columnOptions = $column->columnOptions;
+ }
+
+ Html::addCssClass($columnOptions, 'list-cell__' . $column->name);
+
$input = Html::tag('div', $input, $wrapperOptions);
- return Html::tag('td', $input, [
- 'class' => 'list-cell__' . $column->name,
- ]);
+ return Html::tag('td', $input, $columnOptions);
}
/**
* Renders the action column.
*
- * @param null|int $index
+ * @param null|int|string $index
+ * @param null|ActiveRecordInterface|array $item
+ * @param int $rowIndex
* @return string
- * @throws \Exception
*/
- private function renderActionColumn($index = null)
+ private function renderActionColumn(
+ $index = null,
+ $item = null,
+ $rowIndex = null,
+ $isFirstColumn = false
+ )
{
- return Html::tag('td', $this->getActionButton($index), [
+ $content = $this->getActionButton($index, $rowIndex, $isFirstColumn) . $this->getExtraButtons($index, $item);
+
+ return Html::tag('td', $content, [
'class' => 'list-cell__button',
]);
}
- private function getActionButton($index)
+ /**
+ * Renders the clone column.
+ *
+ * @return string
+ */
+ private function renderCloneColumn()
+ {
+ return Html::tag('td', $this->renderCloneButton(), [
+ 'class' => 'list-cell__button',
+ ]);
+ }
+
+ /**
+ * @param int|string|null $index
+ * @param int $rowIndex
+ * @return string
+ */
+ private function getActionButton($index = null, $rowIndex = null, $isFirstColumn = false)
{
if ($index === null || $this->min === 0) {
- return $this->renderRemoveButton();
+ if ($isFirstColumn) {
+ return $this->isAddButtonPositionRowBegin() ? $this->renderRemoveButton() : '';
+ }
+
+ return $this->isAddButtonPositionRowBegin() ? '' : $this->renderRemoveButton();
}
- $index++;
- if ($index < $this->min) {
+ // rowIndex is zero-based, so we have to increment it to properly cpmpare it with min number of rows
+ $rowIndex++;
+
+ if ($rowIndex < $this->min) {
return '';
- } elseif ($index === $this->min) {
+ }
+
+ if ($rowIndex === $this->min) {
+ if ($isFirstColumn) {
+ return $this->isAddButtonPositionRowBegin() ? $this->renderAddButton() : '';
+ }
+
+
return $this->isAddButtonPositionRow() ? $this->renderAddButton() : '';
- } else {
- return $this->renderRemoveButton();
}
+
+ if ($isFirstColumn) {
+ return $this->isAddButtonPositionRowBegin() ? $this->renderRemoveButton() : '';
+ }
+
+ return $this->isAddButtonPositionRowBegin() ? '' : $this->renderRemoveButton();
}
private function renderAddButton()
{
$options = [
- 'class' => 'btn multiple-input-list__btn js-input-plus',
+ 'class' => 'multiple-input-list__btn js-input-plus',
];
+
Html::addCssClass($options, $this->addButtonOptions['class']);
-
+
return Html::tag('div', $this->addButtonOptions['label'], $options);
}
@@ -313,22 +410,40 @@ private function renderAddButton()
* Renders remove button.
*
* @return string
- * @throws \Exception
*/
private function renderRemoveButton()
{
$options = [
- 'class' => 'btn multiple-input-list__btn js-input-remove',
+ 'class' => 'multiple-input-list__btn js-input-remove',
];
+
Html::addCssClass($options, $this->removeButtonOptions['class']);
-
+
return Html::tag('div', $this->removeButtonOptions['label'], $options);
}
+ /**
+ * Renders clone button.
+ *
+ * @return string
+ */
+ private function renderCloneButton()
+ {
+ $options = [
+ 'class' => 'multiple-input-list__btn js-input-clone',
+ ];
+
+ Html::addCssClass($options, $this->cloneButtonOptions['class']);
+
+ return Html::tag('div', $this->cloneButtonOptions['label'], $options);
+ }
+
/**
* Returns template for using in js.
*
* @return string
+ *
+ * @throws \yii\base\InvalidConfigException
*/
protected function prepareTemplate()
{
diff --git a/tests/unit/MultipleInputAssetTest.php b/tests/unit/MultipleInputAssetTest.php
new file mode 100644
index 0000000..035a87d
--- /dev/null
+++ b/tests/unit/MultipleInputAssetTest.php
@@ -0,0 +1,30 @@
+assertIsString($asset->sourcePath);
+ $this->assertCount(1, $asset->js);
+ $this->assertCount(1, $asset->css);
+ }
+
+ public function testSetEmptyJsViaConfig()
+ {
+ $asset = new MultipleInputAsset([
+ 'js' => [],
+ 'css' => [],
+ 'sourcePath' => 'test',
+ ]);
+ $this->assertEquals('test', $asset->sourcePath);
+ $this->assertCount(0, $asset->js);
+ $this->assertCount(0, $asset->css);
+ }
+}
diff --git a/tests/unit/MultipleInputTest.php b/tests/unit/MultipleInputTest.php
new file mode 100644
index 0000000..4fd54d9
--- /dev/null
+++ b/tests/unit/MultipleInputTest.php
@@ -0,0 +1,78 @@
+ $model,
+ 'attribute' => 'email',
+ ]);
+
+ $expected = [
+ ['name' => 'email', 'type' => MultipleInputColumn::TYPE_TEXT_INPUT]
+ ];
+
+ $this->assertEquals($expected, $widget->columns);
+ }
+
+ public function testEnableGuessTitleInsideGuessColumn()
+ {
+ $model = new TestModel();
+
+ $widget = new MultipleInput([
+ 'model' => $model,
+ 'attribute' => 'email',
+ 'enableGuessTitle' => true,
+ ]);
+
+ $expected = [
+ [
+ 'name' => 'email',
+ 'type' => MultipleInputColumn::TYPE_TEXT_INPUT,
+ 'title' => 'Email',
+ ]
+ ];
+
+ $this->assertEquals($expected, $widget->columns);
+ }
+
+ public function testInitData()
+ {
+ $model = new TestModel();
+
+ $dataExample = [
+ ['email' => 'test@example.com'],
+ ['email' => 'test@example.com'],
+ ];
+
+ $widget = new MultipleInput([
+ 'model' => $model,
+ 'attribute' => 'email',
+ 'data' => $dataExample
+ ]);
+
+ $this->assertEquals($dataExample, $widget->data);
+
+ $model->email = ['test@example.com'];
+
+ $widget = new MultipleInput([
+ 'model' => $model,
+ 'attribute' => 'email',
+ ]);
+
+ $this->assertEquals($model->email, $widget->data);
+ }
+}
\ No newline at end of file
diff --git a/tests/unit/TestCase.php b/tests/unit/TestCase.php
new file mode 100644
index 0000000..e908b41
--- /dev/null
+++ b/tests/unit/TestCase.php
@@ -0,0 +1,9 @@
+assertEquals($defaultValue, $preparer->prepare(null));
+ $this->assertEquals($defaultValue, $preparer->prepare([]));
+ $this->assertEquals($defaultValue, $preparer->prepare(''));
+ }
+
+ public function testPrepareStringOrNumber() {
+ $model = new TestModel();
+ $preparer = new ValuePreparer();
+ $this->assertEquals(1, $preparer->prepare(1));
+ $this->assertEquals('1', $preparer->prepare('1'));
+ }
+
+ public function testPrepareArrayKey() {
+ $model = new TestModel();
+ $preparer = new ValuePreparer('test');
+ $this->assertEquals(1, $preparer->prepare([
+ 'test' => 1
+ ]));
+ }
+
+ public function testPrepareModelAttribute() {
+ $model = new TestModel();
+ $exprectedValue = [
+ 'test'
+ ];
+ $model->email = $exprectedValue;
+ $preparer = new ValuePreparer('email');
+ $this->assertEquals($exprectedValue, $preparer->prepare($model));
+ }
+
+ public function testPrepareActiveRecordDirectAttribute() {
+ $model = new TestActiveRecord();
+ $exprectedValue = 'test';
+ $model->email = $exprectedValue;
+ $preparer = new ValuePreparer('email');
+ $this->assertEquals($exprectedValue, $preparer->prepare($model));
+ }
+
+ public function testPrepareActiveRecordRelation() {
+ $relatedModel = new TestActiveRecordRelated();
+ $model = $this->createMock(TestActiveRecord::class);
+ $query = $this->createMock(ActiveQuery::class);
+ $query->expects($this->once())
+ ->method('findFor')
+ ->with('testRelation', $model)
+ ->willReturn($relatedModel);
+
+ $model->expects($this->once())
+ ->method('getRelation')
+ ->with('testRelation', false)
+ ->willReturn($query);
+
+ $preparer = new ValuePreparer('testRelation');
+
+ $result = $preparer->prepare($model);
+
+ $this->assertEquals($relatedModel, $result);
+ }
+
+ public function testPrepareActiveRecordRelationWithSameAsAttributeName() {
+ $model = new TestActiveRecord();
+ $relatedModel = new TestActiveRecordRelated();
+ $model->testRelation = $relatedModel;
+
+ $preparer = new ValuePreparer( 'testRelation');
+ $this->assertEquals($relatedModel, $preparer->prepare($model));
+ }
+}
\ No newline at end of file
diff --git a/tests/unit/data/TestActiveRecord.php b/tests/unit/data/TestActiveRecord.php
new file mode 100644
index 0000000..757435c
--- /dev/null
+++ b/tests/unit/data/TestActiveRecord.php
@@ -0,0 +1,48 @@
+ 'Email',
+ ];
+ }
+
+ public function getTestHasOneRelation() {}
+
+ public function attributes()
+ {
+ return ['testRelation']; // TODO: Change the autogenerated stub
+ }
+
+ public function getAttribute($name)
+ {
+ if ($name === 'testRelation') {
+ return $this->testRelation;
+ }
+
+ return parent::getAttribute($name);
+ }
+
+ public function getTestRelation() {
+ return $this->hasOne(TestActiveRecordRelated::class, []);
+ }
+}
\ No newline at end of file
diff --git a/tests/unit/data/TestActiveRecordRelated.php b/tests/unit/data/TestActiveRecordRelated.php
new file mode 100644
index 0000000..1890f57
--- /dev/null
+++ b/tests/unit/data/TestActiveRecordRelated.php
@@ -0,0 +1,17 @@
+ 'Email',
+ ];
+ }
+}
\ No newline at end of file