@formio/js 5.0.0-rc.12 → 5.0.0-rc.13

Sign up to get free protection for your applications and to get access to all the features.
@@ -2788,16 +2788,6 @@ eval("\n\nvar cache = {};\nvar start = '(?:^|\\\\s)';\nvar end = '(?:\\\\s|$)';\
2788
2788
 
2789
2789
  /***/ }),
2790
2790
 
2791
- /***/ "./node_modules/dragula/dist/dragula.js":
2792
- /*!**********************************************!*\
2793
- !*** ./node_modules/dragula/dist/dragula.js ***!
2794
- \**********************************************/
2795
- /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
2796
-
2797
- eval("(function(f){if(true){module.exports=f()}else { var g; }})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=undefined;if(!f&&c)return require(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=undefined,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){\n'use strict';\n\nvar cache = {};\nvar start = '(?:^|\\\\s)';\nvar end = '(?:\\\\s|$)';\n\nfunction lookupClass (className) {\n var cached = cache[className];\n if (cached) {\n cached.lastIndex = 0;\n } else {\n cache[className] = cached = new RegExp(start + className + end, 'g');\n }\n return cached;\n}\n\nfunction addClass (el, className) {\n var current = el.className;\n if (!current.length) {\n el.className = className;\n } else if (!lookupClass(className).test(current)) {\n el.className += ' ' + className;\n }\n}\n\nfunction rmClass (el, className) {\n el.className = el.className.replace(lookupClass(className), ' ').trim();\n}\n\nmodule.exports = {\n add: addClass,\n rm: rmClass\n};\n\n},{}],2:[function(require,module,exports){\n(function (global){\n'use strict';\n\nvar emitter = require('contra/emitter');\nvar crossvent = require('crossvent');\nvar classes = require('./classes');\nvar doc = document;\nvar documentElement = doc.documentElement;\n\nfunction dragula (initialContainers, options) {\n var len = arguments.length;\n if (len === 1 && Array.isArray(initialContainers) === false) {\n options = initialContainers;\n initialContainers = [];\n }\n var _mirror; // mirror image\n var _source; // source container\n var _item; // item being dragged\n var _offsetX; // reference x\n var _offsetY; // reference y\n var _moveX; // reference move x\n var _moveY; // reference move y\n var _initialSibling; // reference sibling when grabbed\n var _currentSibling; // reference sibling now\n var _copy; // item used for copying\n var _renderTimer; // timer for setTimeout renderMirrorImage\n var _lastDropTarget = null; // last container item was over\n var _grabbed; // holds mousedown context until first mousemove\n\n var o = options || {};\n if (o.moves === void 0) { o.moves = always; }\n if (o.accepts === void 0) { o.accepts = always; }\n if (o.invalid === void 0) { o.invalid = invalidTarget; }\n if (o.containers === void 0) { o.containers = initialContainers || []; }\n if (o.isContainer === void 0) { o.isContainer = never; }\n if (o.copy === void 0) { o.copy = false; }\n if (o.copySortSource === void 0) { o.copySortSource = false; }\n if (o.revertOnSpill === void 0) { o.revertOnSpill = false; }\n if (o.removeOnSpill === void 0) { o.removeOnSpill = false; }\n if (o.direction === void 0) { o.direction = 'vertical'; }\n if (o.ignoreInputTextSelection === void 0) { o.ignoreInputTextSelection = true; }\n if (o.mirrorContainer === void 0) { o.mirrorContainer = doc.body; }\n\n var drake = emitter({\n containers: o.containers,\n start: manualStart,\n end: end,\n cancel: cancel,\n remove: remove,\n destroy: destroy,\n canMove: canMove,\n dragging: false\n });\n\n if (o.removeOnSpill === true) {\n drake.on('over', spillOver).on('out', spillOut);\n }\n\n events();\n\n return drake;\n\n function isContainer (el) {\n return drake.containers.indexOf(el) !== -1 || o.isContainer(el);\n }\n\n function events (remove) {\n var op = remove ? 'remove' : 'add';\n touchy(documentElement, op, 'mousedown', grab);\n touchy(documentElement, op, 'mouseup', release);\n }\n\n function eventualMovements (remove) {\n var op = remove ? 'remove' : 'add';\n touchy(documentElement, op, 'mousemove', startBecauseMouseMoved);\n }\n\n function movements (remove) {\n var op = remove ? 'remove' : 'add';\n crossvent[op](documentElement, 'selectstart', preventGrabbed); // IE8\n crossvent[op](documentElement, 'click', preventGrabbed);\n }\n\n function destroy () {\n events(true);\n release({});\n }\n\n function preventGrabbed (e) {\n if (_grabbed) {\n e.preventDefault();\n }\n }\n\n function grab (e) {\n _moveX = e.clientX;\n _moveY = e.clientY;\n\n var ignore = whichMouseButton(e) !== 1 || e.metaKey || e.ctrlKey;\n if (ignore) {\n return; // we only care about honest-to-god left clicks and touch events\n }\n var item = e.target;\n var context = canStart(item);\n if (!context) {\n return;\n }\n _grabbed = context;\n eventualMovements();\n if (e.type === 'mousedown') {\n if (isInput(item)) { // see also: https://github.com/bevacqua/dragula/issues/208\n item.focus(); // fixes https://github.com/bevacqua/dragula/issues/176\n } else {\n e.preventDefault(); // fixes https://github.com/bevacqua/dragula/issues/155\n }\n }\n }\n\n function startBecauseMouseMoved (e) {\n if (!_grabbed) {\n return;\n }\n if (whichMouseButton(e) === 0) {\n release({});\n return; // when text is selected on an input and then dragged, mouseup doesn't fire. this is our only hope\n }\n\n // truthy check fixes #239, equality fixes #207, fixes #501\n if ((e.clientX !== void 0 && Math.abs(e.clientX - _moveX) <= (o.slideFactorX || 0)) &&\n (e.clientY !== void 0 && Math.abs(e.clientY - _moveY) <= (o.slideFactorY || 0))) {\n return;\n }\n\n if (o.ignoreInputTextSelection) {\n var clientX = getCoord('clientX', e) || 0;\n var clientY = getCoord('clientY', e) || 0;\n var elementBehindCursor = doc.elementFromPoint(clientX, clientY);\n if (isInput(elementBehindCursor)) {\n return;\n }\n }\n\n var grabbed = _grabbed; // call to end() unsets _grabbed\n eventualMovements(true);\n movements();\n end();\n start(grabbed);\n\n var offset = getOffset(_item);\n _offsetX = getCoord('pageX', e) - offset.left;\n _offsetY = getCoord('pageY', e) - offset.top;\n\n classes.add(_copy || _item, 'gu-transit');\n renderMirrorImage();\n drag(e);\n }\n\n function canStart (item) {\n if (drake.dragging && _mirror) {\n return;\n }\n if (isContainer(item)) {\n return; // don't drag container itself\n }\n var handle = item;\n while (getParent(item) && isContainer(getParent(item)) === false) {\n if (o.invalid(item, handle)) {\n return;\n }\n item = getParent(item); // drag target should be a top element\n if (!item) {\n return;\n }\n }\n var source = getParent(item);\n if (!source) {\n return;\n }\n if (o.invalid(item, handle)) {\n return;\n }\n\n var movable = o.moves(item, source, handle, nextEl(item));\n if (!movable) {\n return;\n }\n\n return {\n item: item,\n source: source\n };\n }\n\n function canMove (item) {\n return !!canStart(item);\n }\n\n function manualStart (item) {\n var context = canStart(item);\n if (context) {\n start(context);\n }\n }\n\n function start (context) {\n if (isCopy(context.item, context.source)) {\n _copy = context.item.cloneNode(true);\n drake.emit('cloned', _copy, context.item, 'copy');\n }\n\n _source = context.source;\n _item = context.item;\n _initialSibling = _currentSibling = nextEl(context.item);\n\n drake.dragging = true;\n drake.emit('drag', _item, _source);\n }\n\n function invalidTarget () {\n return false;\n }\n\n function end () {\n if (!drake.dragging) {\n return;\n }\n var item = _copy || _item;\n drop(item, getParent(item));\n }\n\n function ungrab () {\n _grabbed = false;\n eventualMovements(true);\n movements(true);\n }\n\n function release (e) {\n ungrab();\n\n if (!drake.dragging) {\n return;\n }\n var item = _copy || _item;\n var clientX = getCoord('clientX', e) || 0;\n var clientY = getCoord('clientY', e) || 0;\n var elementBehindCursor = getElementBehindPoint(_mirror, clientX, clientY);\n var dropTarget = findDropTarget(elementBehindCursor, clientX, clientY);\n if (dropTarget && ((_copy && o.copySortSource) || (!_copy || dropTarget !== _source))) {\n drop(item, dropTarget);\n } else if (o.removeOnSpill) {\n remove();\n } else {\n cancel();\n }\n }\n\n function drop (item, target) {\n var parent = getParent(item);\n if (_copy && o.copySortSource && target === _source) {\n parent.removeChild(_item);\n }\n if (isInitialPlacement(target)) {\n drake.emit('cancel', item, _source, _source);\n } else {\n drake.emit('drop', item, target, _source, _currentSibling);\n }\n cleanup();\n }\n\n function remove () {\n if (!drake.dragging) {\n return;\n }\n var item = _copy || _item;\n var parent = getParent(item);\n if (parent) {\n parent.removeChild(item);\n }\n drake.emit(_copy ? 'cancel' : 'remove', item, parent, _source);\n cleanup();\n }\n\n function cancel (revert) {\n if (!drake.dragging) {\n return;\n }\n var reverts = arguments.length > 0 ? revert : o.revertOnSpill;\n var item = _copy || _item;\n var parent = getParent(item);\n var initial = isInitialPlacement(parent);\n if (initial === false && reverts) {\n if (_copy) {\n if (parent) {\n parent.removeChild(_copy);\n }\n } else {\n _source.insertBefore(item, _initialSibling);\n }\n }\n if (initial || reverts) {\n drake.emit('cancel', item, _source, _source);\n } else {\n drake.emit('drop', item, parent, _source, _currentSibling);\n }\n cleanup();\n }\n\n function cleanup () {\n var item = _copy || _item;\n ungrab();\n removeMirrorImage();\n if (item) {\n classes.rm(item, 'gu-transit');\n }\n if (_renderTimer) {\n clearTimeout(_renderTimer);\n }\n drake.dragging = false;\n if (_lastDropTarget) {\n drake.emit('out', item, _lastDropTarget, _source);\n }\n drake.emit('dragend', item);\n _source = _item = _copy = _initialSibling = _currentSibling = _renderTimer = _lastDropTarget = null;\n }\n\n function isInitialPlacement (target, s) {\n var sibling;\n if (s !== void 0) {\n sibling = s;\n } else if (_mirror) {\n sibling = _currentSibling;\n } else {\n sibling = nextEl(_copy || _item);\n }\n return target === _source && sibling === _initialSibling;\n }\n\n function findDropTarget (elementBehindCursor, clientX, clientY) {\n var target = elementBehindCursor;\n while (target && !accepted()) {\n target = getParent(target);\n }\n return target;\n\n function accepted () {\n var droppable = isContainer(target);\n if (droppable === false) {\n return false;\n }\n\n var immediate = getImmediateChild(target, elementBehindCursor);\n var reference = getReference(target, immediate, clientX, clientY);\n var initial = isInitialPlacement(target, reference);\n if (initial) {\n return true; // should always be able to drop it right back where it was\n }\n return o.accepts(_item, target, _source, reference);\n }\n }\n\n function drag (e) {\n if (!_mirror) {\n return;\n }\n e.preventDefault();\n\n var clientX = getCoord('clientX', e) || 0;\n var clientY = getCoord('clientY', e) || 0;\n var x = clientX - _offsetX;\n var y = clientY - _offsetY;\n\n _mirror.style.left = x + 'px';\n _mirror.style.top = y + 'px';\n\n var item = _copy || _item;\n var elementBehindCursor = getElementBehindPoint(_mirror, clientX, clientY);\n var dropTarget = findDropTarget(elementBehindCursor, clientX, clientY);\n var changed = dropTarget !== null && dropTarget !== _lastDropTarget;\n if (changed || dropTarget === null) {\n out();\n _lastDropTarget = dropTarget;\n over();\n }\n var parent = getParent(item);\n if (dropTarget === _source && _copy && !o.copySortSource) {\n if (parent) {\n parent.removeChild(item);\n }\n return;\n }\n var reference;\n var immediate = getImmediateChild(dropTarget, elementBehindCursor);\n if (immediate !== null) {\n reference = getReference(dropTarget, immediate, clientX, clientY);\n } else if (o.revertOnSpill === true && !_copy) {\n reference = _initialSibling;\n dropTarget = _source;\n } else {\n if (_copy && parent) {\n parent.removeChild(item);\n }\n return;\n }\n if (\n (reference === null && changed) ||\n reference !== item &&\n reference !== nextEl(item)\n ) {\n _currentSibling = reference;\n dropTarget.insertBefore(item, reference);\n drake.emit('shadow', item, dropTarget, _source);\n }\n function moved (type) { drake.emit(type, item, _lastDropTarget, _source); }\n function over () { if (changed) { moved('over'); } }\n function out () { if (_lastDropTarget) { moved('out'); } }\n }\n\n function spillOver (el) {\n classes.rm(el, 'gu-hide');\n }\n\n function spillOut (el) {\n if (drake.dragging) { classes.add(el, 'gu-hide'); }\n }\n\n function renderMirrorImage () {\n if (_mirror) {\n return;\n }\n var rect = _item.getBoundingClientRect();\n _mirror = _item.cloneNode(true);\n _mirror.style.width = getRectWidth(rect) + 'px';\n _mirror.style.height = getRectHeight(rect) + 'px';\n classes.rm(_mirror, 'gu-transit');\n classes.add(_mirror, 'gu-mirror');\n o.mirrorContainer.appendChild(_mirror);\n touchy(documentElement, 'add', 'mousemove', drag);\n classes.add(o.mirrorContainer, 'gu-unselectable');\n drake.emit('cloned', _mirror, _item, 'mirror');\n }\n\n function removeMirrorImage () {\n if (_mirror) {\n classes.rm(o.mirrorContainer, 'gu-unselectable');\n touchy(documentElement, 'remove', 'mousemove', drag);\n getParent(_mirror).removeChild(_mirror);\n _mirror = null;\n }\n }\n\n function getImmediateChild (dropTarget, target) {\n var immediate = target;\n while (immediate !== dropTarget && getParent(immediate) !== dropTarget) {\n immediate = getParent(immediate);\n }\n if (immediate === documentElement) {\n return null;\n }\n return immediate;\n }\n\n function getReference (dropTarget, target, x, y) {\n var horizontal = o.direction === 'horizontal';\n var reference = target !== dropTarget ? inside() : outside();\n return reference;\n\n function outside () { // slower, but able to figure out any position\n var len = dropTarget.children.length;\n var i;\n var el;\n var rect;\n for (i = 0; i < len; i++) {\n el = dropTarget.children[i];\n rect = el.getBoundingClientRect();\n if (horizontal && (rect.left + rect.width / 2) > x) { return el; }\n if (!horizontal && (rect.top + rect.height / 2) > y) { return el; }\n }\n return null;\n }\n\n function inside () { // faster, but only available if dropped inside a child element\n var rect = target.getBoundingClientRect();\n if (horizontal) {\n return resolve(x > rect.left + getRectWidth(rect) / 2);\n }\n return resolve(y > rect.top + getRectHeight(rect) / 2);\n }\n\n function resolve (after) {\n return after ? nextEl(target) : target;\n }\n }\n\n function isCopy (item, container) {\n return typeof o.copy === 'boolean' ? o.copy : o.copy(item, container);\n }\n}\n\nfunction touchy (el, op, type, fn) {\n var touch = {\n mouseup: 'touchend',\n mousedown: 'touchstart',\n mousemove: 'touchmove'\n };\n var pointers = {\n mouseup: 'pointerup',\n mousedown: 'pointerdown',\n mousemove: 'pointermove'\n };\n var microsoft = {\n mouseup: 'MSPointerUp',\n mousedown: 'MSPointerDown',\n mousemove: 'MSPointerMove'\n };\n if (global.navigator.pointerEnabled) {\n crossvent[op](el, pointers[type], fn);\n } else if (global.navigator.msPointerEnabled) {\n crossvent[op](el, microsoft[type], fn);\n } else {\n crossvent[op](el, touch[type], fn);\n crossvent[op](el, type, fn);\n }\n}\n\nfunction whichMouseButton (e) {\n if (e.touches !== void 0) { return e.touches.length; }\n if (e.which !== void 0 && e.which !== 0) { return e.which; } // see https://github.com/bevacqua/dragula/issues/261\n if (e.buttons !== void 0) { return e.buttons; }\n var button = e.button;\n if (button !== void 0) { // see https://github.com/jquery/jquery/blob/99e8ff1baa7ae341e94bb89c3e84570c7c3ad9ea/src/event.js#L573-L575\n return button & 1 ? 1 : button & 2 ? 3 : (button & 4 ? 2 : 0);\n }\n}\n\nfunction getOffset (el) {\n var rect = el.getBoundingClientRect();\n return {\n left: rect.left + getScroll('scrollLeft', 'pageXOffset'),\n top: rect.top + getScroll('scrollTop', 'pageYOffset')\n };\n}\n\nfunction getScroll (scrollProp, offsetProp) {\n if (typeof global[offsetProp] !== 'undefined') {\n return global[offsetProp];\n }\n if (documentElement.clientHeight) {\n return documentElement[scrollProp];\n }\n return doc.body[scrollProp];\n}\n\nfunction getElementBehindPoint (point, x, y) {\n point = point || {};\n var state = point.className || '';\n var el;\n point.className += ' gu-hide';\n el = doc.elementFromPoint(x, y);\n point.className = state;\n return el;\n}\n\nfunction never () { return false; }\nfunction always () { return true; }\nfunction getRectWidth (rect) { return rect.width || (rect.right - rect.left); }\nfunction getRectHeight (rect) { return rect.height || (rect.bottom - rect.top); }\nfunction getParent (el) { return el.parentNode === doc ? null : el.parentNode; }\nfunction isInput (el) { return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || isEditable(el); }\nfunction isEditable (el) {\n if (!el) { return false; } // no parents were editable\n if (el.contentEditable === 'false') { return false; } // stop the lookup\n if (el.contentEditable === 'true') { return true; } // found a contentEditable element in the chain\n return isEditable(getParent(el)); // contentEditable is set to 'inherit'\n}\n\nfunction nextEl (el) {\n return el.nextElementSibling || manually();\n function manually () {\n var sibling = el;\n do {\n sibling = sibling.nextSibling;\n } while (sibling && sibling.nodeType !== 1);\n return sibling;\n }\n}\n\nfunction getEventHost (e) {\n // on touchend event, we have to use `e.changedTouches`\n // see http://stackoverflow.com/questions/7192563/touchend-event-properties\n // see https://github.com/bevacqua/dragula/issues/34\n if (e.targetTouches && e.targetTouches.length) {\n return e.targetTouches[0];\n }\n if (e.changedTouches && e.changedTouches.length) {\n return e.changedTouches[0];\n }\n return e;\n}\n\nfunction getCoord (coord, e) {\n var host = getEventHost(e);\n var missMap = {\n pageX: 'clientX', // IE8\n pageY: 'clientY' // IE8\n };\n if (coord in missMap && !(coord in host) && missMap[coord] in host) {\n coord = missMap[coord];\n }\n return host[coord];\n}\n\nmodule.exports = dragula;\n\n}).call(this,typeof __webpack_require__.g !== \"undefined\" ? __webpack_require__.g : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n\n},{\"./classes\":1,\"contra/emitter\":5,\"crossvent\":6}],3:[function(require,module,exports){\nmodule.exports = function atoa (a, n) { return Array.prototype.slice.call(a, n); }\n\n},{}],4:[function(require,module,exports){\n'use strict';\n\nvar ticky = require('ticky');\n\nmodule.exports = function debounce (fn, args, ctx) {\n if (!fn) { return; }\n ticky(function run () {\n fn.apply(ctx || null, args || []);\n });\n};\n\n},{\"ticky\":10}],5:[function(require,module,exports){\n'use strict';\n\nvar atoa = require('atoa');\nvar debounce = require('./debounce');\n\nmodule.exports = function emitter (thing, options) {\n var opts = options || {};\n var evt = {};\n if (thing === undefined) { thing = {}; }\n thing.on = function (type, fn) {\n if (!evt[type]) {\n evt[type] = [fn];\n } else {\n evt[type].push(fn);\n }\n return thing;\n };\n thing.once = function (type, fn) {\n fn._once = true; // thing.off(fn) still works!\n thing.on(type, fn);\n return thing;\n };\n thing.off = function (type, fn) {\n var c = arguments.length;\n if (c === 1) {\n delete evt[type];\n } else if (c === 0) {\n evt = {};\n } else {\n var et = evt[type];\n if (!et) { return thing; }\n et.splice(et.indexOf(fn), 1);\n }\n return thing;\n };\n thing.emit = function () {\n var args = atoa(arguments);\n return thing.emitterSnapshot(args.shift()).apply(this, args);\n };\n thing.emitterSnapshot = function (type) {\n var et = (evt[type] || []).slice(0);\n return function () {\n var args = atoa(arguments);\n var ctx = this || thing;\n if (type === 'error' && opts.throws !== false && !et.length) { throw args.length === 1 ? args[0] : args; }\n et.forEach(function emitter (listen) {\n if (opts.async) { debounce(listen, args, ctx); } else { listen.apply(ctx, args); }\n if (listen._once) { thing.off(type, listen); }\n });\n return thing;\n };\n };\n return thing;\n};\n\n},{\"./debounce\":4,\"atoa\":3}],6:[function(require,module,exports){\n(function (global){\n'use strict';\n\nvar customEvent = require('custom-event');\nvar eventmap = require('./eventmap');\nvar doc = global.document;\nvar addEvent = addEventEasy;\nvar removeEvent = removeEventEasy;\nvar hardCache = [];\n\nif (!global.addEventListener) {\n addEvent = addEventHard;\n removeEvent = removeEventHard;\n}\n\nmodule.exports = {\n add: addEvent,\n remove: removeEvent,\n fabricate: fabricateEvent\n};\n\nfunction addEventEasy (el, type, fn, capturing) {\n return el.addEventListener(type, fn, capturing);\n}\n\nfunction addEventHard (el, type, fn) {\n return el.attachEvent('on' + type, wrap(el, type, fn));\n}\n\nfunction removeEventEasy (el, type, fn, capturing) {\n return el.removeEventListener(type, fn, capturing);\n}\n\nfunction removeEventHard (el, type, fn) {\n var listener = unwrap(el, type, fn);\n if (listener) {\n return el.detachEvent('on' + type, listener);\n }\n}\n\nfunction fabricateEvent (el, type, model) {\n var e = eventmap.indexOf(type) === -1 ? makeCustomEvent() : makeClassicEvent();\n if (el.dispatchEvent) {\n el.dispatchEvent(e);\n } else {\n el.fireEvent('on' + type, e);\n }\n function makeClassicEvent () {\n var e;\n if (doc.createEvent) {\n e = doc.createEvent('Event');\n e.initEvent(type, true, true);\n } else if (doc.createEventObject) {\n e = doc.createEventObject();\n }\n return e;\n }\n function makeCustomEvent () {\n return new customEvent(type, { detail: model });\n }\n}\n\nfunction wrapperFactory (el, type, fn) {\n return function wrapper (originalEvent) {\n var e = originalEvent || global.event;\n e.target = e.target || e.srcElement;\n e.preventDefault = e.preventDefault || function preventDefault () { e.returnValue = false; };\n e.stopPropagation = e.stopPropagation || function stopPropagation () { e.cancelBubble = true; };\n e.which = e.which || e.keyCode;\n fn.call(el, e);\n };\n}\n\nfunction wrap (el, type, fn) {\n var wrapper = unwrap(el, type, fn) || wrapperFactory(el, type, fn);\n hardCache.push({\n wrapper: wrapper,\n element: el,\n type: type,\n fn: fn\n });\n return wrapper;\n}\n\nfunction unwrap (el, type, fn) {\n var i = find(el, type, fn);\n if (i) {\n var wrapper = hardCache[i].wrapper;\n hardCache.splice(i, 1); // free up a tad of memory\n return wrapper;\n }\n}\n\nfunction find (el, type, fn) {\n var i, item;\n for (i = 0; i < hardCache.length; i++) {\n item = hardCache[i];\n if (item.element === el && item.type === type && item.fn === fn) {\n return i;\n }\n }\n}\n\n}).call(this,typeof __webpack_require__.g !== \"undefined\" ? __webpack_require__.g : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n\n},{\"./eventmap\":7,\"custom-event\":8}],7:[function(require,module,exports){\n(function (global){\n'use strict';\n\nvar eventmap = [];\nvar eventname = '';\nvar ron = /^on/;\n\nfor (eventname in global) {\n if (ron.test(eventname)) {\n eventmap.push(eventname.slice(2));\n }\n}\n\nmodule.exports = eventmap;\n\n}).call(this,typeof __webpack_require__.g !== \"undefined\" ? __webpack_require__.g : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n\n},{}],8:[function(require,module,exports){\n(function (global){\n\nvar NativeCustomEvent = global.CustomEvent;\n\nfunction useNative () {\n try {\n var p = new NativeCustomEvent('cat', { detail: { foo: 'bar' } });\n return 'cat' === p.type && 'bar' === p.detail.foo;\n } catch (e) {\n }\n return false;\n}\n\n/**\n * Cross-browser `CustomEvent` constructor.\n *\n * https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent.CustomEvent\n *\n * @public\n */\n\nmodule.exports = useNative() ? NativeCustomEvent :\n\n// IE >= 9\n'undefined' !== typeof document && 'function' === typeof document.createEvent ? function CustomEvent (type, params) {\n var e = document.createEvent('CustomEvent');\n if (params) {\n e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail);\n } else {\n e.initCustomEvent(type, false, false, void 0);\n }\n return e;\n} :\n\n// IE <= 8\nfunction CustomEvent (type, params) {\n var e = document.createEventObject();\n e.type = type;\n if (params) {\n e.bubbles = Boolean(params.bubbles);\n e.cancelable = Boolean(params.cancelable);\n e.detail = params.detail;\n } else {\n e.bubbles = false;\n e.cancelable = false;\n e.detail = void 0;\n }\n return e;\n}\n\n}).call(this,typeof __webpack_require__.g !== \"undefined\" ? __webpack_require__.g : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n\n},{}],9:[function(require,module,exports){\n// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n},{}],10:[function(require,module,exports){\n(function (setImmediate){\nvar si = typeof setImmediate === 'function', tick;\nif (si) {\n tick = function (fn) { setImmediate(fn); };\n} else {\n tick = function (fn) { setTimeout(fn, 0); };\n}\n\nmodule.exports = tick;\n}).call(this,require(\"timers\").setImmediate)\n\n},{\"timers\":11}],11:[function(require,module,exports){\n(function (setImmediate,clearImmediate){\nvar nextTick = require('process/browser.js').nextTick;\nvar apply = Function.prototype.apply;\nvar slice = Array.prototype.slice;\nvar immediateIds = {};\nvar nextImmediateId = 0;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, window, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) { timeout.close(); };\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(window, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// That's not how node.js implements it but the exposed api is the same.\nexports.setImmediate = typeof setImmediate === \"function\" ? setImmediate : function(fn) {\n var id = nextImmediateId++;\n var args = arguments.length < 2 ? false : slice.call(arguments, 1);\n\n immediateIds[id] = true;\n\n nextTick(function onNextTick() {\n if (immediateIds[id]) {\n // fn.call() is faster so we optimize for the common use-case\n // @see http://jsperf.com/call-apply-segu\n if (args) {\n fn.apply(null, args);\n } else {\n fn.call(null);\n }\n // Prevent ids from leaking\n exports.clearImmediate(id);\n }\n });\n\n return id;\n};\n\nexports.clearImmediate = typeof clearImmediate === \"function\" ? clearImmediate : function(id) {\n delete immediateIds[id];\n};\n}).call(this,require(\"timers\").setImmediate,require(\"timers\").clearImmediate)\n\n},{\"process/browser.js\":9,\"timers\":11}]},{},[2])(2)\n});\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJjbGFzc2VzLmpzIiwiZHJhZ3VsYS5qcyIsIm5vZGVfbW9kdWxlcy9hdG9hL2F0b2EuanMiLCJub2RlX21vZHVsZXMvY29udHJhL2RlYm91bmNlLmpzIiwibm9kZV9tb2R1bGVzL2NvbnRyYS9lbWl0dGVyLmpzIiwibm9kZV9tb2R1bGVzL2Nyb3NzdmVudC9zcmMvY3Jvc3N2ZW50LmpzIiwibm9kZV9tb2R1bGVzL2Nyb3NzdmVudC9zcmMvZXZlbnRtYXAuanMiLCJub2RlX21vZHVsZXMvY3VzdG9tLWV2ZW50L2luZGV4LmpzIiwibm9kZV9tb2R1bGVzL3Byb2Nlc3MvYnJvd3Nlci5qcyIsIm5vZGVfbW9kdWxlcy90aWNreS90aWNreS1icm93c2VyLmpzIiwibm9kZV9tb2R1bGVzL3RpbWVycy1icm93c2Vya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ciB0aGUgY29tbW9uIHVzZS1jYXNlXG4gICAgICAvLyBAc2VlIGh0dHA6Ly9qc3BlcmYuY29tL2NhbGwtYXBwbHktc2VndVxuICAgICAgaWYgKGFyZ3MpIHtcbiAgICAgICAgZm4uYXBwbHkobnVsbCwgYXJncyk7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBmbi5jYWxsKG51bGwpO1xuICAgICAgfVxuICAgICAgLy8gUHJldmVudCBpZHMgZnJvbSBsZWFraW5nXG4gICAgICBleHBvcnRzLmNsZWFySW1tZWRpYXRlKGlkKTtcbiAgICB9XG4gIH0pO1xuXG4gIHJldHVybiBpZDtcbn07XG5cbmV4cG9ydHMuY2xlYXJJbW1lZGlhdGUgPSB0eXBlb2YgY2xlYXJJbW1lZGlhdGUgPT09IFwiZnVuY3Rpb25cIiA/IGNsZWFySW1tZWRpYXRlIDogZnVuY3Rpb24oaWQpIHtcbiAgZGVsZXRlIGltbWVkaWF0ZUlkc1tpZF07XG59OyJdfQ==\n\n\n//# sourceURL=webpack://Formio/./node_modules/dragula/dist/dragula.js?");
2798
-
2799
- /***/ }),
2800
-
2801
2791
  /***/ "./node_modules/dragula/dragula.js":
2802
2792
  /*!*****************************************!*\
2803
2793
  !*** ./node_modules/dragula/dragula.js ***!
@@ -5323,7 +5313,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
5323
5313
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5324
5314
 
5325
5315
  "use strict";
5326
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst WebformBuilder_1 = __importDefault(__webpack_require__(/*! ./WebformBuilder */ \"./lib/cjs/WebformBuilder.js\"));\nconst Webform_1 = __importDefault(__webpack_require__(/*! ./Webform */ \"./lib/cjs/Webform.js\"));\nconst builder_1 = __importDefault(__webpack_require__(/*! ./utils/builder */ \"./lib/cjs/utils/builder.js\"));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst utils_1 = __webpack_require__(/*! ./utils/utils */ \"./lib/cjs/utils/utils.js\");\nlet dragula;\nif (typeof window !== 'undefined') {\n // Import from \"dist\" because it would require and \"global\" would not be defined in Angular apps.\n dragula = __webpack_require__(/*! dragula/dist/dragula */ \"./node_modules/dragula/dist/dragula.js\");\n}\nclass WizardBuilder extends WebformBuilder_1.default {\n constructor() {\n let element, options;\n if (arguments[0] instanceof HTMLElement || arguments[1]) {\n element = arguments[0];\n options = arguments[1];\n }\n else {\n options = arguments[0];\n }\n // Reset skipInit in case PDFBuilder has set it.\n options.skipInit = false;\n options.display = 'wizard';\n super(element, options);\n this._form = {\n components: [\n this.getPageConfig(1),\n ],\n };\n this.page = 0;\n // Need to create a component order for each group.\n for (const group in this.groups) {\n if (this.groups[group] && this.groups[group].components) {\n this.groups[group].componentOrder = Object.keys(this.groups[group].components)\n .map(key => this.groups[group].components[key])\n .filter(component => component && !component.ignore)\n .sort((a, b) => a.weight - b.weight)\n .map(component => component.key);\n }\n }\n const originalRenderComponentsHook = this.options.hooks.renderComponents;\n this.options.hooks.renderComponents = (html, { components, self }) => {\n if (self.type === 'form' && !self.root) {\n return html;\n }\n else {\n return originalRenderComponentsHook(html, { components, self });\n }\n };\n const originalAttachComponentsHook = this.options.hooks.attachComponents;\n this.options.hooks.attachComponents = (element, components, container, component) => {\n if (component.type === 'form' && !component.root) {\n return element;\n }\n return originalAttachComponentsHook(element, components, container, component);\n };\n // Wizard pages don't replace themselves in the right array. Do that here.\n this.on('saveComponent', (component, originalComponent) => {\n const webformComponents = this.webform.components.map(({ component }) => component);\n if (this._form.components.includes(originalComponent)) {\n this._form.components[this._form.components.indexOf(originalComponent)] = component;\n this.rebuild();\n }\n else if (webformComponents.includes(originalComponent)) {\n this._form.components.push(component);\n this.rebuild();\n }\n else {\n // Fallback to look for panel based on key.\n const formComponentIndex = this._form.components.findIndex((comp) => originalComponent.key === comp.key);\n if (formComponentIndex !== -1) {\n this._form.components[formComponentIndex] = component;\n this.rebuild();\n }\n }\n }, true);\n }\n removeComponent(component, parent, original) {\n const remove = super.removeComponent(component, parent, original);\n // If user agrees to remove the whole group of the components and it could be a Wizard page, find it and remove\n if (remove && component.type === 'panel') {\n const pageIndex = this.pages.findIndex((page) => page.key === component.key);\n const componentIndex = this._form.components.findIndex((comp) => comp.key === component.key);\n if (pageIndex !== -1) {\n this.removePage(pageIndex, componentIndex);\n }\n }\n return remove;\n }\n allowDrop(element) {\n return (this.webform && this.webform.refs && this.webform.refs.webform === element) ? false : true;\n }\n get pages() {\n return lodash_1.default.filter(this._form.components, { type: 'panel' });\n }\n get currentPage() {\n const pages = this.pages;\n return (pages && (pages.length >= this.page)) ? pages[this.page] : null;\n }\n set form(value) {\n this._form = value;\n if (!this._form.components || !Array.isArray(this._form.components)) {\n this._form.components = [];\n }\n if (this.pages.length === 0) {\n const components = this._form.components.filter((component) => component.type !== 'button');\n this._form.components = [this.getPageConfig(1, components)];\n }\n this.rebuild();\n }\n get form() {\n return this._form;\n }\n get schema() {\n lodash_1.default.assign(this.currentPage, this.webform._form.components[0]);\n const webform = new Webform_1.default(this.options);\n webform.setForm(this._form, { noEmit: true });\n return webform.schema;\n }\n render() {\n return this.renderTemplate('builderWizard', {\n sidebar: this.renderTemplate('builderSidebar', {\n scrollEnabled: this.sideBarScroll,\n groupOrder: this.groupOrder,\n groupId: `builder-sidebar-${this.id}`,\n groups: this.groupOrder.map((groupKey) => this.renderTemplate('builderSidebarGroup', {\n group: this.groups[groupKey],\n groupKey,\n groupId: `builder-sidebar-${this.id}`,\n subgroups: this.groups[groupKey].subgroups.map((group) => this.renderTemplate('builderSidebarGroup', {\n group,\n groupKey: group.key,\n groupId: `group-container-${groupKey}`,\n subgroups: []\n })),\n })),\n }),\n pages: this.pages,\n form: this.webform.render(),\n });\n }\n attach(element) {\n this.loadRefs(element, {\n addPage: 'multiple',\n gotoPage: 'multiple',\n });\n this.refs.gotoPage.forEach((page, index) => {\n page.parentNode.dragInfo = { index };\n });\n if (dragula) {\n dragula([this.element.querySelector('.wizard-pages')])\n .on('drop', this.onReorder.bind(this));\n }\n this.refs.addPage.forEach(link => {\n this.addEventListener(link, 'click', (event) => {\n event.preventDefault();\n this.addPage();\n });\n });\n this.refs.gotoPage.forEach((link, index) => {\n this.addEventListener(link, 'click', (event) => {\n event.preventDefault();\n this.setPage(index);\n });\n });\n return super.attach(element);\n }\n rebuild() {\n var _a;\n const page = this.currentPage;\n this.webform.setForm({\n display: 'form',\n type: 'form',\n components: page ? [page] : [],\n controller: ((_a = this._form) === null || _a === void 0 ? void 0 : _a.controller) || ''\n }, { keepAsReference: true });\n return this.redraw();\n }\n addPage(page) {\n const newPage = page && page.schema ? (0, utils_1.fastCloneDeep)(page.schema) : this.getPageConfig(this.pages.length + 1);\n builder_1.default.uniquify(this._form.components, newPage);\n this._form.components.push(newPage);\n this.emitSaveComponentEvent(newPage, newPage, this._form, 'components', (this._form.components.length - 1), true, newPage);\n this.emit('change', this._form);\n return this.rebuild();\n }\n removePage(pageIndex, componentIndex) {\n this._form.components.splice(componentIndex, 1);\n this.emit('change', this._form);\n if (pageIndex === this.pages.length) {\n // If the last page is removed.\n if (pageIndex === 0) {\n this._form.components.push(this.getPageConfig(1));\n return this.rebuild();\n }\n else {\n return this.setPage(pageIndex - 1);\n }\n }\n else {\n return this.rebuild();\n }\n }\n onReorder(element, _target, _source, sibling) {\n if (!element.dragInfo || (sibling && !sibling.dragInfo)) {\n console.warn('There is no Drag Info available for either dragged or sibling element');\n return;\n }\n const oldPosition = element.dragInfo.index;\n //should drop at next sibling position; no next sibling means drop to last position\n const newPosition = (sibling ? sibling.dragInfo.index : this.pages.length);\n const movedBelow = newPosition > oldPosition;\n const formComponents = (0, utils_1.fastCloneDeep)(this._form.components);\n const draggedRowData = this._form.components[oldPosition];\n //insert element at new position\n formComponents.splice(newPosition, 0, draggedRowData);\n //remove element from old position (if was moved above, after insertion it's at +1 index)\n formComponents.splice(movedBelow ? oldPosition : oldPosition + 1, 1);\n this._form.components = (0, utils_1.fastCloneDeep)(formComponents);\n return this.rebuild().then(() => {\n this.emit('change', this._form);\n });\n }\n setPage(index) {\n if (index === this.page) {\n return;\n }\n this.page = index;\n return this.rebuild();\n }\n getPageConfig(index, components = []) {\n return {\n title: `Page ${index}`,\n label: `Page ${index}`,\n type: 'panel',\n key: `page${index}`,\n components,\n };\n }\n pasteComponent(component) {\n if (component instanceof WizardBuilder) {\n return;\n }\n if (this._form.components.find(comp => lodash_1.default.isEqual(component.component, comp))) {\n this.addPage(component);\n }\n else {\n return super.pasteComponent(component);\n }\n }\n}\nexports[\"default\"] = WizardBuilder;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/WizardBuilder.js?");
5316
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst WebformBuilder_1 = __importDefault(__webpack_require__(/*! ./WebformBuilder */ \"./lib/cjs/WebformBuilder.js\"));\nconst Webform_1 = __importDefault(__webpack_require__(/*! ./Webform */ \"./lib/cjs/Webform.js\"));\nconst builder_1 = __importDefault(__webpack_require__(/*! ./utils/builder */ \"./lib/cjs/utils/builder.js\"));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst utils_1 = __webpack_require__(/*! ./utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst dragula_1 = __importDefault(__webpack_require__(/*! dragula */ \"./node_modules/dragula/dragula.js\"));\nclass WizardBuilder extends WebformBuilder_1.default {\n constructor() {\n let element, options;\n if (arguments[0] instanceof HTMLElement || arguments[1]) {\n element = arguments[0];\n options = arguments[1];\n }\n else {\n options = arguments[0];\n }\n // Reset skipInit in case PDFBuilder has set it.\n options.skipInit = false;\n options.display = 'wizard';\n super(element, options);\n this._form = {\n components: [\n this.getPageConfig(1),\n ],\n };\n this.page = 0;\n // Need to create a component order for each group.\n for (const group in this.groups) {\n if (this.groups[group] && this.groups[group].components) {\n this.groups[group].componentOrder = Object.keys(this.groups[group].components)\n .map(key => this.groups[group].components[key])\n .filter(component => component && !component.ignore)\n .sort((a, b) => a.weight - b.weight)\n .map(component => component.key);\n }\n }\n const originalRenderComponentsHook = this.options.hooks.renderComponents;\n this.options.hooks.renderComponents = (html, { components, self }) => {\n if (self.type === 'form' && !self.root) {\n return html;\n }\n else {\n return originalRenderComponentsHook(html, { components, self });\n }\n };\n const originalAttachComponentsHook = this.options.hooks.attachComponents;\n this.options.hooks.attachComponents = (element, components, container, component) => {\n if (component.type === 'form' && !component.root) {\n return element;\n }\n return originalAttachComponentsHook(element, components, container, component);\n };\n // Wizard pages don't replace themselves in the right array. Do that here.\n this.on('saveComponent', (component, originalComponent) => {\n const webformComponents = this.webform.components.map(({ component }) => component);\n if (this._form.components.includes(originalComponent)) {\n this._form.components[this._form.components.indexOf(originalComponent)] = component;\n this.rebuild();\n }\n else if (webformComponents.includes(originalComponent)) {\n this._form.components.push(component);\n this.rebuild();\n }\n else {\n // Fallback to look for panel based on key.\n const formComponentIndex = this._form.components.findIndex((comp) => originalComponent.key === comp.key);\n if (formComponentIndex !== -1) {\n this._form.components[formComponentIndex] = component;\n this.rebuild();\n }\n }\n }, true);\n }\n removeComponent(component, parent, original) {\n const remove = super.removeComponent(component, parent, original);\n // If user agrees to remove the whole group of the components and it could be a Wizard page, find it and remove\n if (remove && component.type === 'panel') {\n const pageIndex = this.pages.findIndex((page) => page.key === component.key);\n const componentIndex = this._form.components.findIndex((comp) => comp.key === component.key);\n if (pageIndex !== -1) {\n this.removePage(pageIndex, componentIndex);\n }\n }\n return remove;\n }\n allowDrop(element) {\n return (this.webform && this.webform.refs && this.webform.refs.webform === element) ? false : true;\n }\n get pages() {\n return lodash_1.default.filter(this._form.components, { type: 'panel' });\n }\n get currentPage() {\n const pages = this.pages;\n return (pages && (pages.length >= this.page)) ? pages[this.page] : null;\n }\n set form(value) {\n this._form = value;\n if (!this._form.components || !Array.isArray(this._form.components)) {\n this._form.components = [];\n }\n if (this.pages.length === 0) {\n const components = this._form.components.filter((component) => component.type !== 'button');\n this._form.components = [this.getPageConfig(1, components)];\n }\n this.rebuild();\n }\n get form() {\n return this._form;\n }\n get schema() {\n lodash_1.default.assign(this.currentPage, this.webform._form.components[0]);\n const webform = new Webform_1.default(this.options);\n webform.setForm(this._form, { noEmit: true });\n return webform.schema;\n }\n render() {\n return this.renderTemplate('builderWizard', {\n sidebar: this.renderTemplate('builderSidebar', {\n scrollEnabled: this.sideBarScroll,\n groupOrder: this.groupOrder,\n groupId: `builder-sidebar-${this.id}`,\n groups: this.groupOrder.map((groupKey) => this.renderTemplate('builderSidebarGroup', {\n group: this.groups[groupKey],\n groupKey,\n groupId: `builder-sidebar-${this.id}`,\n subgroups: this.groups[groupKey].subgroups.map((group) => this.renderTemplate('builderSidebarGroup', {\n group,\n groupKey: group.key,\n groupId: `group-container-${groupKey}`,\n subgroups: []\n })),\n })),\n }),\n pages: this.pages,\n form: this.webform.render(),\n });\n }\n attach(element) {\n this.loadRefs(element, {\n addPage: 'multiple',\n gotoPage: 'multiple',\n });\n this.refs.gotoPage.forEach((page, index) => {\n page.parentNode.dragInfo = { index };\n });\n if (dragula_1.default) {\n (0, dragula_1.default)([this.element.querySelector('.wizard-pages')])\n .on('drop', this.onReorder.bind(this));\n }\n this.refs.addPage.forEach(link => {\n this.addEventListener(link, 'click', (event) => {\n event.preventDefault();\n this.addPage();\n });\n });\n this.refs.gotoPage.forEach((link, index) => {\n this.addEventListener(link, 'click', (event) => {\n event.preventDefault();\n this.setPage(index);\n });\n });\n return super.attach(element);\n }\n rebuild() {\n var _a;\n const page = this.currentPage;\n this.webform.setForm({\n display: 'form',\n type: 'form',\n components: page ? [page] : [],\n controller: ((_a = this._form) === null || _a === void 0 ? void 0 : _a.controller) || ''\n }, { keepAsReference: true });\n return this.redraw();\n }\n addPage(page) {\n const newPage = page && page.schema ? (0, utils_1.fastCloneDeep)(page.schema) : this.getPageConfig(this.pages.length + 1);\n builder_1.default.uniquify(this._form.components, newPage);\n this._form.components.push(newPage);\n this.emitSaveComponentEvent(newPage, newPage, this._form, 'components', (this._form.components.length - 1), true, newPage);\n this.emit('change', this._form);\n return this.rebuild();\n }\n removePage(pageIndex, componentIndex) {\n this._form.components.splice(componentIndex, 1);\n this.emit('change', this._form);\n if (pageIndex === this.pages.length) {\n // If the last page is removed.\n if (pageIndex === 0) {\n this._form.components.push(this.getPageConfig(1));\n return this.rebuild();\n }\n else {\n return this.setPage(pageIndex - 1);\n }\n }\n else {\n return this.rebuild();\n }\n }\n onReorder(element, _target, _source, sibling) {\n if (!element.dragInfo || (sibling && !sibling.dragInfo)) {\n console.warn('There is no Drag Info available for either dragged or sibling element');\n return;\n }\n const oldPosition = element.dragInfo.index;\n //should drop at next sibling position; no next sibling means drop to last position\n const newPosition = (sibling ? sibling.dragInfo.index : this.pages.length);\n const movedBelow = newPosition > oldPosition;\n const formComponents = (0, utils_1.fastCloneDeep)(this._form.components);\n const draggedRowData = this._form.components[oldPosition];\n //insert element at new position\n formComponents.splice(newPosition, 0, draggedRowData);\n //remove element from old position (if was moved above, after insertion it's at +1 index)\n formComponents.splice(movedBelow ? oldPosition : oldPosition + 1, 1);\n this._form.components = (0, utils_1.fastCloneDeep)(formComponents);\n return this.rebuild().then(() => {\n this.emit('change', this._form);\n });\n }\n setPage(index) {\n if (index === this.page) {\n return;\n }\n this.page = index;\n return this.rebuild();\n }\n getPageConfig(index, components = []) {\n return {\n title: `Page ${index}`,\n label: `Page ${index}`,\n type: 'panel',\n key: `page${index}`,\n components,\n };\n }\n pasteComponent(component) {\n if (component instanceof WizardBuilder) {\n return;\n }\n if (this._form.components.find(comp => lodash_1.default.isEqual(component.component, comp))) {\n this.addPage(component);\n }\n else {\n return super.pasteComponent(component);\n }\n }\n}\nexports[\"default\"] = WizardBuilder;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/WizardBuilder.js?");
5327
5317
 
5328
5318
  /***/ }),
5329
5319
 
@@ -5983,7 +5973,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
5983
5973
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5984
5974
 
5985
5975
  "use strict";
5986
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst NestedArrayComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/nestedarray/NestedArrayComponent */ \"./lib/cjs/components/_classes/nestedarray/NestedArrayComponent.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nlet dragula;\nif (typeof window !== 'undefined') {\n // Import from \"dist\" because it would require and \"global\" would not be defined in Angular apps.\n dragula = __webpack_require__(/*! dragula/dist/dragula */ \"./node_modules/dragula/dist/dragula.js\");\n}\nclass DataGridComponent extends NestedArrayComponent_1.default {\n static schema(...extend) {\n return NestedArrayComponent_1.default.schema({\n label: 'Data Grid',\n key: 'dataGrid',\n type: 'datagrid',\n clearOnHide: true,\n input: true,\n tree: true,\n components: []\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Data Grid',\n icon: 'th',\n group: 'data',\n documentation: '/userguide/form-building/data-components#data-grid',\n weight: 30,\n schema: DataGridComponent.schema()\n };\n }\n constructor(...args) {\n super(...args);\n this.type = 'datagrid';\n this.tabIndex = 0;\n }\n init() {\n this.components = this.components || [];\n // Add new values based on minLength.\n this.rows = [];\n this.columns = [...this.component.components];\n if (this.initRows || !lodash_1.default.isEqual(this.dataValue, this.emptyValue)) {\n this.createRows(true);\n }\n this.visibleColumns = {};\n this.prevHasAddButton = this.hasAddButton();\n this.checkColumns();\n }\n get dataValue() {\n const dataValue = super.dataValue;\n if (!dataValue || !Array.isArray(dataValue)) {\n return this.emptyValue;\n }\n return dataValue;\n }\n set dataValue(value) {\n super.dataValue = value;\n }\n get defaultSchema() {\n return DataGridComponent.schema();\n }\n get initEmpty() {\n return this.component.initEmpty || this.component.noFirstRow;\n }\n get initRows() {\n return this.builderMode || this.path === 'defaultValue' || !this.initEmpty;\n }\n get emptyValue() {\n return this.initEmpty ? [] : [{}];\n }\n get addAnotherPosition() {\n return lodash_1.default.get(this.component, 'addAnotherPosition', 'bottom');\n }\n get minLength() {\n if (this.hasRowGroups()) {\n return lodash_1.default.sum(this.getGroupSizes());\n }\n else {\n return lodash_1.default.get(this.component, 'validate.minLength', 0);\n }\n }\n get defaultValue() {\n const isBuilderMode = this.builderMode;\n const isEmptyInit = this.initEmpty;\n // Ensure we have one and only one row in builder mode.\n if (isBuilderMode || (isEmptyInit && !this.dataValue.length)) {\n return isEmptyInit && !isBuilderMode ? [] : [{}];\n }\n const value = super.defaultValue;\n let defaultValue;\n if (Array.isArray(value)) {\n defaultValue = value;\n }\n else if (value && (typeof value === 'object')) {\n defaultValue = [value];\n }\n else {\n defaultValue = this.emptyValue;\n }\n for (let dIndex = defaultValue.length; dIndex < this.minLength; dIndex++) {\n defaultValue.push({});\n }\n return defaultValue;\n }\n set disabled(disabled) {\n super.disabled = disabled;\n lodash_1.default.each(this.refs[`${this.datagridKey}-addRow`], (button) => {\n button.disabled = disabled;\n });\n lodash_1.default.each(this.refs[`${this.datagridKey}-removeRow`], (button) => {\n button.disabled = disabled;\n });\n }\n get disabled() {\n return super.disabled;\n }\n get datagridKey() {\n return `datagrid-${this.key}`;\n }\n get allowReorder() {\n return !this.options.readOnly && lodash_1.default.get(this.component, 'reorder', false);\n }\n get iteratableRows() {\n return this.rows.map((row, index) => ({\n components: row,\n data: this.dataValue[index],\n }));\n }\n /**\n * Split rows into chunks.\n * @param {Number[]} groups - array of numbers where each item is size of group\n * @param {Array<T>} rows - rows collection\n * @return {Array<T[]>}\n */\n getRowChunks(groups, rows) {\n const [, chunks] = groups.reduce(([startIndex, acc], size) => {\n const endIndex = startIndex + size;\n return [endIndex, [...acc, [startIndex, endIndex]]];\n }, [0, []]);\n return chunks.map(range => lodash_1.default.slice(rows, ...range));\n }\n /**\n * Create groups object.\n * Each key in object represents index of first row in group.\n * @return {Object}\n */\n getGroups() {\n const groups = lodash_1.default.get(this.component, 'rowGroups', []);\n const sizes = lodash_1.default.map(groups, 'numberOfRows').slice(0, -1);\n const indexes = sizes.reduce((groupIndexes, size) => {\n const last = groupIndexes[groupIndexes.length - 1];\n return groupIndexes.concat(last + size);\n }, [0]);\n return groups.reduce((gidxs, group, idx) => {\n return Object.assign(Object.assign({}, gidxs), { [indexes[idx]]: group });\n }, {});\n }\n /**\n * Retrun group sizes.\n * @return {Number[]}\n */\n getGroupSizes() {\n return lodash_1.default.map(lodash_1.default.get(this.component, 'rowGroups', []), 'numberOfRows');\n }\n hasRowGroups() {\n return lodash_1.default.get(this, 'component.enableRowGroups', false) && !this.builderMode;\n }\n totalRowsNumber(groups) {\n return lodash_1.default.sum(lodash_1.default.map(groups, 'numberOfRows'));\n }\n setStaticValue(n) {\n this.dataValue = lodash_1.default.range(n).map(() => ({}));\n }\n hasExtraColumn() {\n return (this.hasRemoveButtons() || this.canAddColumn);\n }\n hasRemoveButtons() {\n return !this.builderMode && !this.component.disableAddingRemovingRows &&\n !this.options.readOnly &&\n !this.disabled &&\n this.fullMode &&\n (this.dataValue.length > lodash_1.default.get(this.component, 'validate.minLength', 0));\n }\n hasTopSubmit() {\n return this.hasAddButton() && ['top', 'both'].includes(this.addAnotherPosition);\n }\n hasBottomSubmit() {\n return this.hasAddButton() && ['bottom', 'both'].includes(this.addAnotherPosition);\n }\n get canAddColumn() {\n return this.builderMode;\n }\n render() {\n const columns = this.getColumns();\n let columnExtra = 0;\n const hasRemoveButtons = this.hasRemoveButtons();\n if (this.component.reorder) {\n columnExtra++;\n }\n if (hasRemoveButtons) {\n columnExtra++;\n }\n if (this.canAddColumn) {\n columnExtra++;\n }\n const colWidth = Math.floor(12 / (columns.length + columnExtra));\n return super.render(this.renderTemplate('datagrid', {\n rows: this.getRows(),\n columns: columns,\n groups: this.hasRowGroups() ? this.getGroups() : [],\n visibleColumns: this.visibleColumns,\n hasToggle: lodash_1.default.get(this, 'component.groupToggle', false),\n hasHeader: this.hasHeader(),\n hasExtraColumn: this.hasExtraColumn(),\n hasAddButton: this.hasAddButton(),\n hasRemoveButtons,\n hasTopSubmit: this.hasTopSubmit(),\n hasBottomSubmit: this.hasBottomSubmit(),\n hasGroups: this.hasRowGroups(),\n numColumns: columns.length + (this.hasExtraColumn() ? 1 : 0),\n datagridKey: this.datagridKey,\n allowReorder: this.allowReorder,\n builder: this.builderMode,\n canAddColumn: this.canAddColumn,\n tabIndex: this.tabIndex,\n placeholder: this.renderTemplate('builderPlaceholder', {\n position: this.componentComponents.length,\n }),\n colWidth: colWidth.toString()\n }));\n }\n getRows() {\n return this.rows.map(row => {\n const components = {};\n lodash_1.default.each(row, (col, key) => {\n components[key] = col.render();\n });\n return components;\n });\n }\n getColumns() {\n return this.columns.filter((comp) => {\n return (!this.visibleColumns.hasOwnProperty(comp.key) || this.visibleColumns[comp.key]);\n });\n }\n hasHeader() {\n return this.component.components.reduce((hasHeader, col) => {\n // If any of the components has a title and it isn't hidden, display the header.\n return hasHeader || ((col.label || col.title) && !col.hideLabel);\n }, false);\n }\n loadRefs(element, refs) {\n super.loadRefs(element, refs);\n if (refs['messageContainer'] === 'single') {\n const container = lodash_1.default.last(element.querySelectorAll('[ref=messageContainer]'));\n this.refs['messageContainer'] = container || this.refs['messageContainer'];\n }\n }\n attach(element) {\n this.loadRefs(element, {\n [`${this.datagridKey}-row`]: 'multiple',\n [`${this.datagridKey}-tbody`]: 'single',\n [`${this.datagridKey}-addRow`]: 'multiple',\n [`${this.datagridKey}-removeRow`]: 'multiple',\n [`${this.datagridKey}-group-header`]: 'multiple',\n [this.datagridKey]: 'multiple',\n 'messageContainer': 'single'\n });\n if (this.allowReorder) {\n this.refs[`${this.datagridKey}-row`].forEach((row, index) => {\n row.dragInfo = { index };\n });\n if (dragula) {\n this.dragula = dragula([this.refs[`${this.datagridKey}-tbody`]], {\n moves: (_draggedElement, _oldParent, clickedElement) => {\n const clickedElementKey = clickedElement.getAttribute('data-key');\n const oldParentKey = _oldParent.getAttribute('data-key');\n //Check if the clicked button belongs to that container, if false, it belongs to the nested container\n if (oldParentKey === clickedElementKey) {\n return clickedElement.classList.contains('formio-drag-button');\n }\n }\n }).on('drop', this.onReorder.bind(this));\n this.dragula.on('cloned', (el, original) => {\n if (el && el.children && original && original.children) {\n lodash_1.default.each(original.children, (child, index) => {\n const styles = getComputedStyle(child, null);\n if (styles.cssText !== '') {\n el.children[index].style.cssText = styles.cssText;\n }\n else {\n const cssText = Object.values(styles).reduce((css, propertyName) => {\n return `${css}${propertyName}:${styles.getPropertyValue(propertyName)};`;\n }, '');\n el.children[index].style.cssText = cssText;\n }\n });\n }\n });\n }\n }\n this.refs[`${this.datagridKey}-addRow`].forEach((addButton) => {\n this.addEventListener(addButton, 'click', this.addRow.bind(this));\n });\n this.refs[`${this.datagridKey}-removeRow`].forEach((removeButton, index) => {\n this.addEventListener(removeButton, 'click', this.removeRow.bind(this, index));\n });\n if (this.hasRowGroups()) {\n this.refs.chunks = this.getRowChunks(this.getGroupSizes(), this.refs[`${this.datagridKey}-row`]);\n this.refs[`${this.datagridKey}-group-header`].forEach((header, index) => {\n this.addEventListener(header, 'click', () => this.toggleGroup(header, index));\n });\n }\n const columns = this.getColumns();\n const rowLength = columns.length;\n this.rows.forEach((row, rowIndex) => {\n let columnIndex = 0;\n columns.forEach((col) => {\n this.attachComponents(this.refs[this.datagridKey][(rowIndex * rowLength) + columnIndex], [this.rows[rowIndex][col.key]], this.getComponentsContainer());\n columnIndex++;\n });\n });\n return super.attach(element);\n }\n getComponentsContainer() {\n return this.component.components;\n }\n onReorder(element, _target, _source, sibling) {\n if (!element.dragInfo || (sibling && !sibling.dragInfo)) {\n console.warn('There is no Drag Info available for either dragged or sibling element');\n return;\n }\n const oldPosition = element.dragInfo.index;\n //should drop at next sibling position; no next sibling means drop to last position\n const newPosition = sibling ? sibling.dragInfo.index : this.dataValue.length;\n const movedBelow = newPosition > oldPosition;\n const dataValue = (0, utils_1.fastCloneDeep)(this.dataValue);\n const draggedRowData = dataValue[oldPosition];\n //insert element at new position\n dataValue.splice(newPosition, 0, draggedRowData);\n //remove element from old position (if was moved above, after insertion it's at +1 index)\n dataValue.splice(movedBelow ? oldPosition : oldPosition + 1, 1);\n //need to re-build rows to re-calculate indexes and other indexed fields for component instance (like rows for ex.)\n this.setValue(dataValue, { isReordered: true });\n this.rebuild();\n }\n focusOnNewRowElement(row) {\n Object.keys(row).find((key) => {\n const focusableElements = (0, utils_1.getFocusableElements)(row[key].element);\n if (focusableElements && focusableElements[0]) {\n focusableElements[0].focus();\n return true;\n }\n return false;\n });\n }\n addRow() {\n const index = this.rows.length;\n // Handle length mismatch between rows and dataValue\n if (this.dataValue.length === index) {\n this.dataValue.push({});\n }\n let row;\n const dataValue = this.dataValue;\n const defaultValue = this.defaultValue;\n if (this.initEmpty && defaultValue[index]) {\n row = defaultValue[index];\n dataValue[index] = row;\n }\n else {\n row = dataValue[index];\n }\n this.rows[index] = this.createRowComponents(row, index);\n this.emit('dataGridAddRow', {\n component: this.component,\n row\n });\n this.checkConditions();\n this.triggerChange();\n this.redraw().then(() => {\n this.focusOnNewRowElement(this.rows[index]);\n });\n }\n updateComponentsRowIndex(components, rowIndex) {\n components.forEach((component, colIndex) => {\n var _a;\n if ((_a = component.options) === null || _a === void 0 ? void 0 : _a.name) {\n const newName = `[${this.key}][${rowIndex}]`;\n component.options.name = component.options.name.replace(`[${this.key}][${component.rowIndex}]`, newName);\n }\n component.rowIndex = rowIndex;\n component.row = `${rowIndex}-${colIndex}`;\n component.path = this.calculateComponentPath(component);\n });\n }\n updateRowsComponents(rowIndex) {\n this.rows.slice(rowIndex).forEach((row, index) => {\n this.updateComponentsRowIndex(Object.values(row), rowIndex + index);\n });\n }\n removeRow(index) {\n this.splice(index, { isReordered: true });\n this.emit('dataGridDeleteRow', { index });\n const [row] = this.rows.splice(index, 1);\n this.removeRowComponents(row);\n this.updateRowsComponents(index);\n this.setValue(this.dataValue, { isReordered: true });\n this.redraw();\n }\n removeRowComponents(row) {\n lodash_1.default.each(row, (component) => this.removeComponent(component));\n }\n getRowValues() {\n return this.dataValue;\n }\n setRowComponentsData(rowIndex, rowData) {\n lodash_1.default.each(this.rows[rowIndex], (component) => {\n component.data = rowData;\n });\n }\n createRows(init, rebuild) {\n let added = false;\n const rowValues = this.getRowValues();\n // Create any missing rows.\n rowValues.forEach((row, index) => {\n if (!rebuild && this.rows[index]) {\n this.setRowComponentsData(index, row);\n }\n else {\n if (this.rows[index]) {\n this.removeRowComponents(this.rows[index]);\n }\n this.rows[index] = this.createRowComponents(row, index);\n added = true;\n }\n });\n // Delete any extra rows.\n const removedRows = this.rows.splice(rowValues.length);\n const removed = !!removedRows.length;\n // Delete components of extra rows (to make sure that this.components contain only components of exisiting rows)\n if (removed) {\n removedRows.forEach(row => this.removeRowComponents(row));\n }\n if (!init && (added || removed)) {\n this.redraw();\n }\n return added;\n }\n createRowComponents(row, rowIndex) {\n const components = {};\n this.tabIndex = 0;\n this.component.components.map((col, colIndex) => {\n const options = lodash_1.default.clone(this.options);\n options.name += `[${rowIndex}]`;\n options.row = `${rowIndex}-${colIndex}`;\n let columnComponent;\n if (this.builderMode) {\n col.id = col.id + rowIndex;\n columnComponent = col;\n }\n else {\n columnComponent = Object.assign(Object.assign({}, col), { id: (col.id + rowIndex) });\n }\n const component = this.createComponent(columnComponent, options, row);\n component.parentDisabled = !!this.disabled;\n component.rowIndex = rowIndex;\n component.inDataGrid = true;\n if (columnComponent.tabindex &&\n parseInt(columnComponent.tabindex) > this.tabIndex) {\n this.tabIndex = parseInt(columnComponent.tabindex);\n }\n components[col.key] = component;\n });\n return components;\n }\n /**\n * Checks the validity of this datagrid.\n *\n * @param data\n * @param dirty\n * @return {*}\n */\n checkValidity(data, dirty, row, silentCheck) {\n data = data || this.rootValue;\n row = row || this.data;\n if (!this.checkCondition(row, data)) {\n this.setCustomValidity('');\n return true;\n }\n if (!this.checkComponentValidity(data, dirty, row, { silentCheck })) {\n return false;\n }\n const isValid = this.checkRows('checkValidity', data, dirty, true, silentCheck);\n this.checkModal(isValid, dirty);\n return isValid;\n }\n checkColumns(data, flags = {}) {\n data = data || this.rootValue;\n let show = false;\n if (!this.rows || !this.rows.length) {\n return { rebuild: false, show: false };\n }\n if (this.builderMode) {\n return { rebuild: false, show: true };\n }\n const visibility = {};\n let logicRebuild = false;\n const dataValue = this.dataValue;\n this.rows.forEach((row, rowIndex) => {\n lodash_1.default.each(row, (col, key) => {\n if (col && (typeof col.checkConditions === 'function')) {\n const firstRowCheck = visibility[key] === undefined;\n visibility[key] = !!visibility[key] ||\n (col.checkConditions(data, flags, dataValue[rowIndex]) && col.type !== 'hidden');\n if (col.component.logic && firstRowCheck) {\n const compIndex = lodash_1.default.findIndex(this.columns, ['key', key]);\n if (!lodash_1.default.isEqual(this.columns[compIndex], col.component)) {\n logicRebuild = true;\n this.columns[compIndex] = col.component;\n }\n }\n }\n });\n });\n const rebuild = !lodash_1.default.isEqual(visibility, this.visibleColumns) || logicRebuild;\n lodash_1.default.each(visibility, (col) => {\n show |= col;\n });\n this.visibleColumns = visibility;\n return { rebuild, show };\n }\n checkComponentConditions(data, flags, row) {\n const isVisible = this.visible;\n // If table isn't visible, don't bother calculating columns.\n if (!super.checkComponentConditions(data, flags, row)) {\n return false;\n }\n const { rebuild, show } = this.checkColumns(data, flags);\n // Check if a rebuild is needed or the visibility changes.\n if (rebuild || !isVisible) {\n this.createRows(false, rebuild);\n }\n // Return if this table should show.\n return show;\n }\n setValue(value, flags = {}) {\n if (!value) {\n this.dataValue = this.defaultValue;\n this.createRows();\n return false;\n }\n if (!Array.isArray(value)) {\n if (typeof value === 'object') {\n value = [value];\n }\n else {\n this.createRows();\n value = [{}];\n }\n }\n // Make sure we always have at least one row.\n // NOTE: Removing this will break \"Public Configurations\" in portal. ;)\n if (value && !value.length && !this.initEmpty) {\n value.push({});\n }\n const isSettingSubmission = flags.fromSubmission && !lodash_1.default.isEqual(value, this.emptyValue);\n const changed = this.hasChanged(value, this.dataValue);\n this.dataValue = value;\n if (this.initRows || isSettingSubmission) {\n if (!this.createRows() && changed) {\n this.redraw();\n }\n }\n if (this.componentModal && isSettingSubmission) {\n this.componentModal.setValue(value);\n }\n this.rows.forEach((row, rowIndex) => {\n if (value.length <= rowIndex) {\n return;\n }\n lodash_1.default.each(row, (col) => {\n col.rowIndex = rowIndex;\n this.setNestedValue(col, value[rowIndex], flags);\n });\n });\n this.updateOnChange(flags, changed);\n return changed;\n }\n restoreComponentsContext() {\n this.rows.forEach((row, index) => lodash_1.default.forIn(row, (component) => component.data = this.dataValue[index]));\n }\n getComponent(path, fn) {\n path = Array.isArray(path) ? path : [path];\n const [key, ...remainingPath] = path;\n let result = [];\n if (lodash_1.default.isNumber(key) && remainingPath.length) {\n const compKey = remainingPath.pop();\n result = this.rows[key][compKey];\n // If the component is inside a Layout Component, try to find it among all the row's components\n if (!result) {\n Object.entries(this.rows[key]).forEach(([, comp]) => {\n if ('getComponent' in comp) {\n const possibleResult = comp.getComponent([compKey], fn);\n if (possibleResult) {\n result = possibleResult;\n }\n }\n });\n }\n if (result && lodash_1.default.isFunction(fn)) {\n fn(result, this.getComponents());\n }\n if (remainingPath.length && 'getComponent' in result) {\n return result.getComponent(remainingPath, fn);\n }\n return result;\n }\n if (!lodash_1.default.isString(key)) {\n return result;\n }\n this.everyComponent((component, components) => {\n if (component.component.key === key) {\n let comp = component;\n if (remainingPath.length > 0 && 'getComponent' in component) {\n comp = component.getComponent(remainingPath, fn);\n }\n else if (fn) {\n fn(component, components);\n }\n result = result.concat(comp);\n }\n });\n return result.length > 0 ? result : null;\n }\n toggleGroup(element, index) {\n element.classList.toggle('collapsed');\n lodash_1.default.each(this.refs.chunks[index], row => {\n row.classList.toggle('hidden');\n });\n }\n}\nexports[\"default\"] = DataGridComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/datagrid/DataGrid.js?");
5976
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst NestedArrayComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/nestedarray/NestedArrayComponent */ \"./lib/cjs/components/_classes/nestedarray/NestedArrayComponent.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst dragula_1 = __importDefault(__webpack_require__(/*! dragula */ \"./node_modules/dragula/dragula.js\"));\nclass DataGridComponent extends NestedArrayComponent_1.default {\n static schema(...extend) {\n return NestedArrayComponent_1.default.schema({\n label: 'Data Grid',\n key: 'dataGrid',\n type: 'datagrid',\n clearOnHide: true,\n input: true,\n tree: true,\n components: []\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Data Grid',\n icon: 'th',\n group: 'data',\n documentation: '/userguide/form-building/data-components#data-grid',\n weight: 30,\n schema: DataGridComponent.schema()\n };\n }\n constructor(...args) {\n super(...args);\n this.type = 'datagrid';\n this.tabIndex = 0;\n }\n init() {\n this.components = this.components || [];\n // Add new values based on minLength.\n this.rows = [];\n this.columns = [...this.component.components];\n if (this.initRows || !lodash_1.default.isEqual(this.dataValue, this.emptyValue)) {\n this.createRows(true);\n }\n this.visibleColumns = {};\n this.prevHasAddButton = this.hasAddButton();\n this.checkColumns();\n }\n get dataValue() {\n const dataValue = super.dataValue;\n if (!dataValue || !Array.isArray(dataValue)) {\n return this.emptyValue;\n }\n return dataValue;\n }\n set dataValue(value) {\n super.dataValue = value;\n }\n get defaultSchema() {\n return DataGridComponent.schema();\n }\n get initEmpty() {\n return this.component.initEmpty || this.component.noFirstRow;\n }\n get initRows() {\n return this.builderMode || this.path === 'defaultValue' || !this.initEmpty;\n }\n get emptyValue() {\n return this.initEmpty ? [] : [{}];\n }\n get addAnotherPosition() {\n return lodash_1.default.get(this.component, 'addAnotherPosition', 'bottom');\n }\n get minLength() {\n if (this.hasRowGroups()) {\n return lodash_1.default.sum(this.getGroupSizes());\n }\n else {\n return lodash_1.default.get(this.component, 'validate.minLength', 0);\n }\n }\n get defaultValue() {\n const isBuilderMode = this.builderMode;\n const isEmptyInit = this.initEmpty;\n // Ensure we have one and only one row in builder mode.\n if (isBuilderMode || (isEmptyInit && !this.dataValue.length)) {\n return isEmptyInit && !isBuilderMode ? [] : [{}];\n }\n const value = super.defaultValue;\n let defaultValue;\n if (Array.isArray(value)) {\n defaultValue = value;\n }\n else if (value && (typeof value === 'object')) {\n defaultValue = [value];\n }\n else {\n defaultValue = this.emptyValue;\n }\n for (let dIndex = defaultValue.length; dIndex < this.minLength; dIndex++) {\n defaultValue.push({});\n }\n return defaultValue;\n }\n set disabled(disabled) {\n super.disabled = disabled;\n lodash_1.default.each(this.refs[`${this.datagridKey}-addRow`], (button) => {\n button.disabled = disabled;\n });\n lodash_1.default.each(this.refs[`${this.datagridKey}-removeRow`], (button) => {\n button.disabled = disabled;\n });\n }\n get disabled() {\n return super.disabled;\n }\n get datagridKey() {\n return `datagrid-${this.key}`;\n }\n get allowReorder() {\n return !this.options.readOnly && lodash_1.default.get(this.component, 'reorder', false);\n }\n get iteratableRows() {\n return this.rows.map((row, index) => ({\n components: row,\n data: this.dataValue[index],\n }));\n }\n /**\n * Split rows into chunks.\n * @param {Number[]} groups - array of numbers where each item is size of group\n * @param {Array<T>} rows - rows collection\n * @return {Array<T[]>}\n */\n getRowChunks(groups, rows) {\n const [, chunks] = groups.reduce(([startIndex, acc], size) => {\n const endIndex = startIndex + size;\n return [endIndex, [...acc, [startIndex, endIndex]]];\n }, [0, []]);\n return chunks.map(range => lodash_1.default.slice(rows, ...range));\n }\n /**\n * Create groups object.\n * Each key in object represents index of first row in group.\n * @return {Object}\n */\n getGroups() {\n const groups = lodash_1.default.get(this.component, 'rowGroups', []);\n const sizes = lodash_1.default.map(groups, 'numberOfRows').slice(0, -1);\n const indexes = sizes.reduce((groupIndexes, size) => {\n const last = groupIndexes[groupIndexes.length - 1];\n return groupIndexes.concat(last + size);\n }, [0]);\n return groups.reduce((gidxs, group, idx) => {\n return Object.assign(Object.assign({}, gidxs), { [indexes[idx]]: group });\n }, {});\n }\n /**\n * Retrun group sizes.\n * @return {Number[]}\n */\n getGroupSizes() {\n return lodash_1.default.map(lodash_1.default.get(this.component, 'rowGroups', []), 'numberOfRows');\n }\n hasRowGroups() {\n return lodash_1.default.get(this, 'component.enableRowGroups', false) && !this.builderMode;\n }\n totalRowsNumber(groups) {\n return lodash_1.default.sum(lodash_1.default.map(groups, 'numberOfRows'));\n }\n setStaticValue(n) {\n this.dataValue = lodash_1.default.range(n).map(() => ({}));\n }\n hasExtraColumn() {\n return (this.hasRemoveButtons() || this.canAddColumn);\n }\n hasRemoveButtons() {\n return !this.builderMode && !this.component.disableAddingRemovingRows &&\n !this.options.readOnly &&\n !this.disabled &&\n this.fullMode &&\n (this.dataValue.length > lodash_1.default.get(this.component, 'validate.minLength', 0));\n }\n hasTopSubmit() {\n return this.hasAddButton() && ['top', 'both'].includes(this.addAnotherPosition);\n }\n hasBottomSubmit() {\n return this.hasAddButton() && ['bottom', 'both'].includes(this.addAnotherPosition);\n }\n get canAddColumn() {\n return this.builderMode;\n }\n render() {\n const columns = this.getColumns();\n let columnExtra = 0;\n const hasRemoveButtons = this.hasRemoveButtons();\n if (this.component.reorder) {\n columnExtra++;\n }\n if (hasRemoveButtons) {\n columnExtra++;\n }\n if (this.canAddColumn) {\n columnExtra++;\n }\n const colWidth = Math.floor(12 / (columns.length + columnExtra));\n return super.render(this.renderTemplate('datagrid', {\n rows: this.getRows(),\n columns: columns,\n groups: this.hasRowGroups() ? this.getGroups() : [],\n visibleColumns: this.visibleColumns,\n hasToggle: lodash_1.default.get(this, 'component.groupToggle', false),\n hasHeader: this.hasHeader(),\n hasExtraColumn: this.hasExtraColumn(),\n hasAddButton: this.hasAddButton(),\n hasRemoveButtons,\n hasTopSubmit: this.hasTopSubmit(),\n hasBottomSubmit: this.hasBottomSubmit(),\n hasGroups: this.hasRowGroups(),\n numColumns: columns.length + (this.hasExtraColumn() ? 1 : 0),\n datagridKey: this.datagridKey,\n allowReorder: this.allowReorder,\n builder: this.builderMode,\n canAddColumn: this.canAddColumn,\n tabIndex: this.tabIndex,\n placeholder: this.renderTemplate('builderPlaceholder', {\n position: this.componentComponents.length,\n }),\n colWidth: colWidth.toString()\n }));\n }\n getRows() {\n return this.rows.map(row => {\n const components = {};\n lodash_1.default.each(row, (col, key) => {\n components[key] = col.render();\n });\n return components;\n });\n }\n getColumns() {\n return this.columns.filter((comp) => {\n return (!this.visibleColumns.hasOwnProperty(comp.key) || this.visibleColumns[comp.key]);\n });\n }\n hasHeader() {\n return this.component.components.reduce((hasHeader, col) => {\n // If any of the components has a title and it isn't hidden, display the header.\n return hasHeader || ((col.label || col.title) && !col.hideLabel);\n }, false);\n }\n loadRefs(element, refs) {\n super.loadRefs(element, refs);\n if (refs['messageContainer'] === 'single') {\n const container = lodash_1.default.last(element.querySelectorAll('[ref=messageContainer]'));\n this.refs['messageContainer'] = container || this.refs['messageContainer'];\n }\n }\n attach(element) {\n this.loadRefs(element, {\n [`${this.datagridKey}-row`]: 'multiple',\n [`${this.datagridKey}-tbody`]: 'single',\n [`${this.datagridKey}-addRow`]: 'multiple',\n [`${this.datagridKey}-removeRow`]: 'multiple',\n [`${this.datagridKey}-group-header`]: 'multiple',\n [this.datagridKey]: 'multiple',\n 'messageContainer': 'single'\n });\n if (this.allowReorder) {\n this.refs[`${this.datagridKey}-row`].forEach((row, index) => {\n row.dragInfo = { index };\n });\n if (dragula_1.default) {\n this.dragula = (0, dragula_1.default)([this.refs[`${this.datagridKey}-tbody`]], {\n moves: (_draggedElement, _oldParent, clickedElement) => {\n const clickedElementKey = clickedElement.getAttribute('data-key');\n const oldParentKey = _oldParent.getAttribute('data-key');\n //Check if the clicked button belongs to that container, if false, it belongs to the nested container\n if (oldParentKey === clickedElementKey) {\n return clickedElement.classList.contains('formio-drag-button');\n }\n }\n }).on('drop', this.onReorder.bind(this));\n this.dragula.on('cloned', (el, original) => {\n if (el && el.children && original && original.children) {\n lodash_1.default.each(original.children, (child, index) => {\n const styles = getComputedStyle(child, null);\n if (styles.cssText !== '') {\n el.children[index].style.cssText = styles.cssText;\n }\n else {\n const cssText = Object.values(styles).reduce((css, propertyName) => {\n return `${css}${propertyName}:${styles.getPropertyValue(propertyName)};`;\n }, '');\n el.children[index].style.cssText = cssText;\n }\n });\n }\n });\n }\n }\n this.refs[`${this.datagridKey}-addRow`].forEach((addButton) => {\n this.addEventListener(addButton, 'click', this.addRow.bind(this));\n });\n this.refs[`${this.datagridKey}-removeRow`].forEach((removeButton, index) => {\n this.addEventListener(removeButton, 'click', this.removeRow.bind(this, index));\n });\n if (this.hasRowGroups()) {\n this.refs.chunks = this.getRowChunks(this.getGroupSizes(), this.refs[`${this.datagridKey}-row`]);\n this.refs[`${this.datagridKey}-group-header`].forEach((header, index) => {\n this.addEventListener(header, 'click', () => this.toggleGroup(header, index));\n });\n }\n const columns = this.getColumns();\n const rowLength = columns.length;\n this.rows.forEach((row, rowIndex) => {\n let columnIndex = 0;\n columns.forEach((col) => {\n this.attachComponents(this.refs[this.datagridKey][(rowIndex * rowLength) + columnIndex], [this.rows[rowIndex][col.key]], this.getComponentsContainer());\n columnIndex++;\n });\n });\n return super.attach(element);\n }\n getComponentsContainer() {\n return this.component.components;\n }\n onReorder(element, _target, _source, sibling) {\n if (!element.dragInfo || (sibling && !sibling.dragInfo)) {\n console.warn('There is no Drag Info available for either dragged or sibling element');\n return;\n }\n const oldPosition = element.dragInfo.index;\n //should drop at next sibling position; no next sibling means drop to last position\n const newPosition = sibling ? sibling.dragInfo.index : this.dataValue.length;\n const movedBelow = newPosition > oldPosition;\n const dataValue = (0, utils_1.fastCloneDeep)(this.dataValue);\n const draggedRowData = dataValue[oldPosition];\n //insert element at new position\n dataValue.splice(newPosition, 0, draggedRowData);\n //remove element from old position (if was moved above, after insertion it's at +1 index)\n dataValue.splice(movedBelow ? oldPosition : oldPosition + 1, 1);\n //need to re-build rows to re-calculate indexes and other indexed fields for component instance (like rows for ex.)\n this.setValue(dataValue, { isReordered: true });\n this.rebuild();\n }\n focusOnNewRowElement(row) {\n Object.keys(row).find((key) => {\n const focusableElements = (0, utils_1.getFocusableElements)(row[key].element);\n if (focusableElements && focusableElements[0]) {\n focusableElements[0].focus();\n return true;\n }\n return false;\n });\n }\n addRow() {\n const index = this.rows.length;\n // Handle length mismatch between rows and dataValue\n if (this.dataValue.length === index) {\n this.dataValue.push({});\n }\n let row;\n const dataValue = this.dataValue;\n const defaultValue = this.defaultValue;\n if (this.initEmpty && defaultValue[index]) {\n row = defaultValue[index];\n dataValue[index] = row;\n }\n else {\n row = dataValue[index];\n }\n this.rows[index] = this.createRowComponents(row, index);\n this.emit('dataGridAddRow', {\n component: this.component,\n row\n });\n this.checkConditions();\n this.triggerChange();\n this.redraw().then(() => {\n this.focusOnNewRowElement(this.rows[index]);\n });\n }\n updateComponentsRowIndex(components, rowIndex) {\n components.forEach((component, colIndex) => {\n var _a;\n if ((_a = component.options) === null || _a === void 0 ? void 0 : _a.name) {\n const newName = `[${this.key}][${rowIndex}]`;\n component.options.name = component.options.name.replace(`[${this.key}][${component.rowIndex}]`, newName);\n }\n component.rowIndex = rowIndex;\n component.row = `${rowIndex}-${colIndex}`;\n component.path = this.calculateComponentPath(component);\n });\n }\n updateRowsComponents(rowIndex) {\n this.rows.slice(rowIndex).forEach((row, index) => {\n this.updateComponentsRowIndex(Object.values(row), rowIndex + index);\n });\n }\n removeRow(index) {\n this.splice(index, { isReordered: true });\n this.emit('dataGridDeleteRow', { index });\n const [row] = this.rows.splice(index, 1);\n this.removeRowComponents(row);\n this.updateRowsComponents(index);\n this.setValue(this.dataValue, { isReordered: true });\n this.redraw();\n }\n removeRowComponents(row) {\n lodash_1.default.each(row, (component) => this.removeComponent(component));\n }\n getRowValues() {\n return this.dataValue;\n }\n setRowComponentsData(rowIndex, rowData) {\n lodash_1.default.each(this.rows[rowIndex], (component) => {\n component.data = rowData;\n });\n }\n createRows(init, rebuild) {\n let added = false;\n const rowValues = this.getRowValues();\n // Create any missing rows.\n rowValues.forEach((row, index) => {\n if (!rebuild && this.rows[index]) {\n this.setRowComponentsData(index, row);\n }\n else {\n if (this.rows[index]) {\n this.removeRowComponents(this.rows[index]);\n }\n this.rows[index] = this.createRowComponents(row, index);\n added = true;\n }\n });\n // Delete any extra rows.\n const removedRows = this.rows.splice(rowValues.length);\n const removed = !!removedRows.length;\n // Delete components of extra rows (to make sure that this.components contain only components of exisiting rows)\n if (removed) {\n removedRows.forEach(row => this.removeRowComponents(row));\n }\n if (!init && (added || removed)) {\n this.redraw();\n }\n return added;\n }\n createRowComponents(row, rowIndex) {\n const components = {};\n this.tabIndex = 0;\n this.component.components.map((col, colIndex) => {\n const options = lodash_1.default.clone(this.options);\n options.name += `[${rowIndex}]`;\n options.row = `${rowIndex}-${colIndex}`;\n let columnComponent;\n if (this.builderMode) {\n col.id = col.id + rowIndex;\n columnComponent = col;\n }\n else {\n columnComponent = Object.assign(Object.assign({}, col), { id: (col.id + rowIndex) });\n }\n const component = this.createComponent(columnComponent, options, row);\n component.parentDisabled = !!this.disabled;\n component.rowIndex = rowIndex;\n component.inDataGrid = true;\n if (columnComponent.tabindex &&\n parseInt(columnComponent.tabindex) > this.tabIndex) {\n this.tabIndex = parseInt(columnComponent.tabindex);\n }\n components[col.key] = component;\n });\n return components;\n }\n /**\n * Checks the validity of this datagrid.\n *\n * @param data\n * @param dirty\n * @return {*}\n */\n checkValidity(data, dirty, row, silentCheck) {\n data = data || this.rootValue;\n row = row || this.data;\n if (!this.checkCondition(row, data)) {\n this.setCustomValidity('');\n return true;\n }\n if (!this.checkComponentValidity(data, dirty, row, { silentCheck })) {\n return false;\n }\n const isValid = this.checkRows('checkValidity', data, dirty, true, silentCheck);\n this.checkModal(isValid, dirty);\n return isValid;\n }\n checkColumns(data, flags = {}) {\n data = data || this.rootValue;\n let show = false;\n if (!this.rows || !this.rows.length) {\n return { rebuild: false, show: false };\n }\n if (this.builderMode) {\n return { rebuild: false, show: true };\n }\n const visibility = {};\n let logicRebuild = false;\n const dataValue = this.dataValue;\n this.rows.forEach((row, rowIndex) => {\n lodash_1.default.each(row, (col, key) => {\n if (col && (typeof col.checkConditions === 'function')) {\n const firstRowCheck = visibility[key] === undefined;\n visibility[key] = !!visibility[key] ||\n (col.checkConditions(data, flags, dataValue[rowIndex]) && col.type !== 'hidden');\n if (col.component.logic && firstRowCheck) {\n const compIndex = lodash_1.default.findIndex(this.columns, ['key', key]);\n if (!lodash_1.default.isEqual(this.columns[compIndex], col.component)) {\n logicRebuild = true;\n this.columns[compIndex] = col.component;\n }\n }\n }\n });\n });\n const rebuild = !lodash_1.default.isEqual(visibility, this.visibleColumns) || logicRebuild;\n lodash_1.default.each(visibility, (col) => {\n show |= col;\n });\n this.visibleColumns = visibility;\n return { rebuild, show };\n }\n checkComponentConditions(data, flags, row) {\n const isVisible = this.visible;\n // If table isn't visible, don't bother calculating columns.\n if (!super.checkComponentConditions(data, flags, row)) {\n return false;\n }\n const { rebuild, show } = this.checkColumns(data, flags);\n // Check if a rebuild is needed or the visibility changes.\n if (rebuild || !isVisible) {\n this.createRows(false, rebuild);\n }\n // Return if this table should show.\n return show;\n }\n setValue(value, flags = {}) {\n if (!value) {\n this.dataValue = this.defaultValue;\n this.createRows();\n return false;\n }\n if (!Array.isArray(value)) {\n if (typeof value === 'object') {\n value = [value];\n }\n else {\n this.createRows();\n value = [{}];\n }\n }\n // Make sure we always have at least one row.\n // NOTE: Removing this will break \"Public Configurations\" in portal. ;)\n if (value && !value.length && !this.initEmpty) {\n value.push({});\n }\n const isSettingSubmission = flags.fromSubmission && !lodash_1.default.isEqual(value, this.emptyValue);\n const changed = this.hasChanged(value, this.dataValue);\n this.dataValue = value;\n if (this.initRows || isSettingSubmission) {\n if (!this.createRows() && changed) {\n this.redraw();\n }\n }\n if (this.componentModal && isSettingSubmission) {\n this.componentModal.setValue(value);\n }\n this.rows.forEach((row, rowIndex) => {\n if (value.length <= rowIndex) {\n return;\n }\n lodash_1.default.each(row, (col) => {\n col.rowIndex = rowIndex;\n this.setNestedValue(col, value[rowIndex], flags);\n });\n });\n this.updateOnChange(flags, changed);\n return changed;\n }\n restoreComponentsContext() {\n this.rows.forEach((row, index) => lodash_1.default.forIn(row, (component) => component.data = this.dataValue[index]));\n }\n getComponent(path, fn) {\n path = Array.isArray(path) ? path : [path];\n const [key, ...remainingPath] = path;\n let result = [];\n if (lodash_1.default.isNumber(key) && remainingPath.length) {\n const compKey = remainingPath.pop();\n result = this.rows[key][compKey];\n // If the component is inside a Layout Component, try to find it among all the row's components\n if (!result) {\n Object.entries(this.rows[key]).forEach(([, comp]) => {\n if ('getComponent' in comp) {\n const possibleResult = comp.getComponent([compKey], fn);\n if (possibleResult) {\n result = possibleResult;\n }\n }\n });\n }\n if (result && lodash_1.default.isFunction(fn)) {\n fn(result, this.getComponents());\n }\n if (remainingPath.length && 'getComponent' in result) {\n return result.getComponent(remainingPath, fn);\n }\n return result;\n }\n if (!lodash_1.default.isString(key)) {\n return result;\n }\n this.everyComponent((component, components) => {\n if (component.component.key === key) {\n let comp = component;\n if (remainingPath.length > 0 && 'getComponent' in component) {\n comp = component.getComponent(remainingPath, fn);\n }\n else if (fn) {\n fn(component, components);\n }\n result = result.concat(comp);\n }\n });\n return result.length > 0 ? result : null;\n }\n toggleGroup(element, index) {\n element.classList.toggle('collapsed');\n lodash_1.default.each(this.refs.chunks[index], row => {\n row.classList.toggle('hidden');\n });\n }\n}\nexports[\"default\"] = DataGridComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/datagrid/DataGrid.js?");
5987
5977
 
5988
5978
  /***/ }),
5989
5979
 
@@ -6918,7 +6908,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
6918
6908
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6919
6909
 
6920
6910
  "use strict";
6921
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst Formio_1 = __webpack_require__(/*! ../../Formio */ \"./lib/cjs/Formio.js\");\nconst ListComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/list/ListComponent */ \"./lib/cjs/components/_classes/list/ListComponent.js\"));\nconst Form_1 = __importDefault(__webpack_require__(/*! ../../Form */ \"./lib/cjs/Form.js\"));\nconst native_promise_only_1 = __importDefault(__webpack_require__(/*! native-promise-only */ \"./node_modules/native-promise-only/lib/npo.src.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nlet Choices;\nif (typeof window !== 'undefined') {\n Choices = (__webpack_require__(/*! ../../utils/ChoicesWrapper */ \"./lib/cjs/utils/ChoicesWrapper.js\")[\"default\"]);\n}\nclass SelectComponent extends ListComponent_1.default {\n static schema(...extend) {\n return ListComponent_1.default.schema({\n type: 'select',\n label: 'Select',\n key: 'select',\n idPath: 'id',\n data: {\n values: [{ label: '', value: '' }],\n json: '',\n url: '',\n resource: '',\n custom: ''\n },\n clearOnRefresh: false,\n limit: 100,\n valueProperty: '',\n lazyLoad: true,\n filter: '',\n searchEnabled: true,\n searchDebounce: 0.3,\n searchField: '',\n minSearch: 0,\n readOnlyValue: false,\n selectFields: '',\n selectThreshold: 0.3,\n uniqueOptions: false,\n tableView: true,\n fuseOptions: {\n include: 'score',\n threshold: 0.3,\n },\n indexeddb: {\n filter: {}\n },\n customOptions: {},\n useExactSearch: false,\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Select',\n group: 'basic',\n icon: 'th-list',\n weight: 70,\n documentation: '/userguide/form-building/form-components#select',\n schema: SelectComponent.schema()\n };\n }\n init() {\n super.init();\n this.templateData = {};\n this.validators = this.validators.concat(['select', 'onlyAvailableItems']);\n // Trigger an update.\n let updateArgs = [];\n const triggerUpdate = lodash_1.default.debounce((...args) => {\n updateArgs = [];\n return this.updateItems.apply(this, args);\n }, 100);\n this.triggerUpdate = (...args) => {\n // Make sure we always resolve the previous promise before reassign it\n if (typeof this.itemsLoadedResolve === 'function') {\n this.itemsLoadedResolve();\n }\n this.itemsLoaded = new native_promise_only_1.default((resolve) => {\n this.itemsLoadedResolve = resolve;\n });\n if (args.length) {\n updateArgs = args;\n }\n return triggerUpdate(...updateArgs);\n };\n // Keep track of the select options.\n this.selectOptions = [];\n if (this.itemsFromUrl) {\n this.isFromSearch = false;\n this.searchServerCount = null;\n this.defaultServerCount = null;\n this.isScrollLoading = false;\n this.searchDownloadedResources = [];\n this.defaultDownloadedResources = [];\n }\n // If this component has been activated.//\n this.activated = false;\n this.itemsLoaded = new native_promise_only_1.default((resolve) => {\n this.itemsLoadedResolve = resolve;\n });\n if (this.isHtmlRenderMode()) {\n this.activate();\n }\n // Get the template keys for this select component.\n this.getTemplateKeys();\n }\n get dataReady() {\n // If the root submission has been set, and we are still not attached, then assume\n // that our data is ready.\n if (this.root &&\n this.root.submissionSet &&\n !this.attached) {\n return native_promise_only_1.default.resolve();\n }\n return this.itemsLoaded;\n }\n get defaultSchema() {\n return SelectComponent.schema();\n }\n get emptyValue() {\n if (this.component.multiple) {\n return [];\n }\n // if select has JSON data source type, we are defining if empty value would be an object or a string by checking JSON's first item\n if (this.component.dataSrc === 'json' && this.component.data.json) {\n const firstItem = this.component.data.json[0];\n let firstValue;\n if (this.valueProperty) {\n firstValue = lodash_1.default.get(firstItem, this.valueProperty);\n }\n else {\n firstValue = firstItem;\n }\n if (firstValue && typeof firstValue === 'string') {\n return '';\n }\n else {\n return {};\n }\n }\n if (this.valueProperty) {\n return '';\n }\n return {};\n }\n get valueProperty() {\n if (this.component.valueProperty) {\n return this.component.valueProperty;\n }\n // Force values datasource to use values without actually setting it on the component settings.\n if (this.component.dataSrc === 'values') {\n return 'value';\n }\n return '';\n }\n get inputInfo() {\n const info = super.elementInfo();\n info.type = 'select';\n info.changeEvent = 'change';\n return info;\n }\n get isSelectResource() {\n return this.component.dataSrc === 'resource';\n }\n get itemsFromUrl() {\n return this.isSelectResource || this.isSelectURL;\n }\n get isInfiniteScrollProvided() {\n return this.itemsFromUrl;\n }\n get shouldDisabled() {\n return super.shouldDisabled || this.parentDisabled;\n }\n isEntireObjectDisplay() {\n return this.component.dataSrc === 'resource' && this.valueProperty === 'data';\n }\n selectValueAndLabel(data) {\n const value = this.getOptionValue((this.isEntireObjectDisplay() && !this.itemValue(data)) ? data : this.itemValue(data));\n return {\n value,\n label: this.itemTemplate((this.isEntireObjectDisplay() && !lodash_1.default.isObject(data.data)) ? { data: data } : data, value)\n };\n }\n itemTemplate(data, value) {\n if (!lodash_1.default.isNumber(data) && lodash_1.default.isEmpty(data)) {\n return '';\n }\n // If they wish to show the value in read only mode, then just return the itemValue here.\n if (this.options.readOnly && this.component.readOnlyValue) {\n return this.itemValue(data);\n }\n // Perform a fast interpretation if we should not use the template.\n if (data && !this.component.template) {\n const itemLabel = data.label || data;\n const value = (typeof itemLabel === 'string') ? this.t(itemLabel, { _userInput: true }) : itemLabel;\n return this.sanitize(value, this.shouldSanitizeValue);\n }\n if (this.component.multiple ? this.dataValue.find((val) => value === val) : (this.dataValue === value)) {\n const selectData = this.selectData;\n if (selectData) {\n const templateValue = this.component.reference && (value === null || value === void 0 ? void 0 : value._id) ? value._id.toString() : value;\n if (!this.templateData || !this.templateData[templateValue]) {\n this.getOptionTemplate(data, value);\n }\n if (this.component.multiple) {\n if (selectData[templateValue]) {\n data = selectData[templateValue];\n }\n }\n else {\n data = selectData;\n }\n }\n }\n if (typeof data === 'string' || typeof data === 'number') {\n return this.sanitize(this.t(data, { _userInput: true }), this.shouldSanitizeValue);\n }\n if (Array.isArray(data)) {\n return data.map((val) => {\n if (typeof val === 'string' || typeof val === 'number') {\n return this.sanitize(this.t(val, { _userInput: true }), this.shouldSanitizeValue);\n }\n return val;\n });\n }\n if (data.data) {\n // checking additional fields in the template for the selected Entire Object option\n const hasNestedFields = /item\\.data\\.\\w*/g.test(this.component.template);\n data.data = this.isEntireObjectDisplay() && lodash_1.default.isObject(data.data) && !hasNestedFields\n ? JSON.stringify(data.data)\n : data.data;\n }\n return super.itemTemplate(data, value);\n }\n /**\n * Adds an option to the select dropdown.\n *\n * @param value\n * @param label\n */\n addOption(value, label, attrs = {}, id = (0, utils_1.getRandomComponentId)()) {\n if (lodash_1.default.isNil(label))\n return;\n const idPath = this.component.idPath\n ? this.component.idPath.split('.').reduceRight((obj, key) => ({ [key]: obj }), id)\n : {};\n const option = Object.assign({ value: this.getOptionValue(value), label }, idPath);\n const skipOption = this.component.uniqueOptions\n ? !!this.selectOptions.find((selectOption) => lodash_1.default.isEqual(selectOption.value, option.value))\n : false;\n if (skipOption) {\n return;\n }\n if (value) {\n this.selectOptions.push(option);\n }\n if (this.refs.selectContainer && (this.component.widget === 'html5')) {\n // Replace an empty Object value to an empty String.\n if (option.value && lodash_1.default.isObject(option.value) && lodash_1.default.isEmpty(option.value)) {\n option.value = '';\n }\n // Add element to option so we can reference it later.\n const div = document.createElement('div');\n div.innerHTML = this.sanitize(this.renderTemplate('selectOption', {\n selected: lodash_1.default.isEqual(this.getOptionValue(this.dataValue), option.value),\n option,\n attrs,\n id,\n useId: (this.valueProperty === '' || this.isEntireObjectDisplay()) && lodash_1.default.isObject(value) && id,\n }), this.shouldSanitizeValue).trim();\n option.element = div.firstChild;\n this.refs.selectContainer.appendChild(option.element);\n }\n }\n addValueOptions(items) {\n items = items || [];\n let added = false;\n let data = this.dataValue;\n // preset submission value with value property before request.\n if (this.options.pdf && !items.length && this.component.dataSrc === 'url' && this.valueProperty) {\n data = Array.isArray(data)\n ? data.map(item => lodash_1.default.set({}, this.valueProperty, item))\n : lodash_1.default.set({}, this.valueProperty, data);\n }\n if (!this.selectOptions.length) {\n // Add the currently selected choices if they don't already exist.\n const currentChoices = Array.isArray(data) && this.component.multiple ? data : [data];\n added = this.addCurrentChoices(currentChoices, items);\n if (!added && !this.component.multiple) {\n this.addPlaceholder();\n }\n }\n return added;\n }\n disableInfiniteScroll() {\n if (!this.downloadedResources) {\n return;\n }\n this.downloadedResources.serverCount = this.downloadedResources.length;\n this.serverCount = this.downloadedResources.length;\n }\n /* eslint-disable max-statements */\n setItems(items, fromSearch) {\n var _a, _b;\n // If the items is a string, then parse as JSON.\n if (typeof items == 'string') {\n try {\n items = JSON.parse(items);\n }\n catch (err) {\n console.warn(err.message);\n items = [];\n }\n }\n // Allow js processing (needed for form builder)\n if (this.component.onSetItems && typeof this.component.onSetItems === 'function') {\n const newItems = this.component.onSetItems(this, items);\n if (newItems) {\n items = newItems;\n }\n }\n if (!this.choices && this.refs.selectContainer) {\n this.empty(this.refs.selectContainer);\n }\n // If they provided select values, then we need to get them instead.\n if (this.component.selectValues) {\n items = lodash_1.default.get(items, this.component.selectValues, items) || [];\n }\n let areItemsEqual;\n if (this.itemsFromUrl) {\n areItemsEqual = this.isSelectURL ? lodash_1.default.isEqual(items, this.downloadedResources) : false;\n const areItemsEnded = this.component.limit > items.length;\n const areItemsDownloaded = areItemsEqual\n && this.downloadedResources\n && this.downloadedResources.length === items.length;\n if (areItemsEnded) {\n this.disableInfiniteScroll();\n }\n else if (areItemsDownloaded) {\n this.selectOptions = [];\n }\n else {\n this.serverCount = items.serverCount;\n }\n }\n if (this.isScrollLoading && items) {\n if (!areItemsEqual) {\n this.downloadedResources = this.downloadedResources\n ? this.downloadedResources.concat(items)\n : items;\n }\n this.downloadedResources.serverCount = items.serverCount || this.downloadedResources.serverCount;\n }\n else {\n this.downloadedResources = items || [];\n this.selectOptions = [];\n // If there is new select option with same id as already selected, set the new one\n if (!lodash_1.default.isEmpty(this.dataValue) && this.component.idPath) {\n const selectedOptionId = lodash_1.default.get(this.dataValue, this.component.idPath, null);\n const newOptionWithSameId = !lodash_1.default.isNil(selectedOptionId) && items.find(item => {\n const itemId = lodash_1.default.get(item, this.component.idPath);\n return itemId === selectedOptionId;\n });\n if (newOptionWithSameId) {\n this.setValue(newOptionWithSameId);\n }\n }\n }\n // Add the value options.\n if (!fromSearch) {\n this.addValueOptions(items);\n }\n if (this.component.widget === 'html5' && !this.component.placeholder) {\n this.addOption(null, '');\n }\n // Iterate through each of the items.\n lodash_1.default.each(items, (item, index) => {\n // preventing references of the components inside the form to the parent form when building forms\n if (this.root && this.root.options.editForm && this.root.options.editForm._id && this.root.options.editForm._id === item._id)\n return;\n const itemValueAndLabel = this.selectValueAndLabel(item);\n this.addOption(itemValueAndLabel.value, itemValueAndLabel.label, {}, lodash_1.default.get(item, this.component.idPath, String(index)));\n });\n if (this.choices) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n else if (this.loading) {\n // Re-attach select input.\n // this.appendTo(this.refs.input[0], this.selectContainer);\n }\n // We are no longer loading.\n this.isScrollLoading = false;\n this.loading = false;\n const searching = fromSearch && ((_b = (_a = this.choices) === null || _a === void 0 ? void 0 : _a.input) === null || _b === void 0 ? void 0 : _b.isFocussed);\n if (!searching) {\n // If a value is provided, then select it.\n if (!this.isEmpty()) {\n this.setValue(this.dataValue, {\n noUpdateEvent: true\n });\n }\n else if (this.shouldAddDefaultValue && !this.options.readOnly) {\n // If a default value is provided then select it.\n const defaultValue = this.defaultValue;\n if (!this.isEmpty(defaultValue)) {\n this.setValue(defaultValue);\n }\n }\n }\n // Say we are done loading the items.\n this.itemsLoadedResolve();\n }\n getSingleItemValueForHTMLMode(data) {\n var _a;\n const option = (_a = this.selectOptions) === null || _a === void 0 ? void 0 : _a.find(({ value }) => lodash_1.default.isEqual(value, data));\n if (option) {\n return option.label || data;\n }\n return data;\n }\n itemValueForHTMLMode(value) {\n if (!this.isHtmlRenderMode()) {\n return super.itemValueForHTMLMode(value);\n }\n if (Array.isArray(value)) {\n const values = value.map(item => Array.isArray(item)\n ? this.itemValueForHTMLMode(item)\n : this.getSingleItemValueForHTMLMode(item));\n return values.join(', ');\n }\n return this.getSingleItemValueForHTMLMode(value);\n }\n /* eslint-enable max-statements */\n get defaultValue() {\n let defaultValue = super.defaultValue;\n if (!defaultValue && (this.component.defaultValue === false || this.component.defaultValue === 0)) {\n defaultValue = this.component.defaultValue;\n }\n return defaultValue;\n }\n getTemplateKeys() {\n this.templateKeys = [];\n if (this.options.readOnly && this.component.template) {\n const keys = this.component.template.match(/({{\\s*(.*?)\\s*}})/g);\n if (keys) {\n keys.forEach((key) => {\n const propKey = key.match(/{{\\s*item\\.(.*?)\\s*}}/);\n if (propKey && propKey.length > 1) {\n this.templateKeys.push(propKey[1]);\n }\n });\n }\n }\n }\n get loadingError() {\n return !this.component.refreshOn && !this.component.refreshOnBlur && this.networkError;\n }\n get selectData() {\n const selectData = lodash_1.default.get(this.root, 'submission.metadata.selectData', {});\n return lodash_1.default.get(selectData, this.path);\n }\n get shouldLoad() {\n if (this.loadingError) {\n return false;\n }\n // Live forms should always load.\n if (!this.options.readOnly) {\n return true;\n }\n // If there are template keys, then we need to see if we have the data.\n if (this.templateKeys && this.templateKeys.length) {\n // See if we already have the data we need.\n const dataValue = this.dataValue;\n const selectData = this.selectData;\n return this.templateKeys.reduce((shouldLoad, key) => {\n const hasValue = lodash_1.default.has(dataValue, key) || lodash_1.default.has(selectData, key);\n return shouldLoad || !hasValue;\n }, false);\n }\n // Return that we should load.\n return true;\n }\n loadItems(url, search, headers, options, method, body) {\n options = options || {};\n // See if we should load items or not.\n if (!this.shouldLoad || (!this.itemsFromUrl && this.options.readOnly)) {\n this.isScrollLoading = false;\n this.loading = false;\n this.itemsLoadedResolve();\n return;\n }\n // See if they have not met the minimum search requirements.\n const minSearch = parseInt(this.component.minSearch, 10);\n if (this.component.searchField &&\n (minSearch > 0) &&\n (!search || (search.length < minSearch))) {\n // Set empty items.\n return this.setItems([]);\n }\n // Ensure we have a method and remove any body if method is get\n method = method || 'GET';\n if (method.toUpperCase() === 'GET') {\n body = null;\n }\n const limit = this.component.limit || 100;\n const skip = this.isScrollLoading ? this.selectOptions.length : 0;\n const query = this.component.disableLimit ? {} : {\n limit,\n skip,\n };\n // Allow for url interpolation.\n url = this.interpolate(url, {\n formioBase: Formio_1.Formio.getBaseUrl(),\n search,\n limit,\n skip,\n page: Math.abs(Math.floor(skip / limit))\n });\n // Add search capability.\n if (this.component.searchField && search) {\n const searchValue = Array.isArray(search) ? search.join(',') : search;\n query[this.component.searchField] = this.component.searchField.endsWith('__regex')\n ? lodash_1.default.escapeRegExp(searchValue)\n : searchValue;\n }\n // If they wish to return only some fields.\n if (this.component.selectFields) {\n query.select = this.component.selectFields;\n }\n // Add sort capability\n if (this.component.sort) {\n query.sort = this.component.sort;\n }\n if (!lodash_1.default.isEmpty(query)) {\n // Add the query string.\n url += (!url.includes('?') ? '?' : '&') + Formio_1.Formio.serialize(query, (item) => this.interpolate(item));\n }\n // Add filter capability\n if (this.component.filter) {\n url += (!url.includes('?') ? '?' : '&') + this.interpolate(this.component.filter);\n }\n // Set ignoreCache if it is\n options.ignoreCache = this.component.ignoreCache;\n // Make the request.\n options.header = headers;\n this.loading = true;\n Formio_1.Formio.makeRequest(this.options.formio, 'select', url, method, body, options)\n .then((response) => {\n this.loading = false;\n this.error = null;\n this.setItems(response, !!search);\n })\n .catch((err) => {\n if (this.itemsFromUrl) {\n this.setItems([]);\n this.disableInfiniteScroll();\n }\n this.isScrollLoading = false;\n this.handleLoadingError(err);\n });\n }\n handleLoadingError(err) {\n this.loading = false;\n if (err.networkError) {\n this.networkError = true;\n }\n this.itemsLoadedResolve();\n this.emit('componentError', {\n component: this.component,\n message: err.toString(),\n });\n console.warn(`Unable to load resources for ${this.key}`);\n }\n /**\n * Get the request headers for this select dropdown.\n */\n get requestHeaders() {\n // Create the headers object.\n const headers = new Formio_1.Formio.Headers();\n // Add custom headers to the url.\n if (this.component.data && this.component.data.headers) {\n try {\n lodash_1.default.each(this.component.data.headers, (header) => {\n if (header.key) {\n headers.set(header.key, this.interpolate(header.value));\n }\n });\n }\n catch (err) {\n console.warn(err.message);\n }\n }\n return headers;\n }\n getCustomItems() {\n const customItems = this.evaluate(this.component.data.custom, {\n values: []\n }, 'values');\n this.asyncValues = (0, utils_1.isPromise)(customItems);\n return customItems;\n }\n asyncCustomValues() {\n if (!lodash_1.default.isBoolean(this.asyncValues)) {\n this.getCustomItems();\n }\n return this.asyncValues;\n }\n updateCustomItems(forceUpdate) {\n if (this.asyncCustomValues()) {\n if (!forceUpdate && !this.active) {\n this.itemsLoadedResolve();\n return;\n }\n this.loading = true;\n this.getCustomItems()\n .then(items => {\n this.loading = false;\n this.setItems(items || []);\n })\n .catch(err => {\n this.handleLoadingError(err);\n });\n }\n else {\n this.setItems(this.getCustomItems() || []);\n }\n }\n isEmpty(value = this.dataValue) {\n return super.isEmpty(value) || value === undefined;\n }\n refresh(value, { instance }) {\n if (this.component.clearOnRefresh && (instance && !instance.pristine)) {\n this.setValue(this.emptyValue);\n }\n this.updateItems(null, true);\n }\n get additionalResourcesAvailable() {\n return lodash_1.default.isNil(this.serverCount) || (this.serverCount > this.downloadedResources.length);\n }\n get serverCount() {\n if (this.isFromSearch) {\n return this.searchServerCount;\n }\n return this.defaultServerCount;\n }\n set serverCount(value) {\n if (this.isFromSearch) {\n this.searchServerCount = value;\n }\n else {\n this.defaultServerCount = value;\n }\n }\n get downloadedResources() {\n if (this.isFromSearch) {\n return this.searchDownloadedResources;\n }\n return this.defaultDownloadedResources;\n }\n set downloadedResources(value) {\n if (this.isFromSearch) {\n this.searchDownloadedResources = value;\n }\n else {\n this.defaultDownloadedResources = value;\n }\n }\n addPlaceholder() {\n if (!this.component.placeholder) {\n return;\n }\n this.addOption('', this.component.placeholder, { placeholder: true });\n }\n /**\n * Activate this select control.\n */\n activate() {\n if (this.loading || !this.active) {\n this.setLoadingItem();\n }\n if (this.active) {\n return;\n }\n this.activated = true;\n this.triggerUpdate();\n }\n setLoadingItem(addToCurrentList = false) {\n if (this.choices) {\n if (addToCurrentList) {\n this.choices.setChoices([{\n value: `${this.id}-loading`,\n label: 'Loading...',\n disabled: true,\n }], 'value', 'label');\n }\n else {\n this.choices.setChoices([{\n value: '',\n label: `<i class=\"${this.iconClass('refresh')}\" style=\"font-size:1.3em;\"></i>`,\n disabled: true,\n }], 'value', 'label', true);\n }\n }\n else if (this.component.dataSrc === 'url' || this.component.dataSrc === 'resource') {\n this.addOption('', this.t('loading...'));\n }\n }\n get active() {\n return !this.component.lazyLoad || this.activated;\n }\n render() {\n const info = this.inputInfo;\n info.attr = info.attr || {};\n info.multiple = this.component.multiple;\n return super.render(this.wrapElement(this.renderTemplate('select', {\n input: info,\n selectOptions: '',\n index: null,\n })));\n }\n wrapElement(element) {\n return this.component.addResource && !this.options.readOnly\n ? (this.renderTemplate('resourceAdd', {\n element\n }))\n : element;\n }\n choicesOptions() {\n const useSearch = this.component.hasOwnProperty('searchEnabled') ? this.component.searchEnabled : true;\n const placeholderValue = this.t(this.component.placeholder, { _userInput: true });\n let customOptions = this.component.customOptions || {};\n if (typeof customOptions == 'string') {\n try {\n customOptions = JSON.parse(customOptions);\n }\n catch (err) {\n console.warn(err.message);\n customOptions = {};\n }\n }\n const commonFuseOptions = {\n maxPatternLength: 1000,\n distance: 1000,\n };\n return Object.assign({ removeItemButton: this.component.disabled ? false : lodash_1.default.get(this.component, 'removeItemButton', true), itemSelectText: '', classNames: {\n containerOuter: 'choices form-group formio-choices',\n containerInner: this.transform('class', 'form-control ui fluid selection dropdown')\n }, addItemText: false, allowHTML: true, placeholder: !!this.component.placeholder, placeholderValue: placeholderValue, noResultsText: this.t('No results found'), noChoicesText: this.t('No choices to choose from'), searchPlaceholderValue: this.t('Type to search'), shouldSort: false, position: (this.component.dropdown || 'auto'), searchEnabled: useSearch, searchChoices: !this.component.searchField, searchFields: lodash_1.default.get(this, 'component.searchFields', ['label']), shadowRoot: this.root ? this.root.shadowRoot : null, fuseOptions: this.component.useExactSearch\n ? Object.assign({ tokenize: true, matchAllTokens: true }, commonFuseOptions) : Object.assign({}, lodash_1.default.get(this, 'component.fuseOptions', {}), Object.assign({ include: 'score', threshold: lodash_1.default.get(this, 'component.selectThreshold', 0.3) }, commonFuseOptions)), valueComparer: lodash_1.default.isEqual, resetScrollPosition: false }, customOptions);\n }\n /* eslint-disable max-statements */\n attach(element) {\n var _a, _b, _c;\n const superAttach = super.attach(element);\n this.loadRefs(element, {\n selectContainer: 'single',\n addResource: 'single',\n autocompleteInput: 'single'\n });\n //enable autocomplete for select\n const autocompleteInput = this.refs.autocompleteInput;\n if (autocompleteInput) {\n this.addEventListener(autocompleteInput, 'change', (event) => {\n this.setValue(event.target.value);\n });\n }\n const input = this.refs.selectContainer;\n if (!input) {\n return;\n }\n this.addEventListener(input, this.inputInfo.changeEvent, () => this.updateValue(null, {\n modified: true\n }));\n this.attachRefreshOnBlur();\n if (this.component.widget === 'html5') {\n this.addFocusBlurEvents(input);\n this.triggerUpdate(null, true);\n if (this.visible) {\n this.setItems(this.selectOptions || []);\n }\n this.focusableElement = input;\n this.addEventListener(input, 'focus', () => this.update());\n this.addEventListener(input, 'keydown', (event) => {\n const { key } = event;\n if (['Backspace', 'Delete'].includes(key)) {\n this.setValue(this.emptyValue);\n }\n });\n return;\n }\n const tabIndex = input.tabIndex;\n this.addPlaceholder();\n if (this.i18next) {\n input.setAttribute('dir', this.i18next.dir());\n }\n if ((_c = (_b = (_a = this.choices) === null || _a === void 0 ? void 0 : _a.containerOuter) === null || _b === void 0 ? void 0 : _b.element) === null || _c === void 0 ? void 0 : _c.parentNode) {\n this.choices.destroy();\n }\n const choicesOptions = this.choicesOptions();\n if (Choices) {\n this.choices = new Choices(input, choicesOptions);\n if (this.selectOptions && this.selectOptions.length) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n if (this.component.multiple) {\n this.focusableElement = this.choices.input.element;\n }\n else {\n this.focusableElement = this.choices.containerInner.element;\n this.choices.containerOuter.element.setAttribute('tabIndex', '-1');\n this.addEventListener(this.choices.containerOuter.element, 'focus', () => this.focusableElement.focus());\n }\n this.addFocusBlurEvents(this.focusableElement);\n if (this.itemsFromUrl && !this.component.noRefreshOnScroll) {\n this.scrollList = this.choices.choiceList.element;\n this.addEventListener(this.scrollList, 'scroll', () => this.onScroll());\n }\n }\n this.focusableElement.setAttribute('tabIndex', tabIndex);\n // If a search field is provided, then add an event listener to update items on search.\n if (this.component.searchField) {\n // Make sure to clear the search when no value is provided.\n if (this.choices && this.choices.input && this.choices.input.element) {\n this.addEventListener(this.choices.input.element, 'input', (event) => {\n this.isFromSearch = !!event.target.value;\n if (!event.target.value) {\n this.triggerUpdate();\n }\n else {\n this.serverCount = null;\n this.downloadedResources = [];\n }\n });\n }\n this.addEventListener(input, 'choice', () => {\n if (this.component.multiple && this.component.dataSrc === 'resource' && this.isFromSearch) {\n this.triggerUpdate();\n }\n this.isFromSearch = false;\n });\n // avoid spamming the resource/url endpoint when we have server side filtering enabled.\n const debounceTimeout = this.component.searchField && (this.isSelectResource || this.isSelectURL) ?\n (this.component.searchDebounce === 0 ? 0 : this.component.searchDebounce || this.defaultSchema.searchDebounce) * 1000\n : 0;\n const updateComponent = (evt) => {\n this.triggerUpdate(evt.detail.value);\n };\n this.addEventListener(input, 'search', lodash_1.default.debounce(updateComponent, debounceTimeout));\n this.addEventListener(input, 'stopSearch', () => this.triggerUpdate());\n this.addEventListener(input, 'hideDropdown', () => {\n if (this.choices && this.choices.input && this.choices.input.element) {\n this.choices.input.element.value = '';\n }\n this.updateItems(null, true);\n });\n }\n this.addEventListener(input, 'showDropdown', () => this.update());\n if (this.choices && choicesOptions.placeholderValue && this.choices._isSelectOneElement) {\n this.addPlaceholderItem(choicesOptions.placeholderValue);\n this.addEventListener(input, 'removeItem', () => {\n this.addPlaceholderItem(choicesOptions.placeholderValue);\n });\n }\n // Add value options.\n this.addValueOptions();\n this.setChoicesValue(this.dataValue);\n if (this.isSelectResource && this.refs.addResource) {\n this.addEventListener(this.refs.addResource, 'click', (event) => {\n event.preventDefault();\n const formioForm = this.ce('div');\n const dialog = this.createModal(formioForm);\n const projectUrl = lodash_1.default.get(this.root, 'formio.projectUrl', Formio_1.Formio.getProjectUrl());\n const formUrl = `${projectUrl}/form/${this.component.data.resource}`;\n new Form_1.default(formioForm, formUrl, {}).ready\n .then((form) => {\n form.on('submit', (submission) => {\n // If valueProperty is set, replace the submission with the corresponding value\n let value = this.valueProperty ? lodash_1.default.get(submission, this.valueProperty) : submission;\n if (this.component.multiple) {\n value = [...this.dataValue, value];\n }\n this.setValue(value);\n this.triggerUpdate();\n dialog.close();\n });\n });\n });\n }\n // Force the disabled state with getters and setters.\n this.disabled = this.shouldDisabled;\n this.triggerUpdate();\n return superAttach;\n }\n get isLoadingAvailable() {\n return !this.isScrollLoading && this.additionalResourcesAvailable;\n }\n onScroll() {\n if (this.isLoadingAvailable) {\n this.isScrollLoading = true;\n this.setLoadingItem(true);\n this.triggerUpdate(this.choices.input.element.value);\n }\n }\n attachRefreshOnBlur() {\n if (this.component.refreshOnBlur) {\n this.on('blur', (instance) => {\n this.checkRefreshOn([{ instance, value: instance.dataValue }], { fromBlur: true });\n });\n }\n }\n addPlaceholderItem(placeholderValue) {\n const items = this.choices._store.activeItems;\n if (!items.length) {\n this.choices._addItem({\n value: placeholderValue,\n label: placeholderValue,\n choiceId: 0,\n groupId: -1,\n customProperties: null,\n placeholder: true,\n keyCode: null\n });\n }\n }\n /* eslint-enable max-statements */\n update() {\n if (this.component.dataSrc === 'custom') {\n this.updateCustomItems();\n }\n // Activate the control.\n this.activate();\n }\n set disabled(disabled) {\n super.disabled = disabled;\n if (!this.choices) {\n return;\n }\n if (disabled) {\n this.setDisabled(this.choices.containerInner.element, true);\n this.focusableElement.removeAttribute('tabIndex');\n this.choices.disable();\n }\n else {\n this.setDisabled(this.choices.containerInner.element, false);\n this.focusableElement.setAttribute('tabIndex', this.component.tabindex || 0);\n this.choices.enable();\n }\n }\n get disabled() {\n return super.disabled;\n }\n set visible(value) {\n // If we go from hidden to visible, trigger a refresh.\n if (value && (!this._visible !== !value)) {\n this.triggerUpdate();\n }\n super.visible = value;\n }\n get visible() {\n return super.visible;\n }\n /**\n * @param {*} value\n * @param {Array} items\n */\n addCurrentChoices(values, items, keyValue) {\n if (!values) {\n return false;\n }\n const notFoundValuesToAdd = [];\n const added = values.reduce((defaultAdded, value) => {\n if (!value || lodash_1.default.isEmpty(value)) {\n return defaultAdded;\n }\n let found = false;\n // Make sure that `items` and `this.selectOptions` points\n // to the same reference. Because `this.selectOptions` is\n // internal property and all items are populated by\n // `this.addOption` method, we assume that items has\n // 'label' and 'value' properties. This assumption allows\n // us to read correct value from the item.\n const isSelectOptions = items === this.selectOptions;\n if (items && items.length) {\n lodash_1.default.each(items, (choice) => {\n if (choice._id && value._id && (choice._id === value._id)) {\n found = true;\n return false;\n }\n const itemValue = keyValue ? choice.value : this.itemValue(choice, isSelectOptions);\n found |= lodash_1.default.isEqual(itemValue, value);\n return found ? false : true;\n });\n }\n // Add the default option if no item is found.\n if (!found) {\n notFoundValuesToAdd.push(this.selectValueAndLabel(value));\n return true;\n }\n return found || defaultAdded;\n }, false);\n if (notFoundValuesToAdd.length) {\n if (this.choices) {\n this.choices.setChoices(notFoundValuesToAdd, 'value', 'label');\n }\n notFoundValuesToAdd.map(notFoundValue => {\n this.addOption(notFoundValue.value, notFoundValue.label);\n });\n }\n return added;\n }\n getValueAsString(data) {\n return (this.component.multiple && Array.isArray(data))\n ? data.map(this.asString.bind(this)).join(', ')\n : this.asString(data);\n }\n getValue() {\n // If the widget isn't active.\n if (this.viewOnly || this.loading\n || (!this.component.lazyLoad && !this.selectOptions.length)\n || !this.element) {\n return this.dataValue;\n }\n let value = this.emptyValue;\n if (this.choices) {\n value = this.choices.getValue(true);\n // Make sure we don't get the placeholder\n if (!this.component.multiple &&\n this.component.placeholder &&\n (value === this.t(this.component.placeholder, { _userInput: true }))) {\n value = this.emptyValue;\n }\n }\n else if (this.refs.selectContainer) {\n value = this.refs.selectContainer.value;\n if (this.valueProperty === '' || this.isEntireObjectDisplay()) {\n if (value === '') {\n return {};\n }\n const option = this.selectOptions[value] ||\n this.selectOptions.find(option => option.id === value);\n if (option && lodash_1.default.isObject(option.value)) {\n value = option.value;\n }\n }\n }\n else {\n value = this.dataValue;\n }\n // Choices will return undefined if nothing is selected. We really want '' to be empty.\n if (value === undefined || value === null) {\n value = '';\n }\n return value;\n }\n redraw() {\n const done = super.redraw();\n this.triggerUpdate();\n return done;\n }\n normalizeSingleValue(value, retainObject) {\n var _a;\n if (lodash_1.default.isNil(value)) {\n return;\n }\n const valueIsObject = lodash_1.default.isObject(value);\n //check if value equals to default emptyValue\n if (valueIsObject && Object.keys(value).length === 0) {\n return value;\n }\n // Check to see if we need to save off the template data into our metadata.\n if (retainObject) {\n const templateValue = this.component.reference && (value === null || value === void 0 ? void 0 : value._id) ? value._id.toString() : value;\n const shouldSaveData = !valueIsObject || this.component.reference;\n if (templateValue && shouldSaveData && (this.templateData && this.templateData[templateValue]) && ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submission)) {\n const submission = this.root.submission;\n if (!submission.metadata) {\n submission.metadata = {};\n }\n if (!submission.metadata.selectData) {\n submission.metadata.selectData = {};\n }\n let templateData = this.templateData[templateValue];\n if (this.component.multiple) {\n templateData = {};\n const dataValue = this.dataValue;\n if (dataValue && dataValue.length) {\n dataValue.forEach((dataValueItem) => {\n const dataValueItemValue = this.component.reference ? dataValueItem._id.toString() : dataValueItem;\n templateData[dataValueItemValue] = this.templateData[dataValueItemValue];\n });\n }\n }\n lodash_1.default.set(submission.metadata.selectData, this.path, templateData);\n }\n }\n const dataType = this.component.dataType || 'auto';\n const normalize = {\n value,\n number() {\n const numberValue = Number(this.value);\n const isEquivalent = value.toString() === numberValue.toString();\n if (!Number.isNaN(numberValue) && Number.isFinite(numberValue) && value !== '' && isEquivalent) {\n this.value = numberValue;\n }\n return this;\n },\n boolean() {\n if (lodash_1.default.isString(this.value)\n && (this.value.toLowerCase() === 'true'\n || this.value.toLowerCase() === 'false')) {\n this.value = (this.value.toLowerCase() === 'true');\n }\n return this;\n },\n string() {\n this.value = String(this.value);\n return this;\n },\n object() {\n return this;\n },\n auto() {\n if (lodash_1.default.isObject(this.value)) {\n this.value = this.object().value;\n }\n else {\n this.value = this.string().number().boolean().value;\n }\n return this;\n }\n };\n try {\n return normalize[dataType]().value;\n }\n catch (err) {\n console.warn('Failed to normalize value', err);\n return value;\n }\n }\n /**\n * Normalize values coming into updateValue.\n *\n * @param value\n * @return {*}\n */\n normalizeValue(value) {\n if (this.component.multiple && Array.isArray(value)) {\n return value.map((singleValue) => this.normalizeSingleValue(singleValue, true));\n }\n return super.normalizeValue(this.normalizeSingleValue(value, true));\n }\n setValue(value, flags = {}) {\n const previousValue = this.dataValue;\n if (this.component.widget === 'html5' && (lodash_1.default.isEqual(value, previousValue) || lodash_1.default.isEqual(previousValue, {}) && lodash_1.default.isEqual(flags, {}))) {\n return false;\n }\n const changed = this.updateValue(value, flags);\n value = this.dataValue;\n const hasPreviousValue = !this.isEmpty(previousValue);\n const hasValue = !this.isEmpty(value);\n // Undo typing when searching to set the value.\n if (this.component.multiple && Array.isArray(value)) {\n value = value.map(value => {\n if (typeof value === 'boolean' || typeof value === 'number') {\n return value.toString();\n }\n return value;\n });\n }\n else {\n if (typeof value === 'boolean' || typeof value === 'number') {\n value = value.toString();\n }\n }\n if (this.isHtmlRenderMode() && flags && flags.fromSubmission && changed) {\n this.itemsLoaded.then(() => {\n this.redraw();\n });\n return changed;\n }\n // Do not set the value if we are loading... that will happen after it is done.\n if (this.loading) {\n return changed;\n }\n // Determine if we need to perform an initial lazyLoad api call if searchField is provided.\n if (this.isInitApiCallNeeded(hasValue)) {\n this.loading = true;\n this.lazyLoadInit = true;\n const searchProperty = this.component.searchField || this.component.valueProperty;\n this.triggerUpdate(lodash_1.default.get(value.data || value, searchProperty, value), true);\n return changed;\n }\n // Add the value options.\n this.itemsLoaded.then(() => {\n this.addValueOptions();\n this.setChoicesValue(value, hasPreviousValue, flags);\n });\n return changed;\n }\n isInitApiCallNeeded(hasValue) {\n return this.component.lazyLoad &&\n !this.lazyLoadInit &&\n !this.active &&\n !this.selectOptions.length &&\n hasValue &&\n this.shouldLoad &&\n this.visible && (this.component.searchField || this.component.valueProperty);\n }\n setChoicesValue(value, hasPreviousValue, flags = {}) {\n const hasValue = !this.isEmpty(value) || flags.fromSubmission;\n hasPreviousValue = (hasPreviousValue === undefined) ? true : hasPreviousValue;\n if (this.choices) {\n // Now set the value.\n if (hasValue) {\n this.choices.removeActiveItems();\n // Add the currently selected choices if they don't already exist.\n const currentChoices = Array.isArray(value) && this.component.multiple ? value : [value];\n if (!this.addCurrentChoices(currentChoices, this.selectOptions, true)) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n this.choices.setChoiceByValue(currentChoices);\n }\n else if (hasPreviousValue || flags.resetValue) {\n this.choices.removeActiveItems();\n }\n }\n else {\n if (hasValue) {\n const values = Array.isArray(value) ? value : [value];\n if (!lodash_1.default.isEqual(this.dataValue, this.defaultValue) && this.selectOptions.length < 2) {\n const { value, label } = this.selectValueAndLabel(this.dataValue);\n this.addOption(value, label);\n }\n lodash_1.default.each(this.selectOptions, (selectOption) => {\n lodash_1.default.each(values, (val) => {\n if (selectOption.value === '') {\n selectOption.value = {};\n }\n if (lodash_1.default.isEqual(val, selectOption.value) && selectOption.element) {\n selectOption.element.selected = true;\n selectOption.element.setAttribute('selected', 'selected');\n return false;\n }\n });\n });\n }\n else {\n lodash_1.default.each(this.selectOptions, (selectOption) => {\n if (selectOption.element) {\n selectOption.element.selected = false;\n selectOption.element.removeAttribute('selected');\n }\n });\n }\n }\n }\n get itemsLoaded() {\n return this._itemsLoaded || native_promise_only_1.default.resolve();\n }\n set itemsLoaded(promise) {\n this._itemsLoaded = promise;\n }\n validateValueAvailability(setting, value) {\n if (!(0, utils_1.boolValue)(setting) || !value) {\n return true;\n }\n const values = this.getOptionsValues();\n if (values) {\n if (lodash_1.default.isObject(value)) {\n const compareComplexValues = (optionValue) => {\n const normalizedOptionValue = this.normalizeSingleValue(optionValue, true);\n if (!lodash_1.default.isObject(normalizedOptionValue)) {\n return false;\n }\n try {\n return (JSON.stringify(normalizedOptionValue) === JSON.stringify(value));\n }\n catch (err) {\n console.warn.error('Error while comparing items', err);\n return false;\n }\n };\n return values.findIndex((optionValue) => compareComplexValues(optionValue)) !== -1;\n }\n return values.findIndex((optionValue) => this.normalizeSingleValue(optionValue) === value) !== -1;\n }\n return false;\n }\n /**\n * Performs required transformations on the initial value to use in selectOptions\n * @param {*} value\n */\n getOptionValue(value) {\n return lodash_1.default.isObject(value) && this.isEntireObjectDisplay()\n ? this.normalizeSingleValue(value)\n : lodash_1.default.isObject(value) && (this.valueProperty || this.component.key !== 'resource')\n ? value\n : lodash_1.default.isObject(value) && !this.valueProperty\n ? this.interpolate(this.component.template, { item: value }).replace(/<\\/?[^>]+(>|$)/g, '')\n : lodash_1.default.isNull(value)\n ? this.emptyValue\n : String(this.normalizeSingleValue(value));\n }\n /**\n * If component has static values (values, json) or custom values, returns an array of them\n * @returns {Array<*>|undefined}\n */\n getOptionsValues() {\n let rawItems = [];\n switch (this.component.dataSrc) {\n case 'values':\n rawItems = this.component.data.values;\n break;\n case 'json':\n rawItems = this.component.data.json;\n break;\n case 'custom':\n rawItems = this.getCustomItems();\n break;\n }\n if (typeof rawItems === 'string') {\n try {\n rawItems = JSON.parse(rawItems);\n }\n catch (err) {\n console.warn(err.message);\n rawItems = [];\n }\n }\n if (!Array.isArray(rawItems)) {\n return;\n }\n return rawItems.map((item) => this.getOptionValue(this.itemValue(item)));\n }\n /**\n * Deletes the value of the component.\n */\n deleteValue() {\n this.setValue('', {\n noUpdateEvent: true\n });\n this.unset();\n }\n /**\n * Check if a component is eligible for multiple validation\n *\n * @return {boolean}\n */\n validateMultiple() {\n // Select component will contain one input when flagged as multiple.\n return false;\n }\n /**\n * Output this select dropdown as a string value.\n * @return {*}\n */\n isBooleanOrNumber(value) {\n return typeof value === 'number' || typeof value === 'boolean';\n }\n getNormalizedValues() {\n if (!this.component || !this.component.data || !this.component.data.values) {\n return;\n }\n return this.component.data.values.map(value => ({ label: value.label, value: String(this.normalizeSingleValue(value.value)) }));\n }\n asString(value) {\n var _a;\n value = value !== null && value !== void 0 ? value : this.getValue();\n //need to convert values to strings to be able to compare values with available options that are strings\n const convertToString = (data, valueProperty) => {\n if (valueProperty) {\n if (Array.isArray(data)) {\n data.forEach((item) => item[valueProperty] = item[valueProperty].toString());\n }\n else {\n data[valueProperty] = data[valueProperty].toString();\n }\n return data;\n }\n if (this.isBooleanOrNumber(data)) {\n data = data.toString();\n }\n if (Array.isArray(data) && data.some(item => this.isBooleanOrNumber(item))) {\n data = data.map(item => {\n if (this.isBooleanOrNumber(item)) {\n item = item.toString();\n }\n });\n }\n return data;\n };\n value = convertToString(value);\n if (['values', 'custom'].includes(this.component.dataSrc) && !this.asyncCustomValues()) {\n const { items, valueProperty, } = this.component.dataSrc === 'values'\n ? {\n items: convertToString(this.getNormalizedValues(), 'value'),\n valueProperty: 'value',\n }\n : {\n items: convertToString(this.getCustomItems(), this.valueProperty),\n valueProperty: this.valueProperty,\n };\n const getFromValues = () => {\n const initialValue = lodash_1.default.find(items, [valueProperty, value]);\n const values = this.defaultSchema.data.values || [];\n return lodash_1.default.isEqual(initialValue, values[0]) ? '-' : initialValue;\n };\n value = (this.component.multiple && Array.isArray(value))\n ? lodash_1.default.filter(items, (item) => value.includes(item.value))\n : valueProperty\n ? (_a = getFromValues()) !== null && _a !== void 0 ? _a : { value, label: value }\n : value;\n }\n if (lodash_1.default.isString(value)) {\n return value;\n }\n if (Array.isArray(value)) {\n const items = [];\n value.forEach(item => items.push(this.itemTemplate(item)));\n if (this.component.dataSrc === 'resource' && items.length > 0) {\n return items.join(', ');\n }\n else if (items.length > 0) {\n return items.join('<br />');\n }\n else {\n return '-';\n }\n }\n return !lodash_1.default.isNil(value)\n ? this.itemTemplate(value)\n : '-';\n }\n detach() {\n var _a, _b;\n this.off('blur');\n if (this.choices) {\n if ((_b = (_a = this.choices.containerOuter) === null || _a === void 0 ? void 0 : _a.element) === null || _b === void 0 ? void 0 : _b.parentNode) {\n this.choices.destroy();\n }\n this.choices = null;\n }\n super.detach();\n }\n focus() {\n if (this.focusableElement) {\n super.focus.call(this);\n this.focusableElement.focus();\n }\n }\n setErrorClasses(elements, dirty, hasError, hasMessages, element = this.element) {\n super.setErrorClasses(elements, dirty, hasError, hasMessages, element);\n if (this.choices) {\n super.setErrorClasses([this.choices.containerInner.element], dirty, hasError, hasMessages, element);\n }\n else {\n super.setErrorClasses([this.refs.selectContainer], dirty, hasError, hasMessages, element);\n }\n }\n}\nexports[\"default\"] = SelectComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/select/Select.js?");
6911
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst Formio_1 = __webpack_require__(/*! ../../Formio */ \"./lib/cjs/Formio.js\");\nconst ListComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/list/ListComponent */ \"./lib/cjs/components/_classes/list/ListComponent.js\"));\nconst Form_1 = __importDefault(__webpack_require__(/*! ../../Form */ \"./lib/cjs/Form.js\"));\nconst native_promise_only_1 = __importDefault(__webpack_require__(/*! native-promise-only */ \"./node_modules/native-promise-only/lib/npo.src.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst ChoicesWrapper_1 = __importDefault(__webpack_require__(/*! ../../utils/ChoicesWrapper */ \"./lib/cjs/utils/ChoicesWrapper.js\"));\nclass SelectComponent extends ListComponent_1.default {\n static schema(...extend) {\n return ListComponent_1.default.schema({\n type: 'select',\n label: 'Select',\n key: 'select',\n idPath: 'id',\n data: {\n values: [{ label: '', value: '' }],\n json: '',\n url: '',\n resource: '',\n custom: ''\n },\n clearOnRefresh: false,\n limit: 100,\n valueProperty: '',\n lazyLoad: true,\n filter: '',\n searchEnabled: true,\n searchDebounce: 0.3,\n searchField: '',\n minSearch: 0,\n readOnlyValue: false,\n selectFields: '',\n selectThreshold: 0.3,\n uniqueOptions: false,\n tableView: true,\n fuseOptions: {\n include: 'score',\n threshold: 0.3,\n },\n indexeddb: {\n filter: {}\n },\n customOptions: {},\n useExactSearch: false,\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Select',\n group: 'basic',\n icon: 'th-list',\n weight: 70,\n documentation: '/userguide/form-building/form-components#select',\n schema: SelectComponent.schema()\n };\n }\n init() {\n super.init();\n this.templateData = {};\n this.validators = this.validators.concat(['select', 'onlyAvailableItems']);\n // Trigger an update.\n let updateArgs = [];\n const triggerUpdate = lodash_1.default.debounce((...args) => {\n updateArgs = [];\n return this.updateItems.apply(this, args);\n }, 100);\n this.triggerUpdate = (...args) => {\n // Make sure we always resolve the previous promise before reassign it\n if (typeof this.itemsLoadedResolve === 'function') {\n this.itemsLoadedResolve();\n }\n this.itemsLoaded = new native_promise_only_1.default((resolve) => {\n this.itemsLoadedResolve = resolve;\n });\n if (args.length) {\n updateArgs = args;\n }\n return triggerUpdate(...updateArgs);\n };\n // Keep track of the select options.\n this.selectOptions = [];\n if (this.itemsFromUrl) {\n this.isFromSearch = false;\n this.searchServerCount = null;\n this.defaultServerCount = null;\n this.isScrollLoading = false;\n this.searchDownloadedResources = [];\n this.defaultDownloadedResources = [];\n }\n // If this component has been activated.//\n this.activated = false;\n this.itemsLoaded = new native_promise_only_1.default((resolve) => {\n this.itemsLoadedResolve = resolve;\n });\n if (this.isHtmlRenderMode()) {\n this.activate();\n }\n // Get the template keys for this select component.\n this.getTemplateKeys();\n }\n get dataReady() {\n // If the root submission has been set, and we are still not attached, then assume\n // that our data is ready.\n if (this.root &&\n this.root.submissionSet &&\n !this.attached) {\n return native_promise_only_1.default.resolve();\n }\n return this.itemsLoaded;\n }\n get defaultSchema() {\n return SelectComponent.schema();\n }\n get emptyValue() {\n if (this.component.multiple) {\n return [];\n }\n // if select has JSON data source type, we are defining if empty value would be an object or a string by checking JSON's first item\n if (this.component.dataSrc === 'json' && this.component.data.json) {\n const firstItem = this.component.data.json[0];\n let firstValue;\n if (this.valueProperty) {\n firstValue = lodash_1.default.get(firstItem, this.valueProperty);\n }\n else {\n firstValue = firstItem;\n }\n if (firstValue && typeof firstValue === 'string') {\n return '';\n }\n else {\n return {};\n }\n }\n if (this.valueProperty) {\n return '';\n }\n return {};\n }\n get valueProperty() {\n if (this.component.valueProperty) {\n return this.component.valueProperty;\n }\n // Force values datasource to use values without actually setting it on the component settings.\n if (this.component.dataSrc === 'values') {\n return 'value';\n }\n return '';\n }\n get inputInfo() {\n const info = super.elementInfo();\n info.type = 'select';\n info.changeEvent = 'change';\n return info;\n }\n get isSelectResource() {\n return this.component.dataSrc === 'resource';\n }\n get itemsFromUrl() {\n return this.isSelectResource || this.isSelectURL;\n }\n get isInfiniteScrollProvided() {\n return this.itemsFromUrl;\n }\n get shouldDisabled() {\n return super.shouldDisabled || this.parentDisabled;\n }\n isEntireObjectDisplay() {\n return this.component.dataSrc === 'resource' && this.valueProperty === 'data';\n }\n selectValueAndLabel(data) {\n const value = this.getOptionValue((this.isEntireObjectDisplay() && !this.itemValue(data)) ? data : this.itemValue(data));\n return {\n value,\n label: this.itemTemplate((this.isEntireObjectDisplay() && !lodash_1.default.isObject(data.data)) ? { data: data } : data, value)\n };\n }\n itemTemplate(data, value) {\n if (!lodash_1.default.isNumber(data) && lodash_1.default.isEmpty(data)) {\n return '';\n }\n // If they wish to show the value in read only mode, then just return the itemValue here.\n if (this.options.readOnly && this.component.readOnlyValue) {\n return this.itemValue(data);\n }\n // Perform a fast interpretation if we should not use the template.\n if (data && !this.component.template) {\n const itemLabel = data.label || data;\n const value = (typeof itemLabel === 'string') ? this.t(itemLabel, { _userInput: true }) : itemLabel;\n return this.sanitize(value, this.shouldSanitizeValue);\n }\n if (this.component.multiple ? this.dataValue.find((val) => value === val) : (this.dataValue === value)) {\n const selectData = this.selectData;\n if (selectData) {\n const templateValue = this.component.reference && (value === null || value === void 0 ? void 0 : value._id) ? value._id.toString() : value;\n if (!this.templateData || !this.templateData[templateValue]) {\n this.getOptionTemplate(data, value);\n }\n if (this.component.multiple) {\n if (selectData[templateValue]) {\n data = selectData[templateValue];\n }\n }\n else {\n data = selectData;\n }\n }\n }\n if (typeof data === 'string' || typeof data === 'number') {\n return this.sanitize(this.t(data, { _userInput: true }), this.shouldSanitizeValue);\n }\n if (Array.isArray(data)) {\n return data.map((val) => {\n if (typeof val === 'string' || typeof val === 'number') {\n return this.sanitize(this.t(val, { _userInput: true }), this.shouldSanitizeValue);\n }\n return val;\n });\n }\n if (data.data) {\n // checking additional fields in the template for the selected Entire Object option\n const hasNestedFields = /item\\.data\\.\\w*/g.test(this.component.template);\n data.data = this.isEntireObjectDisplay() && lodash_1.default.isObject(data.data) && !hasNestedFields\n ? JSON.stringify(data.data)\n : data.data;\n }\n return super.itemTemplate(data, value);\n }\n /**\n * Adds an option to the select dropdown.\n *\n * @param value\n * @param label\n */\n addOption(value, label, attrs = {}, id = (0, utils_1.getRandomComponentId)()) {\n if (lodash_1.default.isNil(label))\n return;\n const idPath = this.component.idPath\n ? this.component.idPath.split('.').reduceRight((obj, key) => ({ [key]: obj }), id)\n : {};\n const option = Object.assign({ value: this.getOptionValue(value), label }, idPath);\n const skipOption = this.component.uniqueOptions\n ? !!this.selectOptions.find((selectOption) => lodash_1.default.isEqual(selectOption.value, option.value))\n : false;\n if (skipOption) {\n return;\n }\n if (value) {\n this.selectOptions.push(option);\n }\n if (this.refs.selectContainer && (this.component.widget === 'html5')) {\n // Replace an empty Object value to an empty String.\n if (option.value && lodash_1.default.isObject(option.value) && lodash_1.default.isEmpty(option.value)) {\n option.value = '';\n }\n // Add element to option so we can reference it later.\n const div = document.createElement('div');\n div.innerHTML = this.sanitize(this.renderTemplate('selectOption', {\n selected: lodash_1.default.isEqual(this.getOptionValue(this.dataValue), option.value),\n option,\n attrs,\n id,\n useId: (this.valueProperty === '' || this.isEntireObjectDisplay()) && lodash_1.default.isObject(value) && id,\n }), this.shouldSanitizeValue).trim();\n option.element = div.firstChild;\n this.refs.selectContainer.appendChild(option.element);\n }\n }\n addValueOptions(items) {\n items = items || [];\n let added = false;\n let data = this.dataValue;\n // preset submission value with value property before request.\n if (this.options.pdf && !items.length && this.component.dataSrc === 'url' && this.valueProperty) {\n data = Array.isArray(data)\n ? data.map(item => lodash_1.default.set({}, this.valueProperty, item))\n : lodash_1.default.set({}, this.valueProperty, data);\n }\n if (!this.selectOptions.length) {\n // Add the currently selected choices if they don't already exist.\n const currentChoices = Array.isArray(data) && this.component.multiple ? data : [data];\n added = this.addCurrentChoices(currentChoices, items);\n if (!added && !this.component.multiple) {\n this.addPlaceholder();\n }\n }\n return added;\n }\n disableInfiniteScroll() {\n if (!this.downloadedResources) {\n return;\n }\n this.downloadedResources.serverCount = this.downloadedResources.length;\n this.serverCount = this.downloadedResources.length;\n }\n /* eslint-disable max-statements */\n setItems(items, fromSearch) {\n var _a, _b;\n // If the items is a string, then parse as JSON.\n if (typeof items == 'string') {\n try {\n items = JSON.parse(items);\n }\n catch (err) {\n console.warn(err.message);\n items = [];\n }\n }\n // Allow js processing (needed for form builder)\n if (this.component.onSetItems && typeof this.component.onSetItems === 'function') {\n const newItems = this.component.onSetItems(this, items);\n if (newItems) {\n items = newItems;\n }\n }\n if (!this.choices && this.refs.selectContainer) {\n this.empty(this.refs.selectContainer);\n }\n // If they provided select values, then we need to get them instead.\n if (this.component.selectValues) {\n items = lodash_1.default.get(items, this.component.selectValues, items) || [];\n }\n let areItemsEqual;\n if (this.itemsFromUrl) {\n areItemsEqual = this.isSelectURL ? lodash_1.default.isEqual(items, this.downloadedResources) : false;\n const areItemsEnded = this.component.limit > items.length;\n const areItemsDownloaded = areItemsEqual\n && this.downloadedResources\n && this.downloadedResources.length === items.length;\n if (areItemsEnded) {\n this.disableInfiniteScroll();\n }\n else if (areItemsDownloaded) {\n this.selectOptions = [];\n }\n else {\n this.serverCount = items.serverCount;\n }\n }\n if (this.isScrollLoading && items) {\n if (!areItemsEqual) {\n this.downloadedResources = this.downloadedResources\n ? this.downloadedResources.concat(items)\n : items;\n }\n this.downloadedResources.serverCount = items.serverCount || this.downloadedResources.serverCount;\n }\n else {\n this.downloadedResources = items || [];\n this.selectOptions = [];\n // If there is new select option with same id as already selected, set the new one\n if (!lodash_1.default.isEmpty(this.dataValue) && this.component.idPath) {\n const selectedOptionId = lodash_1.default.get(this.dataValue, this.component.idPath, null);\n const newOptionWithSameId = !lodash_1.default.isNil(selectedOptionId) && items.find(item => {\n const itemId = lodash_1.default.get(item, this.component.idPath);\n return itemId === selectedOptionId;\n });\n if (newOptionWithSameId) {\n this.setValue(newOptionWithSameId);\n }\n }\n }\n // Add the value options.\n if (!fromSearch) {\n this.addValueOptions(items);\n }\n if (this.component.widget === 'html5' && !this.component.placeholder) {\n this.addOption(null, '');\n }\n // Iterate through each of the items.\n lodash_1.default.each(items, (item, index) => {\n // preventing references of the components inside the form to the parent form when building forms\n if (this.root && this.root.options.editForm && this.root.options.editForm._id && this.root.options.editForm._id === item._id)\n return;\n const itemValueAndLabel = this.selectValueAndLabel(item);\n this.addOption(itemValueAndLabel.value, itemValueAndLabel.label, {}, lodash_1.default.get(item, this.component.idPath, String(index)));\n });\n if (this.choices) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n else if (this.loading) {\n // Re-attach select input.\n // this.appendTo(this.refs.input[0], this.selectContainer);\n }\n // We are no longer loading.\n this.isScrollLoading = false;\n this.loading = false;\n const searching = fromSearch && ((_b = (_a = this.choices) === null || _a === void 0 ? void 0 : _a.input) === null || _b === void 0 ? void 0 : _b.isFocussed);\n if (!searching) {\n // If a value is provided, then select it.\n if (!this.isEmpty()) {\n this.setValue(this.dataValue, {\n noUpdateEvent: true\n });\n }\n else if (this.shouldAddDefaultValue && !this.options.readOnly) {\n // If a default value is provided then select it.\n const defaultValue = this.defaultValue;\n if (!this.isEmpty(defaultValue)) {\n this.setValue(defaultValue);\n }\n }\n }\n // Say we are done loading the items.\n this.itemsLoadedResolve();\n }\n getSingleItemValueForHTMLMode(data) {\n var _a;\n const option = (_a = this.selectOptions) === null || _a === void 0 ? void 0 : _a.find(({ value }) => lodash_1.default.isEqual(value, data));\n if (option) {\n return option.label || data;\n }\n return data;\n }\n itemValueForHTMLMode(value) {\n if (!this.isHtmlRenderMode()) {\n return super.itemValueForHTMLMode(value);\n }\n if (Array.isArray(value)) {\n const values = value.map(item => Array.isArray(item)\n ? this.itemValueForHTMLMode(item)\n : this.getSingleItemValueForHTMLMode(item));\n return values.join(', ');\n }\n return this.getSingleItemValueForHTMLMode(value);\n }\n /* eslint-enable max-statements */\n get defaultValue() {\n let defaultValue = super.defaultValue;\n if (!defaultValue && (this.component.defaultValue === false || this.component.defaultValue === 0)) {\n defaultValue = this.component.defaultValue;\n }\n return defaultValue;\n }\n getTemplateKeys() {\n this.templateKeys = [];\n if (this.options.readOnly && this.component.template) {\n const keys = this.component.template.match(/({{\\s*(.*?)\\s*}})/g);\n if (keys) {\n keys.forEach((key) => {\n const propKey = key.match(/{{\\s*item\\.(.*?)\\s*}}/);\n if (propKey && propKey.length > 1) {\n this.templateKeys.push(propKey[1]);\n }\n });\n }\n }\n }\n get loadingError() {\n return !this.component.refreshOn && !this.component.refreshOnBlur && this.networkError;\n }\n get selectData() {\n const selectData = lodash_1.default.get(this.root, 'submission.metadata.selectData', {});\n return lodash_1.default.get(selectData, this.path);\n }\n get shouldLoad() {\n if (this.loadingError) {\n return false;\n }\n // Live forms should always load.\n if (!this.options.readOnly) {\n return true;\n }\n // If there are template keys, then we need to see if we have the data.\n if (this.templateKeys && this.templateKeys.length) {\n // See if we already have the data we need.\n const dataValue = this.dataValue;\n const selectData = this.selectData;\n return this.templateKeys.reduce((shouldLoad, key) => {\n const hasValue = lodash_1.default.has(dataValue, key) || lodash_1.default.has(selectData, key);\n return shouldLoad || !hasValue;\n }, false);\n }\n // Return that we should load.\n return true;\n }\n loadItems(url, search, headers, options, method, body) {\n options = options || {};\n // See if we should load items or not.\n if (!this.shouldLoad || (!this.itemsFromUrl && this.options.readOnly)) {\n this.isScrollLoading = false;\n this.loading = false;\n this.itemsLoadedResolve();\n return;\n }\n // See if they have not met the minimum search requirements.\n const minSearch = parseInt(this.component.minSearch, 10);\n if (this.component.searchField &&\n (minSearch > 0) &&\n (!search || (search.length < minSearch))) {\n // Set empty items.\n return this.setItems([]);\n }\n // Ensure we have a method and remove any body if method is get\n method = method || 'GET';\n if (method.toUpperCase() === 'GET') {\n body = null;\n }\n const limit = this.component.limit || 100;\n const skip = this.isScrollLoading ? this.selectOptions.length : 0;\n const query = this.component.disableLimit ? {} : {\n limit,\n skip,\n };\n // Allow for url interpolation.\n url = this.interpolate(url, {\n formioBase: Formio_1.Formio.getBaseUrl(),\n search,\n limit,\n skip,\n page: Math.abs(Math.floor(skip / limit))\n });\n // Add search capability.\n if (this.component.searchField && search) {\n const searchValue = Array.isArray(search) ? search.join(',') : search;\n query[this.component.searchField] = this.component.searchField.endsWith('__regex')\n ? lodash_1.default.escapeRegExp(searchValue)\n : searchValue;\n }\n // If they wish to return only some fields.\n if (this.component.selectFields) {\n query.select = this.component.selectFields;\n }\n // Add sort capability\n if (this.component.sort) {\n query.sort = this.component.sort;\n }\n if (!lodash_1.default.isEmpty(query)) {\n // Add the query string.\n url += (!url.includes('?') ? '?' : '&') + Formio_1.Formio.serialize(query, (item) => this.interpolate(item));\n }\n // Add filter capability\n if (this.component.filter) {\n url += (!url.includes('?') ? '?' : '&') + this.interpolate(this.component.filter);\n }\n // Set ignoreCache if it is\n options.ignoreCache = this.component.ignoreCache;\n // Make the request.\n options.header = headers;\n this.loading = true;\n Formio_1.Formio.makeRequest(this.options.formio, 'select', url, method, body, options)\n .then((response) => {\n this.loading = false;\n this.error = null;\n this.setItems(response, !!search);\n })\n .catch((err) => {\n if (this.itemsFromUrl) {\n this.setItems([]);\n this.disableInfiniteScroll();\n }\n this.isScrollLoading = false;\n this.handleLoadingError(err);\n });\n }\n handleLoadingError(err) {\n this.loading = false;\n if (err.networkError) {\n this.networkError = true;\n }\n this.itemsLoadedResolve();\n this.emit('componentError', {\n component: this.component,\n message: err.toString(),\n });\n console.warn(`Unable to load resources for ${this.key}`);\n }\n /**\n * Get the request headers for this select dropdown.\n */\n get requestHeaders() {\n // Create the headers object.\n const headers = new Formio_1.Formio.Headers();\n // Add custom headers to the url.\n if (this.component.data && this.component.data.headers) {\n try {\n lodash_1.default.each(this.component.data.headers, (header) => {\n if (header.key) {\n headers.set(header.key, this.interpolate(header.value));\n }\n });\n }\n catch (err) {\n console.warn(err.message);\n }\n }\n return headers;\n }\n getCustomItems() {\n const customItems = this.evaluate(this.component.data.custom, {\n values: []\n }, 'values');\n this.asyncValues = (0, utils_1.isPromise)(customItems);\n return customItems;\n }\n asyncCustomValues() {\n if (!lodash_1.default.isBoolean(this.asyncValues)) {\n this.getCustomItems();\n }\n return this.asyncValues;\n }\n updateCustomItems(forceUpdate) {\n if (this.asyncCustomValues()) {\n if (!forceUpdate && !this.active) {\n this.itemsLoadedResolve();\n return;\n }\n this.loading = true;\n this.getCustomItems()\n .then(items => {\n this.loading = false;\n this.setItems(items || []);\n })\n .catch(err => {\n this.handleLoadingError(err);\n });\n }\n else {\n this.setItems(this.getCustomItems() || []);\n }\n }\n isEmpty(value = this.dataValue) {\n return super.isEmpty(value) || value === undefined;\n }\n refresh(value, { instance }) {\n if (this.component.clearOnRefresh && (instance && !instance.pristine)) {\n this.setValue(this.emptyValue);\n }\n this.updateItems(null, true);\n }\n get additionalResourcesAvailable() {\n return lodash_1.default.isNil(this.serverCount) || (this.serverCount > this.downloadedResources.length);\n }\n get serverCount() {\n if (this.isFromSearch) {\n return this.searchServerCount;\n }\n return this.defaultServerCount;\n }\n set serverCount(value) {\n if (this.isFromSearch) {\n this.searchServerCount = value;\n }\n else {\n this.defaultServerCount = value;\n }\n }\n get downloadedResources() {\n if (this.isFromSearch) {\n return this.searchDownloadedResources;\n }\n return this.defaultDownloadedResources;\n }\n set downloadedResources(value) {\n if (this.isFromSearch) {\n this.searchDownloadedResources = value;\n }\n else {\n this.defaultDownloadedResources = value;\n }\n }\n addPlaceholder() {\n if (!this.component.placeholder) {\n return;\n }\n this.addOption('', this.component.placeholder, { placeholder: true });\n }\n /**\n * Activate this select control.\n */\n activate() {\n if (this.loading || !this.active) {\n this.setLoadingItem();\n }\n if (this.active) {\n return;\n }\n this.activated = true;\n this.triggerUpdate();\n }\n setLoadingItem(addToCurrentList = false) {\n if (this.choices) {\n if (addToCurrentList) {\n this.choices.setChoices([{\n value: `${this.id}-loading`,\n label: 'Loading...',\n disabled: true,\n }], 'value', 'label');\n }\n else {\n this.choices.setChoices([{\n value: '',\n label: `<i class=\"${this.iconClass('refresh')}\" style=\"font-size:1.3em;\"></i>`,\n disabled: true,\n }], 'value', 'label', true);\n }\n }\n else if (this.component.dataSrc === 'url' || this.component.dataSrc === 'resource') {\n this.addOption('', this.t('loading...'));\n }\n }\n get active() {\n return !this.component.lazyLoad || this.activated;\n }\n render() {\n const info = this.inputInfo;\n info.attr = info.attr || {};\n info.multiple = this.component.multiple;\n return super.render(this.wrapElement(this.renderTemplate('select', {\n input: info,\n selectOptions: '',\n index: null,\n })));\n }\n wrapElement(element) {\n return this.component.addResource && !this.options.readOnly\n ? (this.renderTemplate('resourceAdd', {\n element\n }))\n : element;\n }\n choicesOptions() {\n const useSearch = this.component.hasOwnProperty('searchEnabled') ? this.component.searchEnabled : true;\n const placeholderValue = this.t(this.component.placeholder, { _userInput: true });\n let customOptions = this.component.customOptions || {};\n if (typeof customOptions == 'string') {\n try {\n customOptions = JSON.parse(customOptions);\n }\n catch (err) {\n console.warn(err.message);\n customOptions = {};\n }\n }\n const commonFuseOptions = {\n maxPatternLength: 1000,\n distance: 1000,\n };\n return Object.assign({ removeItemButton: this.component.disabled ? false : lodash_1.default.get(this.component, 'removeItemButton', true), itemSelectText: '', classNames: {\n containerOuter: 'choices form-group formio-choices',\n containerInner: this.transform('class', 'form-control ui fluid selection dropdown')\n }, addItemText: false, allowHTML: true, placeholder: !!this.component.placeholder, placeholderValue: placeholderValue, noResultsText: this.t('No results found'), noChoicesText: this.t('No choices to choose from'), searchPlaceholderValue: this.t('Type to search'), shouldSort: false, position: (this.component.dropdown || 'auto'), searchEnabled: useSearch, searchChoices: !this.component.searchField, searchFields: lodash_1.default.get(this, 'component.searchFields', ['label']), shadowRoot: this.root ? this.root.shadowRoot : null, fuseOptions: this.component.useExactSearch\n ? Object.assign({ tokenize: true, matchAllTokens: true }, commonFuseOptions) : Object.assign({}, lodash_1.default.get(this, 'component.fuseOptions', {}), Object.assign({ include: 'score', threshold: lodash_1.default.get(this, 'component.selectThreshold', 0.3) }, commonFuseOptions)), valueComparer: lodash_1.default.isEqual, resetScrollPosition: false }, customOptions);\n }\n /* eslint-disable max-statements */\n attach(element) {\n var _a, _b, _c;\n const superAttach = super.attach(element);\n this.loadRefs(element, {\n selectContainer: 'single',\n addResource: 'single',\n autocompleteInput: 'single'\n });\n //enable autocomplete for select\n const autocompleteInput = this.refs.autocompleteInput;\n if (autocompleteInput) {\n this.addEventListener(autocompleteInput, 'change', (event) => {\n this.setValue(event.target.value);\n });\n }\n const input = this.refs.selectContainer;\n if (!input) {\n return;\n }\n this.addEventListener(input, this.inputInfo.changeEvent, () => this.updateValue(null, {\n modified: true\n }));\n this.attachRefreshOnBlur();\n if (this.component.widget === 'html5') {\n this.addFocusBlurEvents(input);\n this.triggerUpdate(null, true);\n if (this.visible) {\n this.setItems(this.selectOptions || []);\n }\n this.focusableElement = input;\n this.addEventListener(input, 'focus', () => this.update());\n this.addEventListener(input, 'keydown', (event) => {\n const { key } = event;\n if (['Backspace', 'Delete'].includes(key)) {\n this.setValue(this.emptyValue);\n }\n });\n return;\n }\n const tabIndex = input.tabIndex;\n this.addPlaceholder();\n if (this.i18next) {\n input.setAttribute('dir', this.i18next.dir());\n }\n if ((_c = (_b = (_a = this.choices) === null || _a === void 0 ? void 0 : _a.containerOuter) === null || _b === void 0 ? void 0 : _b.element) === null || _c === void 0 ? void 0 : _c.parentNode) {\n this.choices.destroy();\n }\n const choicesOptions = this.choicesOptions();\n if (ChoicesWrapper_1.default) {\n this.choices = new ChoicesWrapper_1.default(input, choicesOptions);\n if (this.selectOptions && this.selectOptions.length) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n if (this.component.multiple) {\n this.focusableElement = this.choices.input.element;\n }\n else {\n this.focusableElement = this.choices.containerInner.element;\n this.choices.containerOuter.element.setAttribute('tabIndex', '-1');\n this.addEventListener(this.choices.containerOuter.element, 'focus', () => this.focusableElement.focus());\n }\n this.addFocusBlurEvents(this.focusableElement);\n if (this.itemsFromUrl && !this.component.noRefreshOnScroll) {\n this.scrollList = this.choices.choiceList.element;\n this.addEventListener(this.scrollList, 'scroll', () => this.onScroll());\n }\n }\n this.focusableElement.setAttribute('tabIndex', tabIndex);\n // If a search field is provided, then add an event listener to update items on search.\n if (this.component.searchField) {\n // Make sure to clear the search when no value is provided.\n if (this.choices && this.choices.input && this.choices.input.element) {\n this.addEventListener(this.choices.input.element, 'input', (event) => {\n this.isFromSearch = !!event.target.value;\n if (!event.target.value) {\n this.triggerUpdate();\n }\n else {\n this.serverCount = null;\n this.downloadedResources = [];\n }\n });\n }\n this.addEventListener(input, 'choice', () => {\n if (this.component.multiple && this.component.dataSrc === 'resource' && this.isFromSearch) {\n this.triggerUpdate();\n }\n this.isFromSearch = false;\n });\n // avoid spamming the resource/url endpoint when we have server side filtering enabled.\n const debounceTimeout = this.component.searchField && (this.isSelectResource || this.isSelectURL) ?\n (this.component.searchDebounce === 0 ? 0 : this.component.searchDebounce || this.defaultSchema.searchDebounce) * 1000\n : 0;\n const updateComponent = (evt) => {\n this.triggerUpdate(evt.detail.value);\n };\n this.addEventListener(input, 'search', lodash_1.default.debounce(updateComponent, debounceTimeout));\n this.addEventListener(input, 'stopSearch', () => this.triggerUpdate());\n this.addEventListener(input, 'hideDropdown', () => {\n if (this.choices && this.choices.input && this.choices.input.element) {\n this.choices.input.element.value = '';\n }\n this.updateItems(null, true);\n });\n }\n this.addEventListener(input, 'showDropdown', () => this.update());\n if (this.choices && choicesOptions.placeholderValue && this.choices._isSelectOneElement) {\n this.addPlaceholderItem(choicesOptions.placeholderValue);\n this.addEventListener(input, 'removeItem', () => {\n this.addPlaceholderItem(choicesOptions.placeholderValue);\n });\n }\n // Add value options.\n this.addValueOptions();\n this.setChoicesValue(this.dataValue);\n if (this.isSelectResource && this.refs.addResource) {\n this.addEventListener(this.refs.addResource, 'click', (event) => {\n event.preventDefault();\n const formioForm = this.ce('div');\n const dialog = this.createModal(formioForm);\n const projectUrl = lodash_1.default.get(this.root, 'formio.projectUrl', Formio_1.Formio.getProjectUrl());\n const formUrl = `${projectUrl}/form/${this.component.data.resource}`;\n new Form_1.default(formioForm, formUrl, {}).ready\n .then((form) => {\n form.on('submit', (submission) => {\n // If valueProperty is set, replace the submission with the corresponding value\n let value = this.valueProperty ? lodash_1.default.get(submission, this.valueProperty) : submission;\n if (this.component.multiple) {\n value = [...this.dataValue, value];\n }\n this.setValue(value);\n this.triggerUpdate();\n dialog.close();\n });\n });\n });\n }\n // Force the disabled state with getters and setters.\n this.disabled = this.shouldDisabled;\n this.triggerUpdate();\n return superAttach;\n }\n get isLoadingAvailable() {\n return !this.isScrollLoading && this.additionalResourcesAvailable;\n }\n onScroll() {\n if (this.isLoadingAvailable) {\n this.isScrollLoading = true;\n this.setLoadingItem(true);\n this.triggerUpdate(this.choices.input.element.value);\n }\n }\n attachRefreshOnBlur() {\n if (this.component.refreshOnBlur) {\n this.on('blur', (instance) => {\n this.checkRefreshOn([{ instance, value: instance.dataValue }], { fromBlur: true });\n });\n }\n }\n addPlaceholderItem(placeholderValue) {\n const items = this.choices._store.activeItems;\n if (!items.length) {\n this.choices._addItem({\n value: placeholderValue,\n label: placeholderValue,\n choiceId: 0,\n groupId: -1,\n customProperties: null,\n placeholder: true,\n keyCode: null\n });\n }\n }\n /* eslint-enable max-statements */\n update() {\n if (this.component.dataSrc === 'custom') {\n this.updateCustomItems();\n }\n // Activate the control.\n this.activate();\n }\n set disabled(disabled) {\n super.disabled = disabled;\n if (!this.choices) {\n return;\n }\n if (disabled) {\n this.setDisabled(this.choices.containerInner.element, true);\n this.focusableElement.removeAttribute('tabIndex');\n this.choices.disable();\n }\n else {\n this.setDisabled(this.choices.containerInner.element, false);\n this.focusableElement.setAttribute('tabIndex', this.component.tabindex || 0);\n this.choices.enable();\n }\n }\n get disabled() {\n return super.disabled;\n }\n set visible(value) {\n // If we go from hidden to visible, trigger a refresh.\n if (value && (!this._visible !== !value)) {\n this.triggerUpdate();\n }\n super.visible = value;\n }\n get visible() {\n return super.visible;\n }\n /**\n * @param {*} value\n * @param {Array} items\n */\n addCurrentChoices(values, items, keyValue) {\n if (!values) {\n return false;\n }\n const notFoundValuesToAdd = [];\n const added = values.reduce((defaultAdded, value) => {\n if (!value || lodash_1.default.isEmpty(value)) {\n return defaultAdded;\n }\n let found = false;\n // Make sure that `items` and `this.selectOptions` points\n // to the same reference. Because `this.selectOptions` is\n // internal property and all items are populated by\n // `this.addOption` method, we assume that items has\n // 'label' and 'value' properties. This assumption allows\n // us to read correct value from the item.\n const isSelectOptions = items === this.selectOptions;\n if (items && items.length) {\n lodash_1.default.each(items, (choice) => {\n if (choice._id && value._id && (choice._id === value._id)) {\n found = true;\n return false;\n }\n const itemValue = keyValue ? choice.value : this.itemValue(choice, isSelectOptions);\n found |= lodash_1.default.isEqual(itemValue, value);\n return found ? false : true;\n });\n }\n // Add the default option if no item is found.\n if (!found) {\n notFoundValuesToAdd.push(this.selectValueAndLabel(value));\n return true;\n }\n return found || defaultAdded;\n }, false);\n if (notFoundValuesToAdd.length) {\n if (this.choices) {\n this.choices.setChoices(notFoundValuesToAdd, 'value', 'label');\n }\n notFoundValuesToAdd.map(notFoundValue => {\n this.addOption(notFoundValue.value, notFoundValue.label);\n });\n }\n return added;\n }\n getValueAsString(data) {\n return (this.component.multiple && Array.isArray(data))\n ? data.map(this.asString.bind(this)).join(', ')\n : this.asString(data);\n }\n getValue() {\n // If the widget isn't active.\n if (this.viewOnly || this.loading\n || (!this.component.lazyLoad && !this.selectOptions.length)\n || !this.element) {\n return this.dataValue;\n }\n let value = this.emptyValue;\n if (this.choices) {\n value = this.choices.getValue(true);\n // Make sure we don't get the placeholder\n if (!this.component.multiple &&\n this.component.placeholder &&\n (value === this.t(this.component.placeholder, { _userInput: true }))) {\n value = this.emptyValue;\n }\n }\n else if (this.refs.selectContainer) {\n value = this.refs.selectContainer.value;\n if (this.valueProperty === '' || this.isEntireObjectDisplay()) {\n if (value === '') {\n return {};\n }\n const option = this.selectOptions[value] ||\n this.selectOptions.find(option => option.id === value);\n if (option && lodash_1.default.isObject(option.value)) {\n value = option.value;\n }\n }\n }\n else {\n value = this.dataValue;\n }\n // Choices will return undefined if nothing is selected. We really want '' to be empty.\n if (value === undefined || value === null) {\n value = '';\n }\n return value;\n }\n redraw() {\n const done = super.redraw();\n this.triggerUpdate();\n return done;\n }\n normalizeSingleValue(value, retainObject) {\n var _a;\n if (lodash_1.default.isNil(value)) {\n return;\n }\n const valueIsObject = lodash_1.default.isObject(value);\n //check if value equals to default emptyValue\n if (valueIsObject && Object.keys(value).length === 0) {\n return value;\n }\n // Check to see if we need to save off the template data into our metadata.\n if (retainObject) {\n const templateValue = this.component.reference && (value === null || value === void 0 ? void 0 : value._id) ? value._id.toString() : value;\n const shouldSaveData = !valueIsObject || this.component.reference;\n if (templateValue && shouldSaveData && (this.templateData && this.templateData[templateValue]) && ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submission)) {\n const submission = this.root.submission;\n if (!submission.metadata) {\n submission.metadata = {};\n }\n if (!submission.metadata.selectData) {\n submission.metadata.selectData = {};\n }\n let templateData = this.templateData[templateValue];\n if (this.component.multiple) {\n templateData = {};\n const dataValue = this.dataValue;\n if (dataValue && dataValue.length) {\n dataValue.forEach((dataValueItem) => {\n const dataValueItemValue = this.component.reference ? dataValueItem._id.toString() : dataValueItem;\n templateData[dataValueItemValue] = this.templateData[dataValueItemValue];\n });\n }\n }\n lodash_1.default.set(submission.metadata.selectData, this.path, templateData);\n }\n }\n const dataType = this.component.dataType || 'auto';\n const normalize = {\n value,\n number() {\n const numberValue = Number(this.value);\n const isEquivalent = value.toString() === numberValue.toString();\n if (!Number.isNaN(numberValue) && Number.isFinite(numberValue) && value !== '' && isEquivalent) {\n this.value = numberValue;\n }\n return this;\n },\n boolean() {\n if (lodash_1.default.isString(this.value)\n && (this.value.toLowerCase() === 'true'\n || this.value.toLowerCase() === 'false')) {\n this.value = (this.value.toLowerCase() === 'true');\n }\n return this;\n },\n string() {\n this.value = String(this.value);\n return this;\n },\n object() {\n return this;\n },\n auto() {\n if (lodash_1.default.isObject(this.value)) {\n this.value = this.object().value;\n }\n else {\n this.value = this.string().number().boolean().value;\n }\n return this;\n }\n };\n try {\n return normalize[dataType]().value;\n }\n catch (err) {\n console.warn('Failed to normalize value', err);\n return value;\n }\n }\n /**\n * Normalize values coming into updateValue.\n *\n * @param value\n * @return {*}\n */\n normalizeValue(value) {\n if (this.component.multiple && Array.isArray(value)) {\n return value.map((singleValue) => this.normalizeSingleValue(singleValue, true));\n }\n return super.normalizeValue(this.normalizeSingleValue(value, true));\n }\n setValue(value, flags = {}) {\n const previousValue = this.dataValue;\n if (this.component.widget === 'html5' && (lodash_1.default.isEqual(value, previousValue) || lodash_1.default.isEqual(previousValue, {}) && lodash_1.default.isEqual(flags, {}))) {\n return false;\n }\n const changed = this.updateValue(value, flags);\n value = this.dataValue;\n const hasPreviousValue = !this.isEmpty(previousValue);\n const hasValue = !this.isEmpty(value);\n // Undo typing when searching to set the value.\n if (this.component.multiple && Array.isArray(value)) {\n value = value.map(value => {\n if (typeof value === 'boolean' || typeof value === 'number') {\n return value.toString();\n }\n return value;\n });\n }\n else {\n if (typeof value === 'boolean' || typeof value === 'number') {\n value = value.toString();\n }\n }\n if (this.isHtmlRenderMode() && flags && flags.fromSubmission && changed) {\n this.itemsLoaded.then(() => {\n this.redraw();\n });\n return changed;\n }\n // Do not set the value if we are loading... that will happen after it is done.\n if (this.loading) {\n return changed;\n }\n // Determine if we need to perform an initial lazyLoad api call if searchField is provided.\n if (this.isInitApiCallNeeded(hasValue)) {\n this.loading = true;\n this.lazyLoadInit = true;\n const searchProperty = this.component.searchField || this.component.valueProperty;\n this.triggerUpdate(lodash_1.default.get(value.data || value, searchProperty, value), true);\n return changed;\n }\n // Add the value options.\n this.itemsLoaded.then(() => {\n this.addValueOptions();\n this.setChoicesValue(value, hasPreviousValue, flags);\n });\n return changed;\n }\n isInitApiCallNeeded(hasValue) {\n return this.component.lazyLoad &&\n !this.lazyLoadInit &&\n !this.active &&\n !this.selectOptions.length &&\n hasValue &&\n this.shouldLoad &&\n this.visible && (this.component.searchField || this.component.valueProperty);\n }\n setChoicesValue(value, hasPreviousValue, flags = {}) {\n const hasValue = !this.isEmpty(value) || flags.fromSubmission;\n hasPreviousValue = (hasPreviousValue === undefined) ? true : hasPreviousValue;\n if (this.choices) {\n // Now set the value.\n if (hasValue) {\n this.choices.removeActiveItems();\n // Add the currently selected choices if they don't already exist.\n const currentChoices = Array.isArray(value) && this.component.multiple ? value : [value];\n if (!this.addCurrentChoices(currentChoices, this.selectOptions, true)) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n this.choices.setChoiceByValue(currentChoices);\n }\n else if (hasPreviousValue || flags.resetValue) {\n this.choices.removeActiveItems();\n }\n }\n else {\n if (hasValue) {\n const values = Array.isArray(value) ? value : [value];\n if (!lodash_1.default.isEqual(this.dataValue, this.defaultValue) && this.selectOptions.length < 2) {\n const { value, label } = this.selectValueAndLabel(this.dataValue);\n this.addOption(value, label);\n }\n lodash_1.default.each(this.selectOptions, (selectOption) => {\n lodash_1.default.each(values, (val) => {\n if (selectOption.value === '') {\n selectOption.value = {};\n }\n if (lodash_1.default.isEqual(val, selectOption.value) && selectOption.element) {\n selectOption.element.selected = true;\n selectOption.element.setAttribute('selected', 'selected');\n return false;\n }\n });\n });\n }\n else {\n lodash_1.default.each(this.selectOptions, (selectOption) => {\n if (selectOption.element) {\n selectOption.element.selected = false;\n selectOption.element.removeAttribute('selected');\n }\n });\n }\n }\n }\n get itemsLoaded() {\n return this._itemsLoaded || native_promise_only_1.default.resolve();\n }\n set itemsLoaded(promise) {\n this._itemsLoaded = promise;\n }\n validateValueAvailability(setting, value) {\n if (!(0, utils_1.boolValue)(setting) || !value) {\n return true;\n }\n const values = this.getOptionsValues();\n if (values) {\n if (lodash_1.default.isObject(value)) {\n const compareComplexValues = (optionValue) => {\n const normalizedOptionValue = this.normalizeSingleValue(optionValue, true);\n if (!lodash_1.default.isObject(normalizedOptionValue)) {\n return false;\n }\n try {\n return (JSON.stringify(normalizedOptionValue) === JSON.stringify(value));\n }\n catch (err) {\n console.warn.error('Error while comparing items', err);\n return false;\n }\n };\n return values.findIndex((optionValue) => compareComplexValues(optionValue)) !== -1;\n }\n return values.findIndex((optionValue) => this.normalizeSingleValue(optionValue) === value) !== -1;\n }\n return false;\n }\n /**\n * Performs required transformations on the initial value to use in selectOptions\n * @param {*} value\n */\n getOptionValue(value) {\n return lodash_1.default.isObject(value) && this.isEntireObjectDisplay()\n ? this.normalizeSingleValue(value)\n : lodash_1.default.isObject(value) && (this.valueProperty || this.component.key !== 'resource')\n ? value\n : lodash_1.default.isObject(value) && !this.valueProperty\n ? this.interpolate(this.component.template, { item: value }).replace(/<\\/?[^>]+(>|$)/g, '')\n : lodash_1.default.isNull(value)\n ? this.emptyValue\n : String(this.normalizeSingleValue(value));\n }\n /**\n * If component has static values (values, json) or custom values, returns an array of them\n * @returns {Array<*>|undefined}\n */\n getOptionsValues() {\n let rawItems = [];\n switch (this.component.dataSrc) {\n case 'values':\n rawItems = this.component.data.values;\n break;\n case 'json':\n rawItems = this.component.data.json;\n break;\n case 'custom':\n rawItems = this.getCustomItems();\n break;\n }\n if (typeof rawItems === 'string') {\n try {\n rawItems = JSON.parse(rawItems);\n }\n catch (err) {\n console.warn(err.message);\n rawItems = [];\n }\n }\n if (!Array.isArray(rawItems)) {\n return;\n }\n return rawItems.map((item) => this.getOptionValue(this.itemValue(item)));\n }\n /**\n * Deletes the value of the component.\n */\n deleteValue() {\n this.setValue('', {\n noUpdateEvent: true\n });\n this.unset();\n }\n /**\n * Check if a component is eligible for multiple validation\n *\n * @return {boolean}\n */\n validateMultiple() {\n // Select component will contain one input when flagged as multiple.\n return false;\n }\n /**\n * Output this select dropdown as a string value.\n * @return {*}\n */\n isBooleanOrNumber(value) {\n return typeof value === 'number' || typeof value === 'boolean';\n }\n getNormalizedValues() {\n if (!this.component || !this.component.data || !this.component.data.values) {\n return;\n }\n return this.component.data.values.map(value => ({ label: value.label, value: String(this.normalizeSingleValue(value.value)) }));\n }\n asString(value) {\n var _a;\n value = value !== null && value !== void 0 ? value : this.getValue();\n //need to convert values to strings to be able to compare values with available options that are strings\n const convertToString = (data, valueProperty) => {\n if (valueProperty) {\n if (Array.isArray(data)) {\n data.forEach((item) => item[valueProperty] = item[valueProperty].toString());\n }\n else {\n data[valueProperty] = data[valueProperty].toString();\n }\n return data;\n }\n if (this.isBooleanOrNumber(data)) {\n data = data.toString();\n }\n if (Array.isArray(data) && data.some(item => this.isBooleanOrNumber(item))) {\n data = data.map(item => {\n if (this.isBooleanOrNumber(item)) {\n item = item.toString();\n }\n });\n }\n return data;\n };\n value = convertToString(value);\n if (['values', 'custom'].includes(this.component.dataSrc) && !this.asyncCustomValues()) {\n const { items, valueProperty, } = this.component.dataSrc === 'values'\n ? {\n items: convertToString(this.getNormalizedValues(), 'value'),\n valueProperty: 'value',\n }\n : {\n items: convertToString(this.getCustomItems(), this.valueProperty),\n valueProperty: this.valueProperty,\n };\n const getFromValues = () => {\n const initialValue = lodash_1.default.find(items, [valueProperty, value]);\n const values = this.defaultSchema.data.values || [];\n return lodash_1.default.isEqual(initialValue, values[0]) ? '-' : initialValue;\n };\n value = (this.component.multiple && Array.isArray(value))\n ? lodash_1.default.filter(items, (item) => value.includes(item.value))\n : valueProperty\n ? (_a = getFromValues()) !== null && _a !== void 0 ? _a : { value, label: value }\n : value;\n }\n if (lodash_1.default.isString(value)) {\n return value;\n }\n if (Array.isArray(value)) {\n const items = [];\n value.forEach(item => items.push(this.itemTemplate(item)));\n if (this.component.dataSrc === 'resource' && items.length > 0) {\n return items.join(', ');\n }\n else if (items.length > 0) {\n return items.join('<br />');\n }\n else {\n return '-';\n }\n }\n return !lodash_1.default.isNil(value)\n ? this.itemTemplate(value)\n : '-';\n }\n detach() {\n var _a, _b;\n this.off('blur');\n if (this.choices) {\n if ((_b = (_a = this.choices.containerOuter) === null || _a === void 0 ? void 0 : _a.element) === null || _b === void 0 ? void 0 : _b.parentNode) {\n this.choices.destroy();\n }\n this.choices = null;\n }\n super.detach();\n }\n focus() {\n if (this.focusableElement) {\n super.focus.call(this);\n this.focusableElement.focus();\n }\n }\n setErrorClasses(elements, dirty, hasError, hasMessages, element = this.element) {\n super.setErrorClasses(elements, dirty, hasError, hasMessages, element);\n if (this.choices) {\n super.setErrorClasses([this.choices.containerInner.element], dirty, hasError, hasMessages, element);\n }\n else {\n super.setErrorClasses([this.refs.selectContainer], dirty, hasError, hasMessages, element);\n }\n }\n}\nexports[\"default\"] = SelectComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/select/Select.js?");
6922
6912
 
6923
6913
  /***/ }),
6924
6914
 
@@ -7182,7 +7172,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
7182
7172
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
7183
7173
 
7184
7174
  "use strict";
7185
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst Input_1 = __importDefault(__webpack_require__(/*! ../_classes/input/Input */ \"./lib/cjs/components/_classes/input/Input.js\"));\nlet Choices;\nif (typeof window !== 'undefined') {\n Choices = __webpack_require__(/*! @formio/choices.js */ \"./node_modules/@formio/choices.js/public/assets/scripts/choices.js\");\n}\nclass TagsComponent extends Input_1.default {\n static schema(...extend) {\n return Input_1.default.schema({\n type: 'tags',\n label: 'Tags',\n key: 'tags',\n delimeter: ',',\n storeas: 'string',\n maxTags: 0\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Tags',\n icon: 'tags',\n group: 'advanced',\n documentation: '/userguide/form-building/advanced-components#tags',\n weight: 30,\n schema: TagsComponent.schema()\n };\n }\n init() {\n super.init();\n }\n get emptyValue() {\n return (this.component.storeas === 'string') ? '' : [];\n }\n get defaultSchema() {\n return TagsComponent.schema();\n }\n get inputInfo() {\n const info = super.inputInfo;\n info.type = 'input';\n info.attr.type = 'text';\n info.changeEvent = 'change';\n return info;\n }\n get delimiter() {\n return this.component.delimeter || ',';\n }\n attachElement(element, index) {\n super.attachElement(element, index);\n if (!element) {\n return;\n }\n if (this.i18next) {\n element.setAttribute('dir', this.i18next.dir());\n }\n if (this.choices) {\n this.choices.destroy();\n }\n if (!Choices) {\n return;\n }\n const hasPlaceholder = !!this.component.placeholder;\n this.choices = new Choices(element, {\n delimiter: this.delimiter,\n editItems: true,\n allowHTML: true,\n maxItemCount: this.component.maxTags,\n removeItemButton: true,\n duplicateItemsAllowed: false,\n shadowRoot: this.root ? this.root.shadowRoot : null,\n placeholder: hasPlaceholder,\n placeholderValue: hasPlaceholder ? this.t(this.component.placeholder, { _userInput: true }) : null,\n });\n this.choices.itemList.element.tabIndex = element.tabIndex;\n this.addEventListener(this.choices.input.element, 'blur', () => {\n const value = this.choices.input.value;\n const maxTagsNumber = this.component.maxTags;\n const valuesCount = this.choices.getValue(true).length;\n const isRepeatedValue = this.choices.getValue(true).some(existingValue => existingValue.trim() === value.trim());\n if (value) {\n if (maxTagsNumber && valuesCount === maxTagsNumber) {\n this.choices.addItems = false;\n this.choices.clearInput();\n }\n else if (isRepeatedValue) {\n this.choices.clearInput();\n }\n else {\n this.choices.setValue([value]);\n this.choices.clearInput();\n this.choices.hideDropdown(true);\n this.updateValue(null, {\n modified: true\n });\n }\n }\n });\n }\n detach() {\n if (this.choices) {\n this.choices.destroy();\n this.choices = null;\n }\n super.detach();\n }\n normalizeValue(value) {\n if (this.component.storeas === 'string' && Array.isArray(value)) {\n return value.join(this.delimiter);\n }\n else if (this.component.storeas === 'array' && typeof value === 'string') {\n return value.split(this.delimiter).filter(result => result);\n }\n return value;\n }\n setValue(value, flags = {}) {\n const changed = super.setValue(value, flags);\n if (this.choices) {\n let dataValue = this.dataValue;\n this.choices.removeActiveItems();\n if (dataValue) {\n if (typeof dataValue === 'string') {\n dataValue = dataValue.split(this.delimiter).filter(result => result);\n }\n const value = Array.isArray(dataValue) ? dataValue : [dataValue];\n this.choices.setValue(value.map((val) => this.sanitize(val, this.shouldSanitizeValue)));\n }\n }\n return changed;\n }\n set disabled(disabled) {\n super.disabled = disabled;\n if (!this.choices) {\n return;\n }\n if (disabled) {\n this.choices.disable();\n }\n else {\n this.choices.enable();\n }\n }\n get disabled() {\n return super.disabled;\n }\n focus() {\n if (this.refs.input && this.refs.input.length) {\n this.refs.input[0].parentNode.lastChild.focus();\n }\n }\n getValueAsString(value) {\n if (!value) {\n return '';\n }\n if (Array.isArray(value)) {\n return value.join(`${this.delimiter || ','} `);\n }\n const stringValue = value.toString();\n return this.sanitize(stringValue, this.shouldSanitizeValue);\n }\n}\nexports[\"default\"] = TagsComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/tags/Tags.js?");
7175
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst Input_1 = __importDefault(__webpack_require__(/*! ../_classes/input/Input */ \"./lib/cjs/components/_classes/input/Input.js\"));\nconst choices_js_1 = __importDefault(__webpack_require__(/*! @formio/choices.js */ \"./node_modules/@formio/choices.js/public/assets/scripts/choices.js\"));\nclass TagsComponent extends Input_1.default {\n static schema(...extend) {\n return Input_1.default.schema({\n type: 'tags',\n label: 'Tags',\n key: 'tags',\n delimeter: ',',\n storeas: 'string',\n maxTags: 0\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Tags',\n icon: 'tags',\n group: 'advanced',\n documentation: '/userguide/form-building/advanced-components#tags',\n weight: 30,\n schema: TagsComponent.schema()\n };\n }\n init() {\n super.init();\n }\n get emptyValue() {\n return (this.component.storeas === 'string') ? '' : [];\n }\n get defaultSchema() {\n return TagsComponent.schema();\n }\n get inputInfo() {\n const info = super.inputInfo;\n info.type = 'input';\n info.attr.type = 'text';\n info.changeEvent = 'change';\n return info;\n }\n get delimiter() {\n return this.component.delimeter || ',';\n }\n attachElement(element, index) {\n super.attachElement(element, index);\n if (!element) {\n return;\n }\n if (this.i18next) {\n element.setAttribute('dir', this.i18next.dir());\n }\n if (this.choices) {\n this.choices.destroy();\n }\n if (!choices_js_1.default) {\n return;\n }\n const hasPlaceholder = !!this.component.placeholder;\n this.choices = new choices_js_1.default(element, {\n delimiter: this.delimiter,\n editItems: true,\n allowHTML: true,\n maxItemCount: this.component.maxTags,\n removeItemButton: true,\n duplicateItemsAllowed: false,\n shadowRoot: this.root ? this.root.shadowRoot : null,\n placeholder: hasPlaceholder,\n placeholderValue: hasPlaceholder ? this.t(this.component.placeholder, { _userInput: true }) : null,\n });\n this.choices.itemList.element.tabIndex = element.tabIndex;\n this.addEventListener(this.choices.input.element, 'blur', () => {\n const value = this.choices.input.value;\n const maxTagsNumber = this.component.maxTags;\n const valuesCount = this.choices.getValue(true).length;\n const isRepeatedValue = this.choices.getValue(true).some(existingValue => existingValue.trim() === value.trim());\n if (value) {\n if (maxTagsNumber && valuesCount === maxTagsNumber) {\n this.choices.addItems = false;\n this.choices.clearInput();\n }\n else if (isRepeatedValue) {\n this.choices.clearInput();\n }\n else {\n this.choices.setValue([value]);\n this.choices.clearInput();\n this.choices.hideDropdown(true);\n this.updateValue(null, {\n modified: true\n });\n }\n }\n });\n }\n detach() {\n if (this.choices) {\n this.choices.destroy();\n this.choices = null;\n }\n super.detach();\n }\n normalizeValue(value) {\n if (this.component.storeas === 'string' && Array.isArray(value)) {\n return value.join(this.delimiter);\n }\n else if (this.component.storeas === 'array' && typeof value === 'string') {\n return value.split(this.delimiter).filter(result => result);\n }\n return value;\n }\n setValue(value, flags = {}) {\n const changed = super.setValue(value, flags);\n if (this.choices) {\n let dataValue = this.dataValue;\n this.choices.removeActiveItems();\n if (dataValue) {\n if (typeof dataValue === 'string') {\n dataValue = dataValue.split(this.delimiter).filter(result => result);\n }\n const value = Array.isArray(dataValue) ? dataValue : [dataValue];\n this.choices.setValue(value.map((val) => this.sanitize(val, this.shouldSanitizeValue)));\n }\n }\n return changed;\n }\n set disabled(disabled) {\n super.disabled = disabled;\n if (!this.choices) {\n return;\n }\n if (disabled) {\n this.choices.disable();\n }\n else {\n this.choices.enable();\n }\n }\n get disabled() {\n return super.disabled;\n }\n focus() {\n if (this.refs.input && this.refs.input.length) {\n this.refs.input[0].parentNode.lastChild.focus();\n }\n }\n getValueAsString(value) {\n if (!value) {\n return '';\n }\n if (Array.isArray(value)) {\n return value.join(`${this.delimiter || ','} `);\n }\n const stringValue = value.toString();\n return this.sanitize(stringValue, this.shouldSanitizeValue);\n }\n}\nexports[\"default\"] = TagsComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/tags/Tags.js?");
7186
7176
 
7187
7177
  /***/ }),
7188
7178
 
@@ -10219,7 +10209,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo
10219
10209
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
10220
10210
 
10221
10211
  "use strict";
10222
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Formio = void 0;\nconst core_1 = __webpack_require__(/*! @formio/core */ \"./node_modules/@formio/core/lib/index.js\");\nObject.defineProperty(exports, \"Formio\", ({ enumerable: true, get: function () { return core_1.Formio; } }));\nconst CDN_1 = __importDefault(__webpack_require__(/*! ./CDN */ \"./lib/cjs/CDN.js\"));\nconst providers_1 = __importDefault(__webpack_require__(/*! ./providers */ \"./lib/cjs/providers/index.js\"));\ncore_1.Formio.cdn = new CDN_1.default();\ncore_1.Formio.Providers = providers_1.default;\ncore_1.Formio.version = '5.0.0-rc.12';\nconst isNil = (val) => val === null || val === undefined;\ncore_1.Formio.prototype.uploadFile = function (storage, file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, uploadStartCallback, abortCallback) {\n const requestArgs = {\n provider: storage,\n method: 'upload',\n file: file,\n fileName: fileName,\n dir: dir\n };\n fileKey = fileKey || 'file';\n const request = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', storage);\n if (Provider) {\n const provider = new Provider(this);\n if (uploadStartCallback) {\n uploadStartCallback();\n }\n return provider.uploadFile(file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, abortCallback);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\ncore_1.Formio.prototype.downloadFile = function (file, options) {\n const requestArgs = {\n method: 'download',\n file: file\n };\n const request = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (file.storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', file.storage);\n if (Provider) {\n const provider = new Provider(this);\n return provider.downloadFile(file, options);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\ncore_1.Formio.prototype.deleteFile = function (file, options) {\n const requestArgs = {\n method: 'delete',\n file: file\n };\n const request = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (file.storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', file.storage);\n if (Provider) {\n const provider = new Provider(this);\n return provider.deleteFile(file, options);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\n// For reverse compatability.\ncore_1.Formio.Promise = Promise;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Formio.js?");
10212
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Formio = void 0;\nconst core_1 = __webpack_require__(/*! @formio/core */ \"./node_modules/@formio/core/lib/index.js\");\nObject.defineProperty(exports, \"Formio\", ({ enumerable: true, get: function () { return core_1.Formio; } }));\nconst CDN_1 = __importDefault(__webpack_require__(/*! ./CDN */ \"./lib/cjs/CDN.js\"));\nconst providers_1 = __importDefault(__webpack_require__(/*! ./providers */ \"./lib/cjs/providers/index.js\"));\ncore_1.Formio.cdn = new CDN_1.default();\ncore_1.Formio.Providers = providers_1.default;\ncore_1.Formio.version = '5.0.0-rc.13';\nconst isNil = (val) => val === null || val === undefined;\ncore_1.Formio.prototype.uploadFile = function (storage, file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, uploadStartCallback, abortCallback) {\n const requestArgs = {\n provider: storage,\n method: 'upload',\n file: file,\n fileName: fileName,\n dir: dir\n };\n fileKey = fileKey || 'file';\n const request = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', storage);\n if (Provider) {\n const provider = new Provider(this);\n if (uploadStartCallback) {\n uploadStartCallback();\n }\n return provider.uploadFile(file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, abortCallback);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\ncore_1.Formio.prototype.downloadFile = function (file, options) {\n const requestArgs = {\n method: 'download',\n file: file\n };\n const request = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (file.storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', file.storage);\n if (Provider) {\n const provider = new Provider(this);\n return provider.downloadFile(file, options);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\ncore_1.Formio.prototype.deleteFile = function (file, options) {\n const requestArgs = {\n method: 'delete',\n file: file\n };\n const request = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (file.storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', file.storage);\n if (Provider) {\n const provider = new Provider(this);\n return provider.deleteFile(file, options);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\n// For reverse compatability.\ncore_1.Formio.Promise = Promise;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Formio.js?");
10223
10213
 
10224
10214
  /***/ }),
10225
10215