diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index e4a26aa..0000000 --- a/.gitattributes +++ /dev/null @@ -1,8 +0,0 @@ -/.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 deleted file mode 100644 index e454be0..0000000 --- a/.gitbook.yaml +++ /dev/null @@ -1 +0,0 @@ -root: ./docs/ diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml deleted file mode 100644 index b276734..0000000 --- a/.github/workflows/main.yml +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 60ad359..0000000 --- a/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -.idea/* -node_modules/ -vendor/ -composer.lock -package-lock.json diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/404.html b/404.html new file mode 100644 index 0000000..e78adf4 --- /dev/null +++ b/404.html @@ -0,0 +1,418 @@ + + + + + + + + + + + + + + + + + + + + + + Yii2 multiple input + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ +
+ + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ +

404 - Not found

+ +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 3eecd95..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,417 +0,0 @@ -Yii2 multiple input change log -============================== - -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 ------ - -- Bug: Use method `::className` instead of `::class` - -1.3.0 ------ - -- #79 Added support for embedded MultipleInput widget (unclead, execut) -- Enh: Added ability to render `add` button in the footer (unclead) -- Enh: Improving for better work without ActiveForm (unclead) -- Enh: Added ability to render `add` button at several positions (unclead) - -1.2.19 ------- - -- #85: fixed `$enableError` not render element in template (thiagotalma) - -1.2.18 ------- - -- #81 fixed output of errors in case of non-ajax validation - -1.2.17 ------- - -- Enh: increased default value for the property `limit` (ivansal) -- Enh: Added support of associative array in data (ivansal) -- Bug: fixed double execution events for included MultipleInput (fiamma06) - -1.2.16 ------- - -- Bug #70: replacing of the placeholder after preparing the content of row - -1.2.15 ------- - -- Added note about usage widget with ajax - -1.2.14 ------- - -- Bug #71: trigger the event after actual removal of row - -1.2.13 ------- - -- Added new js events (add/remove/clear inputs) and integrated the gulp for minification of assets (veksa) -- Added support of closure for parameter `options` (veksa) - -1.2.12 ------- - -- Hotfix: Fixed error when array_key_exits (kongoon) - -1.2.11 ------- - -- Bug #61: Fixed a rendering of remove button -- Bug #62: Incorrect behavior is case when `min` is equal to `limit` -- Bug #64: Radio/checkbox lists doesn't work correctly - -1.2.10 ------- - -- Enh #59 Added columnClass property (unclead) - -1.2.9 ------ - -- Enh #56: add `rowOptions` property - -1.2.8 ------ - -- Enh: Don't show action column when limit is `equal` to `min` - -1.2.7 ------ - -- Bug #55: Attach click events to the widget wrapper instead of `$(document)` - -1.2.6 ------ - -- Bug #49: urlencoded field token replacement in js template (rolmonk) -- Enh #48: Added option `min` for setting minimum number of rows -- Enh: added option `addButtonPosition` - -1.2.5 ------ - -- Bug #46: Renamed placeholder to avoid conflict with other plugins -- Bug #47: Use Html helper for rendering buttons instead of Button widget -- Enh: Deleted yii2-bootstrap dependency - -1.2.4 ------ - -- Bug #39: TabularInput: now new row does't copy values from the most recent row -- Enh #40: Pass the current row for removal when calling `beforeDeleteRow` event - - -1.2.3 ------ - -- Enh #34: Added option `allowEmptyList` (unclead) -- Enh #35: Added option `enableGuessTitle` for MultipleInput (unclead) -- Bug #36: Use PCRE_MULTILINE modifier in regex - -1.2.2 ------ - -- Enh #31: Added support of anonymous function for `items` attribute (unclead, stepancher) -- Enh: added hidden field for radio and checkbox inputs (unclead, kotchuprik) -- Enh: improved css (fiamma06) - -1.2.1 ------ - -- Bug #25 fixed rendering when data is empty -- Bug #27 fixed element's prefix generation - -1.2.0 ------ - -- Bug #19 Refactoring rendering of inputs (unclead) -- Bug #20 Added hasAttribute checking for AR models (unclead) -- Enh #22 Added `TabularInput` widget (unclead), rendering logic has been moved to separate class (renderer) - -1.1.0 ------ - -- Bug #17: display inline errors (unclead, mikbox74) -- Enh #11: Improve js events (unclead) -- Bug #16: correct use of defaultValue property (unclead) -- code improvements (unclead) - -1.0.4 --------------------- - -- Bug #15: Fix setting current values of dropDownList (unclead) -- Bug #16: fix render of dropDown and similar inputs (unclead) -- Enh: Add attributeOptions property - -1.0.3 ------ -- Bug: Hidden fields no longer break markup (unclead, kotchuprik) - -1.0.2 ------ - -- Enh: added minified version of js script (unclead) -- Enh #8: renamed placeholders for avoid conflicts with other widgets (unclead) -- Enh #7: customization of header cell - -1.0.1 ------ - -- Enh #1: Implemented ability to use widget as column type (unclead) -- Enh: add js events (ZAYEC77) - -1.0.0 ------ - -first stable release diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index bc52ba6..0000000 --- a/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2013, Eugene Tupikov - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -* Neither the names of Eugene Tupikov or unclead nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.md b/README.md deleted file mode 100644 index 61b815b..0000000 --- a/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# Yii2 Multiple input widget. -Yii2 widget for handle multiple inputs for an attribute of model and tabular input for batch of models. - -[![Latest Stable Version](https://poser.pugx.org/unclead/yii2-multiple-input/v/stable)](https://packagist.org/packages/unclead/yii2-multiple-input) -[![Total Downloads](https://poser.pugx.org/unclead/yii2-multiple-input/downloads)](https://packagist.org/packages/unclead/yii2-multiple-input) -[![Daily Downloads](https://poser.pugx.org/unclead/yii2-multiple-input/d/daily)](https://packagist.org/packages/unclead/yii2-multiple-input) -[![Latest Unstable Version](https://poser.pugx.org/unclead/yii2-multiple-input/v/unstable)](https://packagist.org/packages/unclead/yii2-multiple-input) -[![License](https://poser.pugx.org/unclead/yii2-multiple-input/license)](https://packagist.org/packages/unclead/yii2-multiple-input) - -## Latest release -The latest stable version of the extension is v2.27.0 Follow the [instruction](./UPGRADE.md) for upgrading from previous versions - -## 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 "~2.0" -``` - -or add - -``` -"unclead/yii2-multiple-input": "~2.0" -``` - -to the require section of your `composer.json` file. - -## Basic usage - -![Single column example](./resources/images/single-column.gif?raw=true) - -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\multipleinput\MultipleInput; - -... - -field($model, 'emails')->widget(MultipleInput::className(), [ - 'max' => 6, - 'min' => 2, // should be at least 2 rows - 'allowEmptyList' => false, - 'enableGuessTitle' => true, - 'addButtonPosition' => MultipleInput::POS_HEADER, // show add button in the header - ]) - ->label(false); -?> -``` - -## Documentation - -You can find a full version of documentation [here](https://unclead.github.io/yii2-multiple-input/) - -## 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 deleted file mode 100644 index db7f21e..0000000 --- a/UPGRADE.md +++ /dev/null @@ -1,52 +0,0 @@ -Upgrading Instructions for yii2-multiple-widget -=============================================== - -!!!IMPORTANT!!! - -The following upgrading instructions are cumulative. That is, -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 ------------------------ - -- The mechanism of customization configuration by using index placeholder was changed in scope of implementing support of nested `MultipleInput` -If you customize configuration by using index placeholder you have to add ID of widget to the placeholder. -For example, `multiple_index` became `multiple_index_question_list` - - -Upgrade from version less then 1.1.0 ------------------------------------- - -After installing version 1.1.0 you have to rename js events following the next schema: - -- Event `init` rename to `afterInit` -- Event `addNewRow` rename to `afterAddRow` -- Event `removeRow` rename to `afterDeleteRow` diff --git a/assets/images/favicon.png b/assets/images/favicon.png new file mode 100644 index 0000000..1cf13b9 Binary files /dev/null and b/assets/images/favicon.png differ diff --git a/assets/javascripts/bundle.51d95adb.min.js b/assets/javascripts/bundle.51d95adb.min.js new file mode 100644 index 0000000..b20ec68 --- /dev/null +++ b/assets/javascripts/bundle.51d95adb.min.js @@ -0,0 +1,29 @@ +"use strict";(()=>{var Hi=Object.create;var xr=Object.defineProperty;var Pi=Object.getOwnPropertyDescriptor;var $i=Object.getOwnPropertyNames,kt=Object.getOwnPropertySymbols,Ii=Object.getPrototypeOf,Er=Object.prototype.hasOwnProperty,an=Object.prototype.propertyIsEnumerable;var on=(e,t,r)=>t in e?xr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,P=(e,t)=>{for(var r in t||(t={}))Er.call(t,r)&&on(e,r,t[r]);if(kt)for(var r of kt(t))an.call(t,r)&&on(e,r,t[r]);return e};var sn=(e,t)=>{var r={};for(var n in e)Er.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&kt)for(var n of kt(e))t.indexOf(n)<0&&an.call(e,n)&&(r[n]=e[n]);return r};var Ht=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Fi=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $i(t))!Er.call(e,o)&&o!==r&&xr(e,o,{get:()=>t[o],enumerable:!(n=Pi(t,o))||n.enumerable});return e};var yt=(e,t,r)=>(r=e!=null?Hi(Ii(e)):{},Fi(t||!e||!e.__esModule?xr(r,"default",{value:e,enumerable:!0}):r,e));var fn=Ht((wr,cn)=>{(function(e,t){typeof wr=="object"&&typeof cn!="undefined"?t():typeof define=="function"&&define.amd?define(t):t()})(wr,function(){"use strict";function e(r){var n=!0,o=!1,i=null,a={text:!0,search:!0,url:!0,tel:!0,email:!0,password:!0,number:!0,date:!0,month:!0,week:!0,time:!0,datetime:!0,"datetime-local":!0};function s(T){return!!(T&&T!==document&&T.nodeName!=="HTML"&&T.nodeName!=="BODY"&&"classList"in T&&"contains"in T.classList)}function f(T){var Ke=T.type,We=T.tagName;return!!(We==="INPUT"&&a[Ke]&&!T.readOnly||We==="TEXTAREA"&&!T.readOnly||T.isContentEditable)}function c(T){T.classList.contains("focus-visible")||(T.classList.add("focus-visible"),T.setAttribute("data-focus-visible-added",""))}function u(T){T.hasAttribute("data-focus-visible-added")&&(T.classList.remove("focus-visible"),T.removeAttribute("data-focus-visible-added"))}function p(T){T.metaKey||T.altKey||T.ctrlKey||(s(r.activeElement)&&c(r.activeElement),n=!0)}function m(T){n=!1}function d(T){s(T.target)&&(n||f(T.target))&&c(T.target)}function h(T){s(T.target)&&(T.target.classList.contains("focus-visible")||T.target.hasAttribute("data-focus-visible-added"))&&(o=!0,window.clearTimeout(i),i=window.setTimeout(function(){o=!1},100),u(T.target))}function v(T){document.visibilityState==="hidden"&&(o&&(n=!0),B())}function B(){document.addEventListener("mousemove",z),document.addEventListener("mousedown",z),document.addEventListener("mouseup",z),document.addEventListener("pointermove",z),document.addEventListener("pointerdown",z),document.addEventListener("pointerup",z),document.addEventListener("touchmove",z),document.addEventListener("touchstart",z),document.addEventListener("touchend",z)}function re(){document.removeEventListener("mousemove",z),document.removeEventListener("mousedown",z),document.removeEventListener("mouseup",z),document.removeEventListener("pointermove",z),document.removeEventListener("pointerdown",z),document.removeEventListener("pointerup",z),document.removeEventListener("touchmove",z),document.removeEventListener("touchstart",z),document.removeEventListener("touchend",z)}function z(T){T.target.nodeName&&T.target.nodeName.toLowerCase()==="html"||(n=!1,re())}document.addEventListener("keydown",p,!0),document.addEventListener("mousedown",m,!0),document.addEventListener("pointerdown",m,!0),document.addEventListener("touchstart",m,!0),document.addEventListener("visibilitychange",v,!0),B(),r.addEventListener("focus",d,!0),r.addEventListener("blur",h,!0),r.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&r.host?r.host.setAttribute("data-js-focus-visible",""):r.nodeType===Node.DOCUMENT_NODE&&(document.documentElement.classList.add("js-focus-visible"),document.documentElement.setAttribute("data-js-focus-visible",""))}if(typeof window!="undefined"&&typeof document!="undefined"){window.applyFocusVisiblePolyfill=e;var t;try{t=new CustomEvent("focus-visible-polyfill-ready")}catch(r){t=document.createEvent("CustomEvent"),t.initCustomEvent("focus-visible-polyfill-ready",!1,!1,{})}window.dispatchEvent(t)}typeof document!="undefined"&&e(document)})});var un=Ht(Sr=>{(function(e){var t=function(){try{return!!Symbol.iterator}catch(c){return!1}},r=t(),n=function(c){var u={next:function(){var p=c.shift();return{done:p===void 0,value:p}}};return r&&(u[Symbol.iterator]=function(){return u}),u},o=function(c){return encodeURIComponent(c).replace(/%20/g,"+")},i=function(c){return decodeURIComponent(String(c).replace(/\+/g," "))},a=function(){var c=function(p){Object.defineProperty(this,"_entries",{writable:!0,value:{}});var m=typeof p;if(m!=="undefined")if(m==="string")p!==""&&this._fromString(p);else if(p instanceof c){var d=this;p.forEach(function(re,z){d.append(z,re)})}else if(p!==null&&m==="object")if(Object.prototype.toString.call(p)==="[object Array]")for(var h=0;hd[0]?1:0}),c._entries&&(c._entries={});for(var p=0;p1?i(d[1]):"")}})})(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:Sr);(function(e){var t=function(){try{var o=new e.URL("b","http://a");return o.pathname="c d",o.href==="http://a/c%20d"&&o.searchParams}catch(i){return!1}},r=function(){var o=e.URL,i=function(f,c){typeof f!="string"&&(f=String(f)),c&&typeof c!="string"&&(c=String(c));var u=document,p;if(c&&(e.location===void 0||c!==e.location.href)){c=c.toLowerCase(),u=document.implementation.createHTMLDocument(""),p=u.createElement("base"),p.href=c,u.head.appendChild(p);try{if(p.href.indexOf(c)!==0)throw new Error(p.href)}catch(T){throw new Error("URL unable to set base "+c+" due to "+T)}}var m=u.createElement("a");m.href=f,p&&(u.body.appendChild(m),m.href=m.href);var d=u.createElement("input");if(d.type="url",d.value=f,m.protocol===":"||!/:/.test(m.href)||!d.checkValidity()&&!c)throw new TypeError("Invalid URL");Object.defineProperty(this,"_anchorElement",{value:m});var h=new e.URLSearchParams(this.search),v=!0,B=!0,re=this;["append","delete","set"].forEach(function(T){var Ke=h[T];h[T]=function(){Ke.apply(h,arguments),v&&(B=!1,re.search=h.toString(),B=!0)}}),Object.defineProperty(this,"searchParams",{value:h,enumerable:!0});var z=void 0;Object.defineProperty(this,"_updateSearchParams",{enumerable:!1,configurable:!1,writable:!1,value:function(){this.search!==z&&(z=this.search,B&&(v=!1,this.searchParams._fromString(this.search),v=!0))}})},a=i.prototype,s=function(f){Object.defineProperty(a,f,{get:function(){return this._anchorElement[f]},set:function(c){this._anchorElement[f]=c},enumerable:!0})};["hash","host","hostname","port","protocol"].forEach(function(f){s(f)}),Object.defineProperty(a,"search",{get:function(){return this._anchorElement.search},set:function(f){this._anchorElement.search=f,this._updateSearchParams()},enumerable:!0}),Object.defineProperties(a,{toString:{get:function(){var f=this;return function(){return f.href}}},href:{get:function(){return this._anchorElement.href.replace(/\?$/,"")},set:function(f){this._anchorElement.href=f,this._updateSearchParams()},enumerable:!0},pathname:{get:function(){return this._anchorElement.pathname.replace(/(^\/?)/,"/")},set:function(f){this._anchorElement.pathname=f},enumerable:!0},origin:{get:function(){var f={"http:":80,"https:":443,"ftp:":21}[this._anchorElement.protocol],c=this._anchorElement.port!=f&&this._anchorElement.port!=="";return this._anchorElement.protocol+"//"+this._anchorElement.hostname+(c?":"+this._anchorElement.port:"")},enumerable:!0},password:{get:function(){return""},set:function(f){},enumerable:!0},username:{get:function(){return""},set:function(f){},enumerable:!0}}),i.createObjectURL=function(f){return o.createObjectURL.apply(o,arguments)},i.revokeObjectURL=function(f){return o.revokeObjectURL.apply(o,arguments)},e.URL=i};if(t()||r(),e.location!==void 0&&!("origin"in e.location)){var n=function(){return e.location.protocol+"//"+e.location.hostname+(e.location.port?":"+e.location.port:"")};try{Object.defineProperty(e.location,"origin",{get:n,enumerable:!0})}catch(o){setInterval(function(){e.location.origin=n()},100)}}})(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:Sr)});var Qr=Ht((Lt,Kr)=>{/*! + * clipboard.js v2.0.11 + * https://clipboardjs.com/ + * + * Licensed MIT © Zeno Rocha + */(function(t,r){typeof Lt=="object"&&typeof Kr=="object"?Kr.exports=r():typeof define=="function"&&define.amd?define([],r):typeof Lt=="object"?Lt.ClipboardJS=r():t.ClipboardJS=r()})(Lt,function(){return function(){var e={686:function(n,o,i){"use strict";i.d(o,{default:function(){return ki}});var a=i(279),s=i.n(a),f=i(370),c=i.n(f),u=i(817),p=i.n(u);function m(j){try{return document.execCommand(j)}catch(O){return!1}}var d=function(O){var w=p()(O);return m("cut"),w},h=d;function v(j){var O=document.documentElement.getAttribute("dir")==="rtl",w=document.createElement("textarea");w.style.fontSize="12pt",w.style.border="0",w.style.padding="0",w.style.margin="0",w.style.position="absolute",w.style[O?"right":"left"]="-9999px";var k=window.pageYOffset||document.documentElement.scrollTop;return w.style.top="".concat(k,"px"),w.setAttribute("readonly",""),w.value=j,w}var B=function(O,w){var k=v(O);w.container.appendChild(k);var F=p()(k);return m("copy"),k.remove(),F},re=function(O){var w=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{container:document.body},k="";return typeof O=="string"?k=B(O,w):O instanceof HTMLInputElement&&!["text","search","url","tel","password"].includes(O==null?void 0:O.type)?k=B(O.value,w):(k=p()(O),m("copy")),k},z=re;function T(j){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?T=function(w){return typeof w}:T=function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w},T(j)}var Ke=function(){var O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},w=O.action,k=w===void 0?"copy":w,F=O.container,q=O.target,Le=O.text;if(k!=="copy"&&k!=="cut")throw new Error('Invalid "action" value, use either "copy" or "cut"');if(q!==void 0)if(q&&T(q)==="object"&&q.nodeType===1){if(k==="copy"&&q.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if(k==="cut"&&(q.hasAttribute("readonly")||q.hasAttribute("disabled")))throw new Error(`Invalid "target" attribute. You can't cut text from elements with "readonly" or "disabled" attributes`)}else throw new Error('Invalid "target" value, use a valid Element');if(Le)return z(Le,{container:F});if(q)return k==="cut"?h(q):z(q,{container:F})},We=Ke;function Ie(j){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ie=function(w){return typeof w}:Ie=function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w},Ie(j)}function Ti(j,O){if(!(j instanceof O))throw new TypeError("Cannot call a class as a function")}function nn(j,O){for(var w=0;w0&&arguments[0]!==void 0?arguments[0]:{};this.action=typeof F.action=="function"?F.action:this.defaultAction,this.target=typeof F.target=="function"?F.target:this.defaultTarget,this.text=typeof F.text=="function"?F.text:this.defaultText,this.container=Ie(F.container)==="object"?F.container:document.body}},{key:"listenClick",value:function(F){var q=this;this.listener=c()(F,"click",function(Le){return q.onClick(Le)})}},{key:"onClick",value:function(F){var q=F.delegateTarget||F.currentTarget,Le=this.action(q)||"copy",Rt=We({action:Le,container:this.container,target:this.target(q),text:this.text(q)});this.emit(Rt?"success":"error",{action:Le,text:Rt,trigger:q,clearSelection:function(){q&&q.focus(),window.getSelection().removeAllRanges()}})}},{key:"defaultAction",value:function(F){return yr("action",F)}},{key:"defaultTarget",value:function(F){var q=yr("target",F);if(q)return document.querySelector(q)}},{key:"defaultText",value:function(F){return yr("text",F)}},{key:"destroy",value:function(){this.listener.destroy()}}],[{key:"copy",value:function(F){var q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{container:document.body};return z(F,q)}},{key:"cut",value:function(F){return h(F)}},{key:"isSupported",value:function(){var F=arguments.length>0&&arguments[0]!==void 0?arguments[0]:["copy","cut"],q=typeof F=="string"?[F]:F,Le=!!document.queryCommandSupported;return q.forEach(function(Rt){Le=Le&&!!document.queryCommandSupported(Rt)}),Le}}]),w}(s()),ki=Ri},828:function(n){var o=9;if(typeof Element!="undefined"&&!Element.prototype.matches){var i=Element.prototype;i.matches=i.matchesSelector||i.mozMatchesSelector||i.msMatchesSelector||i.oMatchesSelector||i.webkitMatchesSelector}function a(s,f){for(;s&&s.nodeType!==o;){if(typeof s.matches=="function"&&s.matches(f))return s;s=s.parentNode}}n.exports=a},438:function(n,o,i){var a=i(828);function s(u,p,m,d,h){var v=c.apply(this,arguments);return u.addEventListener(m,v,h),{destroy:function(){u.removeEventListener(m,v,h)}}}function f(u,p,m,d,h){return typeof u.addEventListener=="function"?s.apply(null,arguments):typeof m=="function"?s.bind(null,document).apply(null,arguments):(typeof u=="string"&&(u=document.querySelectorAll(u)),Array.prototype.map.call(u,function(v){return s(v,p,m,d,h)}))}function c(u,p,m,d){return function(h){h.delegateTarget=a(h.target,p),h.delegateTarget&&d.call(u,h)}}n.exports=f},879:function(n,o){o.node=function(i){return i!==void 0&&i instanceof HTMLElement&&i.nodeType===1},o.nodeList=function(i){var a=Object.prototype.toString.call(i);return i!==void 0&&(a==="[object NodeList]"||a==="[object HTMLCollection]")&&"length"in i&&(i.length===0||o.node(i[0]))},o.string=function(i){return typeof i=="string"||i instanceof String},o.fn=function(i){var a=Object.prototype.toString.call(i);return a==="[object Function]"}},370:function(n,o,i){var a=i(879),s=i(438);function f(m,d,h){if(!m&&!d&&!h)throw new Error("Missing required arguments");if(!a.string(d))throw new TypeError("Second argument must be a String");if(!a.fn(h))throw new TypeError("Third argument must be a Function");if(a.node(m))return c(m,d,h);if(a.nodeList(m))return u(m,d,h);if(a.string(m))return p(m,d,h);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function c(m,d,h){return m.addEventListener(d,h),{destroy:function(){m.removeEventListener(d,h)}}}function u(m,d,h){return Array.prototype.forEach.call(m,function(v){v.addEventListener(d,h)}),{destroy:function(){Array.prototype.forEach.call(m,function(v){v.removeEventListener(d,h)})}}}function p(m,d,h){return s(document.body,m,d,h)}n.exports=f},817:function(n){function o(i){var a;if(i.nodeName==="SELECT")i.focus(),a=i.value;else if(i.nodeName==="INPUT"||i.nodeName==="TEXTAREA"){var s=i.hasAttribute("readonly");s||i.setAttribute("readonly",""),i.select(),i.setSelectionRange(0,i.value.length),s||i.removeAttribute("readonly"),a=i.value}else{i.hasAttribute("contenteditable")&&i.focus();var f=window.getSelection(),c=document.createRange();c.selectNodeContents(i),f.removeAllRanges(),f.addRange(c),a=f.toString()}return a}n.exports=o},279:function(n){function o(){}o.prototype={on:function(i,a,s){var f=this.e||(this.e={});return(f[i]||(f[i]=[])).push({fn:a,ctx:s}),this},once:function(i,a,s){var f=this;function c(){f.off(i,c),a.apply(s,arguments)}return c._=a,this.on(i,c,s)},emit:function(i){var a=[].slice.call(arguments,1),s=((this.e||(this.e={}))[i]||[]).slice(),f=0,c=s.length;for(f;f{"use strict";/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */var is=/["'&<>]/;Jo.exports=as;function as(e){var t=""+e,r=is.exec(t);if(!r)return t;var n,o="",i=0,a=0;for(i=r.index;i0&&i[i.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function W(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i}function D(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,i;n1||s(m,d)})})}function s(m,d){try{f(n[m](d))}catch(h){p(i[0][3],h)}}function f(m){m.value instanceof Xe?Promise.resolve(m.value.v).then(c,u):p(i[0][2],m)}function c(m){s("next",m)}function u(m){s("throw",m)}function p(m,d){m(d),i.shift(),i.length&&s(i[0][0],i[0][1])}}function mn(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof xe=="function"?xe(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(i){r[i]=e[i]&&function(a){return new Promise(function(s,f){a=e[i](a),o(s,f,a.done,a.value)})}}function o(i,a,s,f){Promise.resolve(f).then(function(c){i({value:c,done:s})},a)}}function A(e){return typeof e=="function"}function at(e){var t=function(n){Error.call(n),n.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var $t=at(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription: +`+r.map(function(n,o){return o+1+") "+n.toString()}).join(` + `):"",this.name="UnsubscriptionError",this.errors=r}});function De(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Fe=function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,r,n,o,i;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var s=xe(a),f=s.next();!f.done;f=s.next()){var c=f.value;c.remove(this)}}catch(v){t={error:v}}finally{try{f&&!f.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}else a.remove(this);var u=this.initialTeardown;if(A(u))try{u()}catch(v){i=v instanceof $t?v.errors:[v]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var m=xe(p),d=m.next();!d.done;d=m.next()){var h=d.value;try{dn(h)}catch(v){i=i!=null?i:[],v instanceof $t?i=D(D([],W(i)),W(v.errors)):i.push(v)}}}catch(v){n={error:v}}finally{try{d&&!d.done&&(o=m.return)&&o.call(m)}finally{if(n)throw n.error}}}if(i)throw new $t(i)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)dn(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(t)}},e.prototype._hasParent=function(t){var r=this._parentage;return r===t||Array.isArray(r)&&r.includes(t)},e.prototype._addParent=function(t){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(t),r):r?[r,t]:t},e.prototype._removeParent=function(t){var r=this._parentage;r===t?this._parentage=null:Array.isArray(r)&&De(r,t)},e.prototype.remove=function(t){var r=this._finalizers;r&&De(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=function(){var t=new e;return t.closed=!0,t}(),e}();var Or=Fe.EMPTY;function It(e){return e instanceof Fe||e&&"closed"in e&&A(e.remove)&&A(e.add)&&A(e.unsubscribe)}function dn(e){A(e)?e():e.unsubscribe()}var Ae={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var st={setTimeout:function(e,t){for(var r=[],n=2;n0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(r){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,r)},t.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},t.prototype._innerSubscribe=function(r){var n=this,o=this,i=o.hasError,a=o.isStopped,s=o.observers;return i||a?Or:(this.currentObservers=null,s.push(r),new Fe(function(){n.currentObservers=null,De(s,r)}))},t.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,i=n.thrownError,a=n.isStopped;o?r.error(i):a&&r.complete()},t.prototype.asObservable=function(){var r=new U;return r.source=this,r},t.create=function(r,n){return new wn(r,n)},t}(U);var wn=function(e){ne(t,e);function t(r,n){var o=e.call(this)||this;return o.destination=r,o.source=n,o}return t.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},t.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},t.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},t.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:Or},t}(E);var Et={now:function(){return(Et.delegate||Date).now()},delegate:void 0};var wt=function(e){ne(t,e);function t(r,n,o){r===void 0&&(r=1/0),n===void 0&&(n=1/0),o===void 0&&(o=Et);var i=e.call(this)||this;return i._bufferSize=r,i._windowTime=n,i._timestampProvider=o,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,r),i._windowTime=Math.max(1,n),i}return t.prototype.next=function(r){var n=this,o=n.isStopped,i=n._buffer,a=n._infiniteTimeWindow,s=n._timestampProvider,f=n._windowTime;o||(i.push(r),!a&&i.push(s.now()+f)),this._trimBuffer(),e.prototype.next.call(this,r)},t.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(r),o=this,i=o._infiniteTimeWindow,a=o._buffer,s=a.slice(),f=0;f0?e.prototype.requestAsyncId.call(this,r,n,o):(r.actions.push(this),r._scheduled||(r._scheduled=ut.requestAnimationFrame(function(){return r.flush(void 0)})))},t.prototype.recycleAsyncId=function(r,n,o){var i;if(o===void 0&&(o=0),o!=null?o>0:this.delay>0)return e.prototype.recycleAsyncId.call(this,r,n,o);var a=r.actions;n!=null&&((i=a[a.length-1])===null||i===void 0?void 0:i.id)!==n&&(ut.cancelAnimationFrame(n),r._scheduled=void 0)},t}(Ut);var On=function(e){ne(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.flush=function(r){this._active=!0;var n=this._scheduled;this._scheduled=void 0;var o=this.actions,i;r=r||o.shift();do if(i=r.execute(r.state,r.delay))break;while((r=o[0])&&r.id===n&&o.shift());if(this._active=!1,i){for(;(r=o[0])&&r.id===n&&o.shift();)r.unsubscribe();throw i}},t}(Wt);var we=new On(Tn);var R=new U(function(e){return e.complete()});function Dt(e){return e&&A(e.schedule)}function kr(e){return e[e.length-1]}function Qe(e){return A(kr(e))?e.pop():void 0}function Se(e){return Dt(kr(e))?e.pop():void 0}function Vt(e,t){return typeof kr(e)=="number"?e.pop():t}var pt=function(e){return e&&typeof e.length=="number"&&typeof e!="function"};function zt(e){return A(e==null?void 0:e.then)}function Nt(e){return A(e[ft])}function qt(e){return Symbol.asyncIterator&&A(e==null?void 0:e[Symbol.asyncIterator])}function Kt(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ki(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Qt=Ki();function Yt(e){return A(e==null?void 0:e[Qt])}function Gt(e){return ln(this,arguments,function(){var r,n,o,i;return Pt(this,function(a){switch(a.label){case 0:r=e.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,Xe(r.read())];case 3:return n=a.sent(),o=n.value,i=n.done,i?[4,Xe(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,Xe(o)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function Bt(e){return A(e==null?void 0:e.getReader)}function $(e){if(e instanceof U)return e;if(e!=null){if(Nt(e))return Qi(e);if(pt(e))return Yi(e);if(zt(e))return Gi(e);if(qt(e))return _n(e);if(Yt(e))return Bi(e);if(Bt(e))return Ji(e)}throw Kt(e)}function Qi(e){return new U(function(t){var r=e[ft]();if(A(r.subscribe))return r.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Yi(e){return new U(function(t){for(var r=0;r=2;return function(n){return n.pipe(e?_(function(o,i){return e(o,i,n)}):me,Oe(1),r?He(t):zn(function(){return new Xt}))}}function Nn(){for(var e=[],t=0;t=2,!0))}function fe(e){e===void 0&&(e={});var t=e.connector,r=t===void 0?function(){return new E}:t,n=e.resetOnError,o=n===void 0?!0:n,i=e.resetOnComplete,a=i===void 0?!0:i,s=e.resetOnRefCountZero,f=s===void 0?!0:s;return function(c){var u,p,m,d=0,h=!1,v=!1,B=function(){p==null||p.unsubscribe(),p=void 0},re=function(){B(),u=m=void 0,h=v=!1},z=function(){var T=u;re(),T==null||T.unsubscribe()};return g(function(T,Ke){d++,!v&&!h&&B();var We=m=m!=null?m:r();Ke.add(function(){d--,d===0&&!v&&!h&&(p=jr(z,f))}),We.subscribe(Ke),!u&&d>0&&(u=new et({next:function(Ie){return We.next(Ie)},error:function(Ie){v=!0,B(),p=jr(re,o,Ie),We.error(Ie)},complete:function(){h=!0,B(),p=jr(re,a),We.complete()}}),$(T).subscribe(u))})(c)}}function jr(e,t){for(var r=[],n=2;ne.next(document)),e}function K(e,t=document){return Array.from(t.querySelectorAll(e))}function V(e,t=document){let r=se(e,t);if(typeof r=="undefined")throw new ReferenceError(`Missing element: expected "${e}" to be present`);return r}function se(e,t=document){return t.querySelector(e)||void 0}function _e(){return document.activeElement instanceof HTMLElement&&document.activeElement||void 0}function tr(e){return L(b(document.body,"focusin"),b(document.body,"focusout")).pipe(ke(1),l(()=>{let t=_e();return typeof t!="undefined"?e.contains(t):!1}),N(e===_e()),Y())}function Be(e){return{x:e.offsetLeft,y:e.offsetTop}}function Yn(e){return L(b(window,"load"),b(window,"resize")).pipe(Ce(0,we),l(()=>Be(e)),N(Be(e)))}function rr(e){return{x:e.scrollLeft,y:e.scrollTop}}function dt(e){return L(b(e,"scroll"),b(window,"resize")).pipe(Ce(0,we),l(()=>rr(e)),N(rr(e)))}var Bn=function(){if(typeof Map!="undefined")return Map;function e(t,r){var n=-1;return t.some(function(o,i){return o[0]===r?(n=i,!0):!1}),n}return function(){function t(){this.__entries__=[]}return Object.defineProperty(t.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),t.prototype.get=function(r){var n=e(this.__entries__,r),o=this.__entries__[n];return o&&o[1]},t.prototype.set=function(r,n){var o=e(this.__entries__,r);~o?this.__entries__[o][1]=n:this.__entries__.push([r,n])},t.prototype.delete=function(r){var n=this.__entries__,o=e(n,r);~o&&n.splice(o,1)},t.prototype.has=function(r){return!!~e(this.__entries__,r)},t.prototype.clear=function(){this.__entries__.splice(0)},t.prototype.forEach=function(r,n){n===void 0&&(n=null);for(var o=0,i=this.__entries__;o0},e.prototype.connect_=function(){!zr||this.connected_||(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),xa?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},e.prototype.disconnect_=function(){!zr||!this.connected_||(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},e.prototype.onTransitionEnd_=function(t){var r=t.propertyName,n=r===void 0?"":r,o=ya.some(function(i){return!!~n.indexOf(i)});o&&this.refresh()},e.getInstance=function(){return this.instance_||(this.instance_=new e),this.instance_},e.instance_=null,e}(),Jn=function(e,t){for(var r=0,n=Object.keys(t);r0},e}(),Zn=typeof WeakMap!="undefined"?new WeakMap:new Bn,eo=function(){function e(t){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var r=Ea.getInstance(),n=new Ra(t,r,this);Zn.set(this,n)}return e}();["observe","unobserve","disconnect"].forEach(function(e){eo.prototype[e]=function(){var t;return(t=Zn.get(this))[e].apply(t,arguments)}});var ka=function(){return typeof nr.ResizeObserver!="undefined"?nr.ResizeObserver:eo}(),to=ka;var ro=new E,Ha=I(()=>H(new to(e=>{for(let t of e)ro.next(t)}))).pipe(x(e=>L(Te,H(e)).pipe(C(()=>e.disconnect()))),J(1));function de(e){return{width:e.offsetWidth,height:e.offsetHeight}}function ge(e){return Ha.pipe(S(t=>t.observe(e)),x(t=>ro.pipe(_(({target:r})=>r===e),C(()=>t.unobserve(e)),l(()=>de(e)))),N(de(e)))}function bt(e){return{width:e.scrollWidth,height:e.scrollHeight}}function ar(e){let t=e.parentElement;for(;t&&(e.scrollWidth<=t.scrollWidth&&e.scrollHeight<=t.scrollHeight);)t=(e=t).parentElement;return t?e:void 0}var no=new E,Pa=I(()=>H(new IntersectionObserver(e=>{for(let t of e)no.next(t)},{threshold:0}))).pipe(x(e=>L(Te,H(e)).pipe(C(()=>e.disconnect()))),J(1));function sr(e){return Pa.pipe(S(t=>t.observe(e)),x(t=>no.pipe(_(({target:r})=>r===e),C(()=>t.unobserve(e)),l(({isIntersecting:r})=>r))))}function oo(e,t=16){return dt(e).pipe(l(({y:r})=>{let n=de(e),o=bt(e);return r>=o.height-n.height-t}),Y())}var cr={drawer:V("[data-md-toggle=drawer]"),search:V("[data-md-toggle=search]")};function io(e){return cr[e].checked}function qe(e,t){cr[e].checked!==t&&cr[e].click()}function je(e){let t=cr[e];return b(t,"change").pipe(l(()=>t.checked),N(t.checked))}function $a(e,t){switch(e.constructor){case HTMLInputElement:return e.type==="radio"?/^Arrow/.test(t):!0;case HTMLSelectElement:case HTMLTextAreaElement:return!0;default:return e.isContentEditable}}function Ia(){return L(b(window,"compositionstart").pipe(l(()=>!0)),b(window,"compositionend").pipe(l(()=>!1))).pipe(N(!1))}function ao(){let e=b(window,"keydown").pipe(_(t=>!(t.metaKey||t.ctrlKey)),l(t=>({mode:io("search")?"search":"global",type:t.key,claim(){t.preventDefault(),t.stopPropagation()}})),_(({mode:t,type:r})=>{if(t==="global"){let n=_e();if(typeof n!="undefined")return!$a(n,r)}return!0}),fe());return Ia().pipe(x(t=>t?R:e))}function Me(){return new URL(location.href)}function ot(e){location.href=e.href}function so(){return new E}function co(e,t){if(typeof t=="string"||typeof t=="number")e.innerHTML+=t.toString();else if(t instanceof Node)e.appendChild(t);else if(Array.isArray(t))for(let r of t)co(e,r)}function M(e,t,...r){let n=document.createElement(e);if(t)for(let o of Object.keys(t))typeof t[o]!="undefined"&&(typeof t[o]!="boolean"?n.setAttribute(o,t[o]):n.setAttribute(o,""));for(let o of r)co(n,o);return n}function fr(e){if(e>999){let t=+((e-950)%1e3>99);return`${((e+1e-6)/1e3).toFixed(t)}k`}else return e.toString()}function fo(){return location.hash.substring(1)}function uo(e){let t=M("a",{href:e});t.addEventListener("click",r=>r.stopPropagation()),t.click()}function Fa(){return b(window,"hashchange").pipe(l(fo),N(fo()),_(e=>e.length>0),J(1))}function po(){return Fa().pipe(l(e=>se(`[id="${e}"]`)),_(e=>typeof e!="undefined"))}function Nr(e){let t=matchMedia(e);return Zt(r=>t.addListener(()=>r(t.matches))).pipe(N(t.matches))}function lo(){let e=matchMedia("print");return L(b(window,"beforeprint").pipe(l(()=>!0)),b(window,"afterprint").pipe(l(()=>!1))).pipe(N(e.matches))}function qr(e,t){return e.pipe(x(r=>r?t():R))}function ur(e,t={credentials:"same-origin"}){return ve(fetch(`${e}`,t)).pipe(ce(()=>R),x(r=>r.status!==200?Tt(()=>new Error(r.statusText)):H(r)))}function Ue(e,t){return ur(e,t).pipe(x(r=>r.json()),J(1))}function mo(e,t){let r=new DOMParser;return ur(e,t).pipe(x(n=>n.text()),l(n=>r.parseFromString(n,"text/xml")),J(1))}function pr(e){let t=M("script",{src:e});return I(()=>(document.head.appendChild(t),L(b(t,"load"),b(t,"error").pipe(x(()=>Tt(()=>new ReferenceError(`Invalid script: ${e}`))))).pipe(l(()=>{}),C(()=>document.head.removeChild(t)),Oe(1))))}function ho(){return{x:Math.max(0,scrollX),y:Math.max(0,scrollY)}}function bo(){return L(b(window,"scroll",{passive:!0}),b(window,"resize",{passive:!0})).pipe(l(ho),N(ho()))}function vo(){return{width:innerWidth,height:innerHeight}}function go(){return b(window,"resize",{passive:!0}).pipe(l(vo),N(vo()))}function yo(){return Q([bo(),go()]).pipe(l(([e,t])=>({offset:e,size:t})),J(1))}function lr(e,{viewport$:t,header$:r}){let n=t.pipe(X("size")),o=Q([n,r]).pipe(l(()=>Be(e)));return Q([r,t,o]).pipe(l(([{height:i},{offset:a,size:s},{x:f,y:c}])=>({offset:{x:a.x-f,y:a.y-c+i},size:s})))}(()=>{function e(n,o){parent.postMessage(n,o||"*")}function t(...n){return n.reduce((o,i)=>o.then(()=>new Promise(a=>{let s=document.createElement("script");s.src=i,s.onload=a,document.body.appendChild(s)})),Promise.resolve())}var r=class{constructor(n){this.url=n,this.onerror=null,this.onmessage=null,this.onmessageerror=null,this.m=a=>{a.source===this.w&&(a.stopImmediatePropagation(),this.dispatchEvent(new MessageEvent("message",{data:a.data})),this.onmessage&&this.onmessage(a))},this.e=(a,s,f,c,u)=>{if(s===this.url.toString()){let p=new ErrorEvent("error",{message:a,filename:s,lineno:f,colno:c,error:u});this.dispatchEvent(p),this.onerror&&this.onerror(p)}};let o=new EventTarget;this.addEventListener=o.addEventListener.bind(o),this.removeEventListener=o.removeEventListener.bind(o),this.dispatchEvent=o.dispatchEvent.bind(o);let i=document.createElement("iframe");i.width=i.height=i.frameBorder="0",document.body.appendChild(this.iframe=i),this.w.document.open(),this.w.document.write(` + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

Clonning

+

Clone button example

+
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);
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/composer.json b/composer.json deleted file mode 100644 index f5e557e..0000000 --- a/composer.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "unclead/yii2-multiple-input", - "description": "Widget for handle multiple inputs for an attribute of Yii2 framework model", - "keywords": [ - "yii2", - "yii2 multiple input", - "yii2 array input", - "yii2 multiple field", - "yii2 tabular input" - ], - "type": "yii2-extension", - "license": "BSD-3-Clause", - "support": { - "issues": "https://github.com/unclead/yii2-multiple-input/issues?state=open", - "source": "https://github.com/unclead/yii2-multiple-input" - }, - "authors": [ - { - "name": "Eugene Tupikov", - "email": "unclead.nsk@gmail.com" - } - ], - "require": { - "php": ">=5.4.0", - "yiisoft/yii2": ">=2.0.38" - }, - "require-dev": { - "phpunit/phpunit": "5.7.*" - }, - "autoload": { - "psr-4": { - "unclead\\multipleinput\\examples\\": "examples/", - "unclead\\multipleinput\\": "src/", - "unclead\\multipleinput\\tests\\": "tests/" - } - } -} diff --git a/configuration/index.html b/configuration/index.html new file mode 100644 index 0000000..f988c84 --- /dev/null +++ b/configuration/index.html @@ -0,0 +1,637 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + Configuration - Yii2 multiple input + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

Configuration

+

Widget support the following options that are additionally recognized over and above the configuration options in the InputWidget.

+

Base options

+

theme string: specify the theme of the widget. Available 2 themes:

+
    +
  • default with only widget css classes
  • +
  • bs (twitter bootstrap) theme with additional BS ccs classes).
  • +
+

Default value is bs

+

max integer: maximum number of rows. If not set will default to unlimited

+

min integer: minimum number of rows. Set to 0 if you need the empty list in case you don't have any data

+

prepend boolean: add a new row to the beginning of the list, not to the end

+

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

+

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.

+

addButtonOptions array: the HTML options for add button. Can contains class and label keys

+

removeButtonOptions array: the HTML options for remove button. Can contains class and label keys

+

cloneButton bool: whether need to enable clone buttons or not

+

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:

+
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
  • +
+

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:

+
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:

+
    +
  • '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
  • +
+

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.

+

Column options

+

name string: input name. Required options

+

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:

+
function($data) {}
+
+

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:

+
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:

+
function($data) {}
+
+

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

+

tabindex integer: use it to customize a form element tabindex

+

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

+

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:

+
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

+

<div class="input-group"><span class="input-group-addon"><i class="fas fa-mobile-alt"></i></span>{input}</div>

+

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
  • +
  • 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:

+
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);
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/docs/clonning.md b/docs/clonning.md deleted file mode 100644 index 0171e82..0000000 --- a/docs/clonning.md +++ /dev/null @@ -1,48 +0,0 @@ -# Clonning - -![Clone button example](https://raw.githubusercontent.com/unclead/yii2-multiple-input/master/resources/images/clone-button.gif) - -```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 deleted file mode 100644 index 42d7df6..0000000 --- a/docs/configuration.md +++ /dev/null @@ -1,169 +0,0 @@ -# Configuration - -Widget support the following options that are additionally recognized over and above the configuration options in the InputWidget. - -## Base options - -**theme** _string_: specify the theme of the widget. Available 2 themes: - -* `default` with only widget css classes -* `bs` \(twitter bootstrap\) theme with additional BS ccs classes\). - -Default value is `bs` - -**max** _integer_: maximum number of rows. If not set will default to unlimited - -**min** _integer_: minimum number of rows. Set to `0` if you need the empty list in case you don't have any data - -**prepend** _boolean_: add a new row to the beginning of the list, not to the end - -**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 - -**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`. - -**addButtonOptions** _array_: the HTML options for `add` button. Can contains `class` and `label` keys - -**removeButtonOptions** _array_: the HTML options for `remove` button. Can contains `class` and `label` keys - -**cloneButton** _bool_: whether need to enable clone buttons or not - -**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 - -**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: - -* `'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 - -**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. - -## Column options - -**name** _string_: input name. _Required options_ - -**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 - -**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: - -```php -function($data) {} -``` - -**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 - -**tabindex** _integer_: use it to customize a form element `tabindex` - -**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 - -**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 - -For using widget as column input you may use the following code: - -```php -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 deleted file mode 100644 index 2e1daa9..0000000 --- a/docs/getting-started.md +++ /dev/null @@ -1,133 +0,0 @@ -# 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 - 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 deleted file mode 100644 index c805877..0000000 --- a/docs/icons.md +++ /dev/null @@ -1,40 +0,0 @@ -# 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 deleted file mode 100644 index e8dbbcf..0000000 --- a/docs/index.md +++ /dev/null @@ -1,11 +0,0 @@ -# Yii2 Multiple input widget. -Yii2 widget for handle multiple inputs for an attribute of model and tabular input for batch of models. - -[![Latest Stable Version](https://poser.pugx.org/unclead/yii2-multiple-input/v/stable)](https://packagist.org/packages/unclead/yii2-multiple-input) -[![Total Downloads](https://poser.pugx.org/unclead/yii2-multiple-input/downloads)](https://packagist.org/packages/unclead/yii2-multiple-input) -[![Daily Downloads](https://poser.pugx.org/unclead/yii2-multiple-input/d/daily)](https://packagist.org/packages/unclead/yii2-multiple-input) -[![Latest Unstable Version](https://poser.pugx.org/unclead/yii2-multiple-input/v/unstable)](https://packagist.org/packages/unclead/yii2-multiple-input) -[![License](https://poser.pugx.org/unclead/yii2-multiple-input/license)](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 deleted file mode 100644 index 8a9b853..0000000 --- a/docs/installation.md +++ /dev/null @@ -1,18 +0,0 @@ -# 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 deleted file mode 100644 index 5a31c25..0000000 --- a/docs/javascript-events.md +++ /dev/null @@ -1,86 +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 -* `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: ''}); -``` - -### 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/renderers.md b/docs/renderers.md deleted file mode 100644 index 67d33bb..0000000 --- a/docs/renderers.md +++ /dev/null @@ -1,60 +0,0 @@ -# Renderers - -Currently widget supports three type of renderers - -## TableRenderer - -![Table renderer](https://raw.githubusercontent.com/unclead/yii2-multiple-input/master/resources/images/table-renderer.jpg?raw=true) - -This renderer is enabled by default. - -## ListRenderer - -![List renderer](https://raw.githubusercontent.com/unclead/yii2-multiple-input/master/resources/images/list-renderer.jpg?raw=true) - -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 - -![List renderer](https://raw.githubusercontent.com/unclead/yii2-multiple-input/master/resources/images/list-renderer.jpg?raw=true) - -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', - ], -... -``` - diff --git a/docs/tips-and-tricks.md b/docs/tips-and-tricks.md deleted file mode 100644 index caa449c..0000000 --- a/docs/tips-and-tricks.md +++ /dev/null @@ -1,218 +0,0 @@ -# Tips and tricks - -## How to customize buttons - -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(), [ - 'max' => 5, - 'addButtonOptions' => [ - 'class' => 'btn btn-success', - 'label' => 'add' // also you can use html code - ], - 'removeButtonOptions' => [ - 'label' => 'remove' - ] - ]) - ->label(false); -``` - -## How to add content after the buttons - -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(), [ - 'max' => 5, - 'allowEmptyList' => true - ]) - ->label(false); -``` - -Also, you can set `0` in `min` option if you don't need the first blank row when data is empty. - -## 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 the option `enableGuessTitle` like in the example below: - -```php - echo $form->field($model, 'emails')->widget(MultipleInput::className(), [ - '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 the modal window. In this case, you MUST: - -* 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 - -You can use a placeholder `{multiple_index}` in a widget configuration, e.g. for implementation of dependent drop-down lists. - -```php - field($model, 'field')->widget(MultipleInput::className(), [ - 'id' => 'my_id', - 'allowEmptyList' => false, - 'rowOptions' => [ - 'id' => 'row{multiple_index_my_id}', - ], - 'columns' => [ - [ - 'name' => 'category', - 'type' => 'dropDownList', - 'title' => 'Category', - 'defaultValue' => '1', - 'items' => [ - '1' => 'Test 1', - '2' => 'Test 2', - '3' => 'Test 3', - '4' => 'Test 4', - ], - 'options' => [ - 'onchange' => <<< JS -$.post("list?id=" + $(this).val(), function(data){ - console.log(data); - $("select#subcat-{multiple_index_my_id}").html(data); -}); -JS - ], - ], - [ - 'name' => 'subcategory', - 'type' => 'dropDownList', - 'title' => 'Subcategory', - 'items' => [], - 'options'=> [ - 'id' => 'subcat-{multiple_index_my_id}' - ], - ], - ] - ]); - ?> -``` - -**Important** Ensure that you added ID of widget to a base placeholder `multiple_index` - -## Custom index of the row - -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 - field($model, 'field')->widget(MultipleInput::className(), [ - 'allowEmptyList' => false, - 'data' => [ - 3 => [ - 'day' => '27.02.2015', - 'user_id' => 31, - 'priority' => 1, - 'enable' => 1 - ], - - 'some-key' => [ - 'day' => '27.02.2015', - 'user_id' => 33, - 'priority' => 2, - 'enable' => 0 - ], - ] - - ... -``` - -## Embedded MultipleInput widget - -You can use nested `MultipleInput` as in the example below: - -```php -echo MultipleInput::widget([ - 'model' => $model, - 'attribute' => 'questions', - 'attributeOptions' => $commonAttributeOptions, - 'columns' => [ - [ - 'name' => 'question', - 'type' => 'textarea', - ], - [ - 'name' => 'answers', - 'type' => MultipleInput::class, - 'options' => [ - 'attributeOptions' => $commonAttributeOptions, - 'columns' => [ - [ - 'name' => 'right', - 'type' => MultipleInputColumn::TYPE_CHECKBOX - ], - [ - 'name' => 'answer' - ] - ] - ] - ] - ], -]); -``` - -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 - $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 deleted file mode 100644 index 654c8a3..0000000 --- a/docs/usage.md +++ /dev/null @@ -1,439 +0,0 @@ -# Usage - -You can find the source code of examples [here](https://github.com/unclead/yii2-multiple-input/tree/master/examples) - -## One column - -![Single column example](https://raw.githubusercontent.com/unclead/yii2-multiple-input/master/resources/images/single-column.gif) - -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. - -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 -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\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, -]);?> - -field($model, 'emails')->widget(MultipleInput::className(), [ - 'max' => 4, - ]); -?> - '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 - -![Multiple columns example](https://raw.githubusercontent.com/unclead/yii2-multiple-input/master/resources/images/multiple-column.gif) - -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, -]);?> - -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' - ] - ] - ] - ]); -?> - 'btn btn-success']);?> - -``` - -For validation of 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); - } - } - } -``` - -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 - -```php -use unclead\multipleinput\MultipleInput; - -... - -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 - ] - ], - 'headerOptions' => [ - 'style' => 'width: 250px;', - 'class' => 'day-css-class' - ] - ], - [ - 'name' => 'priority', - 'enableError' => true, - 'title' => 'Priority', - 'options' => [ - 'class' => 'input-priority' - ] - ], - [ - 'name' => 'comment', - 'type' => 'static', - 'value' => function($data) { - return Html::tag('span', 'static content', ['class' => 'label label-info']); - }, - 'headerOptions' => [ - 'style' => 'width: 70px;', - ] - ] - ] - ]); -?> -``` - -## 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'] - ]; - } -} -``` - -Then we have to use `TabularInput` widget for rendering form field in the view file - -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' - ] -]) ?> - - $models, - 'attributeOptions' => [ - 'enableAjaxValidation' => true, - 'enableClientValidation' => false, - 'validateOnChange' => false, - 'validateOnSubmit' => true, - 'validateOnBlur' => false, - ], - 'columns' => [ - [ - 'name' => 'title', - 'title' => 'Title', - 'type' => \unclead\multipleinput\MultipleInputColumn::TYPE_TEXT_INPUT, - ], - [ - 'name' => 'description', - 'title' => 'Description', - ], - [ - 'name' => 'file', - 'title' => 'File', - 'type' => \vova07\fileapi\Widget::className(), - 'options' => [ - 'settings' => [ - 'url' => ['site/fileapi-upload'] - ] - ], - 'columnOptions' => [ - 'style' => 'width: 250px;', - 'class' => 'custom-css-class' - ] - ], - [ - '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' - ] - ], - ], -]) ?> - - - '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]); - } -} -``` - diff --git a/examples/actions/EmbeddedInputAction.php b/examples/actions/EmbeddedInputAction.php deleted file mode 100644 index 58bfb3b..0000000 --- a/examples/actions/EmbeddedInputAction.php +++ /dev/null @@ -1,39 +0,0 @@ -getRequest(); - if ($request->isPost && $request->post('ajax') !== null) { - $model->load(Yii::$app->request->post()); - Yii::$app->response->format = Response::FORMAT_JSON; - $result = ActiveForm::validate($model); - return $result; - } - - if ($model->load(Yii::$app->request->post())) { - if (!$model->validate()) { - Yii::error('Validation errors: ' . print_r($model->getErrors(), true)); - } - } - - return $this->controller->render('@unclead-examples/views/embedded-input.php', ['model' => $model]); - } -} \ No newline at end of file diff --git a/examples/actions/MultipleInputAction.php b/examples/actions/MultipleInputAction.php deleted file mode 100644 index 5bc0351..0000000 --- a/examples/actions/MultipleInputAction.php +++ /dev/null @@ -1,39 +0,0 @@ -getRequest(); - if ($request->isPost && $request->post('ajax') !== null) { - $model->load(Yii::$app->request->post()); - Yii::$app->response->format = Response::FORMAT_JSON; - $result = ActiveForm::validate($model); - return $result; - } - - if ($model->load(Yii::$app->request->post())) { - if (!$model->validate()) { - Yii::error('Validation errors: ' . print_r($model->getErrors(), true)); - } - } - - return $this->controller->render('@unclead-examples/views/multiple-input.php', ['model' => $model]); - } -} \ No newline at end of file diff --git a/examples/actions/TabularInputAction.php b/examples/actions/TabularInputAction.php deleted file mode 100644 index 70edaee..0000000 --- a/examples/actions/TabularInputAction.php +++ /dev/null @@ -1,72 +0,0 @@ -getItems(); - - $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]); - } - - private function getItems() - { - $data = [ - [ - 'id' => 1, - 'title' => 'Title 1', - 'description' => 'Description 1' - ], - [ - 'id' => 2, - 'title' => 'Title 2', - 'description' => 'Description 2' - ], - ]; - - $items = []; - foreach ($data as $row) { - $item = new Item(); - $item->setAttributes($row); - $items[] = $item; - } - return $items; - } -} \ No newline at end of file diff --git a/examples/models/ExampleModel.php b/examples/models/ExampleModel.php deleted file mode 100644 index b05218d..0000000 --- a/examples/models/ExampleModel.php +++ /dev/null @@ -1,230 +0,0 @@ -emails = [ - 'test@test.com', - 'test2@test.com', - 'test3@test.com', - ]; - - $this->schedule = [ - [ - 'day' => '27.02.2015', - 'user_id' => 31, - 'priority' => 1, - 'enable' => 1 - ], - [ - 'day' => '27.02.2015', - 'user_id' => 33, - 'priority' => 2, - 'enable' => 0 - ], - ]; - - $this->questions = [ - [ - 'question' => 'test1', - 'answers' => [ - [ - 'right' => 0, - 'answer' => 'test1' - ], - [ - 'right' => 1, - 'answer' => 'test2' - ] - ] - ] - ]; - } - - - public function rules() - { - return [ - ['title', 'required'], - ['title', 'string', 'min' => 5], - ['emails', 'validateEmails'], - ['phones', 'validatePhones'], - ['schedule', 'validateSchedule', 'skipOnEmpty' => false], - ['questions', 'validateQuestions'] - ]; - } - - public function attributes() - { - return [ - 'emails', - 'phones', - 'title', - 'schedule', - 'questions' - ]; - } - - public function scenarios() - { - return [ - self::SCENARIO_DEFAULT => $this->attributes() - ]; - } - - /** - * Phone number validation - * - * @param $attribute - */ - public function validatePhones($attribute) - { - $items = $this->$attribute; - - if (!is_array($items)) { - $items = []; - } - - $multiple = true; - if(!is_array($items)) { - $multiple = false; - $items = (array) $items; - } - - foreach ($items as $index => $item) { - $validator = new NumberValidator(); - $error = null; - $validator->validate($item, $error); - if (!empty($error)) { - $key = $attribute . ($multiple ? '[' . $index . ']' : ''); - $this->addError($key, $error); - } - } - } - - /** - * 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); - } - } - } - - public function validateSchedule($attribute) - { - $requiredValidator = new RequiredValidator(); - - foreach($this->$attribute as $index => $row) { - $error = null; - foreach (['user_id', 'priority'] as $name) { - $error = null; - $value = isset($row[$name]) ? $row[$name] : null; - $requiredValidator->validate($value, $error); - if (!empty($error)) { - $key = $attribute . '[' . $index . '][' . $name . ']'; - $this->addError($key, $error); - } - } - } - } - - public function validateQuestions($attribute) - { - foreach($this->$attribute as $questionIndex => $question) { - $this->internalValidateQuestion($questionIndex, $question); - $this->internalValidateAnswers($questionIndex, $question['answers']); - } - } - - private function internalValidateQuestion($questionIndex, $question) - { - $requiredValidator = new RequiredValidator(); - $error = null; - - $value = ArrayHelper::getValue($question, 'question', null); - $requiredValidator->validate($value, $error); - if (!empty($error)) { - $key = sprintf('questions[%d][question]', $questionIndex); - $this->addError($key, $error); - } - } - - private function internalValidateAnswers($questionIndex, $answers) - { - $requiredValidator = new RequiredValidator(); - $error = null; - - foreach ($answers as $answerIndex => $answer) { - $error = null; - $value = ArrayHelper::getValue($answer, 'answer', null); - $requiredValidator->validate($value, $error); - if (!empty($error)) { - $key = sprintf('questions[%d][answers][%d][answer]', $questionIndex, $answerIndex); - $this->addError($key, $error); - } - } - } -} \ No newline at end of file diff --git a/examples/models/Item.php b/examples/models/Item.php deleted file mode 100644 index 2a32feb..0000000 --- a/examples/models/Item.php +++ /dev/null @@ -1,59 +0,0 @@ - [ - 'class' => \vova07\fileapi\behaviors\UploadBehavior::className(), - 'attributes' => [ - 'file' => [ - 'path' => Yii::getAlias('@webroot') . '/images/', - 'tempPath' => Yii::getAlias('@webroot') . '/images/tmp/', - 'url' => '/images/' - ], - ] - ]*/ - ]; - } - - public function rules() - { - return [ - [['title', 'description'], 'required'], - [['title'], 'string', 'min' => 5, 'max' => 64], - [['id', 'file'], 'safe'] - ]; - } - - -} \ No newline at end of file diff --git a/examples/views/embedded-input.php b/examples/views/embedded-input.php deleted file mode 100644 index ba33087..0000000 --- a/examples/views/embedded-input.php +++ /dev/null @@ -1,78 +0,0 @@ - true, - 'enableClientValidation' => false, - 'validateOnChange' => false, - 'validateOnSubmit' => true, - 'validateOnBlur' => false, -]; - -$enableActiveForm = true; -?> - - true, - 'enableClientValidation' => false, - 'validateOnChange' => false, - 'validateOnSubmit' => true, - 'validateOnBlur' => false, - ]); -} else { - echo Html::beginForm(); -} - -?> - - $model, - 'attribute' => 'questions', - 'attributeOptions' => $commonAttributeOptions, - 'columns' => [ - [ - 'name' => 'question', - 'type' => 'textarea', - ], - [ - 'name' => 'answers', - 'type' => MultipleInput::className(), - 'options' => [ - 'attributeOptions' => $commonAttributeOptions, - 'columns' => [ - [ - 'name' => 'right', - 'type' => MultipleInputColumn::TYPE_CHECKBOX - ], - [ - 'name' => 'answer' - ] - ] - ] - ] - ], -]); -?> - - 'btn btn-success']);?> - \ No newline at end of file diff --git a/examples/views/multiple-input.php b/examples/views/multiple-input.php deleted file mode 100644 index 9532cae..0000000 --- a/examples/views/multiple-input.php +++ /dev/null @@ -1,183 +0,0 @@ - - - true, - 'enableClientValidation' => false, - 'validateOnChange' => false, - 'validateOnSubmit' => true, - 'validateOnBlur' => false, -]);?> - - -

Single column

-field($model, 'emails')->widget(MultipleInput::className(), [ - 'max' => 6, - 'allowEmptyList' => false, - 'sortable' => true, - 'columns' => [ - [ - 'name' => 'emails', - 'options' => [ - 'placeholder' => 'E-mail' - ] - ] - ], - 'min' => 2, // should be at least 2 rows - 'addButtonPosition' => [ - MultipleInput::POS_HEADER, - MultipleInput::POS_FOOTER, - MultipleInput::POS_ROW - ] - ]) - ->label(false); -?> - -

Multiple columns

-field($model, 'schedule')->label(false)->widget(MultipleInput::className(), [ - 'id' => 'examplemodel-schedule', - 'max' => 4, - 'sortable' => true, - 'allowEmptyList' => true, - 'showGeneralError' => true, - 'rowOptions' => function($model) { - $options = []; - - if ($model['priority'] > 1) { - $options['class'] = 'danger'; - } - return $options; - }, - 'cloneButton' => true, - - 'columns' => [ - [ - 'name' => 'user_id', - 'type' => MultipleInputColumn::TYPE_DROPDOWN, - 'enableError' => true, - 'title' => 'User', - 'defaultValue' => 33, - /* it can be an anonymous function - 'items' => function($data) { - return [ - 31 => 'item 31', - 32 => 'item 32', - 33 => 'item 33', - 34 => 'item 34', - 35 => 'item 35', - 36 => 'item 36', - ]; - } - */ - 'items' => [ - 31 => 'item 31', - 32 => 'item 32', - 33 => 'item 33', - 34 => 'item 34', - 35 => 'item 35', - 36 => 'item 36', - ] - ], - [ - 'name' => 'day', - 'type' => DatePicker::className(), - 'title' => 'Day', - 'value' => function($data) { - return $data['day']; - }, - 'items' => [ - '0' => 'Saturday', - '1' => 'Monday' - ], - 'options' => [ - 'pluginOptions' => [ - 'format' => 'dd.mm.yyyy', - 'todayHighlight' => true - ] - ], - 'headerOptions' => [ - 'style' => 'width: 250px;', - 'class' => 'day-css-class' - ], - ], - [ - 'name' => 'priority', - 'title' => 'Priority', - 'defaultValue' => 1, - 'enableError' => true, - 'options' => [ - 'class' => 'input-priority' - ] - ], - [ - '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']); - }, - 'headerOptions' => [ - 'style' => 'width: 70px;', - ] - ], - [ - 'type' => MultipleInputColumn::TYPE_CHECKBOX_LIST, - 'name' => 'enable', - 'headerOptions' => [ - 'style' => 'width: 80px;', - ], - 'items' => [ - 1 => 'Test 1', - 2 => 'Test 2', - 3 => 'Test 3', - 4 => 'Test 4' - ], - 'options' => [ - // see checkboxList implementation in the BaseHtml helper for getting more detail - 'unselect' => 2 - ] - ] - ] -]); - -?> - - 'btn btn-success']);?> - - - -registerJs($js); diff --git a/examples/views/tabular-input.php b/examples/views/tabular-input.php deleted file mode 100644 index bba351e..0000000 --- a/examples/views/tabular-input.php +++ /dev/null @@ -1,89 +0,0 @@ - - - 'tabular-form', - 'options' => [ - 'enctype' => 'multipart/form-data' - ] -]) ?> - - $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, - 'enableClientValidation' => false, - 'validateOnChange' => false, - 'validateOnSubmit' => true, - 'validateOnBlur' => false, - ], - 'form' => $form, - 'columns' => [ - [ - 'name' => 'id', - 'type' => TabularColumn::TYPE_HIDDEN_INPUT - ], - [ - 'name' => 'title', - 'title' => 'Title', - 'type' => TabularColumn::TYPE_TEXT_INPUT, - 'attributeOptions' => [ - 'enableClientValidation' => true, - 'validateOnChange' => true, - ], - 'defaultValue' => 'Test', - 'enableError' => true - ], - [ - 'name' => 'description', - 'title' => 'Description', - ], - [ - 'name' => 'date', - 'type' => '\kartik\date\DatePicker', - 'title' => 'Day', - 'defaultValue' => '1970/01/01', - 'options' => [ - 'pluginOptions' => [ - 'autoclose' => true, - 'format' => 'dd/mm/yyyy', - 'todayHighlight' => true, - ], - - ], - 'headerOptions' => [ - 'style' => 'width: 250px;', - 'class' => 'day-css-class' - ] - ], - ], -]) ?> - - - 'btn btn-success']); ?> - diff --git a/getting-started/index.html b/getting-started/index.html new file mode 100644 index 0000000..225531d --- /dev/null +++ b/getting-started/index.html @@ -0,0 +1,609 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + Getting started - Yii2 multiple input + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

Getting started

+

I found this small guide here 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:

+
 <?= $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.

+
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

+
public function rules() {
+    return [
+        ....//other rules
+        [ [ 'schedule'] , 'safe' ]
+    ];
+}
+
+

Add the widget to the newly created column in ActiveForm

+
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

+
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

+
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

+
{
+  "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.

+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js deleted file mode 100644 index 5e2a310..0000000 --- a/gulpfile.js +++ /dev/null @@ -1,18 +0,0 @@ -const {gulp, src, dest} = require('gulp'); -const uglify = require('gulp-uglify-es').default; -const concat = require('gulp-concat'); -const rename = require('gulp-rename'); - -function build () { - var path = './src/assets/src/js/'; - - return src([ - path + 'jquery.multipleInput.js' - ]) - .pipe(concat('jquery.multipleInput.js')) - .pipe(uglify()) - .pipe(rename({suffix: '.min'})) - .pipe(dest(path)); -}; - -exports.default = build; diff --git a/icons/index.html b/icons/index.html new file mode 100644 index 0000000..f7ce367 --- /dev/null +++ b/icons/index.html @@ -0,0 +1,484 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + Custom icons - Yii2 multiple input + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

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. +
  3. Add a mapping for your preferred icon library if it is not in the iconMap array of the widget, like the following;
  4. +
+
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',
+    ]
+];
+
+
    +
  1. Set the preferred icon source
  2. +
+
    public $iconSource = 'my-amazing-icons';
+
+

If you do none of the above, the default behavior which assumes you are using glyphicons is retained.

+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..ca2c75b --- /dev/null +++ b/index.html @@ -0,0 +1,503 @@ + + + + + + + + + + + + + + + + + + + + + + + + Yii2 multiple input + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

Yii2 Multiple input widget.

+

Yii2 widget for handle multiple inputs for an attribute of model and tabular input for batch of models.

+

Latest Stable Version +Total Downloads +Daily Downloads +Latest Unstable Version +License

+

Latest release

+

The latest stable version of the extension is v2.25.0 Follow the instruction for upgrading from previous versions

+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/installation/index.html b/installation/index.html new file mode 100644 index 0000000..979fb5b --- /dev/null +++ b/installation/index.html @@ -0,0 +1,459 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + Installation - Yii2 multiple input + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

Installation

+

The preferred way to install this extension is through composer.

+

Either run

+
php composer.phar require  unclead/yii2-multiple-input "~2.0"
+
+

or add

+
"unclead/yii2-multiple-input": "~2.0"
+
+

to the requiresection of your composer.json file.

+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/javascript-events/index.html b/javascript-events/index.html new file mode 100644 index 0000000..5eaa2cb --- /dev/null +++ b/javascript-events/index.html @@ -0,0 +1,626 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + JS events - Yii2 multiple input + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

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

+
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:

+
$('#multiple-input').multipleInput('add', {first: 10, second: '<option value="2" selected="selected">second</option>'});
+
+

remove

+

Remove row with specified index.

+

Input arguments:

+
    +
  • integer - row number for removing, if not specified then removes last row.
  • +
+

Example:

+
$('#multiple-input').multipleInput('remove', 2);
+
+

clear

+

Remove all rows

+
$('#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:

+
$('#multiple-input').multipleInput('option', 'max');
+$('#multiple-input').multipleInput('option', 'max', 10);
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml deleted file mode 100644 index e006c20..0000000 --- a/mkdocs.yml +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index f566264..0000000 --- a/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "jquery.multipleInput", - "version": "2.27.0", - "description": "jQuery multipleInput", - "scripts": { - "build": "npm install && (gulp || node node_modules/gulp/bin/gulp.js)" - }, - "repository": { - "type": "git", - "url": "https://github.com/unclead/yii2-multiple-input.git" - }, - "author": { - "name": "Eugene Tupikov", - "email": "unclead.nsk@gmail.com" - }, - "keywords": [ - "jquery" - ], - "license": "BSD-3-Clause", - "bugs": { - "url": "https://github.com/unclead/yii2-multiple-input/issues" - }, - "homepage": "https://github.com/unclead/yii2-multiple-input", - "devDependencies": { - "gulp": "^4.0.2", - "gulp-concat": "^2.4.1", - "gulp-rename": "^1.4.0", - "gulp-uglify-es": "3.0.0" - } -} diff --git a/phpunit.xml.dist b/phpunit.xml.dist deleted file mode 100644 index fd3fa65..0000000 --- a/phpunit.xml.dist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - ./tests - ./vendor - - - - - ./tests/unit/ - - - - - - \ No newline at end of file diff --git a/renderers/index.html b/renderers/index.html new file mode 100644 index 0000000..5ed7bf9 --- /dev/null +++ b/renderers/index.html @@ -0,0 +1,569 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + Renderers - Yii2 multiple input + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

Renderers

+

Currently widget supports three type of renderers

+

TableRenderer

+

Table renderer

+

This renderer is enabled by default.

+

ListRenderer

+

List renderer

+

To enable this renderer you have to use an option rendererClass

+
<?php
+echo $form->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

+

List renderer

+

To enable this renderer you have to use an option rendererClass

+
<?php
+echo $form->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',
+    ],
+...
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/resources/images/clone-button.gif b/resources/images/clone-button.gif deleted file mode 100644 index f3718d0..0000000 Binary files a/resources/images/clone-button.gif and /dev/null differ diff --git a/resources/images/list-renderer.jpg b/resources/images/list-renderer.jpg deleted file mode 100644 index 5480716..0000000 Binary files a/resources/images/list-renderer.jpg and /dev/null differ diff --git a/resources/images/multiple-column.gif b/resources/images/multiple-column.gif deleted file mode 100644 index 28265c9..0000000 Binary files a/resources/images/multiple-column.gif and /dev/null differ diff --git a/resources/images/single-column.gif b/resources/images/single-column.gif deleted file mode 100644 index d4d0fc6..0000000 Binary files a/resources/images/single-column.gif and /dev/null differ diff --git a/resources/images/table-renderer.jpg b/resources/images/table-renderer.jpg deleted file mode 100644 index 0ea01df..0000000 Binary files a/resources/images/table-renderer.jpg and /dev/null differ diff --git a/search/search_index.json b/search/search_index.json new file mode 100644 index 0000000..dfb1b74 --- /dev/null +++ b/search/search_index.json @@ -0,0 +1 @@ +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Yii2 Multiple input widget.","text":"

Yii2 widget for handle multiple inputs for an attribute of model and tabular input for batch of models.

"},{"location":"#latest-release","title":"Latest release","text":"

The latest stable version of the extension is v2.25.0 Follow the instruction for upgrading from previous versions

"},{"location":"clonning/","title":"Clonning","text":"
use unclead\\multipleinput\\MultipleInput;\n\n...\n\n$form->field($model, 'products')->widget(MultipleInput::className(), [\n    'max' => 10,\n    'cloneButton' => true,\n    'columns' => [\n        [\n            'name'  => 'product_id',\n            'type'  => 'dropDownList',\n            'title' => 'Special Products',\n            'defaultValue' => 1,\n            'items' => [\n                1 => 'id: 1, price: $19.99, title: product1',\n                2 => 'id: 2, price: $29.99, title: product2',\n                3 => 'id: 3, price: $39.99, title: product3',\n                4 => 'id: 4, price: $49.99, title: product4',\n                5 => 'id: 5, price: $59.99, title: product5',\n            ],\n        ],\n        [\n            'name'  => 'time',\n            'type'  => DateTimePicker::className(),\n            'title' => 'due date',\n            'defaultValue' => date('d-m-Y h:i')\n        ],\n        [\n            'name'  => 'count',\n            'title' => 'Count',\n            'defaultValue' => 1,\n            'enableError' => true,\n            'options' => [\n                'type' => 'number',\n                'class' => 'input-priority',\n            ]\n        ]\n    ]\n])->label(false);\n
"},{"location":"configuration/","title":"Configuration","text":"

Widget support the following options that are additionally recognized over and above the configuration options in the InputWidget.

"},{"location":"configuration/#base-options","title":"Base options","text":"

theme string: specify the theme of the widget. Available 2 themes:

  • default with only widget css classes
  • bs (twitter bootstrap) theme with additional BS ccs classes).

Default value is bs

max integer: maximum number of rows. If not set will default to unlimited

min integer: minimum number of rows. Set to 0 if you need the empty list in case you don't have any data

prepend boolean: add a new row to the beginning of the list, not to the end

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

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.

addButtonOptions array: the HTML options for add button. Can contains class and label keys

removeButtonOptions array: the HTML options for remove button. Can contains class and label keys

cloneButton bool: whether need to enable clone buttons or not

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:

function ($model, $index, $context)\n
  • $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:

function ($model, $index, $context)\n
  • $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:

  • '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

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.

"},{"location":"configuration/#column-options","title":"Column options","text":"

name string: input name. Required options

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:

function($data) {}\n

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:

function($data) {}\n

options array|Closure: the HTML attributes for the input, you can set it as array or an anonymous function with the following signature:

function($data) {}\n

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

tabindex integer: use it to customize a form element tabindex

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

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:

function ($model, $index, $context)\n
  • $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

<div class=\"input-group\"><span class=\"input-group-addon\"><i class=\"fas fa-mobile-alt\"></i></span>{input}</div>

"},{"location":"configuration/#input-types","title":"Input types","text":"

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
  • 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:

echo $form->field($model, 'phones')->widget(MultipleInput::className(), [\n...\n    'columns' => [\n        ...\n        [\n            'name'  => 'phones',\n            'title' => $model->getAttributeLabel('phones'),\n            'type' => \\yii\\widgets\\MaskedInput::className(),\n            'options' => [\n                'class' => 'input-phone',\n                'mask' => '999-999-99-99',\n            ],\n        ],\n    ],\n])->label(false);\n
"},{"location":"getting-started/","title":"Getting started","text":"

I found this small guide here https://stackoverflow.com/a/51849747 and I think it is a good example of basic usage of the widget

"},{"location":"getting-started/#question","title":"Question","text":"

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:

 <?= $form->field($User, 'User')->widget(MultipleInput::className(), [\n        'min' => 0,\n        'max' => 4,\n        'columns' => [\n            [\n                'name'  => 'name',\n                'title' => 'Name',\n                'type' => 'textInput',\n                'options' => [\n                    'onchange' => $onchange,\n                ],\n            ],\n            [\n                'name'  => 'birth',\n                'type'  => \\kartik\\date\\DatePicker::className(),\n                'title' => 'Birth',\n                'value' => function($data) {\n                    return $data['day'];\n                },\n\n                'options' => [\n                    'pluginOptions' => [\n                        'format' => 'dd.mm.yyyy',\n                        'todayHighlight' => true\n                    ]\n                ]\n            ],\n\n        ]\n        ])->label(false);\n

How can I make (for example) 8 rows with different values, and also have the ability to edit/remove/update some of them?

"},{"location":"getting-started/#answer","title":"Answer","text":"

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.

User\nid, name, email\n\nBooks\nid, name\n

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

public function rules() {\n    return [\n        ....//other rules\n        [ [ 'schedule'] , 'safe' ]\n    ];\n}\n

Add the widget to the newly created column in ActiveForm

echo $form->field($model,'schedule')->widget(MultipleInput::class,[\n    'max' => 4,\n    'columns' => [\n        [\n            'name'  => 'book_id',\n            'type'  => 'dropDownList',\n            'title' => 'Book',\n            'items' => ArrayHelper::map( Books::find()->asArray()->all (),'id','name'),\n        ],\n    ]\n\n]);\n

When saving the User model convert the array to JSON string

if( Yii::$app->request->isPost && $model->load(Yii::$app->request->post()) ){\n    $model->schedule = \\yii\\helpers\\Json::encode($model->schedule);\n    $model->save();\n}\n

Override the afterFind() of the User model to covert the JSON back to the array before loading the form

public function afterFind() {\n    parent::afterFind();\n    $this->schedule = \\yii\\helpers\\Json::decode($this->schedule);\n}\n

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

{\n  \"0\": {\n    \"book_id\": \"1\"\n  },\n  \"2\": {\n    \"book_id\": \"2\"\n  },\n  \"3\": {\n    \"book_id\": \"3\"\n  }\n}\n

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.

"},{"location":"icons/","title":"Using other icon libraries","text":"

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;
public $iconMap = [\n    'glyphicons' => [\n        'drag-handle' => 'glyphicon glyphicon-menu-hamburger',\n        'remove' => 'glyphicon glyphicon-remove',\n        'add' => 'glyphicon glyphicon-plus',\n        'clone' => 'glyphicon glyphicon-duplicate',\n    ],\n    'fa' => [\n        'drag-handle' => 'fa fa-bars',\n        'remove' => 'fa fa-times',\n        'add' => 'fa fa-plus',\n        'clone' => 'fa fa-files-o',\n    ],\n    'my-amazing-icons' => [\n        'drag-handle' => 'my my-bars',\n        'remove' => 'my my-times',\n        'add' => 'my my-plus',\n        'clone' => 'my my-files',\n    ]\n];\n
  1. Set the preferred icon source
    public $iconSource = 'my-amazing-icons';\n

If you do none of the above, the default behavior which assumes you are using glyphicons is retained.

"},{"location":"installation/","title":"Installation","text":"

The preferred way to install this extension is through composer.

Either run

php composer.phar require  unclead/yii2-multiple-input \"~2.0\"\n

or add

\"unclead/yii2-multiple-input\": \"~2.0\"\n

to the requiresection of your composer.json file.

"},{"location":"javascript-events/","title":"Javascript events","text":"

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

jQuery('#multiple-input').on('afterInit', function(){\n    console.log('calls on after initialization event');\n}).on('beforeAddRow', function(e, row, currentIndex) {\n    console.log('calls on before add row event');\n}).on('afterAddRow', function(e, row, currentIndex) {\n    console.log('calls on after add row event');\n}).on('beforeDeleteRow', function(e, row, currentIndex){\n    // row - HTML container of the current row for removal.\n    // For TableRenderer it is tr.multiple-input-list__item\n    console.log('calls on before remove row event.');\n    return confirm('Are you sure you want to delete row?')\n}).on('afterDeleteRow', function(e, row, currentIndex){\n    console.log('calls on after remove row event');\n    console.log(row);\n}).on('afterDropRow', function(e, item){       \n    console.log('calls on after drop row', item);\n});\n
"},{"location":"javascript-events/#javascript-operations","title":"JavaScript operations","text":""},{"location":"javascript-events/#add","title":"add","text":"

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:

$('#multiple-input').multipleInput('add', {first: 10, second: '<option value=\"2\" selected=\"selected\">second</option>'});\n
"},{"location":"javascript-events/#remove","title":"remove","text":"

Remove row with specified index.

Input arguments:

  • integer - row number for removing, if not specified then removes last row.

Example:

$('#multiple-input').multipleInput('remove', 2);\n
"},{"location":"javascript-events/#clear","title":"clear","text":"

Remove all rows

$('#multiple-input').multipleInput('clear');\n
"},{"location":"javascript-events/#option","title":"option","text":"

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:

$('#multiple-input').multipleInput('option', 'max');\n$('#multiple-input').multipleInput('option', 'max', 10);\n
"},{"location":"renderers/","title":"Renderers","text":"

Currently widget supports three type of renderers

"},{"location":"renderers/#tablerenderer","title":"TableRenderer","text":"

This renderer is enabled by default.

"},{"location":"renderers/#listrenderer","title":"ListRenderer","text":"

To enable this renderer you have to use an option rendererClass

<?php\necho $form->field($model, 'schedule')->widget(MultipleInput::className(), [\n    'rendererClass' => \\unclead\\multipleinput\\renderers\\ListRenderer::className(),\n    'max' => 4,\n    'allowEmptyList' => true,\n    'rowOptions' => function($model) {\n        $options = [];\n\n        if ($model['priority'] > 1) {\n            $options['class'] = 'danger';\n        }\n        return $options;\n    },\n
"},{"location":"renderers/#divrenderer","title":"DivRenderer","text":"

To enable this renderer you have to use an option rendererClass

<?php\necho $form->field($model, 'schedule')->widget(MultipleInput::className(), [\n    'rendererClass' => \\unclead\\multipleinput\\renderers\\ListRenderer::class,\n    'addButtonPosition' => MultipleInput::POS_ROW, // show add button inside of the row\n    'extraButtons' => function ($model, $index, $context) {\n        if ($index === 0) {\n            return Html::tag('div', Yii::t('object', 'Add object'), ['class' => 'mi-after-add']);\n        }\n\n        return Html::tag('div', Yii::t('object', 'Remove object'), ['class' => 'mi-after-remove']);\n    },\n    'layoutConfig' => [\n        'offsetClass' => 'col-md-offset-2',\n        'labelClass' => 'col-md-2',\n        'wrapperClass' => 'col-md-6',\n        'errorClass' => 'col-md-offset-2 col-md-6',\n        'buttonActionClass' => 'col-md-offset-1 col-md-2',\n    ],\n...\n
"},{"location":"tips-and-tricks/","title":"Tips and tricks","text":""},{"location":"tips-and-tricks/#how-to-customize-buttons","title":"How to customize buttons","text":"

You can customize add and remove buttons via addButtonOptions and removeButtonOptions. Here is a simple example of how you can use those options:

    echo $form->field($model, 'emails')->widget(MultipleInput::className(), [\n        'max' => 5,\n        'addButtonOptions' => [\n            'class' => 'btn btn-success',\n            'label' => 'add' // also you can use html code\n        ],\n        'removeButtonOptions' => [\n            'label' => 'remove'\n        ]\n    ])\n    ->label(false);\n
"},{"location":"tips-and-tricks/#how-to-add-content-after-the-buttons","title":"How to add content after the buttons","text":"

You can add html content after add and remove buttons via extraButtons.

    echo $form->field($model, 'field')->widget(MultipleInput::className(), [\n        'rendererClass' => \\unclead\\multipleinput\\renderers\\ListRenderer::class,\n        'extraButtons' => function ($model, $index, $context) {\n            return Html::tag('span', '', ['class' => \"btn-show-hide-{$index} glyphicon glyphicon-eye-open btn btn-info\"]);\n        },\n    ])\n    ->label(false);\n
"},{"location":"tips-and-tricks/#work-with-an-empty-list","title":"Work with an empty list","text":"

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:

    echo $form->field($model, 'emails')->widget(MultipleInput::className(), [\n        'max' => 5,\n        'allowEmptyList' => true\n    ])\n    ->label(false);\n

Also, you can set 0 in min option if you don't need the first blank row when data is empty.

"},{"location":"tips-and-tricks/#guess-column-title","title":"Guess column title","text":"

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:

    echo $form->field($model, 'emails')->widget(MultipleInput::className(), [\n        'max' => 5,\n        'allowEmptyList' => true,\n        'enableGuessTitle' => true\n    ])\n    ->label(false);\n
"},{"location":"tips-and-tricks/#ajax-loading-of-a-widget","title":"Ajax loading of a widget","text":"

Assume you want to load a widget via ajax and then show it inside the modal window. In this case, you MUST:

  • 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.
"},{"location":"tips-and-tricks/#use-of-a-widgets-placeholder","title":"Use of a widget's placeholder","text":"

You can use a placeholder {multiple_index} in a widget configuration, e.g. for implementation of dependent drop-down lists.

    <?= $form->field($model, 'field')->widget(MultipleInput::className(), [\n            'id' => 'my_id',\n            'allowEmptyList' => false,\n            'rowOptions' => [\n                'id' => 'row{multiple_index_my_id}',\n            ],\n            'columns' => [\n                [\n                    'name'  => 'category',\n                    'type'  => 'dropDownList',\n                    'title' => 'Category',\n                    'defaultValue' => '1',\n                    'items' => [\n                        '1' => 'Test 1',\n                        '2' => 'Test 2',\n                        '3' => 'Test 3',\n                        '4' => 'Test 4',\n                    ],\n                    'options' => [\n                        'onchange' => <<< JS\n$.post(\"list?id=\" + $(this).val(), function(data){\n    console.log(data);\n    $(\"select#subcat-{multiple_index_my_id}\").html(data);\n});\nJS\n                    ],\n                ],\n                [\n                    'name'  => 'subcategory',\n                    'type'  => 'dropDownList',\n                    'title' => 'Subcategory',\n                    'items' => [],\n                    'options'=> [\n                        'id' => 'subcat-{multiple_index_my_id}'\n                    ],\n                ],\n            ]\n    ]);\n    ?>\n

Important Ensure that you added ID of widget to a base placeholder multiple_index

"},{"location":"tips-and-tricks/#custom-index-of-the-row","title":"Custom index of the row","text":"

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:

    <?= $form->field($model, 'field')->widget(MultipleInput::className(), [\n            'allowEmptyList' => false,\n            'data' => [\n                3 => [\n                    'day'       => '27.02.2015',\n                    'user_id'   => 31,\n                    'priority'  => 1,\n                    'enable'    => 1\n                ],\n\n                'some-key' => [\n                    'day'       => '27.02.2015',\n                    'user_id'   => 33,\n                    'priority'  => 2,\n                    'enable'    => 0\n                ],\n            ]\n\n    ...\n
"},{"location":"tips-and-tricks/#embedded-multipleinput-widget","title":"Embedded MultipleInput widget","text":"

You can use nested MultipleInput as in the example below:

echo MultipleInput::widget([\n    'model' => $model,\n    'attribute' => 'questions',\n    'attributeOptions' => $commonAttributeOptions,\n    'columns' => [\n        [\n            'name' => 'question',\n            'type' => 'textarea',\n        ],\n        [\n            'name' => 'answers',\n            'type'  => MultipleInput::class,\n            'options' => [\n                'attributeOptions' => $commonAttributeOptions,\n                'columns' => [\n                    [\n                        'name' => 'right',\n                        'type' => MultipleInputColumn::TYPE_CHECKBOX\n                    ],\n                    [\n                        'name' => 'answer'\n                    ]\n                ]\n            ]\n        ]\n    ],\n]);\n

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.

"},{"location":"tips-and-tricks/#client-validation","title":"Client validation","text":"

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:

<?= TabularInput::widget([\n    'models' => $models,\n    'form' => $form,\n    'attributeOptions' => [\n        'enableAjaxValidation' => true,\n        'enableClientValidation' => false,\n        'validateOnChange' => false,\n        'validateOnSubmit' => true,\n        'validateOnBlur' => false,\n    ],\n    'columns' => [\n        [\n            'name' => 'id',\n            'type' => TabularColumn::TYPE_HIDDEN_INPUT\n        ],\n        [\n            'name' => 'title',\n            'title' => 'Title',\n            'type' => TabularColumn::TYPE_TEXT_INPUT,\n            'attributeOptions' => [\n                'enableClientValidation' => true,\n                'validateOnChange' => true,\n            ],\n            'enableError' => true\n        ],\n        [\n            'name' => 'description',\n            'title' => 'Description',\n        ],\n    ],\n]) ?>\n

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.

"},{"location":"usage/","title":"Usage","text":"

You can find the source code of examples here

"},{"location":"usage/#one-column","title":"One column","text":"

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.

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

class ExampleModel extends Model\n{\n    /**\n     * @var array virtual attribute for keeping emails\n     */\n    public $emails;\n

Then we have to use MultipleInput widget for rendering form field in the view file

use yii\\bootstrap\\ActiveForm;\nuse unclead\\multipleinput\\MultipleInput;\nuse unclead\\multipleinput\\examples\\models\\ExampleModel;\nuse yii\\helpers\\Html;\n\n/* @var $this \\yii\\base\\View */\n/* @var $model ExampleModel */\n?>\n\n<?php $form = ActiveForm::begin([\n    'enableAjaxValidation'      => true,\n    'enableClientValidation'    => false,\n    'validateOnChange'          => false,\n    'validateOnSubmit'          => true,\n    'validateOnBlur'            => false,\n]);?>\n\n<?= $form->field($model, 'emails')->widget(MultipleInput::className(), [\n    'max' => 4,\n ]);\n?>\n<?= Html::submitButton('Update', ['class' => 'btn btn-success']);?>\n<?php ActiveForm::end();?>\n

Options max means that a user is able to input only 4 emails

For validation emails, you can use the following code

    /**\n     * Email validation.\n     *\n     * @param $attribute\n     */\n    public function validateEmails($attribute)\n    {\n        $items = $this->$attribute;\n\n        if (!is_array($items)) {\n            $items = [];\n        }\n\n        foreach ($items as $index => $item) {\n            $validator = new EmailValidator();\n            $error = null;\n            $validator->validate($item, $error);\n            if (!empty($error)) {\n                $key = $attribute . '[' . $index . ']';\n                $this->addError($key, $error);\n            }\n        }\n    }\n
"},{"location":"usage/#multiple-columns","title":"Multiple columns","text":"

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

class ExampleModel extends Model\n{\n    public $schedule;\n\n    public function init()\n    {\n        parent::init();\n\n        $this->schedule = [\n            [\n                'day'       => '27.02.2015',\n                'user_id'   => 1,\n                'priority'  => 1\n            ],\n            [\n                'day'       => '27.02.2015',\n                'user_id'   => 2,\n                'priority'  => 2\n            ],\n        ];\n    }\n

Then we have to use MultipleInput widget for rendering form field in the view file

use yii\\bootstrap\\ActiveForm;\nuse unclead\\multipleinput\\MultipleInput;\nuse unclead\\multipleinput\\examples\\models\\ExampleModel;\nuse yii\\helpers\\Html;\n\n/* @var $this \\yii\\base\\View */\n/* @var $model ExampleModel */\n?>\n\n<?php $form = ActiveForm::begin([\n    'enableAjaxValidation'      => true,\n    'enableClientValidation'    => false,\n    'validateOnChange'          => false,\n    'validateOnSubmit'          => true,\n    'validateOnBlur'            => false,\n]);?>\n\n<?= $form->field($model, 'schedule')->widget(MultipleInput::className(), [\n    'max' => 4,\n    'columns' => [\n        [\n            'name'  => 'user_id',\n            'type'  => 'dropDownList',\n            'title' => 'User',\n            'defaultValue' => 1,\n            'items' => [\n                1 => 'User 1',\n                2 => 'User 2'\n            ]\n        ],\n        [\n            'name'  => 'day',\n            'type'  => \\kartik\\date\\DatePicker::className(),\n            'title' => 'Day',\n            'value' => function($data) {\n                return $data['day'];\n            },\n            'items' => [\n                '0' => 'Saturday',\n                '1' => 'Monday'\n            ],\n            'options' => [\n                'pluginOptions' => [\n                    'format' => 'dd.mm.yyyy',\n                    'todayHighlight' => true\n                ]\n            ]\n        ],\n        [\n            'name'  => 'priority',\n            'title' => 'Priority',\n            'enableError' => true,\n            'options' => [\n                'class' => 'input-priority'\n            ]\n        ]\n    ]\n ]);\n?>\n<?= Html::submitButton('Update', ['class' => 'btn btn-success']);?>\n<?php ActiveForm::end();?>\n

For validation of the schedule you can use the following code

    public function validateSchedule($attribute)\n    {\n        $requiredValidator = new RequiredValidator();\n\n        foreach($this->$attribute as $index => $row) {\n            $error = null;\n            $requiredValidator->validate($row['priority'], $error);\n            if (!empty($error)) {\n                $key = $attribute . '[' . $index . '][priority]';\n                $this->addError($key, $error);\n            }\n        }\n    }\n

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

use unclead\\multipleinput\\MultipleInput;\n\n...\n\n<?= $form->field($model, 'schedule')->widget(MultipleInput::className(), [\n    'max' => 4,\n    'columns' => [\n        [\n            'name'  => 'user_id',\n            'type'  => 'dropDownList',\n            'title' => 'User',\n            'defaultValue' => 1,\n            'items' => [\n                1 => 'User 1',\n                2 => 'User 2'\n            ]\n        ],\n        [\n            'name'  => 'day',\n            'type'  => \\kartik\\date\\DatePicker::className(),\n            'title' => 'Day',\n            'value' => function($data) {\n                return $data['day'];\n            },\n            'items' => [\n                '0' => 'Saturday',\n                '1' => 'Monday'\n            ],\n            'options' => [\n                'pluginOptions' => [\n                    'format' => 'dd.mm.yyyy',\n                    'todayHighlight' => true\n                ]\n            ],\n            'headerOptions' => [\n                'style' => 'width: 250px;',\n                'class' => 'day-css-class'\n            ]\n        ],\n        [\n            'name'  => 'priority',\n            'enableError' => true,\n            'title' => 'Priority',\n            'options' => [\n                'class' => 'input-priority'\n            ]\n        ],\n        [\n            'name'  => 'comment',\n            'type'  => 'static',\n            'value' => function($data) {\n                return Html::tag('span', 'static content', ['class' => 'label label-info']);\n            },\n            'headerOptions' => [\n                'style' => 'width: 70px;',\n            ]\n        ]\n    ]\n ]);\n?>\n
"},{"location":"usage/#tabular-input","title":"Tabular input","text":"

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

namespace unclead\\multipleinput\\examples\\models;\n\nuse Yii;\nuse yii\\base\\Model;\n// you have to install https://github.com/vova07/yii2-fileapi-widget\nuse vova07\\fileapi\\behaviors\\UploadBehavior;\n\n/**\n * Class Item\n * @package unclead\\multipleinput\\examples\\models\n */\nclass Item extends Model\n{\n    public $title;\n    public $description;\n    public $file;\n    public $date;\n\n    public function behaviors()\n    {\n        return [\n            'uploadBehavior' => [\n                'class' => UploadBehavior::className(),\n                'attributes' => [\n                    'file' => [\n                        'path' => Yii::getAlias('@webroot') . '/images/',\n                        'tempPath' => Yii::getAlias('@webroot') . '/images/tmp/',\n                        'url' => '/images/'\n                    ],\n                ]\n            ]\n        ];\n    }\n\n    public function rules()\n    {\n        return [\n            [['title', 'description'], 'required'],\n            ['file', 'safe']\n        ];\n    }\n}\n

Then we have to use TabularInput widget for rendering form field in the view file

Since version 2.18.0 you can configure columnOptions also.

<?php\n\nuse yii\\bootstrap\\ActiveForm;\nuse unclead\\multipleinput\\TabularInput;\nuse yii\\helpers\\Html;\nuse \\unclead\\multipleinput\\examples\\models\\Item;\n\n/* @var $this \\yii\\web\\View */\n/* @var $models Item[] */\n?>\n\n<?php $form = \\yii\\bootstrap\\ActiveForm::begin([\n    'id'                        => 'tabular-form',\n    'enableAjaxValidation'      => true,\n    'enableClientValidation'    => false,\n    'validateOnChange'          => false,\n    'validateOnSubmit'          => true,\n    'validateOnBlur'            => false,\n    'options' => [\n        'enctype' => 'multipart/form-data'\n    ]\n]) ?>\n\n<?= TabularInput::widget([\n    'models' => $models,\n    'attributeOptions' => [\n        'enableAjaxValidation'      => true,\n        'enableClientValidation'    => false,\n        'validateOnChange'          => false,\n        'validateOnSubmit'          => true,\n        'validateOnBlur'            => false,\n    ],\n    'columns' => [\n        [\n            'name'  => 'title',\n            'title' => 'Title',\n            'type'  => \\unclead\\multipleinput\\MultipleInputColumn::TYPE_TEXT_INPUT,\n        ],\n        [\n            'name'  => 'description',\n            'title' => 'Description',\n        ],\n        [\n            'name'  => 'file',\n            'title' => 'File',\n            'type'  => \\vova07\\fileapi\\Widget::className(),\n            'options' => [\n                'settings' => [\n                    'url' => ['site/fileapi-upload']\n                ]\n            ],\n            'columnOptions' => [\n                'style' => 'width: 250px;',\n                'class' => 'custom-css-class'\n            ]\n        ],\n        [\n            'name'  => 'date',\n            'type'  => \\kartik\\date\\DatePicker::className(),\n            'title' => 'Day',\n            'options' => [\n                'pluginOptions' => [\n                    'format' => 'dd.mm.yyyy',\n                    'todayHighlight' => true\n                ]\n            ],\n            'headerOptions' => [\n                'style' => 'width: 250px;',\n                'class' => 'day-css-class'\n            ]\n        ],\n    ],\n]) ?>\n\n\n<?= Html::submitButton('Update', ['class' => 'btn btn-success']);?>\n<?php ActiveForm::end();?>\n

Your action can look like the following code

/**\n * Class TabularInputAction\n * @package unclead\\multipleinput\\examples\\actions\n */\nclass TabularInputAction extends Action\n{\n    public function run()\n    {\n        Yii::setAlias('@unclead-examples', realpath(__DIR__ . '/../'));\n\n        $models = [new Item()];\n        $request = Yii::$app->getRequest();\n        if ($request->isPost && $request->post('ajax') !== null) {\n            $data = Yii::$app->request->post('Item', []);\n            foreach (array_keys($data) as $index) {\n                $models[$index] = new Item();\n            }\n            Model::loadMultiple($models, Yii::$app->request->post());\n            Yii::$app->response->format = Response::FORMAT_JSON;\n            $result = ActiveForm::validateMultiple($models);\n            return $result;\n        }\n\n        if (Model::loadMultiple($models, Yii::$app->request->post())) {\n            // your magic\n        }\n\n\n        return $this->controller->render('@unclead-examples/views/tabular-input.php', ['models' => $models]);\n    }\n}\n
"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml new file mode 100644 index 0000000..0992ecf --- /dev/null +++ b/sitemap.xml @@ -0,0 +1,53 @@ + + + + None + 2024-04-21 + daily + + + None + 2024-04-21 + daily + + + None + 2024-04-21 + daily + + + None + 2024-04-21 + daily + + + None + 2024-04-21 + daily + + + None + 2024-04-21 + daily + + + None + 2024-04-21 + daily + + + None + 2024-04-21 + daily + + + None + 2024-04-21 + daily + + + None + 2024-04-21 + daily + + \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz new file mode 100644 index 0000000..56ba207 Binary files /dev/null and b/sitemap.xml.gz differ diff --git a/src/MultipleInput.php b/src/MultipleInput.php deleted file mode 100644 index dcad5eb..0000000 --- a/src/MultipleInput.php +++ /dev/null @@ -1,384 +0,0 @@ - - */ -class MultipleInput extends InputWidget -{ - 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; - - /** - * @var array columns configuration - */ - public $columns = []; - - /** - * @var integer maximum number of rows - */ - public $max; - - /** - * @var 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. - */ - public $attributeOptions = []; - - /** - * @var array the HTML options for the `remove` button - */ - public $removeButtonOptions; - - /** - * @var array the HTML options for the `add` button - */ - public $addButtonOptions; - - /** - * @var array the HTML options for the `clone` button - */ - public $cloneButtonOptions; - - /** - * @var bool whether to allow the empty list - */ - public $allowEmptyList = false; - - /** - * @var bool whether to guess column title in case if there is no definition of columns - */ - public $enableGuessTitle = false; - - /** - * @var int minimum number of rows - */ - public $min; - - /** - * @var string|array position of add button. - */ - public $addButtonPosition; - - /** - * @var 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 MultipleInput widget object - * - */ - public $rowOptions = []; - - /** - * @var string the name of column class. You can specify your own class to extend base functionality. - * 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. - * - * @throws \yii\base\InvalidConfigException - */ - 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(); - } - - /** - * Initializes data. - */ - protected function initData() - { - if ($this->data !== null) { - return; - } - - if ($this->value !== null) { - $this->data = $this->value; - return; - } - - if ($this->model instanceof Model) { - $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; - } - } - } - - /** - * This function tries to guess the columns to show from the given data - * if [[columns]] are not explicitly specified. - */ - protected function guessColumns() - { - if (empty($this->columns)) { - $column = [ - 'name' => $this->hasModel() ? $this->attribute : $this->name, - 'type' => MultipleInputColumn::TYPE_TEXT_INPUT - ]; - - if ($this->enableGuessTitle && $this->hasModel()) { - $column['title'] = $this->model->getAttributeLabel($this->attribute); - } - $this->columns[] = $column; - } - } - - /** - * Run widget. - */ - public function run() - { - $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 - */ - 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->getId(), - 'columns' => $this->columns, - 'min' => $this->min, - 'max' => $this->max, - 'attributeOptions' => $this->attributeOptions, - 'data' => $this->data, - 'columnClass' => $this->columnClass !== null ? $this->columnClass : MultipleInputColumn::className(), - 'allowEmptyList' => $this->allowEmptyList, - '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 ($this->showGeneralError) { - $config['jsExtraSettings'] = [ - 'showGeneralError' => true - ]; - } - - if ($this->removeButtonOptions !== null) { - $config['removeButtonOptions'] = $this->removeButtonOptions; - } - - if ($this->addButtonOptions !== null) { - $config['addButtonOptions'] = $this->addButtonOptions; - } - - if ($this->cloneButtonOptions !== null) { - $config['cloneButtonOptions'] = $this->cloneButtonOptions; - } - - $config['class'] = $this->rendererClass ?: TableRenderer::className(); - - return Yii::createObject($config); - } -} diff --git a/src/MultipleInputColumn.php b/src/MultipleInputColumn.php deleted file mode 100644 index e92c20c..0000000 --- a/src/MultipleInputColumn.php +++ /dev/null @@ -1,176 +0,0 @@ -enableError && !$this->context->model instanceof Model) { - throw new InvalidConfigException('Property "enableError" available only when model is defined.'); - } - } - - /** - * Returns element's name. - * - * @param int|null|string $index current row index - * @param bool $withPrefix whether to add prefix. - * - * @return string - */ - public function getElementName($index, $withPrefix = true) - { - if ($index === null) { - $index = '{' . $this->renderer->getIndexPlaceholder() . '}'; - } - - $elementName = $this->isRendererHasOneColumn() - ? '[' . $this->name . '][' . $index . ']' - : '[' . $index . '][' . $this->name . ']'; - - 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)); - } - - /** - * @return bool - */ - private function isRendererHasOneColumn() - { - $columns = \array_filter($this->renderer->columns, function(self $column) { - return $column->type !== self::TYPE_DRAGCOLUMN; - }); - - return count($columns) === 1; - } - - /** - * Return prefix for name of input. - * - * @return string - */ - protected function getInputNamePrefix() - { - $model = $this->context->model; - if ($model instanceof Model) { - 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; - } - - protected function hasModelAttribute($name) - { - $model = $this->context->model; - - if ($model->hasProperty($name)) { - return true; - } - - if ($model instanceof ActiveRecordInterface && $model->hasAttribute($name)) { - return true; - } - - if ($model instanceof DynamicModel && isset($model->{$name})) { - return true; - } - - return false; - } - - /** - * @param int|string|null $index - * @return null|string - */ - public function getFirstError($index) - { - if ($index === null) { - return null; - } - - if ($this->isRendererHasOneColumn()) { - $attribute = $this->name . '[' . $index . ']'; - } else { - $attribute = $this->context->attribute . $this->getElementName($index, false); - } - - $model = $this->context->model; - if ($model instanceof Model) { - return $model->getFirstError($attribute); - } - - return null; - } - - /** - * @inheritdoc - */ - 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()) { - $model = $this->context->model; - - // in case of embedding level 2 and more - if (preg_match('/^([\w\.]+)(\[.*)$/', $this->context->attribute, $matches)) { - $search = sprintf('%s[%s]%s', $model->formName(), $matches[1], $matches[2]); - } else { - $search = sprintf('%s[%s]', $model->formName(), $this->context->attribute); - } - - $replace = $this->context->attribute; - - $attribute = str_replace($search, $replace, $name); - - $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); - } -} diff --git a/src/TabularColumn.php b/src/TabularColumn.php deleted file mode 100644 index e5dbf8e..0000000 --- a/src/TabularColumn.php +++ /dev/null @@ -1,74 +0,0 @@ -renderer->getIndexPlaceholder() . '}'; - } - - $elementName = '[' . $index . '][' . $this->name . ']'; - $prefix = $withPrefix ? $this->getModel()->formName() : ''; - - return $prefix . $elementName . (empty($this->nameSuffix) ? '' : ('_' . $this->nameSuffix)); - } - - /** - * Returns first error of the current model. - * - * @param $index - * @return string - */ - public function getFirstError($index) - { - return $this->getModel()->getFirstError($this->name); - } - - /** - * Ensure that model is an instance of yii\base\Model. - * - * @param $model - * @return bool - */ - protected function ensureModel($model) - { - return $model instanceof Model; - } - - /** - * @inheritdoc - */ - public function setModel($model) - { - if ($model === null) { - $model = \Yii::createObject(['class' => $this->context->modelClass]); - } - - parent::setModel($model); - } -} diff --git a/src/TabularInput.php b/src/TabularInput.php deleted file mode 100644 index 95e2f89..0000000 --- a/src/TabularInput.php +++ /dev/null @@ -1,330 +0,0 @@ - [ - '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. - * - * @throws \yii\base\InvalidConfigException - */ - public function init() - { - if (empty($this->models) && !$this->modelClass) { - throw new InvalidConfigException('You must at least specify "models" or "modelClass"'); - } - - 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(); - } - - /** - * Run widget. - */ - public function run() - { - return $this->createRenderer()->render(); - } - - /** - * @return TableRenderer - */ - 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->getId(), - 'columns' => $this->columns, - 'min' => $this->min, - 'max' => $this->max, - 'attributeOptions' => $this->attributeOptions, - 'data' => $this->models, - 'columnClass' => $this->columnClass !== null ? $this->columnClass : TabularColumn::className(), - 'allowEmptyList' => $this->allowEmptyList, - '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 ($this->removeButtonOptions !== null) { - $config['removeButtonOptions'] = $this->removeButtonOptions; - } - - if ($this->addButtonOptions !== null) { - $config['addButtonOptions'] = $this->addButtonOptions; - } - - 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); - } -} diff --git a/src/assets/FontAwesomeAsset.php b/src/assets/FontAwesomeAsset.php deleted file mode 100644 index 47061dc..0000000 --- a/src/assets/FontAwesomeAsset.php +++ /dev/null @@ -1,26 +0,0 @@ -'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 deleted file mode 100644 index df3f426..0000000 --- a/src/assets/MultipleInputAsset.php +++ /dev/null @@ -1,39 +0,0 @@ - __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); - } - - -} diff --git a/src/assets/MultipleInputSortableAsset.php b/src/assets/MultipleInputSortableAsset.php deleted file mode 100644 index 152d558..0000000 --- a/src/assets/MultipleInputSortableAsset.php +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index a7361cb..0000000 --- a/src/assets/src/css/multiple-input.css +++ /dev/null @@ -1,89 +0,0 @@ -.multiple-input-list { -} - -.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 #dddddd; -} - -.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: 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 deleted file mode 100644 index 50a3834..0000000 --- a/src/assets/src/css/multiple-input.min.css +++ /dev/null @@ -1 +0,0 @@ -.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 deleted file mode 100644 index 829393a..0000000 --- a/src/assets/src/css/sorting.css +++ /dev/null @@ -1,46 +0,0 @@ -.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 deleted file mode 100644 index 37ad594..0000000 --- a/src/assets/src/css/sorting.min.css +++ /dev/null @@ -1 +0,0 @@ -.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 deleted file mode 100644 index 596d3ec..0000000 --- a/src/assets/src/js/jquery.multipleInput.js +++ /dev/null @@ -1,545 +0,0 @@ -(function ($) { - 'use strict'; - - $.fn.multipleInput = function (method) { - if (methods[method]) { - return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); - } else if (typeof method === 'object' || !method) { - return methods.init.apply(this, arguments); - } else { - $.error('Method ' + method + ' does not exist on jQuery.multipleInput'); - return false; - } - }; - - var events = { - /** - * afterAddRow event is triggered after widget's initialization. - * The signature of the event handler should be: - * function (event) - * where event is an Event object. - * - */ - afterInit: 'afterInit', - /** - * 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. - * - */ - 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. - * - */ - afterAddRow: 'afterAddRow', - /** - * beforeDeleteRow event is triggered before row will be removed. - * The signature of the event handler should be: - * function (event, row) - * where event is an Event object and row is html container of row for removal - * - * If the handler returns a boolean false, it will stop removal the row. - */ - beforeDeleteRow: 'beforeDeleteRow', - - /** - * afterAddRow event is triggered after successful removal the row. - * The signature of the event handler should be: - * function (event) - * where event is an Event object. - * - */ - 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 ID of related input in case of using widget for an active field - */ - inputId: null, - - /** - * the template of row - */ - template: null, - - /** - * array that collect js templates of widgets which uses in the columns - */ - jsTemplates: [], - - /** - * 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, - - /** - * active form options of attributes - */ - attributes: {}, - - /** - * default prefix of a widget's placeholder - */ - indexPlaceholder: 'multiple_index', - - /** - * 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'), - inputId = settings.inputId; - - for (i in settings.jsInit) { - window.eval(settings.jsInit[i]); - } - - $wrapper.data('multipleInput', { - settings: settings, - currentIndex: 0 - }); - - $wrapper.on('click.multipleInput', '.js-input-remove', function (e) { - e.stopPropagation(); - removeInput($(this)); - }); - - $wrapper.on('click.multipleInput', '.js-input-plus', function (e) { - e.stopPropagation(); - 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', 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) { - defaultAttributeOptions[key] = value; - } - }); - - if (!settings.showGeneralError) { - form.yiiActiveForm('remove', inputId); - } - } - - // append default options to option from settings - $.each(settings.attributes, function (attribute, attributeOptions) { - attributeOptions = $.extend({}, defaultAttributeOptions, attributeOptions); - settings.attributes[attribute] = attributeOptions; - }); - - $wrapper.data('multipleInput').settings = settings; - - $wrapper.find('.multiple-input-list').find('input, select, textarea').each(function () { - addActiveFormAttribute($(this)); - }); - - $wrapper.data('multipleInput').currentIndex = findMaxRowIndex($wrapper); - isActiveFormEnabled = true; - - clearInterval(intervalID); - $wrapper.trigger(event); - } else { - i++; - } - - // 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 (form.length === 0 || i > 10) { - clearInterval(intervalID); - isActiveFormEnabled = false; - - if (typeof $wrapper.data('multipleInput') !== 'undefined') { - $wrapper.data('multipleInput').currentIndex = findMaxRowIndex($wrapper); - } - - $wrapper.trigger(event); - } - }, 100); - }, - - add: function (values) { - addInput($(this), values); - }, - - remove: function (index) { - var row = null; - if (index !== undefined) { - row = $(this).find('.js-input-remove:eq(' + index + ')'); - } else { - row = $(this).find('.js-input-remove').last(); - } - - removeInput(row); - }, - - clear: 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 cloneInput = function (btn) { - let $wrapper = $(btn).closest('.multiple-input').first(); - let data = $wrapper.data('multipleInput'); - let settings = data.settings; - - let values = {}; - - btn.closest('.multiple-input-list__item').find('input, select, textarea').each(function (k, v) { - let $element = $(v); - - 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 ($element.is(':checked')) { - values[columnName].push($element.val()); - } - } else { - values[columnName] = $element.val(); - } - } - }); - - addInput(btn, values); - } - - var addInput = function (btn, rowValues) { - rowValues = rowValues || {}; - - 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; - } - - 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 (settings.prepend) { - $newRow.hide().prependTo(inputList).fadeIn(300); - } else { - $newRow.hide().appendTo(inputList).fadeIn(300); - } - - 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 = newRowIndex; - - var afterAddEvent = $.Event(events.afterAddRow); - $wrapper.trigger(afterAddEvent, [$newRow, newRowIndex]); - }; - - var removeInput = function ($btn) { - var $wrapper = $btn.closest('.multiple-input').first(), - $toDelete = $btn.closest('.multiple-input-list__item'), - data = $wrapper.data('multipleInput'), - settings = data.settings; - - var rowsCount = getRowsCount($wrapper); - if (rowsCount > settings.min) { - var event = $.Event(events.beforeDeleteRow); - $wrapper.trigger(event, [$toDelete, data.currentIndex]); - - if (event.result === false) { - return; - } - - if (isActiveFormEnabled) { - $toDelete.find('input, select, textarea').each(function (index, ele) { - removeActiveFormAttribute($(ele)); - }); - } - - $toDelete.fadeOut(300, function () { - $(this).remove(); - - event = $.Event(events.afterDeleteRow); - $wrapper.trigger(event, [$toDelete, rowsCount]); - }); - } - }; - - /** - * Add an attribute to ActiveForm. - * - * @param input - */ - var addActiveFormAttribute = function (input) { - var id = getInputId(input); - - // skip if we could not get an ID of input - if (id === null) { - return; - } - - var ele = $('#' + id), - 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) { - return; - } - - // check that input has been already added to the activeForm - if (typeof form.yiiActiveForm('find', id) !== 'undefined') { - 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]; - } - } - - form.yiiActiveForm('add', $.extend({}, attributeOptions, { - 'id': id, - 'input': '#' + id, - 'container': '.field-' + id - })); - }; - - /** - * Removes an attribute from ActiveForm. - */ - var removeActiveFormAttribute = function (ele) { - var id = getInputId(ele); - - if (id === null) { - return; - } - - var form = $('#' + id).closest('form'); - - if (form.length !== 0) { - form.yiiActiveForm('remove', id); - } - }; - - var getInputId = function ($input) { - var id = $input.attr('id'); - - if (typeof id === 'undefined') { - id = $input.data('id'); - } - - if (typeof id === 'undefined') { - return null; - } - - return id; - }; - - var getRowsCount = function($wrapper) { - return findRows($wrapper).length; - }; - - var findRows = function($wrapper) { - return $wrapper - .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; - }; - - 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); diff --git a/src/assets/src/js/jquery.multipleInput.min.js b/src/assets/src/js/jquery.multipleInput.min.js deleted file mode 100644 index 636f288..0000000 --- a/src/assets/src/js/jquery.multipleInput.min.js +++ /dev/null @@ -1 +0,0 @@ -!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 deleted file mode 100644 index 98c90ab..0000000 --- a/src/assets/src/js/sortable.js +++ /dev/null @@ -1,3362 +0,0 @@ -/**! - * 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 deleted file mode 100644 index bb99533..0000000 --- a/src/assets/src/js/sortable.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! 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 [ - * ... - * [ - * 'name' => 'column', - * 'items' => function($data) { - * // do your magic - * } - * .... - * ] - * ... - * - * ``` - */ - public $items; - - /** - * @var array - */ - public $options; - - /** - * @var array the HTML attributes for the header cell tag. - */ - public $headerOptions = []; - - /** - * @var bool whether to render inline error for the input. Default to `false` - */ - public $enableError = false; - - /** - * @var array the default options for the error tag - */ - public $errorOptions = ['class' => 'help-block help-block-error']; - - /** - * @var BaseRenderer the renderer instance - */ - public $renderer; - - /** - * @var mixed the context of using a column. It is an instance of widget(MultipleInput or TabularInput). - */ - public $context; - - /** - * @var 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. - * - * @since 2.1 - */ - public $attributeOptions = []; - - /** - * @var string the unique prefix for attribute's name to avoid id duplication e.g. in case of using Select2 widget. - * @since 2.8 - */ - public $nameSuffix; - - /** - * @var 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 - * - * @since 2.18.0 - */ - public $columnOptions = []; - - /** - * @var string the template of input for customize view. - * For example: '
{input}
' - */ - public $inputTemplate = '{input}'; - - /** - * @var Model|ActiveRecordInterface|array - */ - private $_model; - - - /** - * @return Model|ActiveRecordInterface|array - */ - public function getModel() - { - return $this->_model; - } - - /** - * @param Model|ActiveRecordInterface|array $model - */ - public function setModel($model) - { - if ($this->ensureModel($model)) { - $this->_model = $model; - } - } - - protected function ensureModel($model) - { - return true; - } - - /** - * @inheritdoc - */ - public function init() - { - parent::init(); - - if ($this->type === null) { - $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)) { - $this->options = []; - } - } - - 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. - */ - public function isHiddenInput() - { - return $this->type === self::TYPE_HIDDEN_INPUT; - } - - - /** - * 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($contextParams = []) - { - $data = $this->getModel(); - if ($this->value instanceof \Closure) { - $value = call_user_func($this->value, $data, $contextParams); - } else { - $valuePreparer = new ValuePreparer($this->name, $this->defaultValue); - $value = $valuePreparer->prepare($data); - } - - return $value; - } - - /** - * Returns element id. - * - * @param null|int $index - * @return mixed - */ - public function getElementId($index = null) - { - return $this->normalize($this->getElementName($index)); - } - - /** - * Returns element's name. - * - * @param int|null $index current row index - * @param bool $withPrefix whether to add prefix. - * @return string - */ - abstract public function getElementName($index, $withPrefix = true); - - /** - * Normalization name. - * - * @param $name - * @return mixed - */ - private function normalize($name) { - return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], strtolower($name)); - } - - /** - * Renders the 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, $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); - - // @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 = $this->$method($name, $value, $options); - } else { - $input = $this->renderDefault($name, $value, $options); - } - - 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. - * - * @param $name - * @param $value - * @param $options - * @return string - */ - protected function renderDropDownList($name, $value, $options) - { - if ($this->renderer->isBootstrapTheme()) { - Html::addCssClass($options, 'form-control'); - } - - return Html::dropDownList($name, $value, $this->prepareItems($this->items), $options); - } - - /** - * Returns the items for list. - * - * @param mixed $items - * @return array|Closure|mixed - */ - private function prepareItems($items) - { - if ($items instanceof \Closure) { - return $items($this->getModel()); - } - - return $items; - } - - /** - * Renders list box. - * - * @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 renderListBox($name, $value, $options) - { - if ($this->renderer->isBootstrapTheme()) { - Html::addCssClass($options, 'form-control'); - } - - return Html::listBox($name, $value, $this->prepareItems($this->items), $options); - } - - /** - * Renders hidden input. - * - * @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 renderHiddenInput($name, $value, $options) - { - return Html::hiddenInput($name, $value, $options); - } - - /** - * Renders radio button. - * - * @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 renderRadio($name, $value, $options) - { - if (!isset($options['label'])) { - $options['label'] = ''; - } - - if (!array_key_exists('uncheck', $options)) { - $options['uncheck'] = 0; - } - - $input = Html::radio($name, $value, $options); - - return Html::tag('div', $input, ['class' => 'radio']); - } - - /** - * Renders radio button list. - * - * @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 renderRadioList($name, $value, $options) - { - if (!array_key_exists('unselect', $options)) { - $options['unselect'] = ''; - } - - $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'), - ]); - - return Html::tag('div', $content, ['class' => 'radio']); - }; - - $input = Html::radioList($name, $value, $this->prepareItems($this->items), $options); - - return Html::tag('div', $input, ['class' => 'radio-list']); - } - - /** - * Renders checkbox. - * - * @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 renderCheckbox($name, $value, $options) - { - if (!isset($options['label'])) { - $options['label'] = ''; - } - - if (!array_key_exists('uncheck', $options)) { - $options['uncheck'] = 0; - } - - $input = Html::checkbox($name, $value, $options); - - return Html::tag('div', $input, ['class' => 'checkbox']); - } - - /** - * Renders checkbox list. - * - * @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 renderCheckboxList($name, $value, $options) - { - if (!array_key_exists('unselect', $options)) { - $options['unselect'] = ''; - } - - $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'), - ]); - - return Html::tag('div', $content, ['class' => 'checkbox']); - }; - - $input = Html::checkboxList($name, $value, $this->prepareItems($this->items), $options); - - return Html::tag('div', $input, ['class' => 'checkbox-list']); - } - - /** - * 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) - { - 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 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 - */ - protected function renderDefault($name, $value, $options) - { - $type = $this->type; - - if (method_exists('yii\helpers\Html', $type)) { - 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); - } else { - throw new InvalidConfigException("Invalid column type '$type'"); - } - - return $input; - } - - /** - * Renders a widget. - * - * @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 = [ - 'model' => $model, - 'attribute' => $this->name, - 'value' => $value, - 'options' => [ - 'id' => $id, - 'name' => $name, - 'tabindex' => $tabindex, - 'value' => $value - ] - ]; - } else { - $widgetOptions = [ - 'name' => $name, - 'value' => $value, - 'options' => [ - 'id' => $id, - 'name' => $name, - 'tabindex' => $tabindex, - 'value' => $value - ] - ]; - } - - $options = ArrayHelper::merge($options, $widgetOptions); - - return $type::widget($options); - } - - - /** - * Renders an error. - * - * @param string $error - * @return string - */ - public function renderError($error) - { - $options = $this->errorOptions; - $tag = isset($options['tag']) ? $options['tag'] : 'div'; - $encode = !isset($options['encode']) || $options['encode'] !== false; - unset($options['tag'], $options['encode']); - - return Html::tag($tag, $encode ? Html::encode($error) : $error, $options); - } - - /** - * @param $index - * @return mixed - */ - abstract public function getFirstError($index); -} diff --git a/src/components/ValuePreparer.php b/src/components/ValuePreparer.php deleted file mode 100644 index 91e01fb..0000000 --- a/src/components/ValuePreparer.php +++ /dev/null @@ -1,82 +0,0 @@ -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 deleted file mode 100644 index 5a701a1..0000000 --- a/src/renderers/BaseRenderer.php +++ /dev/null @@ -1,614 +0,0 @@ -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 deleted file mode 100644 index 80e3056..0000000 --- a/src/renderers/DivRenderer.php +++ /dev/null @@ -1,390 +0,0 @@ -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 deleted file mode 100644 index 7661a41..0000000 --- a/src/renderers/ListRenderer.php +++ /dev/null @@ -1,370 +0,0 @@ -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 deleted file mode 100644 index 395ef3e..0000000 --- a/src/renderers/RendererInterface.php +++ /dev/null @@ -1,47 +0,0 @@ -hasHeader()) { - $content[] = $this->renderHeader(); - } - - $content[] = $this->renderBody(); - $content[] = $this->renderFooter(); - - $options = []; - 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, [ - 'id' => $this->id, - 'class' => 'multiple-input' - ]); - } - - /** - * Renders the header. - * - * @return string - */ - public function renderHeader() - { - $cells = []; - if ($this->isAddButtonPositionRowBegin()) { - $cells[] = $this->renderButtonHeaderCell(); - } - - foreach ($this->columns as $column) { - /* @var $column BaseColumn */ - $cells[] = $this->renderHeaderCell($column); - } - - if ($this->max === null || ($this->max >= 1 && $this->max !== $this->min)) { - $button = $this->isAddButtonPositionHeader() ? $this->renderAddButton() : ''; - - if ($this->cloneButton) { - $cells[] = $this->renderButtonHeaderCell(); - } - - $cells[] = $this->renderButtonHeaderCell($button); - } - - return Html::tag('thead', Html::tag('tr', implode("\n", $cells))); - } - - /** - * Renders the footer. - * - * @return string - */ - public function renderFooter() - { - if (!$this->isAddButtonPositionFooter()) { - 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' => $columnsCount]); - $cells[] = Html::tag('td', $this->renderAddButton(), [ - 'class' => 'list-cell__button' - ]); - - return Html::tag('tfoot', Html::tag('tr', implode("\n", $cells))); - } - - - /** - * Check that at least one column has a header. - * - * @return bool - */ - 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; - } - - /** - * Renders the header cell. - * @param BaseColumn $column - * @return null|string - */ - 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() - { - 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) - { - $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, $columnIndex++); - } else { - $cells[] = $this->renderCellContent($column, $index, $columnIndex++); - } - } - - 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) { - $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 - * @return string - * - * @todo rethink visibility level (make it private) - */ - 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; - } - - $hasError = false; - $error = ''; - - if ($index !== null) { - $error = $column->getFirstError($index); - $hasError = !empty($error); - } - - if ($column->enableError) { - $input .= "\n" . $column->renderError($error); - } - - $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, $columnOptions); - } - - - /** - * Renders the action column. - * - * @param null|int|string $index - * @param null|ActiveRecordInterface|array $item - * @param int $rowIndex - * @return string - */ - private function renderActionColumn( - $index = null, - $item = null, - $rowIndex = null, - $isFirstColumn = false - ) - { - $content = $this->getActionButton($index, $rowIndex, $isFirstColumn) . $this->getExtraButtons($index, $item); - - return Html::tag('td', $content, [ - 'class' => 'list-cell__button', - ]); - } - - /** - * 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) { - if ($isFirstColumn) { - return $this->isAddButtonPositionRowBegin() ? $this->renderRemoveButton() : ''; - } - - return $this->isAddButtonPositionRowBegin() ? '' : $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) { - if ($isFirstColumn) { - return $this->isAddButtonPositionRowBegin() ? $this->renderAddButton() : ''; - } - - - return $this->isAddButtonPositionRow() ? $this->renderAddButton() : ''; - } - - if ($isFirstColumn) { - return $this->isAddButtonPositionRowBegin() ? $this->renderRemoveButton() : ''; - } - - return $this->isAddButtonPositionRowBegin() ? '' : $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/tests/unit/MultipleInputAssetTest.php b/tests/unit/MultipleInputAssetTest.php deleted file mode 100644 index 035a87d..0000000 --- a/tests/unit/MultipleInputAssetTest.php +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index 4fd54d9..0000000 --- a/tests/unit/MultipleInputTest.php +++ /dev/null @@ -1,78 +0,0 @@ - $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 deleted file mode 100644 index e908b41..0000000 --- a/tests/unit/TestCase.php +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 757435c..0000000 --- a/tests/unit/data/TestActiveRecord.php +++ /dev/null @@ -1,48 +0,0 @@ - '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 deleted file mode 100644 index 1890f57..0000000 --- a/tests/unit/data/TestActiveRecordRelated.php +++ /dev/null @@ -1,17 +0,0 @@ - 'Email', - ]; - } -} \ No newline at end of file diff --git a/tips-and-tricks/index.html b/tips-and-tricks/index.html new file mode 100644 index 0000000..246cb20 --- /dev/null +++ b/tips-and-tricks/index.html @@ -0,0 +1,788 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + Tips and Tricks - Yii2 multiple input + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + + + + + +
+
+ + + + + + + + +

Tips and tricks

+

How to customize buttons

+

You can customize add and remove buttons via addButtonOptions and removeButtonOptions. Here is a simple example of how you can use those options:

+
    echo $form->field($model, 'emails')->widget(MultipleInput::className(), [
+        'max' => 5,
+        'addButtonOptions' => [
+            'class' => 'btn btn-success',
+            'label' => 'add' // also you can use html code
+        ],
+        'removeButtonOptions' => [
+            'label' => 'remove'
+        ]
+    ])
+    ->label(false);
+
+

How to add content after the buttons

+

You can add html content after add and remove buttons via extraButtons.

+
    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:

+
    echo $form->field($model, 'emails')->widget(MultipleInput::className(), [
+        'max' => 5,
+        'allowEmptyList' => true
+    ])
+    ->label(false);
+
+

Also, you can set 0 in min option if you don't need the first blank row when data is empty.

+

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 the option enableGuessTitle like in the example below:

+
    echo $form->field($model, 'emails')->widget(MultipleInput::className(), [
+        '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 the modal window. In this case, you MUST:

+
    +
  • 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

+

You can use a placeholder {multiple_index} in a widget configuration, e.g. for implementation of dependent drop-down lists.

+
    <?= $form->field($model, 'field')->widget(MultipleInput::className(), [
+            'id' => 'my_id',
+            'allowEmptyList' => false,
+            'rowOptions' => [
+                'id' => 'row{multiple_index_my_id}',
+            ],
+            'columns' => [
+                [
+                    'name'  => 'category',
+                    'type'  => 'dropDownList',
+                    'title' => 'Category',
+                    'defaultValue' => '1',
+                    'items' => [
+                        '1' => 'Test 1',
+                        '2' => 'Test 2',
+                        '3' => 'Test 3',
+                        '4' => 'Test 4',
+                    ],
+                    'options' => [
+                        'onchange' => <<< JS
+$.post("list?id=" + $(this).val(), function(data){
+    console.log(data);
+    $("select#subcat-{multiple_index_my_id}").html(data);
+});
+JS
+                    ],
+                ],
+                [
+                    'name'  => 'subcategory',
+                    'type'  => 'dropDownList',
+                    'title' => 'Subcategory',
+                    'items' => [],
+                    'options'=> [
+                        'id' => 'subcat-{multiple_index_my_id}'
+                    ],
+                ],
+            ]
+    ]);
+    ?>
+
+

Important Ensure that you added ID of widget to a base placeholder multiple_index

+

Custom index of the row

+

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:

+
    <?= $form->field($model, 'field')->widget(MultipleInput::className(), [
+            'allowEmptyList' => false,
+            'data' => [
+                3 => [
+                    'day'       => '27.02.2015',
+                    'user_id'   => 31,
+                    'priority'  => 1,
+                    'enable'    => 1
+                ],
+
+                'some-key' => [
+                    'day'       => '27.02.2015',
+                    'user_id'   => 33,
+                    'priority'  => 2,
+                    'enable'    => 0
+                ],
+            ]
+
+    ...
+
+

Embedded MultipleInput widget

+

You can use nested MultipleInput as in the example below:

+
echo MultipleInput::widget([
+    'model' => $model,
+    'attribute' => 'questions',
+    'attributeOptions' => $commonAttributeOptions,
+    'columns' => [
+        [
+            'name' => 'question',
+            'type' => 'textarea',
+        ],
+        [
+            'name' => 'answers',
+            'type'  => MultipleInput::class,
+            'options' => [
+                'attributeOptions' => $commonAttributeOptions,
+                'columns' => [
+                    [
+                        'name' => 'right',
+                        'type' => MultipleInputColumn::TYPE_CHECKBOX
+                    ],
+                    [
+                        'name' => 'answer'
+                    ]
+                ]
+            ]
+        ]
+    ],
+]);
+
+

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:

+
<?= 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.

+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/usage/index.html b/usage/index.html new file mode 100644 index 0000000..e5f2590 --- /dev/null +++ b/usage/index.html @@ -0,0 +1,915 @@ + + + + + + + + + + + + + + + + + + + + + + + + Usage - Yii2 multiple input + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + + +

Usage

+

You can find the source code of examples here

+

One column

+

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 a form and then you can save them to the 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 a virtual attribute in the model

+
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

+
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 */
+?>
+
+<?php $form = ActiveForm::begin([
+    'enableAjaxValidation'      => 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']);?>
+<?php ActiveForm::end();?>
+
+

Options max means that a user is able to input only 4 emails

+

For validation emails, you can use the following code

+
    /**
+     * 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

+

Multiple columns example

+

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

+
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

+
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 */
+?>
+
+<?php $form = ActiveForm::begin([
+    'enableAjaxValidation'      => 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']);?>
+<?php ActiveForm::end();?>
+
+

For validation of the schedule you can use the following code

+
    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 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

+
use unclead\multipleinput\MultipleInput;
+
+...
+
+<?= $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
+                ]
+            ],
+            'headerOptions' => [
+                'style' => 'width: 250px;',
+                'class' => 'day-css-class'
+            ]
+        ],
+        [
+            'name'  => 'priority',
+            'enableError' => true,
+            'title' => 'Priority',
+            'options' => [
+                'class' => 'input-priority'
+            ]
+        ],
+        [
+            'name'  => 'comment',
+            'type'  => 'static',
+            'value' => function($data) {
+                return Html::tag('span', 'static content', ['class' => 'label label-info']);
+            },
+            'headerOptions' => [
+                'style' => 'width: 70px;',
+            ]
+        ]
+    ]
+ ]);
+?>
+
+

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

+
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']
+        ];
+    }
+}
+
+

Then we have to use TabularInput widget for rendering form field in the view file

+

Since version 2.18.0 you can configure columnOptions also.

+
<?php
+
+use yii\bootstrap\ActiveForm;
+use unclead\multipleinput\TabularInput;
+use yii\helpers\Html;
+use \unclead\multipleinput\examples\models\Item;
+
+/* @var $this \yii\web\View */
+/* @var $models Item[] */
+?>
+
+<?php $form = \yii\bootstrap\ActiveForm::begin([
+    'id'                        => '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\multipleinput\MultipleInputColumn::TYPE_TEXT_INPUT,
+        ],
+        [
+            'name'  => 'description',
+            'title' => 'Description',
+        ],
+        [
+            'name'  => 'file',
+            'title' => 'File',
+            'type'  => \vova07\fileapi\Widget::className(),
+            'options' => [
+                'settings' => [
+                    'url' => ['site/fileapi-upload']
+                ]
+            ],
+            'columnOptions' => [
+                'style' => 'width: 250px;',
+                'class' => 'custom-css-class'
+            ]
+        ],
+        [
+            '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']);?>
+<?php ActiveForm::end();?>
+
+

Your action can look like the following code

+
/**
+ * 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]);
+    }
+}
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file