UNPKG

@mopinion/survey

Version:

Collect customer feedback with the Mopinion survey library

272 lines (271 loc) 16.4 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = Rating; var _preact = require("preact"); var _hooks = require("preact/hooks"); var _utils = require("../../../utils"); var _api = _interopRequireDefault(require("../../../api")); var _conversational = require("../../conversational"); var _form = require("../../form"); var _Selectable = _interopRequireDefault(require("./Selectable")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function Rating(_ref) { var _currentPageBreak$blo, _properties$elements; var block = _ref.block, state = _ref.state, setValue = _ref.setValue, showScoreOnly = _ref.showScoreOnly, showErrors = _ref.showErrors, _ref$disabled = _ref.disabled, disabled = _ref$disabled === void 0 ? false : _ref$disabled, role = _ref.role, elementIndex = _ref.elementIndex; var _useFormProps = (0, _form.useFormProps)(), cacheDomain = _useFormProps.cacheDomain, domain = _useFormProps.domain; var _useFormStore = (0, _form.useFormStore)(), currentConversationalFocusRef = _useFormStore.currentConversationalFocusRef, actions = _useFormStore.actions, formType = _useFormStore.formType, lastKeyPressed = _useFormStore.lastKeyPressed, activePage = _useFormStore.activePage; var _useConfigStore = (0, _form.useConfigStore)(), text = _useConfigStore.text; var _useProperties = (0, _form.useProperties)(), conversational = _useProperties.conversational; var _useAdvanced = (0, _form.useAdvanced)(), lastPageAutoPost = _useAdvanced.lastPageAutoPost; var _useState = (0, _hooks.useState)(-1), _useState2 = _slicedToArray(_useState, 2), hoverScore = _useState2[0], setHoverScore = _useState2[1]; var _useState3 = (0, _hooks.useState)({ angry: '', sad: '', neutral: '', happy: '', 'extra-happy': '' }), _useState4 = _slicedToArray(_useState3, 2), emojis = _useState4[0], setEmojis = _useState4[1]; var currentPageBreak = (0, _form.useBlock)({ typeName: 'page_break', typeOf: activePage - 1 }); var withWcagKeyboardEvents = conversational || lastPageAutoPost && formType === 'embed' || (currentPageBreak === null || currentPageBreak === void 0 || (_currentPageBreak$blo = currentPageBreak.block) === null || _currentPageBreak$blo === void 0 || (_currentPageBreak$blo = _currentPageBreak$blo.properties) === null || _currentPageBreak$blo === void 0 ? void 0 : _currentPageBreak$blo.autopost) && formType === 'embed'; (0, _hooks.useEffect)(function () { if (conversational && elementIndex !== 0) { actions.handleConversationalFocus(); actions.updateLastKeyPressed(null); } }, []); var _useWcagKeyboardEvent = (0, _conversational.useWcagKeyboardEvents)({ onArrowKeyPressed: function onArrowKeyPressed(e) { var updateHelperText = (0, _utils.debounce)(function () { var _text$wcag$ratingHelp, _text$wcag; return actions.updateScreenReaderHelper((_text$wcag$ratingHelp = text === null || text === void 0 || (_text$wcag = text.wcag) === null || _text$wcag === void 0 ? void 0 : _text$wcag.ratingHelperText) !== null && _text$wcag$ratingHelp !== void 0 ? _text$wcag$ratingHelp : ''); }, 1000); updateHelperText(); actions.updateLastKeyPressed(e.key); }, onTabSpaceEnter: function onTabSpaceEnter() { if (pendingScore) { setValue(pendingScore); updatePendingScore(null); setTimeout(function () { actions.updateScreenReaderHelper(''); }, 100); } }, onChangedValue: function onChangedValue(e) { updatePendingScore(e.target.value); actions.updateLastKeyPressed(null); }, onChangedValueConfirm: function onChangedValueConfirm(e) { actions.handleConversationalFocus(true); setValue(pendingScore); updatePendingScore(null); }, onClickValue: function onClickValue(e, isMouseClick) { updatePendingScore(!isMouseClick ? e.target.value : null); setTimeout(function () { actions.updateScreenReaderHelper(''); }, 100); } }), _onKeyDown = _useWcagKeyboardEvent.onKeyDown, _onChange = _useWcagKeyboardEvent.onChange, _onClick = _useWcagKeyboardEvent.onClick, pendingScore = _useWcagKeyboardEvent.pendingScore, updatePendingScore = _useWcagKeyboardEvent.updatePendingScore; var ratingRefs = (0, _hooks.useRef)({}); var wrapperRef = (0, _hooks.useRef)(null); var properties = block.properties, typeName = block.typeName; var selectedScore = (pendingScore !== null && pendingScore !== void 0 ? pendingScore : state.value) || -1; var emojiOrder = ['angry', 'sad', 'neutral', 'happy', 'extra-happy']; var barInner = ['--', '-', '0', '+', '++']; (0, _hooks.useEffect)(function () { if (block.properties.type === 'emoji') { (0, _api["default"])({ domain: domain, cacheDomain: cacheDomain }).getEmoji(block.id).then(function (emojis) { return setEmojis(_objectSpread({}, emojis)); }); } }, []); var getStateClass = function getStateClass(score) { return "".concat(hoverScore === -1 && !properties.reverseScore && score > selectedScore || hoverScore === -1 && properties.reverseScore && score < selectedScore || hoverScore !== -1 && !properties.reverseScore && score > hoverScore || hoverScore !== -1 && properties.reverseScore && score < hoverScore ? 'ui-stars-star-default' : '', "\n\t\t\t").concat(hoverScore !== -1 && !properties.reverseScore && score <= hoverScore || hoverScore !== -1 && properties.reverseScore && score >= hoverScore ? 'ui-stars-star-hover' : '', "\n\t\t\t").concat(hoverScore === -1 && selectedScore !== -1 && !properties.reverseScore && score <= selectedScore || hoverScore === -1 && selectedScore !== -1 && properties.reverseScore && score >= selectedScore ? 'ui-stars-star-on' : ''); }; var scale = typeName === 'nps' ? 10 : properties.type === 'bar' || typeName === 'ces' || properties.type === 'emoji' ? 5 : properties.scale; var start = properties.type === 'numeric' || properties.type === 'stars' ? properties.includeZero ? 0 : 1 : typeName === 'nps' ? 0 : 1; var list = properties.reverseScore ? (0, _utils.range)(start, scale).reverse() : (0, _utils.range)(start, scale); var legendLow = properties.legend ? properties.legend.legendLow : ''; var legendHigh = properties.legend ? properties.legend.legendHigh : ''; var emojiList = properties.reverseScore ? [].concat(emojiOrder).reverse() : emojiOrder; var selectedOrHoverScore = hoverScore > -1 ? hoverScore : selectedScore > -1 ? selectedScore : -1; var selectedOrHoverClass = selectedOrHoverScore > -1 ? "score-".concat(selectedOrHoverScore) : ''; var selectedOrHoverScoreLabel = selectedOrHoverScore > -1 ? (_properties$elements = properties.elements) === null || _properties$elements === void 0 || (_properties$elements = _properties$elements[selectedOrHoverScore]) === null || _properties$elements === void 0 ? void 0 : _properties$elements.label : null; return (0, _preact.h)("div", { ref: currentConversationalFocusRef, "class": "rating-group ".concat(typeName, "-group ").concat(typeName === 'ces' ? typeName : '', " ").concat(properties.type ? properties.type : '', " ").concat(properties.type ? properties.type : '', "-group ").concat(['emoji', 'stars'].indexOf(properties.type) > -1 && properties.showCaptions ? 'show-labels' : '', " ").concat(properties.reverseScore ? 'reversed' : '', " ").concat(properties.legend && (properties.legend.legendLow || properties.legend.legendHigh) ? 'has-legend' : '', " ").concat(!properties.required ? 'with-dummyscore' : '') }, (0, _preact.h)("div", _extends({ "class": "".concat(properties.type === 'stars' || typeName === 'ces' ? '' : 'choice-row'), ref: wrapperRef, role: "radiogroup" }, properties.required && { 'aria-required': true }, conversational && { 'aria-labelledby': "block-title-".concat(typeName, "-").concat(block.id) }), list.map(function (score, i) { var scoreValue = ['emoji', 'stars'].indexOf(properties.type) > -1 && properties.labelsAsValue ? properties[properties.type === 'emoji' ? 'emoji' : 'elements'][score].label : score; if (showScoreOnly && String(state.value) !== String(scoreValue)) { return null; } var scoreLabel = properties[properties.type === 'emoji' ? 'emoji' : 'elements'] && properties[properties.type === 'emoji' ? 'emoji' : 'elements'][score] ? properties[properties.type === 'emoji' ? 'emoji' : 'elements'][score].label : score; var attr = _objectSpread(_objectSpread(_objectSpread({ onChange: function onChange(e) { if (withWcagKeyboardEvents && pendingScore) { _onChange(e, { key: lastKeyPressed }); } else { setValue(e.target.value); setHoverScore(-1); } }, block: block, key: i, selectableIndex: i, value: scoreValue, checked: String(selectedScore) === String(scoreValue), ariaLabel: scoreLabel }, properties.required && showErrors && state.showError && { ariaInvalid: true, 'aria-describedby': "error-message-".concat(block.id) }), showScoreOnly && { tabIndex: -1 }), {}, { disabled: disabled, role: role, onKeyDown: function onKeyDown(e) { if (withWcagKeyboardEvents) { _onKeyDown(e); } }, onClick: function onClick(e) { if (withWcagKeyboardEvents) { _onClick(e); } } }); if (properties.type === 'emoji') { var _properties$emoji$sco, _properties$emoji$sco2; attr.labelAtts = { "class": 'emoji-' + emojiList[i], 'aria-label': (_properties$emoji$sco = properties.emoji[score].label) !== null && _properties$emoji$sco !== void 0 ? _properties$emoji$sco : score, 'data-label': (_properties$emoji$sco2 = properties.emoji[score].label) !== null && _properties$emoji$sco2 !== void 0 ? _properties$emoji$sco2 : score }; } if (properties.type === 'stars' || typeName === 'ces') { var _properties$elements$; attr.labelAtts = { "class": 'ui-stars-star star_' + score, 'aria-label': (_properties$elements$ = properties.elements[score].label) !== null && _properties$elements$ !== void 0 ? _properties$elements$ : score }; return (0, _preact.h)(_Selectable["default"], _extends({}, attr, { ref: function ref(_ref2) { return ratingRefs.current[score] = _ref2; } }), (0, _preact.h)("span", { className: "ui-stars-star star_".concat(score, " ").concat(getStateClass(score)), onMouseEnter: function onMouseEnter() { if (state.hoverScore !== score) { setHoverScore(score); } }, onMouseLeave: function onMouseLeave() { setHoverScore(-1); } }, properties.type === 'stars' && (0, _preact.h)(_form.SvgIcon, { icon: "star", className: "is-before", alt: scoreLabel }))); } else { var html = properties.type === 'emoji' ? { dangerouslySetInnerHTML: { __html: emojis[emojiList[i]] || null } } : null; return (0, _preact.h)(_Selectable["default"], attr, (0, _preact.h)("span", html, properties.type !== 'emoji' && properties.type !== 'bar' ? score : properties.type === 'bar' ? barInner[i] : null)); } }), properties.showCaptions && (properties.type === 'stars' || typeName === 'ces') && (0, _preact.h)(Caption, { wrapperRef: wrapperRef, positioner: hoverScore !== -1 ? ratingRefs.current[hoverScore] : ratingRefs.current[selectedScore], className: "caption ".concat(selectedOrHoverClass), id: "caption-".concat(block.id, "-").concat(hoverScore !== -1 ? hoverScore : selectedScore) }, selectedOrHoverScoreLabel)), properties.legend && !showScoreOnly && (0, _preact.h)(_preact.Fragment, null, (0, _preact.h)("span", { className: "rating-legend legend-low ".concat(pendingScore > -1 ? 'wcag-legend' : '') }, legendLow), (0, _preact.h)("span", { className: "rating-legend legend-high ".concat(pendingScore > -1 ? 'wcag-legend' : '') }, legendHigh))); } function Caption(_ref3) { var positioner = _ref3.positioner, className = _ref3.className, children = _ref3.children, id = _ref3.id, wrapperRef = _ref3.wrapperRef; var captionRef = (0, _hooks.useRef)(null); var left = (positioner === null || positioner === void 0 ? void 0 : positioner.offsetLeft) !== undefined ? positioner.offsetLeft + positioner.scrollWidth / 2 : null; if (children === null) return null; return (0, _preact.h)("span", { ref: captionRef, id: id, role: "tooltip", style: { left: left, opacity: left === null ? 0 : 1 }, className: className }, children); } //# sourceMappingURL=Rating.js.map