diff --git a/blocks/resource-block/build/index.asset.php b/blocks/resource-block/build/index.asset.php index 72a872e8..24327a3c 100644 --- a/blocks/resource-block/build/index.asset.php +++ b/blocks/resource-block/build/index.asset.php @@ -1 +1 @@ - array('jquery', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n'), 'version' => '44ab36e89c9f46be223e6f98d0148956'); \ No newline at end of file + array('jquery', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n'), 'version' => '7343f57c8a68204fb2888f7554c4f7e4'); \ No newline at end of file diff --git a/blocks/resource-block/build/index.css b/blocks/resource-block/build/index.css index 47c75d67..d62db48c 100644 --- a/blocks/resource-block/build/index.css +++ b/blocks/resource-block/build/index.css @@ -1 +1,29 @@ -.wp-block-create-block-wp-oer-resource-block{border:1px dotted red}.block-editor-block-inspector .components-panel__row .components-base-control.components-checkbox-control .components-checkbox-control__label{margin-bottom:0}.wp-block-wp-oer-resource-block h4{margin:0}.wp-block-wp-oer-resource-block .oer-resource-block-description p{font-size:14px}.wp-block-wp-oer-resource-block .oer-empty-block{color:#cdcdcd} +/*!****************************************************************************************************************************************************************************************************************************************!*\ + !*** css ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[3]!./src/editor.scss ***! + \****************************************************************************************************************************************************************************************************************************************/ +/** + * The following styles get applied inside the editor only. + * + * Replace them with your own styles or remove the file completely. + */ +.wp-block-create-block-wp-oer-resource-block { + border: 1px dotted #f00; +} + +.block-editor-block-inspector .components-panel__row .components-base-control.components-checkbox-control .components-checkbox-control__label { + margin-bottom: 0; +} + +.wp-block-wp-oer-resource-block h4 { + margin: 0; +} + +.wp-block-wp-oer-resource-block .oer-resource-block-description p { + font-size: 14px; +} + +.wp-block-wp-oer-resource-block .oer-empty-block { + color: #cdcdcd; +} + +/*# sourceMappingURL=index.css.map*/ \ No newline at end of file diff --git a/blocks/resource-block/build/index.css.map b/blocks/resource-block/build/index.css.map new file mode 100644 index 00000000..c7d248b5 --- /dev/null +++ b/blocks/resource-block/build/index.css.map @@ -0,0 +1 @@ +{"version":3,"file":"index.css","mappings":";;;AAAA;;;;EAAA;AAMA;EACC;AAAD;;AAEA;EAAgJ;AAEhJ;;AADA;EAAqC;AAKrC;;AAJA;EAAoE;AAQpE;;AAPA;EAAmD;AAWnD,C","sources":["webpack://wp-oer-resource-block/./src/editor.scss"],"sourcesContent":["/**\n * The following styles get applied inside the editor only.\n *\n * Replace them with your own styles or remove the file completely.\n */\n\n.wp-block-create-block-wp-oer-resource-block {\n\tborder: 1px dotted #f00;\n}\n.block-editor-block-inspector .components-panel__row .components-base-control.components-checkbox-control .components-checkbox-control__label { margin-bottom:0; }\n.wp-block-wp-oer-resource-block h4 { margin:0; }\n.wp-block-wp-oer-resource-block .oer-resource-block-description p { font-size:14px; }\n.wp-block-wp-oer-resource-block .oer-empty-block { color:#cdcdcd; }"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/blocks/resource-block/build/index.js b/blocks/resource-block/build/index.js index 23eee9b4..a9886f34 100644 --- a/blocks/resource-block/build/index.js +++ b/blocks/resource-block/build/index.js @@ -1 +1,679 @@ -!function(){"use strict";var e,o={557:function(e,o,r){var l=window.wp.blocks,t=window.wp.i18n,c=JSON.parse('{"$schema":"https://json.schemastore.org/block.json","apiVersion":2,"name":"wp-oer-plugin/wp-oer-resource-block","version":"0.1.0","title":"OER Resource Block","category":"oer-block-category","keywords":["OER","resource"],"icon":{"foreground":"#121212","src":"media-document"},"description":"This block displays a single resource on a page.","attributes":{"resources":{"type":"object"},"selectedResource":{"type":"number"},"alignment":{"type":"string"},"blockWidth":{"type":"string"},"showThumbnail":{"type":"boolean","default":false},"showTitle":{"type":"boolean","default":false},"showDescription":{"type":"boolean","default":false},"showSubjects":{"type":"boolean","default":false},"showGrades":{"type":"boolean","default":false},"withBorder":{"type":"boolean","default":false},"blockId":{"type":"string"},"firstLoad":{"type":"boolean","default":true},"isChanged":{"type":"boolean","default":false}},"supports":{"html":false},"textdomain":"wp-oer-resource-block","editorScript":"file:./build/index.js","editorStyle":"file:./build/index.css","style":"file:./build/style-index.css"}'),n=window.wp.element,s=window.wp.blockEditor,a=window.wp.components,u=window.jQuery,i=r.n(u);(0,l.registerBlockType)(c,{edit:function(e){var o=(0,t.__)("Loading...","wp-oer-resource-block"),r=[{label:(0,t.__)("Select a resource","wp-oer-resource-block"),value:""}];const{attributes:l,setAttributes:c,className:u,clientId:b}=e,p=[{label:(0,t.__)("Select Alignment","wp-oer-resource-block"),value:""},{label:(0,t.__)("Left","wp-oer-resource-block"),value:"left"},{label:(0,t.__)("Center","wp-oer-resource-block"),value:"center"},{label:(0,t.__)("Right","wp-oer-resource-block"),value:"right"}];if(void 0!==l.resources){l.resources.length>0&&(o=(0,t.__)("There are ","wp-oer-resource-block")+l.resources.length+(0,t.__)(" resources to choose from. Please select one.","wp-oer-resource-block"));let e=l.resources.map((e=>({label:e.title,value:e.id})));r=r.concat(e)}else wp.apiFetch({url:oer_resource.home_url+"/wp-json/oer-resource-block/v1/resources"}).then((e=>{c({resources:e})}));return b!==l.blockId&&c({blockId:b}),void 0!==l.selectedResource&&(h=l,d=l.blockId,w={action:"oer_display_resource_block",params:h},i().ajax({url:oer_resource.ajaxurl,type:"POST",data:w,success:function(e){i()("#block-"+d+" .wp-block-wp-oer-plugin-wp-oer-resource-block").html(""),i()("#block-"+d+" .wp-block-wp-oer-plugin-wp-oer-resource-block").html(e)},error:function(e,o,r){console.log(r)}})),[(0,n.createElement)(n.Fragment,null,(0,n.createElement)(s.InspectorControls,{className:u},(0,n.createElement)(a.PanelBody,{title:(0,t.__)("OER Resource Options","wp-oer-resource-block"),initialOpen:!0},(0,n.createElement)(a.PanelRow,null,(0,n.createElement)(a.SelectControl,{className:"oer-resource-block-resource-field",label:(0,t.__)("Resource","wp-oer-resource-block"),value:l.selectedResource,options:r,onChange:e=>{c({selectedResource:parseInt(e),isChanged:!0})}})),(0,n.createElement)(a.PanelRow,null,(0,n.createElement)(a.SelectControl,{className:"oer-resource-block-alignment-field",label:(0,t.__)("Alignment","wp-oer-resource-block"),value:l.alignment,options:p,onChange:e=>{c({alignment:e,isChanged:!0})}})),(0,n.createElement)(a.PanelRow,null,(0,n.createElement)(a.TextControl,{className:"oer-resource-block-width-field",label:(0,t.__)("Width in pixels(optional)","wp-oer-resource-block"),value:l.blockWidth,onChange:e=>{c({blockWidth:e,isChanged:!0})}})),(0,n.createElement)(a.PanelRow,null,(0,n.createElement)(a.CheckboxControl,{className:"oer-resource-block-show-thumbnail",label:(0,t.__)("Show thumbnail","wp-oer-resource-block"),checked:l.showThumbnail,onChange:e=>{c({showThumbnail:e,isChanged:!0})}})),(0,n.createElement)(a.PanelRow,null,(0,n.createElement)(a.CheckboxControl,{className:"oer-resource-block-show-title",label:(0,t.__)("Show title","wp-oer-resource-block"),checked:l.showTitle,onChange:e=>{c({showTitle:e,isChanged:!0})}})),(0,n.createElement)(a.PanelRow,null,(0,n.createElement)(a.CheckboxControl,{className:"oer-resource-block-show-description",label:(0,t.__)("Show description","wp-oer-resource-block"),checked:l.showDescription,onChange:e=>{c({showDescription:e,isChanged:!0})}})),(0,n.createElement)(a.PanelRow,null,(0,n.createElement)(a.CheckboxControl,{className:"oer-resource-block-show-subjects",label:(0,t.__)("Show subjects","wp-oer-resource-block"),checked:l.showSubjects,onChange:e=>{c({showSubjects:e,isChanged:!0})}})),(0,n.createElement)(a.PanelRow,null,(0,n.createElement)(a.CheckboxControl,{className:"oer-resource-block-show-grade-levels",label:(0,t.__)("Show grade levels","wp-oer-resource-block"),checked:l.showGrades,onChange:e=>{c({showGrades:e,isChanged:!0})}})),(0,n.createElement)(a.PanelRow,null,(0,n.createElement)(a.CheckboxControl,{className:"oer-resource-block-show-with-border",label:(0,t.__)("Show block with border","wp-oer-resource-block"),checked:l.withBorder,onChange:e=>{c({withBorder:e,isChanged:!0})}}))))),(0,n.createElement)("div",(0,s.useBlockProps)(),(0,n.createElement)("div",{className:"wp-block-wp-oer-plugin-wp-oer-resource-block"},o))];var h,d,w}})}},r={};function l(e){var t=r[e];if(void 0!==t)return t.exports;var c=r[e]={exports:{}};return o[e](c,c.exports,l),c.exports}l.m=o,e=[],l.O=function(o,r,t,c){if(!r){var n=1/0;for(i=0;i=c)&&Object.keys(l.O).every((function(e){return l.O[e](r[a])}))?r.splice(a--,1):(s=!1,c0&&e[i-1][2]>c;i--)e[i]=e[i-1];e[i]=[r,t,c]},l.n=function(e){var o=e&&e.__esModule?function(){return e.default}:function(){return e};return l.d(o,{a:o}),o},l.d=function(e,o){for(var r in o)l.o(o,r)&&!l.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:o[r]})},l.o=function(e,o){return Object.prototype.hasOwnProperty.call(e,o)},function(){var e={826:0,46:0};l.O.j=function(o){return 0===e[o]};var o=function(o,r){var t,c,n=r[0],s=r[1],a=r[2],u=0;if(n.some((function(o){return 0!==e[o]}))){for(t in s)l.o(s,t)&&(l.m[t]=s[t]);if(a)var i=a(l)}for(o&&o(r);u { + if (oer_resource.perm_structure) { + wp.apiFetch({ + url: oer_resource.home_url + '/wp-json/oer-resource-block/v1/resources' + }).then(resources => { + setAttributes({ + resources: resources + }); + }); + } else { + wp.apiFetch({ + url: oer_resource.home_url + '?rest_route=/oer-resource-block/v1/resources' + }).then(resources => { + setAttributes({ + resources: resources + }); + }); + } + }; + + (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => { + getResources(); + }, []); + + if (typeof attributes.resources !== 'undefined') { + if (attributes.resources.length > 0) display = (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('There are ', 'wp-oer-resource-block') + attributes.resources.length + (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)(' resources to choose from. Please select one.', 'wp-oer-resource-block'); + let resources = attributes.resources.map(resource => { + return { + label: resource.title, + value: resource.id + }; + }); + optionResources = optionResources.concat(resources); + } + + const onChangeResource = newResource => { + setAttributes({ + selectedResource: parseInt(newResource), + isChanged: true + }); + }; + + const onChangeAlignment = newAlignment => { + setAttributes({ + alignment: newAlignment, + isChanged: true + }); + }; + + const onChangeWidth = newWidth => { + setAttributes({ + blockWidth: newWidth, + isChanged: true + }); + }; + + const onShowThumbnail = checked => { + setAttributes({ + showThumbnail: checked, + isChanged: true + }); + }; + + const onShowTitle = checked => { + setAttributes({ + showTitle: checked, + isChanged: true + }); + }; + + const onShowDescription = checked => { + setAttributes({ + showDescription: checked, + isChanged: true + }); + }; + + const onShowSubjects = checked => { + setAttributes({ + showSubjects: checked, + isChanged: true + }); + }; + + const onShowGradeLevels = checked => { + setAttributes({ + showGrades: checked, + isChanged: true + }); + }; + + const onWithBorder = checked => { + setAttributes({ + withBorder: checked, + isChanged: true + }); + }; + + const setBlockId = blockId => { + setAttributes({ + blockId + }); + }; + + if (clientId !== attributes.blockId) { + setBlockId(clientId); + } + + if (typeof attributes.selectedResource !== 'undefined') { + preview_block(attributes, attributes.blockId); + } + + return [(0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.Fragment, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_block_editor__WEBPACK_IMPORTED_MODULE_2__.InspectorControls, { + className: className + }, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelBody, { + title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('OER Resource Options', 'wp-oer-resource-block'), + initialOpen: true + }, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.SelectControl, { + className: 'oer-resource-block-resource-field', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Resource', 'wp-oer-resource-block'), + value: attributes.selectedResource, + options: optionResources, + onChange: onChangeResource + })), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.SelectControl, { + className: 'oer-resource-block-alignment-field', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Alignment', 'wp-oer-resource-block'), + value: attributes.alignment, + options: alignmentOptions, + onChange: onChangeAlignment + })), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.TextControl, { + className: 'oer-resource-block-width-field', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Width in pixels(optional)', 'wp-oer-resource-block'), + value: attributes.blockWidth, + onChange: onChangeWidth + })), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.CheckboxControl, { + className: 'oer-resource-block-show-thumbnail', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Show thumbnail', 'wp-oer-resource-block'), + checked: attributes.showThumbnail, + onChange: onShowThumbnail + })), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.CheckboxControl, { + className: 'oer-resource-block-show-title', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Show title', 'wp-oer-resource-block'), + checked: attributes.showTitle, + onChange: onShowTitle + })), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.CheckboxControl, { + className: 'oer-resource-block-show-description', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Show description', 'wp-oer-resource-block'), + checked: attributes.showDescription, + onChange: onShowDescription + })), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.CheckboxControl, { + className: 'oer-resource-block-show-subjects', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Show subjects', 'wp-oer-resource-block'), + checked: attributes.showSubjects, + onChange: onShowSubjects + })), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.CheckboxControl, { + className: 'oer-resource-block-show-grade-levels', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Show grade levels', 'wp-oer-resource-block'), + checked: attributes.showGrades, + onChange: onShowGradeLevels + })), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.CheckboxControl, { + className: 'oer-resource-block-show-with-border', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Show block with border', 'wp-oer-resource-block'), + checked: attributes.withBorder, + onChange: onWithBorder + }))))), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)("div", (0,_wordpress_block_editor__WEBPACK_IMPORTED_MODULE_2__.useBlockProps)(), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)("div", { + className: "wp-block-wp-oer-plugin-wp-oer-resource-block" + }, display))]; +} + +/***/ }), + +/***/ "./src/index.js": +/*!**********************!*\ + !*** ./src/index.js ***! + \**********************/ +/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _wordpress_blocks__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @wordpress/blocks */ "@wordpress/blocks"); +/* harmony import */ var _wordpress_blocks__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_wordpress_blocks__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n"); +/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _style_scss__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./style.scss */ "./src/style.scss"); +/* harmony import */ var _block_json__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../block.json */ "./block.json"); +/* harmony import */ var _edit__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./edit */ "./src/edit.js"); +/** + * Registers a new block provided a unique name and an object defining its behavior. + * + * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/ + */ + + +/** + * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files. + * All files containing `style` keyword are bundled together. The code used + * gets applied both to the front of your site and to the editor. + * + * @see https://www.npmjs.com/package/@wordpress/scripts#using-css + */ + + + +/** + * Internal dependencies + */ + + +/** + * Every block starts by registering a new block type definition. + * + * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/ + */ +// registerBlockType('wp-oer-plugin/wp-oer-resource-block', { +// /** +// * This is the display title for your block, which can be translated with `i18n` functions. +// * The block inserter will show this name. +// */ +// title: __('OER Resource Block', 'wp-oer-resource-block'), +// /** +// * This is a short description for your block, can be translated with `i18n` functions. +// * It will be shown in the Block Tab in the Settings Sidebar. +// */ +// description: __('This block displays a single resource on a page.','wp-oer-resource-block'), +// /** +// * Blocks are grouped into categories to help users browse and discover them. +// * The categories provided by core are `common`, `embed`, `formatting`, `layout` and `widgets`. +// */ +// category: 'oer-block-category', +// /** +// * An icon property should be specified to make it easier to identify a block. +// * These can be any of WordPress’ Dashicons, or a custom svg element. +// */ +// icon: { +// foreground: '#121212', +// src: 'media-document' +// }, +// keywords: [__('OER', 'oer-subject-resource-block'), __('Resource', 'oer-subject-resource-block')], +// attributes : { +// resources: { +// type: 'object' +// }, +// selectedResource: { +// type: 'number' +// }, +// alignment: { +// type: 'string', +// }, +// blockWidth: { +// type: 'string' +// }, +// showThumbnail: { +// type:'boolean', +// default: false +// }, +// showTitle: { +// type:'boolean', +// default:false +// }, +// showDescription: { +// type:'boolean', +// default: false +// }, +// showSubjects: { +// type: 'boolean', +// default: false +// }, +// showGrades: { +// type: 'boolean', +// default: false +// }, +// withBorder: { +// type: 'boolean', +// default: false +// }, +// blockId: { +// type: 'string' +// }, +// firstLoad: { +// type: 'boolean', +// default: true +// }, +// isChanged: { +// type: 'boolean', +// default: false +// } +// }, +// /** +// * @see ./edit.js +// */ +// edit: Edit, +// }); + +(0,_wordpress_blocks__WEBPACK_IMPORTED_MODULE_0__.registerBlockType)(_block_json__WEBPACK_IMPORTED_MODULE_3__, { + edit: _edit__WEBPACK_IMPORTED_MODULE_4__["default"] +}); + +/***/ }), + +/***/ "./src/editor.scss": +/*!*************************!*\ + !*** ./src/editor.scss ***! + \*************************/ +/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +__webpack_require__.r(__webpack_exports__); +// extracted by mini-css-extract-plugin + + +/***/ }), + +/***/ "./src/style.scss": +/*!************************!*\ + !*** ./src/style.scss ***! + \************************/ +/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +__webpack_require__.r(__webpack_exports__); +// extracted by mini-css-extract-plugin + + +/***/ }), + +/***/ "jquery": +/*!*************************!*\ + !*** external "jQuery" ***! + \*************************/ +/***/ (function(module) { + +module.exports = window["jQuery"]; + +/***/ }), + +/***/ "@wordpress/block-editor": +/*!*************************************!*\ + !*** external ["wp","blockEditor"] ***! + \*************************************/ +/***/ (function(module) { + +module.exports = window["wp"]["blockEditor"]; + +/***/ }), + +/***/ "@wordpress/blocks": +/*!********************************!*\ + !*** external ["wp","blocks"] ***! + \********************************/ +/***/ (function(module) { + +module.exports = window["wp"]["blocks"]; + +/***/ }), + +/***/ "@wordpress/components": +/*!************************************!*\ + !*** external ["wp","components"] ***! + \************************************/ +/***/ (function(module) { + +module.exports = window["wp"]["components"]; + +/***/ }), + +/***/ "@wordpress/element": +/*!*********************************!*\ + !*** external ["wp","element"] ***! + \*********************************/ +/***/ (function(module) { + +module.exports = window["wp"]["element"]; + +/***/ }), + +/***/ "@wordpress/i18n": +/*!******************************!*\ + !*** external ["wp","i18n"] ***! + \******************************/ +/***/ (function(module) { + +module.exports = window["wp"]["i18n"]; + +/***/ }), + +/***/ "./block.json": +/*!********************!*\ + !*** ./block.json ***! + \********************/ +/***/ (function(module) { + +module.exports = JSON.parse('{"$schema":"https://json.schemastore.org/block.json","apiVersion":2,"name":"wp-oer-plugin/wp-oer-resource-block","version":"0.1.0","title":"OER Resource Block","category":"oer-block-category","keywords":["OER","resource"],"icon":{"foreground":"#121212","src":"media-document"},"description":"This block displays a single resource on a page.","attributes":{"resources":{"type":"object"},"selectedResource":{"type":"number"},"alignment":{"type":"string"},"blockWidth":{"type":"string"},"showThumbnail":{"type":"boolean","default":false},"showTitle":{"type":"boolean","default":false},"showDescription":{"type":"boolean","default":false},"showSubjects":{"type":"boolean","default":false},"showGrades":{"type":"boolean","default":false},"withBorder":{"type":"boolean","default":false},"blockId":{"type":"string"},"firstLoad":{"type":"boolean","default":true},"isChanged":{"type":"boolean","default":false}},"supports":{"html":false},"textdomain":"wp-oer-resource-block","editorScript":"file:./build/index.js","editorStyle":"file:./build/index.css","style":"file:./build/style-index.css"}'); + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = __webpack_modules__; +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/chunk loaded */ +/******/ !function() { +/******/ var deferred = []; +/******/ __webpack_require__.O = function(result, chunkIds, fn, priority) { +/******/ if(chunkIds) { +/******/ priority = priority || 0; +/******/ for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1]; +/******/ deferred[i] = [chunkIds, fn, priority]; +/******/ return; +/******/ } +/******/ var notFulfilled = Infinity; +/******/ for (var i = 0; i < deferred.length; i++) { +/******/ var chunkIds = deferred[i][0]; +/******/ var fn = deferred[i][1]; +/******/ var priority = deferred[i][2]; +/******/ var fulfilled = true; +/******/ for (var j = 0; j < chunkIds.length; j++) { +/******/ if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every(function(key) { return __webpack_require__.O[key](chunkIds[j]); })) { +/******/ chunkIds.splice(j--, 1); +/******/ } else { +/******/ fulfilled = false; +/******/ if(priority < notFulfilled) notFulfilled = priority; +/******/ } +/******/ } +/******/ if(fulfilled) { +/******/ deferred.splice(i--, 1) +/******/ var r = fn(); +/******/ if (r !== undefined) result = r; +/******/ } +/******/ } +/******/ return result; +/******/ }; +/******/ }(); +/******/ +/******/ /* webpack/runtime/compat get default export */ +/******/ !function() { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function() { return module['default']; } : +/******/ function() { return module; }; +/******/ __webpack_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ }(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ !function() { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = function(exports, definition) { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ }(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ !function() { +/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } +/******/ }(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ !function() { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ }(); +/******/ +/******/ /* webpack/runtime/jsonp chunk loading */ +/******/ !function() { +/******/ // no baseURI +/******/ +/******/ // object to store loaded and loading chunks +/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched +/******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded +/******/ var installedChunks = { +/******/ "index": 0, +/******/ "style-index": 0 +/******/ }; +/******/ +/******/ // no chunk on demand loading +/******/ +/******/ // no prefetching +/******/ +/******/ // no preloaded +/******/ +/******/ // no HMR +/******/ +/******/ // no HMR manifest +/******/ +/******/ __webpack_require__.O.j = function(chunkId) { return installedChunks[chunkId] === 0; }; +/******/ +/******/ // install a JSONP callback for chunk loading +/******/ var webpackJsonpCallback = function(parentChunkLoadingFunction, data) { +/******/ var chunkIds = data[0]; +/******/ var moreModules = data[1]; +/******/ var runtime = data[2]; +/******/ // add "moreModules" to the modules object, +/******/ // then flag all "chunkIds" as loaded and fire callback +/******/ var moduleId, chunkId, i = 0; +/******/ if(chunkIds.some(function(id) { return installedChunks[id] !== 0; })) { +/******/ for(moduleId in moreModules) { +/******/ if(__webpack_require__.o(moreModules, moduleId)) { +/******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; +/******/ } +/******/ } +/******/ if(runtime) var result = runtime(__webpack_require__); +/******/ } +/******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data); +/******/ for(;i < chunkIds.length; i++) { +/******/ chunkId = chunkIds[i]; +/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { +/******/ installedChunks[chunkId][0](); +/******/ } +/******/ installedChunks[chunkIds[i]] = 0; +/******/ } +/******/ return __webpack_require__.O(result); +/******/ } +/******/ +/******/ var chunkLoadingGlobal = self["webpackChunkwp_oer_resource_block"] = self["webpackChunkwp_oer_resource_block"] || []; +/******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0)); +/******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal)); +/******/ }(); +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module depends on other loaded chunks and execution need to be delayed +/******/ var __webpack_exports__ = __webpack_require__.O(undefined, ["style-index"], function() { return __webpack_require__("./src/index.js"); }) +/******/ __webpack_exports__ = __webpack_require__.O(__webpack_exports__); +/******/ +/******/ })() +; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/blocks/resource-block/build/index.js.map b/blocks/resource-block/build/index.js.map new file mode 100644 index 00000000..ff86621a --- /dev/null +++ b/blocks/resource-block/build/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;;AACA;;AAEA,SAASW,aAAT,CAAuBC,IAAvB,EAA6BC,OAA7B,EAAqC;AACjC,MAAIC,IAAI,GAAG;AACPC,IAAAA,MAAM,EAAG,4BADF;AAEPC,IAAAA,MAAM,EAAEJ;AAFD,GAAX;AAIDH,EAAAA,kDAAA,CAAO;AACFS,IAAAA,GAAG,EAAEC,YAAY,CAACC,OADhB;AAEFC,IAAAA,IAAI,EAAE,MAFJ;AAGFP,IAAAA,IAAI,EAAEA,IAHJ;AAIFQ,IAAAA,OAAO,EAAC,UAASC,QAAT,EAAkB;AACtBd,MAAAA,6CAAC,CAAC,YAAYI,OAAZ,GAAsB,gDAAvB,CAAD,CAA0EW,IAA1E,CAA+E,EAA/E;AACAf,MAAAA,6CAAC,CAAC,YAAYI,OAAZ,GAAsB,gDAAvB,CAAD,CAA0EW,IAA1E,CAA+ED,QAA/E;AACH,KAPC;AAQFE,IAAAA,KAAK,EAAE,UAASC,cAAT,EAAyBC,UAAzB,EAAqCC,WAArC,EAAiD;AACpDC,MAAAA,OAAO,CAACC,GAAR,CAAYF,WAAZ;AACH;AAVC,GAAP;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AAK,EAAK9E,mDAAE,CAAE,wBAAF,EAA6B,uBAA7B,CAFhB;AAGI,WAAO,EAAK4C,UAAU,CAACqC,UAH3B;AAII,YAAQ,EAAKD;AAJjB,IADJ,CArEJ,CADJ,CADJ,CADA,EAoFA,yEAAUtE,sEAAa,EAAvB,EACI;AAAK,aAAS,EAAG;AAAjB,KAAoEuB,OAApE,CADJ,CApFA,CAAP;AAwFA;;;;;;;;;;;;;;;;;;AC3OD;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AACA;AACA;AACA;AACA;;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACAkD,oEAAiB,CAAEC,wCAAF,EAAY;AACzBC,EAAAA,IAAI,EAAEtD,6CAAIA;AADe,CAAZ,CAAjB;;;;;;;;;;;AC/GA;;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;UCAA;UACA;;UAEA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;;UAEA;UACA;;UAEA;UACA;UACA;;UAEA;UACA;;;;;WCzBA;WACA;WACA;WACA;WACA,+BAA+B,wCAAwC;WACvE;WACA;WACA;WACA;WACA,iBAAiB,qBAAqB;WACtC;WACA;WACA;WACA;WACA,kBAAkB,qBAAqB;WACvC,oHAAoH,iDAAiD;WACrK;WACA,KAAK;WACL;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;;;;WC7BA;WACA;WACA;WACA,eAAe,4BAA4B;WAC3C,eAAe;WACf,iCAAiC,WAAW;WAC5C;WACA;;;;;WCPA;WACA;WACA;WACA;WACA,yCAAyC,wCAAwC;WACjF;WACA;WACA;;;;;WCPA,8CAA8C;;;;;WCA9C;WACA;WACA;WACA,uDAAuD,iBAAiB;WACxE;WACA,gDAAgD,aAAa;WAC7D;;;;;WCNA;;WAEA;WACA;WACA;WACA;WACA;WACA;WACA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA,8CAA8C;;WAE9C;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA,iCAAiC,mCAAmC;WACpE;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA,MAAM,qBAAqB;WAC3B;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;WAEA;WACA;WACA;;;;;UEnDA;UACA;UACA;UACA,yFAAyF,+CAA+C;UACxI","sources":["webpack://wp-oer-resource-block/./src/edit.js","webpack://wp-oer-resource-block/./src/index.js","webpack://wp-oer-resource-block/./src/editor.scss","webpack://wp-oer-resource-block/./src/style.scss","webpack://wp-oer-resource-block/external window \"jQuery\"","webpack://wp-oer-resource-block/external window [\"wp\",\"blockEditor\"]","webpack://wp-oer-resource-block/external window [\"wp\",\"blocks\"]","webpack://wp-oer-resource-block/external window [\"wp\",\"components\"]","webpack://wp-oer-resource-block/external window [\"wp\",\"element\"]","webpack://wp-oer-resource-block/external window [\"wp\",\"i18n\"]","webpack://wp-oer-resource-block/webpack/bootstrap","webpack://wp-oer-resource-block/webpack/runtime/chunk loaded","webpack://wp-oer-resource-block/webpack/runtime/compat get default export","webpack://wp-oer-resource-block/webpack/runtime/define property getters","webpack://wp-oer-resource-block/webpack/runtime/hasOwnProperty shorthand","webpack://wp-oer-resource-block/webpack/runtime/make namespace object","webpack://wp-oer-resource-block/webpack/runtime/jsonp chunk loading","webpack://wp-oer-resource-block/webpack/before-startup","webpack://wp-oer-resource-block/webpack/startup","webpack://wp-oer-resource-block/webpack/after-startup"],"sourcesContent":["/**\n * Retrieves the translation of text.\n *\n * @see https://developer.wordpress.org/block-editor/packages/packages-i18n/\n */\nimport { __ } from '@wordpress/i18n';\nimport { InspectorControls } from '@wordpress/block-editor';\nimport { PanelBody, PanelRow, SelectControl, CheckboxControl, TextControl } from '@wordpress/components';\nimport { Fragment, useEffect } from '@wordpress/element';\nimport $ from 'jquery';\n\n/**\n * React hook that is used to mark the block wrapper element.\n * It provides all the necessary props like the class name.\n *\n * @see https://developer.wordpress.org/block-editor/packages/packages-block-editor/#useBlockProps\n */\nimport { useBlockProps } from '@wordpress/block-editor';\n\n/**\n * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.\n * Those files can contain any CSS code that gets applied to the editor.\n *\n * @see https://www.npmjs.com/package/@wordpress/scripts#using-css\n */\nimport './editor.scss';\n\nfunction preview_block(args, blockId){\n var data = {\n action : 'oer_display_resource_block',\n params: args,\n };\n $.ajax({ \n url: oer_resource.ajaxurl, \n type: 'POST',\n data: data,\n success:function(response){\n $('#block-' + blockId + ' .wp-block-wp-oer-plugin-wp-oer-resource-block').html(\"\");\n $('#block-' + blockId + ' .wp-block-wp-oer-plugin-wp-oer-resource-block').html(response);\n },\n error: function(XMLHttpRequest, textStatus, errorThrown){\n console.log(errorThrown);\n }\n })\n}\n\n/**\n * The edit function describes the structure of your block in the context of the\n * editor. This represents what the editor will render when the block is used.\n *\n * @see https://developer.wordpress.org/block-editor/developers/block-api/block-edit-save/#edit\n *\n * @return {WPElement} Element to render.\n */\nexport default function Edit(props) {\n var display = __(\"Loading...\",\"wp-oer-resource-block\");\n var resourceOptions;\n var optionResources = [{ label:__( 'Select a resource' , 'wp-oer-resource-block' ), value:'' }];\n var showThumbnail = false;\n var showTitle = false;\n var showDescription = false;\n var showSubjects = false;\n var showGradeLevels = false;\n var wBorder = false;\n\n const { attributes, setAttributes, className, clientId } = props;\n\n const alignmentOptions = [\n { label:__('Select Alignment','wp-oer-resource-block') , value: '' },\n { label:__('Left','wp-oer-resource-block') , value: 'left' },\n { label:__('Center','wp-oer-resource-block') , value: 'center' },\n { label:__('Right','wp-oer-resource-block') , value: 'right' }\n ];\n\n // get all resources\n const getResources = () => {\n if (oer_resource.perm_structure){\n wp.apiFetch( { url:oer_resource.home_url + '/wp-json/oer-resource-block/v1/resources'} ).then( resources => {\n setAttributes( { resources: resources } );\n });\n } else {\n wp.apiFetch( { url:oer_resource.home_url + '?rest_route=/oer-resource-block/v1/resources'} ).then( resources => {\n setAttributes( { resources: resources } );\n });\n }\n }\n\n useEffect(() => {\n getResources();\n },[]);\n \n if (typeof attributes.resources !== 'undefined'){\n if (attributes.resources.length>0)\n display = __('There are ','wp-oer-resource-block')+ attributes.resources.length + __(' resources to choose from. Please select one.','wp-oer-resource-block');\n\n let resources = (attributes.resources.map((resource) => {\n return { label: resource.title, value: resource.id }\n }));\n optionResources = optionResources.concat(resources);\n } \n\n const onChangeResource = ( newResource ) => {\n setAttributes( { selectedResource: parseInt(newResource), isChanged: true } );\n }\n\n const onChangeAlignment = ( newAlignment ) => {\n setAttributes( { alignment: newAlignment, isChanged: true } );\n }\n\n const onChangeWidth = ( newWidth ) => {\n setAttributes( { blockWidth:newWidth, isChanged: true } );\n }\n\n const onShowThumbnail = ( checked ) => {\n setAttributes( { showThumbnail: checked, isChanged: true } );\n }\n\n const onShowTitle = ( checked ) => {\n setAttributes( { showTitle: checked, isChanged: true } );\n }\n\n const onShowDescription = ( checked ) => {\n setAttributes( { showDescription: checked, isChanged: true } );\n }\n\n const onShowSubjects = ( checked ) => {\n setAttributes( { showSubjects: checked, isChanged: true } );\n }\n\n const onShowGradeLevels = ( checked ) => {\n setAttributes( { showGrades: checked, isChanged: true } );\n }\n\n const onWithBorder = ( checked ) => {\n setAttributes( { withBorder: checked, isChanged: true } );\n }\n\n const setBlockId = (blockId) => { setAttributes( { blockId } ); }\n\n if( clientId !== attributes.blockId ){\n setBlockId(clientId);\n }\n\n if (typeof attributes.selectedResource !== 'undefined'){\n preview_block(attributes, attributes.blockId);\n }\n\n\treturn [(\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ),\n
\n
{ display }
\n
\n ];\n}\n","/**\n * Registers a new block provided a unique name and an object defining its behavior.\n *\n * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/\n */\nimport { registerBlockType } from '@wordpress/blocks';\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.\n * All files containing `style` keyword are bundled together. The code used\n * gets applied both to the front of your site and to the editor.\n *\n * @see https://www.npmjs.com/package/@wordpress/scripts#using-css\n */\nimport './style.scss';\nimport metadata from '../block.json';\n/**\n * Internal dependencies\n */\nimport Edit from './edit';\n\n/**\n * Every block starts by registering a new block type definition.\n *\n * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/\n */\n// registerBlockType('wp-oer-plugin/wp-oer-resource-block', {\n// /**\n// * This is the display title for your block, which can be translated with `i18n` functions.\n// * The block inserter will show this name.\n// */\n// title: __('OER Resource Block', 'wp-oer-resource-block'),\n\n// /**\n// * This is a short description for your block, can be translated with `i18n` functions.\n// * It will be shown in the Block Tab in the Settings Sidebar.\n// */\n// description: __('This block displays a single resource on a page.','wp-oer-resource-block'),\n\n// /**\n// * Blocks are grouped into categories to help users browse and discover them.\n// * The categories provided by core are `common`, `embed`, `formatting`, `layout` and `widgets`.\n// */\n// category: 'oer-block-category',\n\n// /**\n// * An icon property should be specified to make it easier to identify a block.\n// * These can be any of WordPress’ Dashicons, or a custom svg element.\n// */\n// icon: {\n// foreground: '#121212',\n// src: 'media-document'\n// },\n\n// keywords: [__('OER', 'oer-subject-resource-block'), __('Resource', 'oer-subject-resource-block')],\n\n// attributes : {\n// resources: {\n// type: 'object'\n// },\n// selectedResource: {\n// type: 'number'\n// },\n// alignment: {\n// type: 'string',\n// },\n// blockWidth: {\n// type: 'string'\n// },\n// showThumbnail: {\n// type:'boolean',\n// default: false\n// }, \n// showTitle: {\n// type:'boolean',\n// default:false\n// },\n// showDescription: {\n// type:'boolean',\n// default: false\n// }, \n// showSubjects: {\n// type: 'boolean',\n// default: false\n// },\n// showGrades: {\n// type: 'boolean',\n// default: false\n// },\n// withBorder: {\n// type: 'boolean',\n// default: false\n// },\n// blockId: {\n// type: 'string'\n// },\n// firstLoad: {\n// type: 'boolean',\n// default: true\n// },\n// isChanged: {\n// type: 'boolean',\n// default: false\n// }\n// },\n// \t/**\n// \t * @see ./edit.js\n// \t */\n// \tedit: Edit,\n// });\nregisterBlockType( metadata, {\n edit: Edit,\n});\n","// extracted by mini-css-extract-plugin\nexport {};","// extracted by mini-css-extract-plugin\nexport {};","module.exports = window[\"jQuery\"];","module.exports = window[\"wp\"][\"blockEditor\"];","module.exports = window[\"wp\"][\"blocks\"];","module.exports = window[\"wp\"][\"components\"];","module.exports = window[\"wp\"][\"element\"];","module.exports = window[\"wp\"][\"i18n\"];","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","var deferred = [];\n__webpack_require__.O = function(result, chunkIds, fn, priority) {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar chunkIds = deferred[i][0];\n\t\tvar fn = deferred[i][1];\n\t\tvar priority = deferred[i][2];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every(function(key) { return __webpack_require__.O[key](chunkIds[j]); })) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = function(module) {\n\tvar getter = module && module.__esModule ?\n\t\tfunction() { return module['default']; } :\n\t\tfunction() { return module; };\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = function(exports, definition) {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }","// define __esModule on exports\n__webpack_require__.r = function(exports) {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t\"index\": 0,\n\t\"style-index\": 0\n};\n\n// no chunk on demand loading\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = function(chunkId) { return installedChunks[chunkId] === 0; };\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = function(parentChunkLoadingFunction, data) {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some(function(id) { return installedChunks[id] !== 0; })) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkIds[i]] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkwp_oer_resource_block\"] = self[\"webpackChunkwp_oer_resource_block\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [\"style-index\"], function() { return __webpack_require__(\"./src/index.js\"); })\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n",""],"names":["__","InspectorControls","PanelBody","PanelRow","SelectControl","CheckboxControl","TextControl","Fragment","useEffect","$","useBlockProps","preview_block","args","blockId","data","action","params","ajax","url","oer_resource","ajaxurl","type","success","response","html","error","XMLHttpRequest","textStatus","errorThrown","console","log","Edit","props","display","resourceOptions","optionResources","label","value","showThumbnail","showTitle","showDescription","showSubjects","showGradeLevels","wBorder","attributes","setAttributes","className","clientId","alignmentOptions","getResources","perm_structure","wp","apiFetch","home_url","then","resources","length","map","resource","title","id","concat","onChangeResource","newResource","selectedResource","parseInt","isChanged","onChangeAlignment","newAlignment","alignment","onChangeWidth","newWidth","blockWidth","onShowThumbnail","checked","onShowTitle","onShowDescription","onShowSubjects","onShowGradeLevels","showGrades","onWithBorder","withBorder","setBlockId","registerBlockType","metadata","edit"],"sourceRoot":""} \ No newline at end of file diff --git a/blocks/resource-block/build/style-index.css b/blocks/resource-block/build/style-index.css index ed59cfcc..7d142559 100644 --- a/blocks/resource-block/build/style-index.css +++ b/blocks/resource-block/build/style-index.css @@ -1 +1,53 @@ -.wp-block-create-block-wp-oer-resource-block{background-color:#21759b;color:#fff;padding:2px}.wp-block-wp-oer-resource-block{padding:25px}.wp-block-wp-oer-resource-block h3{margin-bottom:15px}.wp-block-wp-oer-resource-block div{margin:15px 0}.wp-block-wp-oer-resource-block .oer-resource-block-subjects ul{margin:0;padding:0}.wp-block-wp-oer-resource-block .oer-resource-block-subjects ul li{display:inline-block;float:none;font-size:14px;list-style:none;padding:10px}.wp-block-wp-oer-resource-block .oer-resource-block-grade-levels{font-size:14px} +/*!***************************************************************************************************************************************************************************************************************************************!*\ + !*** css ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[3]!./src/style.scss ***! + \***************************************************************************************************************************************************************************************************************************************/ +/** + * The following styles get applied both on the front of your site + * and in the editor. + * + * Replace them with your own styles or remove the file completely. + */ +.wp-block-create-block-wp-oer-resource-block { + background-color: #21759b; + color: #fff; + padding: 2px; +} + +.wp-block-wp-oer-resource-block { + padding: 25px; +} + +.wp-block-wp-oer-resource-block h3 { + margin-bottom: 15px; +} + +.wp-block-wp-oer-resource-block div { + margin: 15px 0; +} + +.wp-block-wp-oer-resource-block .oer-resource-block-subjects ul { + margin: 0; + padding: 0; +} + +.wp-block-wp-oer-resource-block .oer-resource-block-subjects ul li { + list-style: none; + display: inline-block; +} + +.wp-block-wp-oer-resource-block .oer-resource-block-subjects ul li { + float: none; + font-size: 14px; + padding: 10px; +} + +.wp-block-wp-oer-resource-block .oer-resource-block-grade-levels { + font-size: 14px; +} + +.wp-block-wp-oer-resource-block .oer-resource-block-featured-image img { + width: 100%; + height: auto; +} + +/*# sourceMappingURL=style-index.css.map*/ \ No newline at end of file diff --git a/blocks/resource-block/build/style-index.css.map b/blocks/resource-block/build/style-index.css.map new file mode 100644 index 00000000..a492ead5 --- /dev/null +++ b/blocks/resource-block/build/style-index.css.map @@ -0,0 +1 @@ +{"version":3,"file":"style-index.css","mappings":";;;AAAA;;;;;EAAA;AAOA;EACC;EACA;EACA;AAAD;;AAEA;EAAkC;AAElC;;AADA;EAAqC;AAKrC;;AAJA;EAAsC;AAQtC;;AAPA;EAAkE;EAAU;AAY5E;;AAXA;EAAqE;EAAiB;AAgBtF;;AAfA;EAAqE;EAAY;EAAiB;AAqBlG;;AApBA;EAAmE;AAwBnE;;AAvBA;EAAyE;EAAY;AA4BrF,C","sources":["webpack://wp-oer-resource-block/./src/style.scss"],"sourcesContent":["/**\n * The following styles get applied both on the front of your site\n * and in the editor.\n *\n * Replace them with your own styles or remove the file completely.\n */\n\n.wp-block-create-block-wp-oer-resource-block {\n\tbackground-color: #21759b;\n\tcolor: #fff;\n\tpadding: 2px;\n}\n.wp-block-wp-oer-resource-block { padding:25px; }\n.wp-block-wp-oer-resource-block h3 { margin-bottom:15px; }\n.wp-block-wp-oer-resource-block div { margin: 15px 0; }\n.wp-block-wp-oer-resource-block .oer-resource-block-subjects ul { margin:0; padding:0; }\n.wp-block-wp-oer-resource-block .oer-resource-block-subjects ul li { list-style:none; display:inline-block; }\n.wp-block-wp-oer-resource-block .oer-resource-block-subjects ul li { float:none; font-size: 14px; padding: 10px; }\n.wp-block-wp-oer-resource-block .oer-resource-block-grade-levels { font-size:14px; }\n.wp-block-wp-oer-resource-block .oer-resource-block-featured-image img { width:100%; height:auto; }"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/blocks/resource-block/init.php b/blocks/resource-block/init.php index b0089180..2b796235 100644 --- a/blocks/resource-block/init.php +++ b/blocks/resource-block/init.php @@ -23,7 +23,8 @@ function oer_create_block_wp_oer_resource_block_init() { $script_asset['dependencies'], $script_asset['version'] ); - wp_localize_script( 'wp-oer-resource-block-editor', 'oer_resource', array( 'home_url' => home_url(), 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); + $perm_structure = empty(get_option('permalink_structure'))?false:true; + wp_localize_script( 'wp-oer-resource-block-editor', 'oer_resource', array( 'home_url' => home_url(), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'perm_structure' => $perm_structure ) ); wp_set_script_translations( 'wp-oer-resource-block-editor', 'wp-oer-resource-block', OER_PATH.'/lang/js' ); register_block_type( @@ -98,62 +99,66 @@ function oer_display_resource_block( $attributes, $ajax = false ){ if (!empty($style)) $style ="style='".$style."'"; - + + $showThumbnail = is_bool($showThumbnail)?$showThumbnail:($showThumbnail=="true"?true:false); + $showTitle = is_bool($showTitle)?$showTitle:($showTitle=="true"?true:false); + $showDescription = is_bool($showDescription)?$showDescription:($showDescription=="true"?true:false); + $showSubjects = is_bool($showSubjects)?$showSubjects:($showSubjects=="true"?true:false); + $showGrades = is_bool($showGrades)?$showGrades:($showGrades=="true"?true:false); + $withBorder = is_bool($withBorder)?$withBorder:($withBorder=="true"?true:false); if ($showThumbnail==false && $showTitle==false && $showDescription==false && $showSubjects==false && $showGrades==false && $withBorder==false) - $empty = true; - + $empty = true; + if (!empty($selectedResource)){ $resource = get_post($selectedResource); ob_start(); ?> -
> +
> -
+
- -

post_title); ?>

+ +

post_title; ?>

- ID)): $featured_image = wp_get_attachment_image_src(get_post_thumbnail_id($resource->ID)); ?> - +

post_content); ?>

- ID); ?>
0): ?>
    -
  • +
- ID); - if ($grade_levels): ?> -
- : -
- +
+ Grade Levels: +
+
array('jquery', 'wp-i18n', 'wp-polyfill'), 'version' => '417ae7c5e6142dbafe1f5bc1a5d8ccdf'); \ No newline at end of file + array('jquery', 'wp-i18n', 'wp-polyfill'), 'version' => '9ea8f92db12277332be9a71767c49644'); \ No newline at end of file diff --git a/blocks/subject-resources-block-v2/build/index.asset.php b/blocks/subject-resources-block-v2/build/index.asset.php index dce124d6..c566ed36 100644 --- a/blocks/subject-resources-block-v2/build/index.asset.php +++ b/blocks/subject-resources-block-v2/build/index.asset.php @@ -1 +1 @@ - array('jquery', 'wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-polyfill'), 'version' => '43016d1cca0e72f3b682ec736bd67c83'); \ No newline at end of file + array('jquery', 'wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-polyfill'), 'version' => '45062fb4ac63e1e4b00d7a67be00f4a1'); \ No newline at end of file diff --git a/blocks/subject-resources-block-v2/build/index.js b/blocks/subject-resources-block-v2/build/index.js index f9fa275e..927bed00 100644 --- a/blocks/subject-resources-block-v2/build/index.js +++ b/blocks/subject-resources-block-v2/build/index.js @@ -1 +1,835 @@ -!function(){"use strict";var e,t={321:function(e,t,r){var o=window.wp.blocks,s=window.wp.i18n,c=window.jQuery,l=r.n(c),a=JSON.parse('{"$schema":"https://json.schemastore.org/block.json","apiVersion":2,"name":"wp-oer-plugin/subject-resources-block","version":"0.1.0","title":"OER Subject Resources","category":"oer-block-category","keywords":["OER","resource","subject areas"],"icon":{"foreground":"#121212","src":"welcome-widgets-menus"},"description":"Displays list of resources according to subject areas.","attributes":{"content":{"type":"string","selector":"p"},"title":{"type":"string","selector":"h2"},"link":{"type":"string","selector":"a"},"displayCount":{"type":"string","selector":"display-count","default":5},"selectedSubject":{"type":"number","default":0},"sort":{"type":"string","selector":"sort-option","default":"modified"},"selectedSubjectResources":{"type":"array"},"subjects":{"type":"array"},"selectedSubjects":{"type":"array"},"childSubjects":{"type":"array"},"isChanged":{"type":"boolean","default":false},"blockId":{"type":"string"},"firstLoad":{"type":"boolean","default":true}},"supports":{"html":false},"textdomain":"oer-subject-resources-block","editorScript":"file:./build/index.js","editorStyle":"file:./build/index.css","style":"file:./build/style-index.css"}'),n=window.wp.element,u=window.wp.blockEditor,i=window.wp.components;function d(e){var t,r=[],o=[];String.prototype.ucwords=function(){return this.toLowerCase().replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g,(function(e){return e.toUpperCase()}))};const{attributes:c,setAttributes:a,clientId:d}=e,b=e=>{var t,r=c.selectedSubjects,o=c.displayCount,s=c.sort;"object"==typeof wp.api.collections&&(e=>{try{new e}catch(e){return!1}return!0})(wp.api.collections.Resource)&&(t=new wp.api.collections.Resource,c.selectedSubjects?t.fetch({data:{per_page:o,orderby:s,order:"asc","resource-subject-area":r}}).then((e=>{a({selectedSubjectResources:e})})):t.fetch({data:{per_page:o,orderby:s,order:"asc"}}).then((e=>{a({selectedSubjectResources:e})})))};d!==c.blockId&&a({blockId:d}),c.firstLoad&&(wp.apiFetch({url:oer_subject_resources.home_url+"/wp-json/oer/v2/subjects"}).then((e=>{a({subjects:e})})),setTimeout((function(){b()}),2e3),a({firstLoad:!1}));let p=[{value:"5",label:(0,s.__)("5")},{value:"10",label:(0,s.__)("10")},{value:"15",label:(0,s.__)("15")},{value:"20",label:(0,s.__)("20")},{value:"25",label:(0,s.__)("25")},{value:"30",label:(0,s.__)("30")}],y=[{value:"modified",label:(0,s.__)("Date Updated","oer-subject-resources-block")},{value:"date",label:(0,s.__)("Date Added","oer-subject-resources-block")},{value:"title",label:(0,s.__)("Title a-z","oer-subject-resources-block")}];void 0===c.subjects?r=(0,s.__)("Loading...","oer-subject-resources-block"):o=c.subjects.sort(((e,t)=>e.labelt.label?1:0));const _=o.map(((e,r)=>(t=-1!==l().inArray(e.term_id,c.selectedSubjects),(0,n.createElement)(i.CheckboxControl,{value:e.term_id,label:e.name,key:r,name:"selectedSubjects[]",className:"child"==e.type?"oer-subject-area-child":"oer-subject-area-parent",checked:t[r],id:e.term_id,onChange:function(r){let o=c.selectedSubjects?c.selectedSubjects:[];t=r,l()("#"+e.term_id).prop("checked",t),t&&l()("#"+e.term_id).parent().append(''),r?(t=!0,o.push(e.term_id)):(t=!1,o=c.selectedSubjects.filter((t=>t!==e.term_id))),a({selectedSubjects:o,isChanged:!0}),b()}}))));return void 0===c?r="Loading...":(r=(e=>{var t,r={action:"oer_get_subject_resources",attributes:e};return l().ajax({url:oer_subject_resources.ajax_url,type:"POST",data:r,dataType:"html",async:!1,success:function(e){t=e},error:function(e,t,r){console.log(r)}}),t})(c),a({isChanged:!1})),[(0,n.createElement)(n.Fragment,null,(0,n.createElement)(u.InspectorControls,{className:"oer-subject-resources-block-inspector"},(0,n.createElement)(i.PanelBody,{title:(0,s.__)("OER Subject Resources Option","oer-subject-resources-block"),initialOpen:!0},(0,n.createElement)(i.PanelRow,null,(0,n.createElement)("div",{className:"form-group oer-inspector-subjects"},(0,n.createElement)("label",null,(0,s.__)("Subject(s):","oer-subject-resources-block")),(0,n.createElement)("div",{className:"editor-post-taxonomies__hierarchical-terms-list"},_))),(0,n.createElement)(i.PanelRow,null,(0,n.createElement)(i.SelectControl,{className:"display-count",label:(0,s.__)("# of Resources to display:","oer-subject-resources-block"),value:c.displayCount,options:p,onChange:e=>{a({displayCount:e,isChanged:!0}),b()}})),(0,n.createElement)(i.PanelRow,null,(0,n.createElement)(i.SelectControl,{className:"sort-option",label:(0,s.__)("Sort:","oer-subject-resources-block"),value:c.sort,options:y,onChange:e=>{a({sort:e,isChanged:!0}),b()}}))))),(0,n.createElement)("div",(0,u.useBlockProps)(),(0,n.createElement)("div",{className:"oer-subject-resources-list",dangerouslySetInnerHTML:{__html:r}}))]}window.wp.apiFetch,1==oer_subject_resources.version_58?(0,o.registerBlockType)(a,{edit:d}):(0,o.registerBlockType)("oer-block/subject-resources-block",{title:(0,s.__)("WP OER Subject Resources Block","oer-subject-resources-block"),description:(0,s.__)("Displays list of resources according to subject areas.","oer-subject-resources-block"),category:"oer-block-category",icon:{foreground:"#121212",src:"welcome-widgets-menus"},keywords:[(0,s.__)("OER","oer-subject-resources-block"),(0,s.__)("Resource","oer-subject-resources-block"),(0,s.__)("Subject Areas","oer-subject-resources-block")],attributes:{content:{type:"string",selector:"p"},title:{type:"string",selector:"h2"},link:{type:"string",selector:"a"},displayCount:{type:"string",selector:"display-count",default:5},selectedSubject:{type:"number",default:0},sort:{type:"string",selector:"sort-option",default:"modified"},selectedSubjectResources:{type:"array"},subjects:{type:"array"},selectedSubjects:{type:"array"},childSubjects:{type:"array"},isChanged:{type:"boolean",default:!1},blockId:{type:"string"},firstLoad:{type:"boolean",default:!0}},edit:d})}},r={};function o(e){var s=r[e];if(void 0!==s)return s.exports;var c=r[e]={exports:{}};return t[e](c,c.exports,o),c.exports}o.m=t,e=[],o.O=function(t,r,s,c){if(!r){var l=1/0;for(i=0;i=c)&&Object.keys(o.O).every((function(e){return o.O[e](r[n])}))?r.splice(n--,1):(a=!1,c0&&e[i-1][2]>c;i--)e[i]=e[i-1];e[i]=[r,s,c]},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,{a:t}),t},o.d=function(e,t){for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},function(){var e={826:0,46:0};o.O.j=function(t){return 0===e[t]};var t=function(t,r){var s,c,l=r[0],a=r[1],n=r[2],u=0;if(l.some((function(t){return 0!==e[t]}))){for(s in a)o.o(a,s)&&(o.m[s]=a[s]);if(n)var i=n(o)}for(t&&t(r);u { + try { + new func(); + } catch (err) { + return false; + } + + return true; + }; + + const { + attributes, + setAttributes, + clientId + } = props; + + const getSubjectAreas = () => { + // pretty permalink structure + if (oer_subject_resources.perm_structure) { + wp.apiFetch({ + url: oer_subject_resources.home_url + '/wp-json/oer/v2/subjects/' + }).then(subjects => { + setAttributes({ + subjects: subjects + }); + }); + } else { + // plain permalink structure + wp.apiFetch({ + url: oer_subject_resources.home_url + '?rest_route=/oer/v2/subjects/' + }).then(subjects => { + setAttributes({ + subjects: subjects + }); + }); + } + }; + + (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => { + getSubjectAreas(); + }, []); + + const getOptions = () => { + if (typeof wp.api.collections !== 'undefined') { + if (typeof wp.api.collections === 'object' && isConstructor(wp.api.collections.Posts)) { + return new wp.api.collections.Posts().fetch().then(posts => { + if (typeof this.state.selectedSubject !== 'undefined') { + if (posts && 0 !== this.state.selectedSubject) { + const post = posts.find(item => { + return item.id == this.state.selectedSubject; + }); + this.setState({ + post, + posts + }); + } else { + this.setState({ + posts + }); + } + } + }); + } + } + }; + + const onChangeDisplayCount = newValue => { + setAttributes({ + displayCount: newValue, + isChanged: true + }); + selectResources(true); + }; + + const onChangeSelectedSubject = newValue => { + const post = this.state.posts.find(item => { + return item.id == parseInt(newValue); + }); + this.setState({ + selectedSubject: parseInt(newValue), + post + }); + setAttributes({ + selectedSubject: parseInt(value), + title: post.title.rendered, + content: post.excerpt.rendered, + link: post.link, + isChanged: true + }); + selectResources(true); + }; + + const onChangeSorting = newValue => { + setAttributes({ + sort: newValue, + isChanged: true + }); + selectResources(true); + }; + + const sortSubjects = (a, b) => { + if (a.label < b.label) { + return -1; + } + + if (a.label > b.label) { + return 1; + } + + return 0; + }; + + const getChildSubjects = subject_id => { + var output; + var subjectAreas = new wp.api.models.ResourceSubjectArea(); + var resource_subjects = []; + subjectAreas.fetch({ + data: { + per_page: 100, + parent: subject_id + } + }).then(subjects => { + if (subjects.length > 0) { + resource_subjects = [].concat.apply(resource_subjects, subjects); + resource_subjects = resource_subjects.sort(this.sortSubjects); + this.setState({ + childSubjects: resource_subjects + }); + return resource_subjects; + } + }); + }; + /**-- Select resources after selecting a subject --**/ + + + const selectResources = reload => { + var subjects = attributes.selectedSubjects; + var count = attributes.displayCount; + var sortOption = attributes.sort; + var resources; + + if (typeof wp.api.collections === 'object' && isConstructor(wp.api.collections.Resource)) { + resources = new wp.api.collections.Resource(); + + if (attributes.selectedSubjects) { + resources.fetch({ + data: { + per_page: count, + orderby: sortOption, + order: 'asc', + 'resource-subject-area': subjects + } + }).then(posts => { + setAttributes({ + selectedSubjectResources: posts + }); + }); + } else { + resources.fetch({ + data: { + per_page: count, + orderby: sortOption, + order: 'asc' + } + }).then(posts => { + setAttributes({ + selectedSubjectResources: posts + }); + }); + } + } + }; + + const oer_preview_subject_resources = props => { + var responseText; + var data = { + action: 'oer_get_subject_resources', + attributes: JSON.stringify(props) + }; + jquery__WEBPACK_IMPORTED_MODULE_5___default().ajax({ + url: oer_subject_resources.ajax_url, + type: 'POST', + data: data, + dataType: 'html', + async: false, + success: function (response) { + responseText = response; + }, + error: function (XMLHttpRequest, textStatus, errorThrown) { + console.log(errorThrown); + } + }); + return responseText; + }; + + const setBlockId = blockId => { + setAttributes({ + blockId + }); + }; + + if (clientId !== attributes.blockId) { + setBlockId(clientId); + } + + if (attributes.firstLoad) { + setTimeout(function () { + selectResources(false); + }, 2000); + setAttributes({ + firstLoad: false + }); + } + + let display_count_options = [{ + value: "5", + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('5') + }, { + value: "10", + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('10') + }, { + value: "15", + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('15') + }, { + value: "20", + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('20') + }, { + value: "25", + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('25') + }, { + value: "30", + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('30') + }]; + let sort_options = [{ + value: 'modified', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Date Updated', 'oer-subject-resources-block') + }, { + value: 'date', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Date Added', 'oer-subject-resources-block') + }, { + value: 'title', + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Title a-z', 'oer-subject-resources-block') + }]; + + if (typeof attributes.subjects === 'undefined') { + bOutput = (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Loading...', 'oer-subject-resources-block'); + } else { + subjects = attributes.subjects.sort(sortSubjects); + } + + const subject_areas_display = subjects.map((subject, index) => { + if (jquery__WEBPACK_IMPORTED_MODULE_5___default().inArray(subject.term_id, attributes.selectedSubjects) !== -1) checkedState = true;else checkedState = false; + return (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.CheckboxControl, { + value: subject.term_id, + label: subject.name, + key: index, + name: "selectedSubjects[]", + className: subject.type == 'child' ? 'oer-subject-area-child' : 'oer-subject-area-parent', + checked: checkedState[index], + id: subject.term_id, + onChange: function (val) { + let data = attributes.selectedSubjects ? attributes.selectedSubjects : []; + checkedState = val; + jquery__WEBPACK_IMPORTED_MODULE_5___default()("#" + subject.term_id).prop("checked", checkedState); + if (checkedState) jquery__WEBPACK_IMPORTED_MODULE_5___default()("#" + subject.term_id).parent().append(checkedBox); + + if (val) { + checkedState = true; + data.push(subject.term_id); + /**--if (typeof data !== 'undefined') { + if (data.indexOf(subject.term_id) === -1) { + data.push(subject.term_id) + } + } else { + data.push(subject.term_id); + }--**/ + } else { + checkedState = false; + data = attributes.selectedSubjects.filter(v => v !== subject.term_id); + } + + setAttributes({ + selectedSubjects: data, + isChanged: true + }); + selectResources(true); + } + }); + }); + + if (typeof attributes === 'undefined') { + bOutput = 'Loading...'; + } else { + bOutput = oer_preview_subject_resources(attributes); + setAttributes({ + isChanged: false + }); + } + + return [(0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.Fragment, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_block_editor__WEBPACK_IMPORTED_MODULE_2__.InspectorControls, { + className: "oer-subject-resources-block-inspector" + }, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelBody, { + title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)("OER Subject Resources Option", "oer-subject-resources-block"), + initialOpen: true + }, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)("div", { + className: "form-group oer-inspector-subjects" + }, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)("label", null, (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)("Subject(s):", "oer-subject-resources-block")), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)("div", { + className: "editor-post-taxonomies__hierarchical-terms-list" + }, subject_areas_display))), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.SelectControl, { + className: "display-count", + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)("# of Resources to display:", "oer-subject-resources-block"), + value: attributes.displayCount, + options: display_count_options, + onChange: onChangeDisplayCount + })), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.PanelRow, null, (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)(_wordpress_components__WEBPACK_IMPORTED_MODULE_3__.SelectControl, { + className: "sort-option", + label: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)("Sort:", "oer-subject-resources-block"), + value: attributes.sort, + options: sort_options, + onChange: onChangeSorting + }))))), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)("div", (0,_wordpress_block_editor__WEBPACK_IMPORTED_MODULE_2__.useBlockProps)(), (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_0__.createElement)("div", { + className: "oer-subject-resources-list", + dangerouslySetInnerHTML: { + __html: bOutput + } + }))]; +} + +/***/ }), + +/***/ "./src/index.js": +/*!**********************!*\ + !*** ./src/index.js ***! + \**********************/ +/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _wordpress_blocks__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @wordpress/blocks */ "@wordpress/blocks"); +/* harmony import */ var _wordpress_blocks__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_wordpress_blocks__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n"); +/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jquery */ "jquery"); +/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _style_scss__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./style.scss */ "./src/style.scss"); +/* harmony import */ var _block_json__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../block.json */ "./block.json"); +/* harmony import */ var _edit__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./edit */ "./src/edit.js"); +/** + * Registers a new block provided a unique name and an object defining its behavior. + * + * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/ + */ + +/** + * Retrieves the translation of text. + * + * @see https://developer.wordpress.org/block-editor/packages/packages-i18n/ + */ + + + +/** + * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files. + * All files containing `style` keyword are bundled together. The code used + * gets applied both to the front of your site and to the editor. + * + * @see https://www.npmjs.com/package/@wordpress/scripts#using-css + */ + + + +/** + * Internal dependencies + */ + + +/** + * Every block starts by registering a new block type definition. + * + * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/ + */ + +if (oer_subject_resources.version_58 == 1) { + (0,_wordpress_blocks__WEBPACK_IMPORTED_MODULE_0__.registerBlockType)(_block_json__WEBPACK_IMPORTED_MODULE_4__, { + edit: _edit__WEBPACK_IMPORTED_MODULE_5__["default"] + }); +} else { + (0,_wordpress_blocks__WEBPACK_IMPORTED_MODULE_0__.registerBlockType)('oer-block/subject-resources-block', { + /** + * This is the display title for your block, which can be translated with `i18n` functions. + * The block inserter will show this name. + */ + title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('WP OER Subject Resources Block', 'oer-subject-resources-block'), + + /** + * This is a short description for your block, can be translated with `i18n` functions. + * It will be shown in the Block Tab in the Settings Sidebar. + */ + description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Displays list of resources according to subject areas.', 'oer-subject-resources-block'), + + /** + * Blocks are grouped into categories to help users browse and discover them. + * The categories provided by core are `common`, `embed`, `formatting`, `layout` and `widgets`. + */ + category: 'oer-block-category', + + /** + * An icon property should be specified to make it easier to identify a block. + * These can be any of WordPress’ Dashicons, or a custom svg element. + */ + icon: { + foreground: '#121212', + src: 'welcome-widgets-menus' + }, + keywords: [(0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('OER', 'oer-subject-resources-block'), (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Resource', 'oer-subject-resources-block'), (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_1__.__)('Subject Areas', 'oer-subject-resources-block')], + attributes: { + content: { + type: 'string', + selector: 'p' + }, + title: { + type: 'string', + selector: 'h2' + }, + link: { + type: 'string', + selector: 'a' + }, + displayCount: { + type: 'string', + selector: 'display-count', + default: 5 + }, + selectedSubject: { + type: 'number', + default: 0 + }, + sort: { + type: 'string', + selector: 'sort-option', + default: "modified" + }, + selectedSubjectResources: { + type: 'array' + }, + subjects: { + type: 'array' + }, + selectedSubjects: { + type: 'array' + }, + childSubjects: { + type: 'array' + }, + isChanged: { + type: 'boolean', + default: false + }, + blockId: { + type: 'string' + }, + firstLoad: { + type: 'boolean', + default: true + } + }, + + /** + * @see ./edit.js + */ + edit: _edit__WEBPACK_IMPORTED_MODULE_5__["default"] + /** + * @see ./save.js + */ + //save, + + }); +} + +/***/ }), + +/***/ "./src/editor.scss": +/*!*************************!*\ + !*** ./src/editor.scss ***! + \*************************/ +/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +__webpack_require__.r(__webpack_exports__); +// extracted by mini-css-extract-plugin + + +/***/ }), + +/***/ "./src/style.scss": +/*!************************!*\ + !*** ./src/style.scss ***! + \************************/ +/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +__webpack_require__.r(__webpack_exports__); +// extracted by mini-css-extract-plugin + + +/***/ }), + +/***/ "jquery": +/*!*************************!*\ + !*** external "jQuery" ***! + \*************************/ +/***/ (function(module) { + +module.exports = window["jQuery"]; + +/***/ }), + +/***/ "@wordpress/api-fetch": +/*!**********************************!*\ + !*** external ["wp","apiFetch"] ***! + \**********************************/ +/***/ (function(module) { + +module.exports = window["wp"]["apiFetch"]; + +/***/ }), + +/***/ "@wordpress/block-editor": +/*!*************************************!*\ + !*** external ["wp","blockEditor"] ***! + \*************************************/ +/***/ (function(module) { + +module.exports = window["wp"]["blockEditor"]; + +/***/ }), + +/***/ "@wordpress/blocks": +/*!********************************!*\ + !*** external ["wp","blocks"] ***! + \********************************/ +/***/ (function(module) { + +module.exports = window["wp"]["blocks"]; + +/***/ }), + +/***/ "@wordpress/components": +/*!************************************!*\ + !*** external ["wp","components"] ***! + \************************************/ +/***/ (function(module) { + +module.exports = window["wp"]["components"]; + +/***/ }), + +/***/ "@wordpress/element": +/*!*********************************!*\ + !*** external ["wp","element"] ***! + \*********************************/ +/***/ (function(module) { + +module.exports = window["wp"]["element"]; + +/***/ }), + +/***/ "@wordpress/i18n": +/*!******************************!*\ + !*** external ["wp","i18n"] ***! + \******************************/ +/***/ (function(module) { + +module.exports = window["wp"]["i18n"]; + +/***/ }), + +/***/ "./block.json": +/*!********************!*\ + !*** ./block.json ***! + \********************/ +/***/ (function(module) { + +module.exports = JSON.parse('{"$schema":"https://json.schemastore.org/block.json","apiVersion":2,"name":"wp-oer-plugin/subject-resources-block","version":"0.1.0","title":"OER Subject Resources","category":"oer-block-category","keywords":["OER","resource","subject areas"],"icon":{"foreground":"#121212","src":"welcome-widgets-menus"},"description":"Displays list of resources according to subject areas.","attributes":{"content":{"type":"string","selector":"p"},"title":{"type":"string","selector":"h2"},"link":{"type":"string","selector":"a"},"displayCount":{"type":"string","selector":"display-count","default":5},"selectedSubject":{"type":"number","default":0},"sort":{"type":"string","selector":"sort-option","default":"modified"},"selectedSubjectResources":{"type":"array"},"subjects":{"type":"array"},"selectedSubjects":{"type":"array"},"childSubjects":{"type":"array"},"isChanged":{"type":"boolean","default":false},"blockId":{"type":"string"},"firstLoad":{"type":"boolean","default":true}},"supports":{"html":false},"textdomain":"oer-subject-resources-block","editorScript":"file:./build/index.js","editorStyle":"file:./build/index.css","style":"file:./build/style-index.css"}'); + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = __webpack_modules__; +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/chunk loaded */ +/******/ !function() { +/******/ var deferred = []; +/******/ __webpack_require__.O = function(result, chunkIds, fn, priority) { +/******/ if(chunkIds) { +/******/ priority = priority || 0; +/******/ for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1]; +/******/ deferred[i] = [chunkIds, fn, priority]; +/******/ return; +/******/ } +/******/ var notFulfilled = Infinity; +/******/ for (var i = 0; i < deferred.length; i++) { +/******/ var chunkIds = deferred[i][0]; +/******/ var fn = deferred[i][1]; +/******/ var priority = deferred[i][2]; +/******/ var fulfilled = true; +/******/ for (var j = 0; j < chunkIds.length; j++) { +/******/ if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every(function(key) { return __webpack_require__.O[key](chunkIds[j]); })) { +/******/ chunkIds.splice(j--, 1); +/******/ } else { +/******/ fulfilled = false; +/******/ if(priority < notFulfilled) notFulfilled = priority; +/******/ } +/******/ } +/******/ if(fulfilled) { +/******/ deferred.splice(i--, 1) +/******/ var r = fn(); +/******/ if (r !== undefined) result = r; +/******/ } +/******/ } +/******/ return result; +/******/ }; +/******/ }(); +/******/ +/******/ /* webpack/runtime/compat get default export */ +/******/ !function() { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function() { return module['default']; } : +/******/ function() { return module; }; +/******/ __webpack_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ }(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ !function() { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = function(exports, definition) { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ }(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ !function() { +/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } +/******/ }(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ !function() { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ }(); +/******/ +/******/ /* webpack/runtime/jsonp chunk loading */ +/******/ !function() { +/******/ // no baseURI +/******/ +/******/ // object to store loaded and loading chunks +/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched +/******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded +/******/ var installedChunks = { +/******/ "index": 0, +/******/ "style-index": 0 +/******/ }; +/******/ +/******/ // no chunk on demand loading +/******/ +/******/ // no prefetching +/******/ +/******/ // no preloaded +/******/ +/******/ // no HMR +/******/ +/******/ // no HMR manifest +/******/ +/******/ __webpack_require__.O.j = function(chunkId) { return installedChunks[chunkId] === 0; }; +/******/ +/******/ // install a JSONP callback for chunk loading +/******/ var webpackJsonpCallback = function(parentChunkLoadingFunction, data) { +/******/ var chunkIds = data[0]; +/******/ var moreModules = data[1]; +/******/ var runtime = data[2]; +/******/ // add "moreModules" to the modules object, +/******/ // then flag all "chunkIds" as loaded and fire callback +/******/ var moduleId, chunkId, i = 0; +/******/ if(chunkIds.some(function(id) { return installedChunks[id] !== 0; })) { +/******/ for(moduleId in moreModules) { +/******/ if(__webpack_require__.o(moreModules, moduleId)) { +/******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; +/******/ } +/******/ } +/******/ if(runtime) var result = runtime(__webpack_require__); +/******/ } +/******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data); +/******/ for(;i < chunkIds.length; i++) { +/******/ chunkId = chunkIds[i]; +/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { +/******/ installedChunks[chunkId][0](); +/******/ } +/******/ installedChunks[chunkIds[i]] = 0; +/******/ } +/******/ return __webpack_require__.O(result); +/******/ } +/******/ +/******/ var chunkLoadingGlobal = self["webpackChunkoer_subject_resources_block"] = self["webpackChunkoer_subject_resources_block"] || []; +/******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0)); +/******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal)); +/******/ }(); +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module depends on other loaded chunks and execution need to be delayed +/******/ var __webpack_exports__ = __webpack_require__.O(undefined, ["style-index"], function() { return __webpack_require__("./src/index.js"); }) +/******/ __webpack_exports__ = __webpack_require__.O(__webpack_exports__); +/******/ +/******/ })() +; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/blocks/subject-resources-block-v2/build/index.js.map b/blocks/subject-resources-block-v2/build/index.js.map new file mode 100644 index 00000000..a1af73ba --- /dev/null +++ b/blocks/subject-resources-block-v2/build/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACe,SAASmB,IAAT,CAAeC,KAAf,EAAuB;AAClC,MAAIC,eAAe,GAAG,EAAtB;AACA,MAAIC,OAAO,GAAG,EAAd;AACA,MAAIC,aAAa,GAAG,EAApB;AACA,MAAIC,QAAQ,GAAG,EAAf;AACA,MAAIC,GAAJ;AACA,MAAIC,OAAJ;AACA,MAAIC,OAAJ;AACA,MAAIC,YAAJ;AACA,MAAIC,kBAAJ;AAEA,QAAMC,UAAU,GAAG,8PAAnB;;AAEAC,EAAAA,MAAM,CAACC,SAAP,CAAiBC,OAAjB,GAA2B,YAAW;AACpC,QAAIC,GAAG,GAAG,KAAKC,WAAL,EAAV;AACA,WAAOD,GAAG,CAACE,OAAJ,CAAY,yCAAZ,EACL,UAASC,CAAT,EAAW;AACT,aAAOA,CAAC,CAACC,WAAF,EAAP;AACD,KAHI,CAAP;AAID,GAND,CAbkC,CAqBlC;;;AACA,QAAMC,aAAa,GAAIC,IAAD,IAAU;AAC5B,QAAI;AACA,UAAIA,IAAJ;AACH,KAFD,CAEG,OAAOC,GAAP,EAAW;AACV,aAAO,KAAP;AACH;;AACD,WAAO,IAAP;AACH,GAPD;;AASA,QAAM;AAAEC,IAAAA,UAAF;AAAcC,IAAAA,aAAd;AAA6BC,IAAAA;AAA7B,MAA0CxB,KAAhD;;AAEA,QAAMyB,eAAe,GAAE,MAAM;AACzB;AACA,QAAIC,qBAAqB,CAACC,cAA1B,EAAyC;AACrCC,MAAAA,EAAE,CAAC/B,QAAH,CAAa;AAAEgC,QAAAA,GAAG,EAACH,qBAAqB,CAACI,QAAtB,GAAkC;AAAxC,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WACA;WACA,+BAA+B,wCAAwC;WACvE;WACA;WACA;WACA;WACA,iBAAiB,qBAAqB;WACtC;WACA;WACA;WACA;WACA,kBAAkB,qBAAqB;WACvC,oHAAoH,iDAAiD;WACrK;WACA,KAAK;WACL;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;;;;WC7BA;WACA;WACA;WACA,eAAe,4BAA4B;WAC3C,eAAe;WACf,iCAAiC,WAAW;WAC5C;WACA;;;;;WCPA;WACA;WACA;WACA;WACA,yCAAyC,wCAAwC;WACjF;WACA;WACA;;;;;WCPA,8CAA8C;;;;;WCA9C;WACA;WACA;WACA,uDAAuD,iBAAiB;WACxE;WACA,gDAAgD,aAAa;WAC7D;;;;;WCNA;;WAEA;WACA;WACA;WACA;WACA;WACA;WACA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA,8CAA8C;;WAE9C;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA,iCAAiC,mCAAmC;WACpE;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA,MAAM,qBAAqB;WAC3B;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;WAEA;WACA;WACA;;;;;UEnDA;UACA;UACA;UACA,yFAAyF,+CAA+C;UACxI","sources":["webpack://oer-subject-resources-block/./src/edit.js","webpack://oer-subject-resources-block/./src/index.js","webpack://oer-subject-resources-block/./src/editor.scss","webpack://oer-subject-resources-block/./src/style.scss","webpack://oer-subject-resources-block/external window \"jQuery\"","webpack://oer-subject-resources-block/external window [\"wp\",\"apiFetch\"]","webpack://oer-subject-resources-block/external window [\"wp\",\"blockEditor\"]","webpack://oer-subject-resources-block/external window [\"wp\",\"blocks\"]","webpack://oer-subject-resources-block/external window [\"wp\",\"components\"]","webpack://oer-subject-resources-block/external window [\"wp\",\"element\"]","webpack://oer-subject-resources-block/external window [\"wp\",\"i18n\"]","webpack://oer-subject-resources-block/webpack/bootstrap","webpack://oer-subject-resources-block/webpack/runtime/chunk loaded","webpack://oer-subject-resources-block/webpack/runtime/compat get default export","webpack://oer-subject-resources-block/webpack/runtime/define property getters","webpack://oer-subject-resources-block/webpack/runtime/hasOwnProperty shorthand","webpack://oer-subject-resources-block/webpack/runtime/make namespace object","webpack://oer-subject-resources-block/webpack/runtime/jsonp chunk loading","webpack://oer-subject-resources-block/webpack/before-startup","webpack://oer-subject-resources-block/webpack/startup","webpack://oer-subject-resources-block/webpack/after-startup"],"sourcesContent":["/**\n * Retrieves the translation of text.\n *\n * @see https://developer.wordpress.org/block-editor/packages/packages-i18n/\n */\nimport { __ } from '@wordpress/i18n';\nimport { useBlockProps, RichText, InspectorControls, BlockControls, AlignmentToolbar } from '@wordpress/block-editor';\nimport { ToggleControl, PanelBody, PanelRow, CheckboxControl, SelectControl, ColorPicker, IconButton, Toolbar } from '@wordpress/components';\nimport { Fragment, useState, useEffect } from \"@wordpress/element\";\nimport { apiFetch } from '@wordpress/api-fetch';\nimport $ from 'jquery';\n\n/**\n * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.\n * Those files can contain any CSS code that gets applied to the editor.\n *\n * @see https://www.npmjs.com/package/@wordpress/scripts#using-css\n */\nimport './editor.scss';\n\n/**\n * The edit function describes the structure of your block in the context of the\n * editor. This represents what the editor will render when the block is used.\n *\n * @see https://developer.wordpress.org/block-editor/developers/block-api/block-edit-save/#edit\n *\n * @param {Object} [props] Properties passed from the editor.\n * @param {string} [props.className] Class name generated for the block.\n *\n * @return {WPElement} Element to render.\n */\nexport default function Edit( props ) {\n var subject_display = [];\n var bOutput = [];\n var childSubjects = [];\n var subjects = [];\n var key;\n let sortbox;\n let heading;\n var checkedState;\n var selectedSortOption;\n\n const checkedBox = '';\n\n String.prototype.ucwords = function() {\n var str = this.toLowerCase();\n return str.replace(/(^([a-zA-Z\\p{M}]))|([ -][a-zA-Z\\p{M}])/g,\n function(s){\n return s.toUpperCase();\n });\n };\n\n // Check if function is a constructor\n const isConstructor = (func) => {\n try {\n new func();\n } catch (err){\n return false;\n } \n return true;\n }\n\n const { attributes, setAttributes, clientId } = props;\n\n const getSubjectAreas =() => {\n // pretty permalink structure\n if (oer_subject_resources.perm_structure){\n wp.apiFetch( { url:oer_subject_resources.home_url + '/wp-json/oer/v2/subjects/'} ).then( subjects => {\n setAttributes( { subjects: subjects } );\n });\n } else {\n // plain permalink structure\n wp.apiFetch( { url:oer_subject_resources.home_url + '?rest_route=/oer/v2/subjects/'} ).then( subjects => {\n setAttributes( { subjects: subjects } );\n });\n }\n }\n\n useEffect(() => {\n getSubjectAreas();\n },[]);\n\n const getOptions = () => {\n if (typeof wp.api.collections !== 'undefined'){\n if (typeof wp.api.collections === 'object' && isConstructor(wp.api.collections.Posts)) {\n return ( new wp.api.collections.Posts() ).fetch().then( (posts) => {\n if (typeof this.state.selectedSubject !== 'undefined'){\n if ( posts && 0 !== this.state.selectedSubject ){\n const post = posts.find( (item) => { return item.id == this.state.selectedSubject } );\n\n this.setState( { post, posts });\n } else {\n this.setState( {posts} );\n }\n }\n });\n }\n }\n }\n \n const onChangeDisplayCount = ( newValue ) => {\n setAttributes( { displayCount: newValue, isChanged: true } );\n selectResources(true);\n }\n\n const onChangeSelectedSubject = ( newValue ) => {\n const post = this.state.posts.find( (item) => { return item.id==parseInt(newValue)} );\n this.setState( { selectedSubject: parseInt(newValue), post } );\n setAttributes( { \n selectedSubject: parseInt(value),\n title: post.title.rendered,\n content: post.excerpt.rendered,\n link: post.link,\n isChanged: true\n } );\n selectResources(true);\n }\n\n const onChangeSorting = ( newValue ) => {\n setAttributes( { sort: newValue, isChanged: true} );\n selectResources(true);\n }\n\n const sortSubjects = (a,b) => {\n if(a.label < b.label) { return -1; }\n if(a.label > b.label) { return 1; }\n return 0;\n }\n\n const getChildSubjects = ( subject_id ) => {\n var output;\n var subjectAreas = new wp.api.models.ResourceSubjectArea;\n var resource_subjects = [];\n subjectAreas.fetch( { data: { per_page: 100, parent: subject_id } } ).then( (subjects) => {\n if (subjects.length>0){\n resource_subjects = [].concat.apply(resource_subjects,subjects);\n resource_subjects = resource_subjects.sort(this.sortSubjects);\n this.setState({ childSubjects: resource_subjects });\n return resource_subjects;\n }\n });\n }\n\n /**-- Select resources after selecting a subject --**/\n const selectResources = ( reload ) => {\n var subjects = attributes.selectedSubjects;\n var count = attributes.displayCount;\n var sortOption = attributes.sort;\n var resources;\n if (typeof wp.api.collections === 'object' && isConstructor(wp.api.collections.Resource)) {\n resources = new wp.api.collections.Resource();\n if (attributes.selectedSubjects){\n resources.fetch( { data: { per_page: count, orderby: sortOption, order: 'asc', 'resource-subject-area': subjects } } ).then( (posts) => {\n setAttributes( { selectedSubjectResources: posts } );\n } ); \n } else {\n resources.fetch( { data: { per_page: count, orderby: sortOption, order: 'asc' } } ).then( (posts) => {\n setAttributes( { selectedSubjectResources: posts } );\n }); \n }\n }\n }\n\n const oer_preview_subject_resources = (props) => {\n var responseText;\n var data = {\n action : 'oer_get_subject_resources',\n attributes: JSON.stringify(props),\n };\n $.ajax({ \n url:oer_subject_resources.ajax_url, \n type:'POST',\n data: data,\n dataType: 'html',\n async: false,\n success:function(response){\n responseText = response;\n },\n error: function(XMLHttpRequest, textStatus, errorThrown){\n console.log(errorThrown);\n }\n })\n return responseText;\n }\n\n const setBlockId = (blockId) => { setAttributes( { blockId } ); }\n\n if( clientId !== attributes.blockId ){\n setBlockId(clientId);\n }\n\n if (attributes.firstLoad){\n setTimeout( function() { \n selectResources(false);\n }, 2000);\n setAttributes({ firstLoad: false });\n }\n\n let display_count_options = [ \n { value:\"5\", label: __('5') }, \n { value:\"10\", label: __('10') }, \n { value:\"15\", label: __('15') }, \n { value:\"20\", label: __('20') }, \n { value:\"25\", label: __('25') },\n { value:\"30\", label: __('30') } \n ];\n let sort_options = [\n { value:'modified', label:__('Date Updated', 'oer-subject-resources-block')},\n { value:'date', label:__('Date Added', 'oer-subject-resources-block')},\n { value:'title', label:__('Title a-z', 'oer-subject-resources-block')},\n ];\n\n if (typeof attributes.subjects === 'undefined' ){\n bOutput = __('Loading...', 'oer-subject-resources-block');\n } else {\n subjects = attributes.subjects.sort(sortSubjects);\n }\n\n const subject_areas_display = subjects.map( ( subject, index) => {\n if ($.inArray(subject.term_id,attributes.selectedSubjects)!==-1)\n checkedState = true;\n else\n checkedState = false;\n return (\n v !== subject.term_id);\n }\n setAttributes({ selectedSubjects: data, isChanged: true });\n selectResources(true);\n } }\n />)\n });\n\n if (typeof attributes === 'undefined'){\n bOutput = 'Loading...';\n } else {\n bOutput = oer_preview_subject_resources(attributes);\n setAttributes({ isChanged:false });\n } \n\n return [(\n \n \n \n \n
\n \n
\n { subject_areas_display }\n
\n
\n
\n \n \n \n \n \n \n \n
\n
\n ),\n
\n
]\n}\n","/**\n * Registers a new block provided a unique name and an object defining its behavior.\n *\n * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/\n */\nimport { registerBlockType } from '@wordpress/blocks';\n\n/**\n * Retrieves the translation of text.\n *\n * @see https://developer.wordpress.org/block-editor/packages/packages-i18n/\n */\nimport { __ } from '@wordpress/i18n';\nimport $ from 'jquery';\n\n/**\n * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.\n * All files containing `style` keyword are bundled together. The code used\n * gets applied both to the front of your site and to the editor.\n *\n * @see https://www.npmjs.com/package/@wordpress/scripts#using-css\n */\nimport './style.scss';\nimport metadata from '../block.json';\n/**\n * Internal dependencies\n */\nimport Edit from './edit';\n\n/**\n * Every block starts by registering a new block type definition.\n *\n * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/\n */\n if (oer_subject_resources.version_58==1){\n registerBlockType( metadata, {\n edit: Edit,\n });\n } else {\n registerBlockType( 'oer-block/subject-resources-block', {\n /**\n * This is the display title for your block, which can be translated with `i18n` functions.\n * The block inserter will show this name.\n */\n title: __( 'WP OER Subject Resources Block', 'oer-subject-resources-block' ),\n\n\n /**\n * This is a short description for your block, can be translated with `i18n` functions.\n * It will be shown in the Block Tab in the Settings Sidebar.\n */\n description: __( 'Displays list of resources according to subject areas.', 'oer-subject-resources-block' ),\n\n /**\n * Blocks are grouped into categories to help users browse and discover them.\n * The categories provided by core are `common`, `embed`, `formatting`, `layout` and `widgets`.\n */\n category: 'oer-block-category',\n\n /**\n * An icon property should be specified to make it easier to identify a block.\n * These can be any of WordPress’ Dashicons, or a custom svg element.\n */\n icon: {\n foreground: '#121212',\n src: 'welcome-widgets-menus'\n },\n\n keywords: [__('OER', 'oer-subject-resources-block'), __('Resource', 'oer-subject-resources-block'), __('Subject Areas', 'oer-subject-resources-block')],\n\n attributes : {\n content: {\n type: 'string',\n selector: 'p'\n },\n title: {\n type: 'string',\n selector: 'h2'\n },\n link: {\n type: 'string',\n selector: 'a'\n },\n displayCount: {\n type: 'string',\n selector: 'display-count',\n default: 5\n },\n selectedSubject: {\n type: 'number',\n default: 0\n },\n sort: {\n type: 'string',\n selector: 'sort-option',\n default: \"modified\"\n },\n selectedSubjectResources: {\n type: 'array'\n },\n subjects: {\n type:'array'\n }, \n selectedSubjects: {\n type:'array'\n },\n childSubjects: {\n type:'array'\n }, \n isChanged: {\n type: 'boolean',\n default: false\n },\n blockId: {\n type: 'string'\n },\n firstLoad: {\n type: 'boolean',\n default: true\n }\n },\n\n /**\n * @see ./edit.js\n */\n edit: Edit,\n\n /**\n * @see ./save.js\n */\n //save,\n } );\n }\n","// extracted by mini-css-extract-plugin\nexport {};","// extracted by mini-css-extract-plugin\nexport {};","module.exports = window[\"jQuery\"];","module.exports = window[\"wp\"][\"apiFetch\"];","module.exports = window[\"wp\"][\"blockEditor\"];","module.exports = window[\"wp\"][\"blocks\"];","module.exports = window[\"wp\"][\"components\"];","module.exports = window[\"wp\"][\"element\"];","module.exports = window[\"wp\"][\"i18n\"];","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","var deferred = [];\n__webpack_require__.O = function(result, chunkIds, fn, priority) {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar chunkIds = deferred[i][0];\n\t\tvar fn = deferred[i][1];\n\t\tvar priority = deferred[i][2];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every(function(key) { return __webpack_require__.O[key](chunkIds[j]); })) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = function(module) {\n\tvar getter = module && module.__esModule ?\n\t\tfunction() { return module['default']; } :\n\t\tfunction() { return module; };\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = function(exports, definition) {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }","// define __esModule on exports\n__webpack_require__.r = function(exports) {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t\"index\": 0,\n\t\"style-index\": 0\n};\n\n// no chunk on demand loading\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = function(chunkId) { return installedChunks[chunkId] === 0; };\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = function(parentChunkLoadingFunction, data) {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some(function(id) { return installedChunks[id] !== 0; })) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkIds[i]] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkoer_subject_resources_block\"] = self[\"webpackChunkoer_subject_resources_block\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [\"style-index\"], function() { return __webpack_require__(\"./src/index.js\"); })\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n",""],"names":["__","useBlockProps","RichText","InspectorControls","BlockControls","AlignmentToolbar","ToggleControl","PanelBody","PanelRow","CheckboxControl","SelectControl","ColorPicker","IconButton","Toolbar","Fragment","useState","useEffect","apiFetch","$","Edit","props","subject_display","bOutput","childSubjects","subjects","key","sortbox","heading","checkedState","selectedSortOption","checkedBox","String","prototype","ucwords","str","toLowerCase","replace","s","toUpperCase","isConstructor","func","err","attributes","setAttributes","clientId","getSubjectAreas","oer_subject_resources","perm_structure","wp","url","home_url","then","getOptions","api","collections","Posts","fetch","posts","state","selectedSubject","post","find","item","id","setState","onChangeDisplayCount","newValue","displayCount","isChanged","selectResources","onChangeSelectedSubject","parseInt","value","title","rendered","content","excerpt","link","onChangeSorting","sort","sortSubjects","a","b","label","getChildSubjects","subject_id","output","subjectAreas","models","ResourceSubjectArea","resource_subjects","data","per_page","parent","length","concat","apply","reload","selectedSubjects","count","sortOption","resources","Resource","orderby","order","selectedSubjectResources","oer_preview_subject_resources","responseText","action","JSON","stringify","ajax","ajax_url","type","dataType","async","success","response","error","XMLHttpRequest","textStatus","errorThrown","console","log","setBlockId","blockId","firstLoad","setTimeout","display_count_options","sort_options","subject_areas_display","map","subject","index","inArray","term_id","name","val","prop","append","push","filter","v","__html","registerBlockType","metadata","version_58","edit","description","category","icon","foreground","src","keywords","selector","default"],"sourceRoot":""} \ No newline at end of file diff --git a/blocks/subject-resources-block-v2/init.php b/blocks/subject-resources-block-v2/init.php index 55656002..c3f008a5 100644 --- a/blocks/subject-resources-block-v2/init.php +++ b/blocks/subject-resources-block-v2/init.php @@ -25,7 +25,8 @@ function wp_oer_subject_resources_block_init() { $script_asset['dependencies'], $script_asset['version'] ); - wp_localize_script( 'oer-subject-resources-block-editor', 'oer_subject_resources', array( 'home_url' => home_url(), 'ajax_url' => admin_url( 'admin-ajax.php' ), 'version_58' => $version_58 ) ); + $perm_structure = empty(get_option('permalink_structure'))?false:true; + wp_localize_script( 'oer-subject-resources-block-editor', 'oer_subject_resources', array( 'home_url' => home_url(), 'ajax_url' => admin_url( 'admin-ajax.php' ), 'version_58' => $version_58, 'perm_structure' => $perm_structure ) ); wp_set_script_translations('oer-subject-resources-block-editor', 'oer-subject-resources-block', OER_PATH . '/lang/js'); $front_asset_path = "$dir/build/front.asset.php"; @@ -90,7 +91,8 @@ function wp_oer_subject_resources_block_json_init() { $script_asset['dependencies'], $script_asset['version'] ); - wp_localize_script( 'oer-subject-resources-block-editor', 'oer_subject_resources', array( 'home_url' => home_url(), 'ajax_url' => admin_url( 'admin-ajax.php' ), 'version_58' => $version_58 ) ); + $perm_structure = empty(get_option('permalink_structure'))?false:true; + wp_localize_script( 'oer-subject-resources-block-editor', 'oer_subject_resources', array( 'home_url' => home_url(), 'ajax_url' => admin_url( 'admin-ajax.php' ), 'version_58' => $version_58, 'perm_structure' => $perm_structure ) ); wp_set_script_translations('oer-subject-resources-block-editor', 'oer-subject-resources-block', OER_PATH . '/lang/js'); $front_asset_path = "$dir/build/front.asset.php"; @@ -245,6 +247,7 @@ function oer_display_subject_resources_block( $attributes , $ajax = false){ if (empty($selectedSubjectResources)) $selectedSubjectResources = oer_srb_get_resources($attributes,true); if (is_array($selectedSubjectResources)){ + $selectedSubjectResources = oer_srb_get_resources($attributes,true); $selectedSubjectResources = (object)$selectedSubjectResources; if (!empty((array)$selectedSubjectResources)){ foreach ($selectedSubjectResources as $subject){ @@ -542,6 +545,7 @@ function oer_get_subject_resources($args, $ajax=false){ if ($ajax && isset($args['attributes'])) $args = $args['attributes']; + $resources = oer_srb_get_resources($args,true); if (is_array($resources)){ @@ -587,21 +591,20 @@ function oer_get_subject_resources($args, $ajax=false){ function oer_ajax_get_subject_resources(){ $allowed_tags = oer_allowed_html(); - // Sanitize POST parameters $params = array(); $params['action'] = sanitize_text_field($_POST['action']); - if (isset($_POST['attributes'])) - $params['attributes'] = $_POST['attributes']; - else + + if (isset($_POST['attributes'])){ + $attributes = $_POST['attributes']; + $attributes = html_entity_decode($attributes); + $attributes = (array)json_decode(stripcslashes($attributes)); + $params['attributes'] = $attributes; + } else $params['attributes'] = $_POST; - array_walk($params['attributes'], function(&$value, &$key){ - $value['displayCount'] = sanitize_text_field($value['displayCount']); - $value['sort'] = sanitize_text_field($value['sort']); - $value['isChanged'] = sanitize_text_field($value['isChanged']); - $value['blockId'] = sanitize_text_field($value['blockId']); - $value['firstLoad'] = sanitize_text_field($value['firstLoad']); + array_walk($params['attributes'], function($value, $key){ + $value = sanitize_text_field($value); }); $resources = oer_get_subject_resources($params, true); diff --git a/css/back_styles.css b/css/back_styles.css index f4bf028e..31a60676 100644 --- a/css/back_styles.css +++ b/css/back_styles.css @@ -49,6 +49,7 @@ standardModaloer_metawpr { /*float: right;*/ } +.resource-notice-legend { padding:20px 0 0; } .oer_snglfld .oer_txt { width: 180px; @@ -200,6 +201,7 @@ ul.oer_slctstandard > li font-size: 25px; padding: 20px 0; } +.oer_settings_form .form-inline-error { color:#FF0000; margin-left:5px; } .oer_imprtrwpr .fields { margin-bottom:10px; } @@ -229,6 +231,7 @@ ul.oer_slctstandard > li .oer-plugin-row fieldset, .oer-import-row fieldset { margin-bottom:15px; } .oer-plugin-row .form-table th { width:0; display:none; } .oer-plugin-row .form-table td label { margin-right:10px; } +.oer-plugin-row .bottom-margin { margin-bottom:10px; } .oer-plugin-row .form-table td .indent { margin-left:25px; } .oer-plugin-row .form-table td textarea { width:100%; } .oer-plugin-row .form-table td .inline-desc { @@ -406,4 +409,7 @@ label.selected span.relatedResourceSelectorImage { div#standardModal { z-index: 9999 !important; } .oer_settings_form input::placeholder { color:#707d86; } .oer_text_red { color:#ce1212; } -.components-button.button.button-primary { font-weight:bold; } \ No newline at end of file +.components-button.button.button-primary { font-weight:bold; } +.resource-notice-legend, .resource-path-legend { padding-bottom:0px !important; } +#oer_configurable_resource_path, +#oer_nalrc_resources_page_title { width:50%; padding: 5px 10px; } \ No newline at end of file diff --git a/css/front_styles.css b/css/front_styles.css index 59e4d8f5..c1d4c0a6 100644 --- a/css/front_styles.css +++ b/css/front_styles.css @@ -470,7 +470,8 @@ article.oer_sngl_resource_wrapper div#sngl-resource header.entry-header h1.entry .oer_blgpst .rght-sd-cntnr-blg { width:100%; float:none; } .oer_sngl_stndrd { margin-left:5px; } } -a.oer-featureimg .dashicons { +a.oer-featureimg .dashicons, +div.oer-featureimg .dashicons { font-size: 165px; width: 100%; height: 400px; diff --git a/css/resource-print.css b/css/resource-print.css new file mode 100644 index 00000000..12dc22ef --- /dev/null +++ b/css/resource-print.css @@ -0,0 +1,73 @@ +body.print-preview { + background-color:none; +} +body.print-preview #header, +body.print-preview #footer { display:none; } +body.print-preview .oer-cntnr .site-content { padding-top:0px; } +body.print-preview .oer-cntnr .site-content .oer_resource_posts .oer_blgpst { margin-left:0; max-width:100%; } +body.print-preview .oer-cntnr .site-content .oer_resource_posts .oer_blgpst +body.print-preview .oer-cntnr .site-content .archive-header.resource-resources-header { margin-bottom:25px; } +body.print-preview .oer-cntnr .site-content table.oer-resources-posts-table { width:100%; } +body.print-preview .oer-cntnr .site-content table.oer-resources-posts-table thead { display:none; } +body.print-preview .oer-cntnr .site-content table.oer-resources-posts-table td { border-bottom:1px solid #d1d1d1; } +body.print-preview .oer-cntnr .site-content table.oer-resources-posts-table tr:first-child td { border-top:1px solid #d1d1d1; padding-top:5px; } +body.print-preview .oer-cntnr .site-content table.oer-resources-posts-table tr:first-child td .oer_blgpst { margin-top:5px; } +body.print-preview table.oer_resource_posts { width:100%; } +body.print-preview table.oer_resource_posts thead { width:100%; } +body.print-preview table.oer_resource_posts thead tr th { background-color:#F1F1F1 !important; text-align:left; } +body.print-preview table.oer_resource_posts thead tr th:first-child{ background-color:#F1F1F1 !important; } +body.print-preview table.oer_resource_posts tr td, +body.print-preview table.oer_resource_posts thead tr th { padding:5px; } +body.print-preview table.oer_resource_posts tr:nth-child(odd){ background-color:#FFFFFF !important; } +body.print-preview table.oer_resource_posts tr:nth-child(even){ background-color:#F9F9F9 !important; } +body.print-preview table.oer_resource_posts tr td:last-child { width:10%; white-space: normal; word-break:break-all; } +body.print-preview table.oer_resource_posts tr .resource-thumbnail { width:10%; } +body.print-preview table.oer_resource_posts tr .resource-thumbnail img { width:150px; height:auto; } +body.print-preview table.oer_resource_posts tr .resource-title { width:15%; } +body.print-preview table.oer_resource_posts tr .resource-date-created { width:10%; } +body.print-preview table.oer_resource_posts tr .resource-type { width:15%; } +body.print-preview table.oer_resource_posts tr .resource-description { width:25%; } +body.print-preview table.oer_resource_posts tr .resource-grade-level { width:10%; } +body.print-preview table.oer_resource_posts tr .resource-link { width:15%; } +body.print-preview .oer_blgpst { border-bottom:none; padding:10px 0; } +body.print-preview .oer_blgpst .oer-feature-image { width:20%; } +body.print-preview .oer_blgpst .rght-sd-cntnr-blg { width:80%; } +body.print-preview hr { display:none; } +@page { + size: auto !important; +} +@media print { + body.print-preview #header, + body.print-preview #footer { display:none; } + body.print-preview .oer-cntnr .site-content { padding-top:0px; } + body.print-preview .oer-cntnr .site-content .oer_resource_posts .oer_blgpst { margin-left:0; max-width:100%; } + body.print-preview .oer-cntnr .site-content .oer_resource_posts .oer_blgpst + body.print-preview .oer-cntnr .site-content .archive-header.resource-resources-header { margin-bottom:25px; } + body.print-preview .oer-cntnr .site-content table.oer-resources-posts-table { width:100%; } + body.print-preview .oer-cntnr .site-content table.oer-resources-posts-table thead { display:none; } + body.print-preview .oer-cntnr .site-content table.oer-resources-posts-table td { border-bottom:1px solid #d1d1d1; padding:5px; } + body.print-preview .oer-cntnr .site-content table.oer-resources-posts-table tr:first-child td { border-top:1px solid #d1d1d1; } + body.print-preview .oer-cntnr .site-content table.oer-resources-posts-table tr:first-child td .oer_blgpst { margin-top:5px; } + body.print-preview table.oer_resource_posts { width:100%; page-break-after:auto; } + body.print-preview table.oer_resource_posts thead { width:100%; } + body.print-preview table.oer_resource_posts thead tr th { background-color:#F1F1F1 !important; text-align:left; } + body.print-preview table.oer_resource_posts thead tr th:first-child{ background-color:#F1F1F1 !important; } + body.print-preview table.oer_resource_posts tr { page-break-inside:avoid; page-break-after:auto; } + body.print-preview table.oer_resource_posts tr td, + body.print-preview table.oer_resource_posts thead tr th { padding:5px; font-size:14px; } + body.print-preview table.oer_resource_posts tr:nth-child(odd){ background-color:#FFFFFF !important; } + body.print-preview table.oer_resource_posts tr:nth-child(even){ background-color:#F9F9F9 !important; } + body.print-preview table.oer_resource_posts tr td:last-child { width:10%; white-space: normal; word-break:break-all; } + body.print-preview table.oer_resource_posts tr .resource-thumbnail { width:10%; } + body.print-preview table.oer_resource_posts tr .resource-thumbnail img { width:90%; height:auto; } + body.print-preview table.oer_resource_posts tr .resource-title { width:15%; } + body.print-preview table.oer_resource_posts tr .resource-date-created { width:10%; } + body.print-preview table.oer_resource_posts tr .resource-type { width:15%; } + body.print-preview table.oer_resource_posts tr .resource-description { width:25%; } + body.print-preview table.oer_resource_posts tr .resource-grade-level { width:10%; } + body.print-preview table.oer_resource_posts tr .resource-link { width:15%; } + body.print-preview .oer_blgpst .oer-feature-image { width:20%; } + body.print-preview .oer_blgpst .rght-sd-cntnr-blg { width:80%; } + body.print-preview .oer_blgpst { border-bottom:none; padding:10px 0; } + body.print-preview hr { display:none; } +} \ No newline at end of file diff --git a/css/resources.css b/css/resources.css new file mode 100644 index 00000000..5bbb817e --- /dev/null +++ b/css/resources.css @@ -0,0 +1,153 @@ +.archive-header .oer-resources-title { margin:0; } +.resource-search-filters { padding: 20px 20px 30px; border-radius: 5px; position: relative; border: 1px solid #cdcdcd; } +.resource-search-filters .filter-title h2 { margin:0; } +.resource-search-filters .resource-search-keyword { position:relative; } +.resource-search-filters .resource-search-keyword i { position: absolute; top: 10px; left: 25px; color:#686868; } +.resource-search-filters .resource-search-keyword input { + padding-left: 30px; + border-radius: 4px; + border: 1px solid #414141; + width: 100%; + height: 38px; + color: #000000; +} +.resource-select-wrapper { + position: relative; + background: #FFFFFF; + height: 38px; + border-radius: 4px; + border: 1px solid #414141; +} +.resource-search-grade-level .resource-select-wrapper select.selectpicker, +.resource-search-product .resource-select-wrapper select.selectpicker { + position: absolute!important; + bottom: 0; + left: 50%; + display: block!important; + width: 0.5px!important; + height: 100%!important; + padding: 0!important; + opacity: 0!important; + border: none; + z-index: 0!important; +} +.resource-search-product .resource-select-wrapper .bootstrap-select .dropdown-toggle, +.resource-search-grade-level .resource-select-wrapper .bootstrap-select .dropdown-toggle { + position: relative; + width: 100%; + text-align: right; + white-space: nowrap; + display: -webkit-inline-box; + display: -webkit-inline-flex; + display: -ms-inline-flexbox; + display: inline-flex; + -webkit-box-align: center; + -webkit-align-items: center; + -ms-flex-align: center; + align-items: center; + -webkit-box-pack: justify; + -webkit-justify-content: space-between; + -ms-flex-pack: justify; + justify-content: space-between; + padding-left: 5px; +} +.resource-search-grade-level .resource-select-wrapper .bootstrap-select .dropdown-toggle .filter-option, +.resource-search-product .resource-select-wrapper .bootstrap-select .dropdown-toggle .filter-option { overflow: hidden; } +.resource-search-product .resource-select-wrapper .bootstrap-select .dropdown-toggle .filter-option .filter-option-inner-inner { color:#414141; } +.resource-search-grade-level .resource-select-wrapper .bootstrap-select .dropdown-menu, +.resource-search-product .resource-select-wrapper .bootstrap-select .dropdown-menu { + width: 100%; + padding-bottom: 0; +} +.resource-search-grade-level .resource-select-wrapper .bootstrap-select .dropdown-menu.inner, +.resource-search-product .resource-select-wrapper .bootstrap-select .dropdown-menu.inner { + position:relative; + float: none; + border: 0; + padding: 0; + margin: 0; + border-radius: 0; + -webkit-box-shadow: none; + box-shadow: none; +} +.resource-search-grade-level .resource-select-wrapper .bootstrap-select .dropdown-menu li, +.resource-search-product .resource-select-wrapper .bootstrap-select .dropdown-menu li { position:relative; } +.resource-search-filters .resource-search-button-wrapper { + flex-basis: 11%; + max-width: 11%; + text-align: right; + padding-right: 0; +} +.resource-search-button { + display: inline-block; + width: auto; + height: 100%; + border: 1px solid #cdcdcd; + border-radius: 6px; + padding: 0 15px; + cursor: pointer; +} +.resource-search-grade-level .resource-select-wrapper .bootstrap-select .dropdown-menu li a, +.resource-search-product .resource-select-wrapper .bootstrap-select .dropdown-menu li a { + color: #212529; + padding-left: 15px; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} +.resource-search-grade-level .resource-select-wrapper .bootstrap-select.show-tick .dropdown-menu .selected span.check-mark, +.resource-search-product .resource-select-wrapper .bootstrap-select.show-tick .dropdown-menu .selected span.check-mark { + position: absolute; + display: inline-block; + right: 15px; + top: 5px; +} +.resource-search-grade-level .resource-select-wrapper .bootstrap-select.show-tick .dropdown-menu .selected .bs-ok-default:after, +.resource-search-product .resource-select-wrapper .bootstrap-select.show-tick .dropdown-menu .selected .bs-ok-default:after, +.resource-search-grade-level .resource-select-wrapper .bootstrap-select.show-tick .dropdown-menu .selected .glyphicon-ok:after, +.resource-search-product .resource-select-wrapper .bootstrap-select.show-tick .dropdown-menu .selected .glyphicon-ok:after { + content: ''; + display: block; + width: 0.5em; + height: 1em; + border-style: solid; + border-width: 0 0.26em 0.26em 0; + -webkit-transform: rotate(45deg); + -ms-transform: rotate(45deg); + -o-transform: rotate(45deg); + transform: rotate(45deg); +} +.resource-search-product .nalrc-select-wrapper .bootstrap-select .dropdown-menu li a.dropdown-item span.text { padding-right:5px; } +.post-type-archive-resource .oer-cntnr { overflow:unset; } +.oer_blgpst { + padding: 25px 0; + max-width: 97%; + margin: auto; + border-bottom: 1px solid #d1d1d1; +} +.oer_blgpst .oer-feature-image img { + width: 100%; + height: auto; + border: 1px solid #cdcdcd; + border-radius: 5px; +} +.oer_blgpst .oer-feature-image { width: 16.67% !important; padding-left: 0; } +.oer_blgpst .rght-sd-cntnr-blg { width: 100%; padding-right: 0; } +.oer_blgpst .rght-sd-cntnr-blg h4, .oer_blgpst .rght-sd-cntnr-blg h3 { + margin-top: 0 !important; + margin-bottom: 5px; + font-size: 18px !important; + font-weight: bold; + line-height: 20px; +} +.resource-search-filters .action-btns { + position: absolute; + top: 10px; + right: 5px; +} +.resource-search-filters .action-btns a { + padding: 10px; + border-radius: 3px; +} \ No newline at end of file diff --git a/includes/categories-importer.php b/includes/categories-importer.php index 80bc0e1d..a31f5368 100644 --- a/includes/categories-importer.php +++ b/includes/categories-importer.php @@ -1,11 +1,13 @@ - +
- +
" target="_blank"> diff --git a/includes/init.php b/includes/init.php index e939c02f..70849be8 100644 --- a/includes/init.php +++ b/includes/init.php @@ -152,6 +152,16 @@ function oer_frontside_scripts() wp_enqueue_script('front-scripts', OER_URL.'js/front_scripts.js'); wp_enqueue_style( "resource-category-styles", OER_URL . "css/resource-category-style.css" ); + + if (is_post_type_archive('resource')){ + wp_enqueue_script("bootstrap-select",OER_URL."js/bootstrap-select.min.js"); + if (isset($_GET['action']) && $_GET['action']=='print'){ + wp_enqueue_style( + "resource-print", + OER_URL."css/resource-print.css" + ); + } + } } //Add style block @@ -171,9 +181,12 @@ function oer_add_style_block(){ //register custom post add_action( 'init' , 'oer_postcreation' ); function oer_postcreation(){ - global $_use_gutenberg; + global $_use_gutenberg, $_resources_path; + + $resources_slug = ($_resources_path?$_resources_path:"resources"); + $labels = array( - 'name' => __( 'Resource', OER_SLUG ), + 'name' => __( 'Resources', OER_SLUG ), 'singular_name' => __( 'Resource', OER_SLUG ), 'add_new' => __( 'Add Resource', OER_SLUG ), 'add_new_item' => __( 'Add Resource', OER_SLUG ), @@ -199,7 +212,8 @@ function oer_postcreation(){ 'menu_icon' => 'dashicons-welcome-learn-more', 'supports' => array( 'title', 'editor', 'thumbnail', 'revisions', ), 'taxonomies' => array('post_tag'), - 'has_archive' => true, + 'rewrite' => array( 'slug' => 'resource' ), + 'has_archive' => $resources_slug, 'register_meta_box_cb' => 'oer_resources_custom_metaboxes' ); @@ -207,10 +221,11 @@ function oer_postcreation(){ $args['show_in_rest'] = true; register_post_type( 'resource', $args); + flush_rewrite_rules(); } function oer_resources_custom_metaboxes(){ - add_meta_box('oer_metaboxid',__('Open Resource Meta Fields',OER_SLUG),'oermeta_callback','resource','advanced'); + add_meta_box('oer_metaboxid',__('Open Resource Meta Fields',OER_SLUG),'oermeta_callback','resource','normal','high'); } //metafield callback @@ -224,15 +239,19 @@ function oermeta_callback() add_action( 'init', 'oer_create_resource_taxonomies', 0 ); function oer_create_resource_taxonomies() { global $_use_gutenberg; + $singular = "Subject Area"; + $plural = "Subject Areas"; + $grade_singular = "Grade Level"; + $grade_plural = "Grade Levels"; $arr_tax = array( - array("slug"=>"resource-subject-area","singular_name"=>"Subject Area", "plural_name"=>"Subject Areas"), - array("slug"=>"resource-grade-level","singular_name"=>"Grade Level", "plural_name"=>"Grade Levels") + array("slug"=>"resource-subject-area","singular_name"=>$singular, "plural_name"=>$plural), + array("slug"=>"resource-grade-level","singular_name"=>$grade_singular, "plural_name"=>$grade_plural) ); foreach($arr_tax as $tax){ $labels = array( - 'name' => esc_html__( $tax['singular_name'],OER_SLUG ), + 'name' => esc_html__( $tax['plural_name'],OER_SLUG ), 'singular_name' => esc_html_x( $tax['singular_name'], 'taxonomy singular name', OER_SLUG ), 'search_items' => esc_html__( "Search ".$tax['plural_name'],OER_SLUG ), 'all_items' => esc_html__( 'All '.$tax['plural_name'], OER_SLUG ), @@ -290,16 +309,17 @@ function oer_sort_grade_level_terms( $args, $taxonomies ) add_action( 'resource-subject-area_add_form_fields', 'oer_add_upload_image_fields', 10 ); function oer_add_upload_image_fields($taxonomy) { global $feature_groups; + $label = "Subject Area"; ?>
- +
- + @@ -312,12 +332,12 @@ function oer_add_upload_image_fields($taxonomy) { **/ add_action( 'resource-subject-area_edit_form_fields', 'oer_edit_upload_image_fields', 10, 2 ); function oer_edit_upload_image_fields( $term, $taxonomy ) { - + $label = "Subject Area"; $mainIcon = get_term_meta( $term->term_id, 'mainIcon', true ); ?> - +
@@ -328,7 +348,7 @@ function oer_edit_upload_image_fields( $term, $taxonomy ) { $hoverIcon = get_term_meta( $term->term_id, 'hoverIcon', true ); ?> - +
@@ -507,6 +527,14 @@ function oer_save_customfields() } update_post_meta( $post->ID , 'oer_isbasedonurl' , $oer_isbasedonurl); } + + // Save Resource Notice + if(isset($_POST['oer_resource_notice'])) + { + // Sanitize wp_editor content + $oer_resource_notice = sanitize_post_field('post_content', $_POST['oer_resource_notice'], $post->ID, 'db'); + update_post_meta( $post->ID , 'oer_resource_notice' , $oer_resource_notice); + } if(isset($_POST['oer_standard_alignment'])) { @@ -956,4 +984,4 @@ function oer_reinitialize_tinymce_on_firefox(){ +?> \ No newline at end of file diff --git a/includes/oer-functions.php b/includes/oer-functions.php index 2b6ec187..969af1e4 100644 --- a/includes/oer-functions.php +++ b/includes/oer-functions.php @@ -1211,7 +1211,11 @@ function oer_importResources($default=false) { else { // Categories are not found then assign as keyword - $oer_kywrd .= ",".$oer_categories [$i]; + //$oer_kywrd .= ",".$oer_categories [$i]; + + // add the term if category does not exist + $cat = wp_insert_term($oer_categories[$i], 'resource-subject-area'); + $category_id[$i] = $cat['term_id']; } } } @@ -1268,12 +1272,11 @@ function oer_importResources($default=false) { update_post_meta( $post_id , 'oer_highlight' , $oer_highlight); } - if(!empty($oer_grade)) - { + if(!empty($oer_grade)){ $oer_grades = ""; $oer_grade = trim($oer_grade, '"'); - if(strpos($oer_grade , "-")) - { + + if(strpos($oer_grade , "-")){ $oer_grade = explode("-",$oer_grade); if(is_array($oer_grade)) { @@ -1286,12 +1289,34 @@ function oer_importResources($default=false) { $oer_grades .= $j.","; } } - } - else - { + } else { $oer_grades = $oer_grade; } + update_post_meta( $post_id , 'oer_grade' , $oer_grades); + + if (!is_array($oer_grades)){ + $oer_grades = explode(",",$oer_grades); + $grade_ids = array(); + for($i = 0; $i <= sizeof($oer_grades); $i++) + { + if(!empty($oer_grades[$i])) + { + $cat = get_term_by( 'name', trim($oer_grades[$i]), 'resource-grade-level' ); + if($cat) + { + $grade_ids[$i] = $cat->term_id; + } + else + { + // Categories are not found then assign as keyword + $oer_kywrd .= ",".$oer_grades [$i]; + } + } + } + } + + $grades = wp_set_object_terms( $post_id, $grade_ids, 'resource-grade-level', true ); } if(!empty($oer_datecreated) && !($oer_datecreated=="")) @@ -3305,6 +3330,9 @@ function oer_get_meta_label($key){ case "oer_related_resource": $label = __("Related Resources", OER_SLUG); break; + case "oer_resource_notice": + $label = __("Resource Notice", OER_SLUG); + break; } return $label; } @@ -3588,7 +3616,7 @@ function oer_get_related_resource_content($content, $limit) { $content = preg_replace('/[.+]/','', $content); //$content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); - if(strlen(trim($content,'')) > '') $content .= ' ...'; + if(strlen(trim($content,'')) > '') $content .= ' ...'; return strip_tags($content); } } @@ -3969,4 +3997,41 @@ function oer_allowed_html() { return $allowedposttags; } +/** Get Date Created Year **/ +function oer_get_created_year(){ + $years = array(); + $args = array( + 'numberposts' => -1, + 'post_type' => 'resource', + 'post_status' => 'publish' + ); + $resources = get_posts($args); + foreach($resources as $resource){ + $dateCreated = get_post_meta($resource->ID,'oer_datecreated')[0]; + if ($dateCreated){ + $time = strtotime($dateCreated); + $year = date('Y', $time); + $years[] = $year; + } + } + $years = array_unique($years); + rsort($years); + return $years; +} + +/** Get limited excerpt **/ +function oer_get_limited_excerpt($content, $limit){ + + $excerpt = $content; + $excerpt = preg_replace(" (\[.*?\])",'',$excerpt); + $excerpt = strip_shortcodes($excerpt); + $excerpt = strip_tags($excerpt); + $excerpt = substr($excerpt, 0, $limit); + if (strlen($content)> $limit){ + $excerpt = substr($excerpt, 0, strripos($excerpt, " ")); + $excerpt = trim(preg_replace( '/\s+/', ' ', $excerpt)); + $excerpt .= '...'; + } + return $excerpt; +} ?> \ No newline at end of file diff --git a/includes/resource_metafields.php b/includes/resource_metafields.php index 1b7e30c9..43a844c4 100644 --- a/includes/resource_metafields.php +++ b/includes/resource_metafields.php @@ -1,9 +1,8 @@
- -
- ID, 'oer_lrtype', true)); ?> + ID, 'oer_lrtype', true); ?>
@@ -431,7 +369,7 @@ function chck_val($atr , $oer_grade)
- + +
+ -
+ +
+
+
+
+
+ +
+
diff --git a/js/back_scripts.js b/js/back_scripts.js index ea3ca227..697b60e6 100644 --- a/js/back_scripts.js +++ b/js/back_scripts.js @@ -1,6 +1,7 @@ const __oer = wp.i18n.__; var formfield, invoker; +var frm_error; jQuery(document).ready(function(e) { jQuery( ".oer_datepicker" ).datepicker( { dateFormat: 'MM d, yy' } ); jQuery( ".oer_datepicker" ).datepicker( "option", "showAnim", "slideDown" ); @@ -168,6 +169,28 @@ jQuery(document).ready(function(e) { var loader = jQuery('.loader'); jQuery('#wpcontent').append(loader); } + + /** Validate Resource URL **/ + var frm = jQuery('.oer_settings_form'); + if (frm.length){ + jQuery(document).on('submit','.oer_settings_form', function(e){ + var path = jQuery(this).find('#oer_configurable_resource_path').val(); + var pathRegEx = /^[^\/](?:.*[^\/])?$/; + var validPath = pathRegEx.test(path); + if (validPath) { + window.frm_error = false; + jQuery(this).find('.form-inline-error').remove(); + } else { + e.preventDefault(); + if (jQuery(this).find('.form-inline-error').length) + jQuery(this).find('.form-inline-error').remove(); + jQuery(this).find('#oer_configurable_resource_path').after('Invalid path! Please enter a valid path.'); + jQuery(this).find('#oer_configurable_resource_path').focus(); + window.frm_error = true; + return false; + } + }); + } }); jQuery(document).ajaxComplete(function(event, xhr, settings) { @@ -360,9 +383,11 @@ function get_standardlist(ref) //Process Initial Setup function processInitialSettings(form) { setTimeout(function() { - var Top = document.documentElement.scrollTop || document.body.scrollTop; - jQuery('.loader .loader-img').css({'padding-top':Top + 'px'}); - jQuery('.loader').show(); + if (!window.frm_error){ + var Top = document.documentElement.scrollTop || document.body.scrollTop; + jQuery('.loader .loader-img').css({'padding-top':Top + 'px'}); + jQuery('.loader').show(); + } } ,1000); return true; } diff --git a/js/bootstrap-select.js b/js/bootstrap-select.js new file mode 100644 index 00000000..58be5a2c --- /dev/null +++ b/js/bootstrap-select.js @@ -0,0 +1,3250 @@ +/*! + * Bootstrap-select v1.13.18 (https://developer.snapappointments.com/bootstrap-select) + * + * Copyright 2012-2020 SnapAppointments, LLC + * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) + */ + +(function (root, factory) { + if (root === undefined && window !== undefined) root = window; + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module unless amdModuleId is set + define(["jquery"], function (a0) { + return (factory(a0)); + }); + } else if (typeof module === 'object' && module.exports) { + // Node. Does not work with strict CommonJS, but + // only CommonJS-like environments that support module.exports, + // like Node. + module.exports = factory(require("jquery")); + } else { + factory(root["jQuery"]); + } +}(this, function (jQuery) { + +(function ($) { + 'use strict'; + + var DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn']; + + var uriAttrs = [ + 'background', + 'cite', + 'href', + 'itemtype', + 'longdesc', + 'poster', + 'src', + 'xlink:href' + ]; + + var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i; + + var DefaultWhitelist = { + // Global attributes allowed on any supplied element below. + '*': ['class', 'dir', 'id', 'lang', 'role', 'tabindex', 'style', ARIA_ATTRIBUTE_PATTERN], + a: ['target', 'href', 'title', 'rel'], + area: [], + b: [], + br: [], + col: [], + code: [], + div: [], + em: [], + hr: [], + h1: [], + h2: [], + h3: [], + h4: [], + h5: [], + h6: [], + i: [], + img: ['src', 'alt', 'title', 'width', 'height'], + li: [], + ol: [], + p: [], + pre: [], + s: [], + small: [], + span: [], + sub: [], + sup: [], + strong: [], + u: [], + ul: [] + } + + /** + * A pattern that recognizes a commonly useful subset of URLs that are safe. + * + * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts + */ + var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi; + + /** + * A pattern that matches safe data URLs. Only matches image, video and audio types. + * + * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts + */ + var DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i; + + function allowedAttribute (attr, allowedAttributeList) { + var attrName = attr.nodeName.toLowerCase() + + if ($.inArray(attrName, allowedAttributeList) !== -1) { + if ($.inArray(attrName, uriAttrs) !== -1) { + return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN)) + } + + return true + } + + var regExp = $(allowedAttributeList).filter(function (index, value) { + return value instanceof RegExp + }) + + // Check if a regular expression validates the attribute. + for (var i = 0, l = regExp.length; i < l; i++) { + if (attrName.match(regExp[i])) { + return true + } + } + + return false + } + + function sanitizeHtml (unsafeElements, whiteList, sanitizeFn) { + if (sanitizeFn && typeof sanitizeFn === 'function') { + return sanitizeFn(unsafeElements); + } + + var whitelistKeys = Object.keys(whiteList); + + for (var i = 0, len = unsafeElements.length; i < len; i++) { + var elements = unsafeElements[i].querySelectorAll('*'); + + for (var j = 0, len2 = elements.length; j < len2; j++) { + var el = elements[j]; + var elName = el.nodeName.toLowerCase(); + + if (whitelistKeys.indexOf(elName) === -1) { + el.parentNode.removeChild(el); + + continue; + } + + var attributeList = [].slice.call(el.attributes); + var whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || []); + + for (var k = 0, len3 = attributeList.length; k < len3; k++) { + var attr = attributeList[k]; + + if (!allowedAttribute(attr, whitelistedAttributes)) { + el.removeAttribute(attr.nodeName); + } + } + } + } + } + + // Polyfill for browsers with no classList support + // Remove in v2 + if (!('classList' in document.createElement('_'))) { + (function (view) { + if (!('Element' in view)) return; + + var classListProp = 'classList', + protoProp = 'prototype', + elemCtrProto = view.Element[protoProp], + objCtr = Object, + classListGetter = function () { + var $elem = $(this); + + return { + add: function (classes) { + classes = Array.prototype.slice.call(arguments).join(' '); + return $elem.addClass(classes); + }, + remove: function (classes) { + classes = Array.prototype.slice.call(arguments).join(' '); + return $elem.removeClass(classes); + }, + toggle: function (classes, force) { + return $elem.toggleClass(classes, force); + }, + contains: function (classes) { + return $elem.hasClass(classes); + } + } + }; + + if (objCtr.defineProperty) { + var classListPropDesc = { + get: classListGetter, + enumerable: true, + configurable: true + }; + try { + objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); + } catch (ex) { // IE 8 doesn't support enumerable:true + // adding undefined to fight this issue https://github.com/eligrey/classList.js/issues/36 + // modernie IE8-MSW7 machine has IE8 8.0.6001.18702 and is affected + if (ex.number === undefined || ex.number === -0x7FF5EC54) { + classListPropDesc.enumerable = false; + objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); + } + } + } else if (objCtr[protoProp].__defineGetter__) { + elemCtrProto.__defineGetter__(classListProp, classListGetter); + } + }(window)); + } + + var testElement = document.createElement('_'); + + testElement.classList.add('c1', 'c2'); + + if (!testElement.classList.contains('c2')) { + var _add = DOMTokenList.prototype.add, + _remove = DOMTokenList.prototype.remove; + + DOMTokenList.prototype.add = function () { + Array.prototype.forEach.call(arguments, _add.bind(this)); + } + + DOMTokenList.prototype.remove = function () { + Array.prototype.forEach.call(arguments, _remove.bind(this)); + } + } + + testElement.classList.toggle('c3', false); + + // Polyfill for IE 10 and Firefox <24, where classList.toggle does not + // support the second argument. + if (testElement.classList.contains('c3')) { + var _toggle = DOMTokenList.prototype.toggle; + + DOMTokenList.prototype.toggle = function (token, force) { + if (1 in arguments && !this.contains(token) === !force) { + return force; + } else { + return _toggle.call(this, token); + } + }; + } + + testElement = null; + + // shallow array comparison + function isEqual (array1, array2) { + return array1.length === array2.length && array1.every(function (element, index) { + return element === array2[index]; + }); + }; + + // + if (!String.prototype.startsWith) { + (function () { + 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` + var defineProperty = (function () { + // IE 8 only supports `Object.defineProperty` on DOM elements + try { + var object = {}; + var $defineProperty = Object.defineProperty; + var result = $defineProperty(object, object, object) && $defineProperty; + } catch (error) { + } + return result; + }()); + var toString = {}.toString; + var startsWith = function (search) { + if (this == null) { + throw new TypeError(); + } + var string = String(this); + if (search && toString.call(search) == '[object RegExp]') { + throw new TypeError(); + } + var stringLength = string.length; + var searchString = String(search); + var searchLength = searchString.length; + var position = arguments.length > 1 ? arguments[1] : undefined; + // `ToInteger` + var pos = position ? Number(position) : 0; + if (pos != pos) { // better `isNaN` + pos = 0; + } + var start = Math.min(Math.max(pos, 0), stringLength); + // Avoid the `indexOf` call if no match is possible + if (searchLength + start > stringLength) { + return false; + } + var index = -1; + while (++index < searchLength) { + if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) { + return false; + } + } + return true; + }; + if (defineProperty) { + defineProperty(String.prototype, 'startsWith', { + 'value': startsWith, + 'configurable': true, + 'writable': true + }); + } else { + String.prototype.startsWith = startsWith; + } + }()); + } + + if (!Object.keys) { + Object.keys = function ( + o, // object + k, // key + r // result array + ) { + // initialize object and result + r = []; + // iterate over object keys + for (k in o) { + // fill result array with non-prototypical keys + r.hasOwnProperty.call(o, k) && r.push(k); + } + // return result + return r; + }; + } + + if (HTMLSelectElement && !HTMLSelectElement.prototype.hasOwnProperty('selectedOptions')) { + Object.defineProperty(HTMLSelectElement.prototype, 'selectedOptions', { + get: function () { + return this.querySelectorAll(':checked'); + } + }); + } + + function getSelectedOptions (select, ignoreDisabled) { + var selectedOptions = select.selectedOptions, + options = [], + opt; + + if (ignoreDisabled) { + for (var i = 0, len = selectedOptions.length; i < len; i++) { + opt = selectedOptions[i]; + + if (!(opt.disabled || opt.parentNode.tagName === 'OPTGROUP' && opt.parentNode.disabled)) { + options.push(opt); + } + } + + return options; + } + + return selectedOptions; + } + + // much faster than $.val() + function getSelectValues (select, selectedOptions) { + var value = [], + options = selectedOptions || select.selectedOptions, + opt; + + for (var i = 0, len = options.length; i < len; i++) { + opt = options[i]; + + if (!(opt.disabled || opt.parentNode.tagName === 'OPTGROUP' && opt.parentNode.disabled)) { + value.push(opt.value); + } + } + + if (!select.multiple) { + return !value.length ? null : value[0]; + } + + return value; + } + + // set data-selected on select element if the value has been programmatically selected + // prior to initialization of bootstrap-select + // * consider removing or replacing an alternative method * + var valHooks = { + useDefault: false, + _set: $.valHooks.select.set + }; + + $.valHooks.select.set = function (elem, value) { + if (value && !valHooks.useDefault) $(elem).data('selected', true); + + return valHooks._set.apply(this, arguments); + }; + + var changedArguments = null; + + var EventIsSupported = (function () { + try { + new Event('change'); + return true; + } catch (e) { + return false; + } + })(); + + $.fn.triggerNative = function (eventName) { + var el = this[0], + event; + + if (el.dispatchEvent) { // for modern browsers & IE9+ + if (EventIsSupported) { + // For modern browsers + event = new Event(eventName, { + bubbles: true + }); + } else { + // For IE since it doesn't support Event constructor + event = document.createEvent('Event'); + event.initEvent(eventName, true, false); + } + + el.dispatchEvent(event); + } else if (el.fireEvent) { // for IE8 + event = document.createEventObject(); + event.eventType = eventName; + el.fireEvent('on' + eventName, event); + } else { + // fall back to jQuery.trigger + this.trigger(eventName); + } + }; + // + + function stringSearch (li, searchString, method, normalize) { + var stringTypes = [ + 'display', + 'subtext', + 'tokens' + ], + searchSuccess = false; + + for (var i = 0; i < stringTypes.length; i++) { + var stringType = stringTypes[i], + string = li[stringType]; + + if (string) { + string = string.toString(); + + // Strip HTML tags. This isn't perfect, but it's much faster than any other method + if (stringType === 'display') { + string = string.replace(/<[^>]+>/g, ''); + } + + if (normalize) string = normalizeToBase(string); + string = string.toUpperCase(); + + if (method === 'contains') { + searchSuccess = string.indexOf(searchString) >= 0; + } else { + searchSuccess = string.startsWith(searchString); + } + + if (searchSuccess) break; + } + } + + return searchSuccess; + } + + function toInteger (value) { + return parseInt(value, 10) || 0; + } + + // Borrowed from Lodash (_.deburr) + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to compose unicode character classes. */ + var rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboMarksExtendedRange = '\\u1ab0-\\u1aff', + rsComboMarksSupplementRange = '\\u1dc0-\\u1dff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange + rsComboMarksExtendedRange + rsComboMarksSupplementRange; + + /** Used to compose unicode capture groups. */ + var rsCombo = '[' + rsComboRange + ']'; + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + function deburrLetter (key) { + return deburredLetters[key]; + }; + + function normalizeToBase (string) { + string = string.toString(); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + // List of HTML entities for escaping. + var escapeMap = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + + // Functions for escaping and unescaping strings to/from HTML interpolation. + var createEscaper = function (map) { + var escaper = function (match) { + return map[match]; + }; + // Regexes for identifying a key that needs to be escaped. + var source = '(?:' + Object.keys(map).join('|') + ')'; + var testRegexp = RegExp(source); + var replaceRegexp = RegExp(source, 'g'); + return function (string) { + string = string == null ? '' : '' + string; + return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; + }; + }; + + var htmlEscape = createEscaper(escapeMap); + + /** + * ------------------------------------------------------------------------ + * Constants + * ------------------------------------------------------------------------ + */ + + var keyCodeMap = { + 32: ' ', + 48: '0', + 49: '1', + 50: '2', + 51: '3', + 52: '4', + 53: '5', + 54: '6', + 55: '7', + 56: '8', + 57: '9', + 59: ';', + 65: 'A', + 66: 'B', + 67: 'C', + 68: 'D', + 69: 'E', + 70: 'F', + 71: 'G', + 72: 'H', + 73: 'I', + 74: 'J', + 75: 'K', + 76: 'L', + 77: 'M', + 78: 'N', + 79: 'O', + 80: 'P', + 81: 'Q', + 82: 'R', + 83: 'S', + 84: 'T', + 85: 'U', + 86: 'V', + 87: 'W', + 88: 'X', + 89: 'Y', + 90: 'Z', + 96: '0', + 97: '1', + 98: '2', + 99: '3', + 100: '4', + 101: '5', + 102: '6', + 103: '7', + 104: '8', + 105: '9' + }; + + var keyCodes = { + ESCAPE: 27, // KeyboardEvent.which value for Escape (Esc) key + ENTER: 13, // KeyboardEvent.which value for Enter key + SPACE: 32, // KeyboardEvent.which value for space key + TAB: 9, // KeyboardEvent.which value for tab key + ARROW_UP: 38, // KeyboardEvent.which value for up arrow key + ARROW_DOWN: 40 // KeyboardEvent.which value for down arrow key + } + + var version = { + success: false, + major: '3' + }; + + try { + version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.'); + version.major = version.full[0]; + version.success = true; + } catch (err) { + // do nothing + } + + var selectId = 0; + + var EVENT_KEY = '.bs.select'; + + var classNames = { + DISABLED: 'disabled', + DIVIDER: 'divider', + SHOW: 'open', + DROPUP: 'dropup', + MENU: 'dropdown-menu', + MENURIGHT: 'dropdown-menu-right', + MENULEFT: 'dropdown-menu-left', + // to-do: replace with more advanced template/customization options + BUTTONCLASS: 'btn-default', + POPOVERHEADER: 'popover-title', + ICONBASE: 'glyphicon', + TICKICON: 'glyphicon-ok' + } + + var Selector = { + MENU: '.' + classNames.MENU + } + + var elementTemplates = { + div: document.createElement('div'), + span: document.createElement('span'), + i: document.createElement('i'), + subtext: document.createElement('small'), + a: document.createElement('a'), + li: document.createElement('li'), + whitespace: document.createTextNode('\u00A0'), + fragment: document.createDocumentFragment() + } + + elementTemplates.noResults = elementTemplates.li.cloneNode(false); + elementTemplates.noResults.className = 'no-results'; + + elementTemplates.a.setAttribute('role', 'option'); + elementTemplates.a.className = 'dropdown-item'; + + elementTemplates.subtext.className = 'text-muted'; + + elementTemplates.text = elementTemplates.span.cloneNode(false); + elementTemplates.text.className = 'text'; + + elementTemplates.checkMark = elementTemplates.span.cloneNode(false); + + var REGEXP_ARROW = new RegExp(keyCodes.ARROW_UP + '|' + keyCodes.ARROW_DOWN); + var REGEXP_TAB_OR_ESCAPE = new RegExp('^' + keyCodes.TAB + '$|' + keyCodes.ESCAPE); + + var generateOption = { + li: function (content, classes, optgroup) { + var li = elementTemplates.li.cloneNode(false); + + if (content) { + if (content.nodeType === 1 || content.nodeType === 11) { + li.appendChild(content); + } else { + li.innerHTML = content; + } + } + + if (typeof classes !== 'undefined' && classes !== '') li.className = classes; + if (typeof optgroup !== 'undefined' && optgroup !== null) li.classList.add('optgroup-' + optgroup); + + return li; + }, + + a: function (text, classes, inline) { + var a = elementTemplates.a.cloneNode(true); + + if (text) { + if (text.nodeType === 11) { + a.appendChild(text); + } else { + a.insertAdjacentHTML('beforeend', text); + } + } + + if (typeof classes !== 'undefined' && classes !== '') a.classList.add.apply(a.classList, classes.split(/\s+/)); + if (inline) a.setAttribute('style', inline); + + return a; + }, + + text: function (options, useFragment) { + var textElement = elementTemplates.text.cloneNode(false), + subtextElement, + iconElement; + + if (options.content) { + textElement.innerHTML = options.content; + } else { + textElement.textContent = options.text; + + if (options.icon) { + var whitespace = elementTemplates.whitespace.cloneNode(false); + + // need to use for icons in the button to prevent a breaking change + // note: switch to span in next major release + iconElement = (useFragment === true ? elementTemplates.i : elementTemplates.span).cloneNode(false); + iconElement.className = this.options.iconBase + ' ' + options.icon; + + elementTemplates.fragment.appendChild(iconElement); + elementTemplates.fragment.appendChild(whitespace); + } + + if (options.subtext) { + subtextElement = elementTemplates.subtext.cloneNode(false); + subtextElement.textContent = options.subtext; + textElement.appendChild(subtextElement); + } + } + + if (useFragment === true) { + while (textElement.childNodes.length > 0) { + elementTemplates.fragment.appendChild(textElement.childNodes[0]); + } + } else { + elementTemplates.fragment.appendChild(textElement); + } + + return elementTemplates.fragment; + }, + + label: function (options) { + var textElement = elementTemplates.text.cloneNode(false), + subtextElement, + iconElement; + + textElement.innerHTML = options.display; + + if (options.icon) { + var whitespace = elementTemplates.whitespace.cloneNode(false); + + iconElement = elementTemplates.span.cloneNode(false); + iconElement.className = this.options.iconBase + ' ' + options.icon; + + elementTemplates.fragment.appendChild(iconElement); + elementTemplates.fragment.appendChild(whitespace); + } + + if (options.subtext) { + subtextElement = elementTemplates.subtext.cloneNode(false); + subtextElement.textContent = options.subtext; + textElement.appendChild(subtextElement); + } + + elementTemplates.fragment.appendChild(textElement); + + return elementTemplates.fragment; + } + } + + function showNoResults (searchMatch, searchValue) { + if (!searchMatch.length) { + elementTemplates.noResults.innerHTML = this.options.noneResultsText.replace('{0}', '"' + htmlEscape(searchValue) + '"'); + this.$menuInner[0].firstChild.appendChild(elementTemplates.noResults); + } + } + + var Selectpicker = function (element, options) { + var that = this; + + // bootstrap-select has been initialized - revert valHooks.select.set back to its original function + if (!valHooks.useDefault) { + $.valHooks.select.set = valHooks._set; + valHooks.useDefault = true; + } + + this.$element = $(element); + this.$newElement = null; + this.$button = null; + this.$menu = null; + this.options = options; + this.selectpicker = { + main: {}, + search: {}, + current: {}, // current changes if a search is in progress + view: {}, + isSearching: false, + keydown: { + keyHistory: '', + resetKeyHistory: { + start: function () { + return setTimeout(function () { + that.selectpicker.keydown.keyHistory = ''; + }, 800); + } + } + } + }; + + this.sizeInfo = {}; + + // If we have no title yet, try to pull it from the html title attribute (jQuery doesnt' pick it up as it's not a + // data-attribute) + if (this.options.title === null) { + this.options.title = this.$element.attr('title'); + } + + // Format window padding + var winPad = this.options.windowPadding; + if (typeof winPad === 'number') { + this.options.windowPadding = [winPad, winPad, winPad, winPad]; + } + + // Expose public methods + this.val = Selectpicker.prototype.val; + this.render = Selectpicker.prototype.render; + this.refresh = Selectpicker.prototype.refresh; + this.setStyle = Selectpicker.prototype.setStyle; + this.selectAll = Selectpicker.prototype.selectAll; + this.deselectAll = Selectpicker.prototype.deselectAll; + this.destroy = Selectpicker.prototype.destroy; + this.remove = Selectpicker.prototype.remove; + this.show = Selectpicker.prototype.show; + this.hide = Selectpicker.prototype.hide; + + this.init(); + }; + + Selectpicker.VERSION = '1.13.18'; + + // part of this is duplicated in i18n/defaults-en_US.js. Make sure to update both. + Selectpicker.DEFAULTS = { + noneSelectedText: 'Nothing selected', + noneResultsText: 'No results matched {0}', + countSelectedText: function (numSelected, numTotal) { + return (numSelected == 1) ? '{0} item selected' : '{0} items selected'; + }, + maxOptionsText: function (numAll, numGroup) { + return [ + (numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)', + (numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)' + ]; + }, + selectAllText: 'Select All', + deselectAllText: 'Deselect All', + doneButton: false, + doneButtonText: 'Close', + multipleSeparator: ', ', + styleBase: 'btn', + style: classNames.BUTTONCLASS, + size: 'auto', + title: null, + selectedTextFormat: 'values', + width: false, + container: false, + hideDisabled: false, + showSubtext: false, + showIcon: true, + showContent: true, + dropupAuto: true, + header: false, + liveSearch: false, + liveSearchPlaceholder: null, + liveSearchNormalize: false, + liveSearchStyle: 'contains', + actionsBox: false, + iconBase: classNames.ICONBASE, + tickIcon: classNames.TICKICON, + showTick: false, + template: { + caret: '' + }, + maxOptions: false, + mobile: false, + selectOnTab: false, + dropdownAlignRight: false, + windowPadding: 0, + virtualScroll: 600, + display: false, + sanitize: true, + sanitizeFn: null, + whiteList: DefaultWhitelist + }; + + Selectpicker.prototype = { + + constructor: Selectpicker, + + init: function () { + var that = this, + id = this.$element.attr('id'), + element = this.$element[0], + form = element.form; + + selectId++; + this.selectId = 'bs-select-' + selectId; + + element.classList.add('bs-select-hidden'); + + this.multiple = this.$element.prop('multiple'); + this.autofocus = this.$element.prop('autofocus'); + + if (element.classList.contains('show-tick')) { + this.options.showTick = true; + } + + this.$newElement = this.createDropdown(); + this.buildData(); + this.$element + .after(this.$newElement) + .prependTo(this.$newElement); + + // ensure select is associated with form element if it got unlinked after moving it inside newElement + if (form && element.form === null) { + if (!form.id) form.id = 'form-' + this.selectId; + element.setAttribute('form', form.id); + } + + this.$button = this.$newElement.children('button'); + this.$menu = this.$newElement.children(Selector.MENU); + this.$menuInner = this.$menu.children('.inner'); + this.$searchbox = this.$menu.find('input'); + + element.classList.remove('bs-select-hidden'); + + if (this.options.dropdownAlignRight === true) this.$menu[0].classList.add(classNames.MENURIGHT); + + if (typeof id !== 'undefined') { + this.$button.attr('data-id', id); + } + + this.checkDisabled(); + this.clickListener(); + + if (this.options.liveSearch) { + this.liveSearchListener(); + this.focusedParent = this.$searchbox[0]; + } else { + this.focusedParent = this.$menuInner[0]; + } + + this.setStyle(); + this.render(); + this.setWidth(); + if (this.options.container) { + this.selectPosition(); + } else { + this.$element.on('hide' + EVENT_KEY, function () { + if (that.isVirtual()) { + // empty menu on close + var menuInner = that.$menuInner[0], + emptyMenu = menuInner.firstChild.cloneNode(false); + + // replace the existing UL with an empty one - this is faster than $.empty() or innerHTML = '' + menuInner.replaceChild(emptyMenu, menuInner.firstChild); + menuInner.scrollTop = 0; + } + }); + } + this.$menu.data('this', this); + this.$newElement.data('this', this); + if (this.options.mobile) this.mobile(); + + this.$newElement.on({ + 'hide.bs.dropdown': function (e) { + that.$element.trigger('hide' + EVENT_KEY, e); + }, + 'hidden.bs.dropdown': function (e) { + that.$element.trigger('hidden' + EVENT_KEY, e); + }, + 'show.bs.dropdown': function (e) { + that.$element.trigger('show' + EVENT_KEY, e); + }, + 'shown.bs.dropdown': function (e) { + that.$element.trigger('shown' + EVENT_KEY, e); + } + }); + + if (element.hasAttribute('required')) { + this.$element.on('invalid' + EVENT_KEY, function () { + that.$button[0].classList.add('bs-invalid'); + + that.$element + .on('shown' + EVENT_KEY + '.invalid', function () { + that.$element + .val(that.$element.val()) // set the value to hide the validation message in Chrome when menu is opened + .off('shown' + EVENT_KEY + '.invalid'); + }) + .on('rendered' + EVENT_KEY, function () { + // if select is no longer invalid, remove the bs-invalid class + if (this.validity.valid) that.$button[0].classList.remove('bs-invalid'); + that.$element.off('rendered' + EVENT_KEY); + }); + + that.$button.on('blur' + EVENT_KEY, function () { + that.$element.trigger('focus').trigger('blur'); + that.$button.off('blur' + EVENT_KEY); + }); + }); + } + + setTimeout(function () { + that.buildList(); + that.$element.trigger('loaded' + EVENT_KEY); + }); + }, + + createDropdown: function () { + // Options + // If we are multiple or showTick option is set, then add the show-tick class + var showTick = (this.multiple || this.options.showTick) ? ' show-tick' : '', + multiselectable = this.multiple ? ' aria-multiselectable="true"' : '', + inputGroup = '', + autofocus = this.autofocus ? ' autofocus' : ''; + + if (version.major < 4 && this.$element.parent().hasClass('input-group')) { + inputGroup = ' input-group-btn'; + } + + // Elements + var drop, + header = '', + searchbox = '', + actionsbox = '', + donebutton = ''; + + if (this.options.header) { + header = + '
' + + '' + + this.options.header + + '
'; + } + + if (this.options.liveSearch) { + searchbox = + ''; + } + + if (this.multiple && this.options.actionsBox) { + actionsbox = + '
' + + '
' + + '' + + '' + + '
' + + '
'; + } + + if (this.multiple && this.options.doneButton) { + donebutton = + '
' + + '
' + + '' + + '
' + + '
'; + } + + drop = + ''; + + return $(drop); + }, + + setPositionData: function () { + this.selectpicker.view.canHighlight = []; + this.selectpicker.view.size = 0; + this.selectpicker.view.firstHighlightIndex = false; + + for (var i = 0; i < this.selectpicker.current.data.length; i++) { + var li = this.selectpicker.current.data[i], + canHighlight = true; + + if (li.type === 'divider') { + canHighlight = false; + li.height = this.sizeInfo.dividerHeight; + } else if (li.type === 'optgroup-label') { + canHighlight = false; + li.height = this.sizeInfo.dropdownHeaderHeight; + } else { + li.height = this.sizeInfo.liHeight; + } + + if (li.disabled) canHighlight = false; + + this.selectpicker.view.canHighlight.push(canHighlight); + + if (canHighlight) { + this.selectpicker.view.size++; + li.posinset = this.selectpicker.view.size; + if (this.selectpicker.view.firstHighlightIndex === false) this.selectpicker.view.firstHighlightIndex = i; + } + + li.position = (i === 0 ? 0 : this.selectpicker.current.data[i - 1].position) + li.height; + } + }, + + isVirtual: function () { + return (this.options.virtualScroll !== false) && (this.selectpicker.main.elements.length >= this.options.virtualScroll) || this.options.virtualScroll === true; + }, + + createView: function (isSearching, setSize, refresh) { + var that = this, + scrollTop = 0, + active = [], + selected, + prevActive; + + this.selectpicker.isSearching = isSearching; + this.selectpicker.current = isSearching ? this.selectpicker.search : this.selectpicker.main; + + this.setPositionData(); + + if (setSize) { + if (refresh) { + scrollTop = this.$menuInner[0].scrollTop; + } else if (!that.multiple) { + var element = that.$element[0], + selectedIndex = (element.options[element.selectedIndex] || {}).liIndex; + + if (typeof selectedIndex === 'number' && that.options.size !== false) { + var selectedData = that.selectpicker.main.data[selectedIndex], + position = selectedData && selectedData.position; + + if (position) { + scrollTop = position - ((that.sizeInfo.menuInnerHeight + that.sizeInfo.liHeight) / 2); + } + } + } + } + + scroll(scrollTop, true); + + this.$menuInner.off('scroll.createView').on('scroll.createView', function (e, updateValue) { + if (!that.noScroll) scroll(this.scrollTop, updateValue); + that.noScroll = false; + }); + + function scroll (scrollTop, init) { + var size = that.selectpicker.current.elements.length, + chunks = [], + chunkSize, + chunkCount, + firstChunk, + lastChunk, + currentChunk, + prevPositions, + positionIsDifferent, + previousElements, + menuIsDifferent = true, + isVirtual = that.isVirtual(); + + that.selectpicker.view.scrollTop = scrollTop; + + chunkSize = Math.ceil(that.sizeInfo.menuInnerHeight / that.sizeInfo.liHeight * 1.5); // number of options in a chunk + chunkCount = Math.round(size / chunkSize) || 1; // number of chunks + + for (var i = 0; i < chunkCount; i++) { + var endOfChunk = (i + 1) * chunkSize; + + if (i === chunkCount - 1) { + endOfChunk = size; + } + + chunks[i] = [ + (i) * chunkSize + (!i ? 0 : 1), + endOfChunk + ]; + + if (!size) break; + + if (currentChunk === undefined && scrollTop - 1 <= that.selectpicker.current.data[endOfChunk - 1].position - that.sizeInfo.menuInnerHeight) { + currentChunk = i; + } + } + + if (currentChunk === undefined) currentChunk = 0; + + prevPositions = [that.selectpicker.view.position0, that.selectpicker.view.position1]; + + // always display previous, current, and next chunks + firstChunk = Math.max(0, currentChunk - 1); + lastChunk = Math.min(chunkCount - 1, currentChunk + 1); + + that.selectpicker.view.position0 = isVirtual === false ? 0 : (Math.max(0, chunks[firstChunk][0]) || 0); + that.selectpicker.view.position1 = isVirtual === false ? size : (Math.min(size, chunks[lastChunk][1]) || 0); + + positionIsDifferent = prevPositions[0] !== that.selectpicker.view.position0 || prevPositions[1] !== that.selectpicker.view.position1; + + if (that.activeIndex !== undefined) { + prevActive = that.selectpicker.main.elements[that.prevActiveIndex]; + active = that.selectpicker.main.elements[that.activeIndex]; + selected = that.selectpicker.main.elements[that.selectedIndex]; + + if (init) { + if (that.activeIndex !== that.selectedIndex) { + that.defocusItem(active); + } + that.activeIndex = undefined; + } + + if (that.activeIndex && that.activeIndex !== that.selectedIndex) { + that.defocusItem(selected); + } + } + + if (that.prevActiveIndex !== undefined && that.prevActiveIndex !== that.activeIndex && that.prevActiveIndex !== that.selectedIndex) { + that.defocusItem(prevActive); + } + + if (init || positionIsDifferent) { + previousElements = that.selectpicker.view.visibleElements ? that.selectpicker.view.visibleElements.slice() : []; + + if (isVirtual === false) { + that.selectpicker.view.visibleElements = that.selectpicker.current.elements; + } else { + that.selectpicker.view.visibleElements = that.selectpicker.current.elements.slice(that.selectpicker.view.position0, that.selectpicker.view.position1); + } + + that.setOptionStatus(); + + // if searching, check to make sure the list has actually been updated before updating DOM + // this prevents unnecessary repaints + if (isSearching || (isVirtual === false && init)) menuIsDifferent = !isEqual(previousElements, that.selectpicker.view.visibleElements); + + // if virtual scroll is disabled and not searching, + // menu should never need to be updated more than once + if ((init || isVirtual === true) && menuIsDifferent) { + var menuInner = that.$menuInner[0], + menuFragment = document.createDocumentFragment(), + emptyMenu = menuInner.firstChild.cloneNode(false), + marginTop, + marginBottom, + elements = that.selectpicker.view.visibleElements, + toSanitize = []; + + // replace the existing UL with an empty one - this is faster than $.empty() + menuInner.replaceChild(emptyMenu, menuInner.firstChild); + + for (var i = 0, visibleElementsLen = elements.length; i < visibleElementsLen; i++) { + var element = elements[i], + elText, + elementData; + + if (that.options.sanitize) { + elText = element.lastChild; + + if (elText) { + elementData = that.selectpicker.current.data[i + that.selectpicker.view.position0]; + + if (elementData && elementData.content && !elementData.sanitized) { + toSanitize.push(elText); + elementData.sanitized = true; + } + } + } + + menuFragment.appendChild(element); + } + + if (that.options.sanitize && toSanitize.length) { + sanitizeHtml(toSanitize, that.options.whiteList, that.options.sanitizeFn); + } + + if (isVirtual === true) { + marginTop = (that.selectpicker.view.position0 === 0 ? 0 : that.selectpicker.current.data[that.selectpicker.view.position0 - 1].position); + marginBottom = (that.selectpicker.view.position1 > size - 1 ? 0 : that.selectpicker.current.data[size - 1].position - that.selectpicker.current.data[that.selectpicker.view.position1 - 1].position); + + menuInner.firstChild.style.marginTop = marginTop + 'px'; + menuInner.firstChild.style.marginBottom = marginBottom + 'px'; + } else { + menuInner.firstChild.style.marginTop = 0; + menuInner.firstChild.style.marginBottom = 0; + } + + menuInner.firstChild.appendChild(menuFragment); + + // if an option is encountered that is wider than the current menu width, update the menu width accordingly + // switch to ResizeObserver with increased browser support + if (isVirtual === true && that.sizeInfo.hasScrollBar) { + var menuInnerInnerWidth = menuInner.firstChild.offsetWidth; + + if (init && menuInnerInnerWidth < that.sizeInfo.menuInnerInnerWidth && that.sizeInfo.totalMenuWidth > that.sizeInfo.selectWidth) { + menuInner.firstChild.style.minWidth = that.sizeInfo.menuInnerInnerWidth + 'px'; + } else if (menuInnerInnerWidth > that.sizeInfo.menuInnerInnerWidth) { + // set to 0 to get actual width of menu + that.$menu[0].style.minWidth = 0; + + var actualMenuWidth = menuInner.firstChild.offsetWidth; + + if (actualMenuWidth > that.sizeInfo.menuInnerInnerWidth) { + that.sizeInfo.menuInnerInnerWidth = actualMenuWidth; + menuInner.firstChild.style.minWidth = that.sizeInfo.menuInnerInnerWidth + 'px'; + } + + // reset to default CSS styling + that.$menu[0].style.minWidth = ''; + } + } + } + } + + that.prevActiveIndex = that.activeIndex; + + if (!that.options.liveSearch) { + that.$menuInner.trigger('focus'); + } else if (isSearching && init) { + var index = 0, + newActive; + + if (!that.selectpicker.view.canHighlight[index]) { + index = 1 + that.selectpicker.view.canHighlight.slice(1).indexOf(true); + } + + newActive = that.selectpicker.view.visibleElements[index]; + + that.defocusItem(that.selectpicker.view.currentActive); + + that.activeIndex = (that.selectpicker.current.data[index] || {}).index; + + that.focusItem(newActive); + } + } + + $(window) + .off('resize' + EVENT_KEY + '.' + this.selectId + '.createView') + .on('resize' + EVENT_KEY + '.' + this.selectId + '.createView', function () { + var isActive = that.$newElement.hasClass(classNames.SHOW); + + if (isActive) scroll(that.$menuInner[0].scrollTop); + }); + }, + + focusItem: function (li, liData, noStyle) { + if (li) { + liData = liData || this.selectpicker.main.data[this.activeIndex]; + var a = li.firstChild; + + if (a) { + a.setAttribute('aria-setsize', this.selectpicker.view.size); + a.setAttribute('aria-posinset', liData.posinset); + + if (noStyle !== true) { + this.focusedParent.setAttribute('aria-activedescendant', a.id); + li.classList.add('active'); + a.classList.add('active'); + } + } + } + }, + + defocusItem: function (li) { + if (li) { + li.classList.remove('active'); + if (li.firstChild) li.firstChild.classList.remove('active'); + } + }, + + setPlaceholder: function () { + var that = this, + updateIndex = false; + + if (this.options.title && !this.multiple) { + if (!this.selectpicker.view.titleOption) this.selectpicker.view.titleOption = document.createElement('option'); + + // this option doesn't create a new
  • element, but does add a new option at the start, + // so startIndex should increase to prevent having to check every option for the bs-title-option class + updateIndex = true; + + var element = this.$element[0], + selectTitleOption = false, + titleNotAppended = !this.selectpicker.view.titleOption.parentNode, + selectedIndex = element.selectedIndex, + selectedOption = element.options[selectedIndex], + navigation = window.performance && window.performance.getEntriesByType('navigation'), + // Safari doesn't support getEntriesByType('navigation') - fall back to performance.navigation + isNotBackForward = (navigation && navigation.length) ? navigation[0].type !== 'back_forward' : window.performance.navigation.type !== 2; + + if (titleNotAppended) { + // Use native JS to prepend option (faster) + this.selectpicker.view.titleOption.className = 'bs-title-option'; + this.selectpicker.view.titleOption.value = ''; + + // Check if selected or data-selected attribute is already set on an option. If not, select the titleOption option. + // the selected item may have been changed by user or programmatically before the bootstrap select plugin runs, + // if so, the select will have the data-selected attribute + selectTitleOption = !selectedOption || (selectedIndex === 0 && selectedOption.defaultSelected === false && this.$element.data('selected') === undefined); + } + + if (titleNotAppended || this.selectpicker.view.titleOption.index !== 0) { + element.insertBefore(this.selectpicker.view.titleOption, element.firstChild); + } + + // Set selected *after* appending to select, + // otherwise the option doesn't get selected in IE + // set using selectedIndex, as setting the selected attr to true here doesn't work in IE11 + if (selectTitleOption && isNotBackForward) { + element.selectedIndex = 0; + } else if (document.readyState !== 'complete') { + // if navigation type is back_forward, there's a chance the select will have its value set by BFCache + // wait for that value to be set, then run render again + window.addEventListener('pageshow', function () { + if (that.selectpicker.view.displayedValue !== element.value) that.render(); + }); + } + } + + return updateIndex; + }, + + buildData: function () { + var optionSelector = ':not([hidden]):not([data-hidden="true"])', + mainData = [], + optID = 0, + startIndex = this.setPlaceholder() ? 1 : 0; // append the titleOption if necessary and skip the first option in the loop + + if (this.options.hideDisabled) optionSelector += ':not(:disabled)'; + + var selectOptions = this.$element[0].querySelectorAll('select > *' + optionSelector); + + function addDivider (config) { + var previousData = mainData[mainData.length - 1]; + + // ensure optgroup doesn't create back-to-back dividers + if ( + previousData && + previousData.type === 'divider' && + (previousData.optID || config.optID) + ) { + return; + } + + config = config || {}; + config.type = 'divider'; + + mainData.push(config); + } + + function addOption (option, config) { + config = config || {}; + + config.divider = option.getAttribute('data-divider') === 'true'; + + if (config.divider) { + addDivider({ + optID: config.optID + }); + } else { + var liIndex = mainData.length, + cssText = option.style.cssText, + inlineStyle = cssText ? htmlEscape(cssText) : '', + optionClass = (option.className || '') + (config.optgroupClass || ''); + + if (config.optID) optionClass = 'opt ' + optionClass; + + config.optionClass = optionClass.trim(); + config.inlineStyle = inlineStyle; + config.text = option.textContent; + + config.content = option.getAttribute('data-content'); + config.tokens = option.getAttribute('data-tokens'); + config.subtext = option.getAttribute('data-subtext'); + config.icon = option.getAttribute('data-icon'); + + option.liIndex = liIndex; + + config.display = config.content || config.text; + config.type = 'option'; + config.index = liIndex; + config.option = option; + config.selected = !!option.selected; + config.disabled = config.disabled || !!option.disabled; + + mainData.push(config); + } + } + + function addOptgroup (index, selectOptions) { + var optgroup = selectOptions[index], + // skip placeholder option + previous = index - 1 < startIndex ? false : selectOptions[index - 1], + next = selectOptions[index + 1], + options = optgroup.querySelectorAll('option' + optionSelector); + + if (!options.length) return; + + var config = { + display: htmlEscape(optgroup.label), + subtext: optgroup.getAttribute('data-subtext'), + icon: optgroup.getAttribute('data-icon'), + type: 'optgroup-label', + optgroupClass: ' ' + (optgroup.className || '') + }, + headerIndex, + lastIndex; + + optID++; + + if (previous) { + addDivider({ optID: optID }); + } + + config.optID = optID; + + mainData.push(config); + + for (var j = 0, len = options.length; j < len; j++) { + var option = options[j]; + + if (j === 0) { + headerIndex = mainData.length - 1; + lastIndex = headerIndex + len; + } + + addOption(option, { + headerIndex: headerIndex, + lastIndex: lastIndex, + optID: config.optID, + optgroupClass: config.optgroupClass, + disabled: optgroup.disabled + }); + } + + if (next) { + addDivider({ optID: optID }); + } + } + + for (var len = selectOptions.length, i = startIndex; i < len; i++) { + var item = selectOptions[i]; + + if (item.tagName !== 'OPTGROUP') { + addOption(item, {}); + } else { + addOptgroup(i, selectOptions); + } + } + + this.selectpicker.main.data = this.selectpicker.current.data = mainData; + }, + + buildList: function () { + var that = this, + selectData = this.selectpicker.main.data, + mainElements = [], + widestOptionLength = 0; + + if ((that.options.showTick || that.multiple) && !elementTemplates.checkMark.parentNode) { + elementTemplates.checkMark.className = this.options.iconBase + ' ' + that.options.tickIcon + ' check-mark'; + elementTemplates.a.appendChild(elementTemplates.checkMark); + } + + function buildElement (item) { + var liElement, + combinedLength = 0; + + switch (item.type) { + case 'divider': + liElement = generateOption.li( + false, + classNames.DIVIDER, + (item.optID ? item.optID + 'div' : undefined) + ); + + break; + + case 'option': + liElement = generateOption.li( + generateOption.a( + generateOption.text.call(that, item), + item.optionClass, + item.inlineStyle + ), + '', + item.optID + ); + + if (liElement.firstChild) { + liElement.firstChild.id = that.selectId + '-' + item.index; + } + + break; + + case 'optgroup-label': + liElement = generateOption.li( + generateOption.label.call(that, item), + 'dropdown-header' + item.optgroupClass, + item.optID + ); + + break; + } + + item.element = liElement; + mainElements.push(liElement); + + // count the number of characters in the option - not perfect, but should work in most cases + if (item.display) combinedLength += item.display.length; + if (item.subtext) combinedLength += item.subtext.length; + // if there is an icon, ensure this option's width is checked + if (item.icon) combinedLength += 1; + + if (combinedLength > widestOptionLength) { + widestOptionLength = combinedLength; + + // guess which option is the widest + // use this when calculating menu width + // not perfect, but it's fast, and the width will be updating accordingly when scrolling + that.selectpicker.view.widestOption = mainElements[mainElements.length - 1]; + } + } + + for (var len = selectData.length, i = 0; i < len; i++) { + var item = selectData[i]; + + buildElement(item); + } + + this.selectpicker.main.elements = this.selectpicker.current.elements = mainElements; + }, + + findLis: function () { + return this.$menuInner.find('.inner > li'); + }, + + render: function () { + var that = this, + element = this.$element[0], + // ensure titleOption is appended and selected (if necessary) before getting selectedOptions + placeholderSelected = this.setPlaceholder() && element.selectedIndex === 0, + selectedOptions = getSelectedOptions(element, this.options.hideDisabled), + selectedCount = selectedOptions.length, + button = this.$button[0], + buttonInner = button.querySelector('.filter-option-inner-inner'), + multipleSeparator = document.createTextNode(this.options.multipleSeparator), + titleFragment = elementTemplates.fragment.cloneNode(false), + showCount, + countMax, + hasContent = false; + + button.classList.toggle('bs-placeholder', that.multiple ? !selectedCount : !getSelectValues(element, selectedOptions)); + + if (!that.multiple && selectedOptions.length === 1) { + that.selectpicker.view.displayedValue = getSelectValues(element, selectedOptions); + } + + if (this.options.selectedTextFormat === 'static') { + titleFragment = generateOption.text.call(this, { text: this.options.title }, true); + } else { + showCount = this.multiple && this.options.selectedTextFormat.indexOf('count') !== -1 && selectedCount > 1; + + // determine if the number of selected options will be shown (showCount === true) + if (showCount) { + countMax = this.options.selectedTextFormat.split('>'); + showCount = (countMax.length > 1 && selectedCount > countMax[1]) || (countMax.length === 1 && selectedCount >= 2); + } + + // only loop through all selected options if the count won't be shown + if (showCount === false) { + if (!placeholderSelected) { + for (var selectedIndex = 0; selectedIndex < selectedCount; selectedIndex++) { + if (selectedIndex < 50) { + var option = selectedOptions[selectedIndex], + thisData = this.selectpicker.main.data[option.liIndex], + titleOptions = {}; + + if (this.multiple && selectedIndex > 0) { + titleFragment.appendChild(multipleSeparator.cloneNode(false)); + } + + if (option.title) { + titleOptions.text = option.title; + } else if (thisData) { + if (thisData.content && that.options.showContent) { + titleOptions.content = thisData.content.toString(); + hasContent = true; + } else { + if (that.options.showIcon) { + titleOptions.icon = thisData.icon; + } + if (that.options.showSubtext && !that.multiple && thisData.subtext) titleOptions.subtext = ' ' + thisData.subtext; + titleOptions.text = option.textContent.trim(); + } + } + + titleFragment.appendChild(generateOption.text.call(this, titleOptions, true)); + } else { + break; + } + } + + // add ellipsis + if (selectedCount > 49) { + titleFragment.appendChild(document.createTextNode('...')); + } + } + } else { + var optionSelector = ':not([hidden]):not([data-hidden="true"]):not([data-divider="true"])'; + if (this.options.hideDisabled) optionSelector += ':not(:disabled)'; + + // If this is a multiselect, and selectedTextFormat is count, then show 1 of 2 selected, etc. + var totalCount = this.$element[0].querySelectorAll('select > option' + optionSelector + ', optgroup' + optionSelector + ' option' + optionSelector).length, + tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedCount, totalCount) : this.options.countSelectedText; + + titleFragment = generateOption.text.call(this, { + text: tr8nText.replace('{0}', selectedCount.toString()).replace('{1}', totalCount.toString()) + }, true); + } + } + + if (this.options.title == undefined) { + // use .attr to ensure undefined is returned if title attribute is not set + this.options.title = this.$element.attr('title'); + } + + // If the select doesn't have a title, then use the default, or if nothing is set at all, use noneSelectedText + if (!titleFragment.childNodes.length) { + titleFragment = generateOption.text.call(this, { + text: typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText + }, true); + } + + // strip all HTML tags and trim the result, then unescape any escaped tags + button.title = titleFragment.textContent.replace(/<[^>]*>?/g, '').trim(); + + if (this.options.sanitize && hasContent) { + sanitizeHtml([titleFragment], that.options.whiteList, that.options.sanitizeFn); + } + + buttonInner.innerHTML = ''; + buttonInner.appendChild(titleFragment); + + if (version.major < 4 && this.$newElement[0].classList.contains('bs3-has-addon')) { + var filterExpand = button.querySelector('.filter-expand'), + clone = buttonInner.cloneNode(true); + + clone.className = 'filter-expand'; + + if (filterExpand) { + button.replaceChild(clone, filterExpand); + } else { + button.appendChild(clone); + } + } + + this.$element.trigger('rendered' + EVENT_KEY); + }, + + /** + * @param [style] + * @param [status] + */ + setStyle: function (newStyle, status) { + var button = this.$button[0], + newElement = this.$newElement[0], + style = this.options.style.trim(), + buttonClass; + + if (this.$element.attr('class')) { + this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi, '')); + } + + if (version.major < 4) { + newElement.classList.add('bs3'); + + if (newElement.parentNode.classList && newElement.parentNode.classList.contains('input-group') && + (newElement.previousElementSibling || newElement.nextElementSibling) && + (newElement.previousElementSibling || newElement.nextElementSibling).classList.contains('input-group-addon') + ) { + newElement.classList.add('bs3-has-addon'); + } + } + + if (newStyle) { + buttonClass = newStyle.trim(); + } else { + buttonClass = style; + } + + if (status == 'add') { + if (buttonClass) button.classList.add.apply(button.classList, buttonClass.split(' ')); + } else if (status == 'remove') { + if (buttonClass) button.classList.remove.apply(button.classList, buttonClass.split(' ')); + } else { + if (style) button.classList.remove.apply(button.classList, style.split(' ')); + if (buttonClass) button.classList.add.apply(button.classList, buttonClass.split(' ')); + } + }, + + liHeight: function (refresh) { + if (!refresh && (this.options.size === false || Object.keys(this.sizeInfo).length)) return; + + var newElement = elementTemplates.div.cloneNode(false), + menu = elementTemplates.div.cloneNode(false), + menuInner = elementTemplates.div.cloneNode(false), + menuInnerInner = document.createElement('ul'), + divider = elementTemplates.li.cloneNode(false), + dropdownHeader = elementTemplates.li.cloneNode(false), + li, + a = elementTemplates.a.cloneNode(false), + text = elementTemplates.span.cloneNode(false), + header = this.options.header && this.$menu.find('.' + classNames.POPOVERHEADER).length > 0 ? this.$menu.find('.' + classNames.POPOVERHEADER)[0].cloneNode(true) : null, + search = this.options.liveSearch ? elementTemplates.div.cloneNode(false) : null, + actions = this.options.actionsBox && this.multiple && this.$menu.find('.bs-actionsbox').length > 0 ? this.$menu.find('.bs-actionsbox')[0].cloneNode(true) : null, + doneButton = this.options.doneButton && this.multiple && this.$menu.find('.bs-donebutton').length > 0 ? this.$menu.find('.bs-donebutton')[0].cloneNode(true) : null, + firstOption = this.$element.find('option')[0]; + + this.sizeInfo.selectWidth = this.$newElement[0].offsetWidth; + + text.className = 'text'; + a.className = 'dropdown-item ' + (firstOption ? firstOption.className : ''); + newElement.className = this.$menu[0].parentNode.className + ' ' + classNames.SHOW; + newElement.style.width = 0; // ensure button width doesn't affect natural width of menu when calculating + if (this.options.width === 'auto') menu.style.minWidth = 0; + menu.className = classNames.MENU + ' ' + classNames.SHOW; + menuInner.className = 'inner ' + classNames.SHOW; + menuInnerInner.className = classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : ''); + divider.className = classNames.DIVIDER; + dropdownHeader.className = 'dropdown-header'; + + text.appendChild(document.createTextNode('\u200b')); + + if (this.selectpicker.current.data.length) { + for (var i = 0; i < this.selectpicker.current.data.length; i++) { + var data = this.selectpicker.current.data[i]; + if (data.type === 'option') { + li = data.element; + break; + } + } + } else { + li = elementTemplates.li.cloneNode(false); + a.appendChild(text); + li.appendChild(a); + } + + dropdownHeader.appendChild(text.cloneNode(true)); + + if (this.selectpicker.view.widestOption) { + menuInnerInner.appendChild(this.selectpicker.view.widestOption.cloneNode(true)); + } + + menuInnerInner.appendChild(li); + menuInnerInner.appendChild(divider); + menuInnerInner.appendChild(dropdownHeader); + if (header) menu.appendChild(header); + if (search) { + var input = document.createElement('input'); + search.className = 'bs-searchbox'; + input.className = 'form-control'; + search.appendChild(input); + menu.appendChild(search); + } + if (actions) menu.appendChild(actions); + menuInner.appendChild(menuInnerInner); + menu.appendChild(menuInner); + if (doneButton) menu.appendChild(doneButton); + newElement.appendChild(menu); + + document.body.appendChild(newElement); + + var liHeight = li.offsetHeight, + dropdownHeaderHeight = dropdownHeader ? dropdownHeader.offsetHeight : 0, + headerHeight = header ? header.offsetHeight : 0, + searchHeight = search ? search.offsetHeight : 0, + actionsHeight = actions ? actions.offsetHeight : 0, + doneButtonHeight = doneButton ? doneButton.offsetHeight : 0, + dividerHeight = $(divider).outerHeight(true), + // fall back to jQuery if getComputedStyle is not supported + menuStyle = window.getComputedStyle ? window.getComputedStyle(menu) : false, + menuWidth = menu.offsetWidth, + $menu = menuStyle ? null : $(menu), + menuPadding = { + vert: toInteger(menuStyle ? menuStyle.paddingTop : $menu.css('paddingTop')) + + toInteger(menuStyle ? menuStyle.paddingBottom : $menu.css('paddingBottom')) + + toInteger(menuStyle ? menuStyle.borderTopWidth : $menu.css('borderTopWidth')) + + toInteger(menuStyle ? menuStyle.borderBottomWidth : $menu.css('borderBottomWidth')), + horiz: toInteger(menuStyle ? menuStyle.paddingLeft : $menu.css('paddingLeft')) + + toInteger(menuStyle ? menuStyle.paddingRight : $menu.css('paddingRight')) + + toInteger(menuStyle ? menuStyle.borderLeftWidth : $menu.css('borderLeftWidth')) + + toInteger(menuStyle ? menuStyle.borderRightWidth : $menu.css('borderRightWidth')) + }, + menuExtras = { + vert: menuPadding.vert + + toInteger(menuStyle ? menuStyle.marginTop : $menu.css('marginTop')) + + toInteger(menuStyle ? menuStyle.marginBottom : $menu.css('marginBottom')) + 2, + horiz: menuPadding.horiz + + toInteger(menuStyle ? menuStyle.marginLeft : $menu.css('marginLeft')) + + toInteger(menuStyle ? menuStyle.marginRight : $menu.css('marginRight')) + 2 + }, + scrollBarWidth; + + menuInner.style.overflowY = 'scroll'; + + scrollBarWidth = menu.offsetWidth - menuWidth; + + document.body.removeChild(newElement); + + this.sizeInfo.liHeight = liHeight; + this.sizeInfo.dropdownHeaderHeight = dropdownHeaderHeight; + this.sizeInfo.headerHeight = headerHeight; + this.sizeInfo.searchHeight = searchHeight; + this.sizeInfo.actionsHeight = actionsHeight; + this.sizeInfo.doneButtonHeight = doneButtonHeight; + this.sizeInfo.dividerHeight = dividerHeight; + this.sizeInfo.menuPadding = menuPadding; + this.sizeInfo.menuExtras = menuExtras; + this.sizeInfo.menuWidth = menuWidth; + this.sizeInfo.menuInnerInnerWidth = menuWidth - menuPadding.horiz; + this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth; + this.sizeInfo.scrollBarWidth = scrollBarWidth; + this.sizeInfo.selectHeight = this.$newElement[0].offsetHeight; + + this.setPositionData(); + }, + + getSelectPosition: function () { + var that = this, + $window = $(window), + pos = that.$newElement.offset(), + $container = $(that.options.container), + containerPos; + + if (that.options.container && $container.length && !$container.is('body')) { + containerPos = $container.offset(); + containerPos.top += parseInt($container.css('borderTopWidth')); + containerPos.left += parseInt($container.css('borderLeftWidth')); + } else { + containerPos = { top: 0, left: 0 }; + } + + var winPad = that.options.windowPadding; + + this.sizeInfo.selectOffsetTop = pos.top - containerPos.top - $window.scrollTop(); + this.sizeInfo.selectOffsetBot = $window.height() - this.sizeInfo.selectOffsetTop - this.sizeInfo.selectHeight - containerPos.top - winPad[2]; + this.sizeInfo.selectOffsetLeft = pos.left - containerPos.left - $window.scrollLeft(); + this.sizeInfo.selectOffsetRight = $window.width() - this.sizeInfo.selectOffsetLeft - this.sizeInfo.selectWidth - containerPos.left - winPad[1]; + this.sizeInfo.selectOffsetTop -= winPad[0]; + this.sizeInfo.selectOffsetLeft -= winPad[3]; + }, + + setMenuSize: function (isAuto) { + this.getSelectPosition(); + + var selectWidth = this.sizeInfo.selectWidth, + liHeight = this.sizeInfo.liHeight, + headerHeight = this.sizeInfo.headerHeight, + searchHeight = this.sizeInfo.searchHeight, + actionsHeight = this.sizeInfo.actionsHeight, + doneButtonHeight = this.sizeInfo.doneButtonHeight, + divHeight = this.sizeInfo.dividerHeight, + menuPadding = this.sizeInfo.menuPadding, + menuInnerHeight, + menuHeight, + divLength = 0, + minHeight, + _minHeight, + maxHeight, + menuInnerMinHeight, + estimate, + isDropup; + + if (this.options.dropupAuto) { + // Get the estimated height of the menu without scrollbars. + // This is useful for smaller menus, where there might be plenty of room + // below the button without setting dropup, but we can't know + // the exact height of the menu until createView is called later + estimate = liHeight * this.selectpicker.current.elements.length + menuPadding.vert; + + isDropup = this.sizeInfo.selectOffsetTop - this.sizeInfo.selectOffsetBot > this.sizeInfo.menuExtras.vert && estimate + this.sizeInfo.menuExtras.vert + 50 > this.sizeInfo.selectOffsetBot; + + // ensure dropup doesn't change while searching (so menu doesn't bounce back and forth) + if (this.selectpicker.isSearching === true) { + isDropup = this.selectpicker.dropup; + } + + this.$newElement.toggleClass(classNames.DROPUP, isDropup); + this.selectpicker.dropup = isDropup; + } + + if (this.options.size === 'auto') { + _minHeight = this.selectpicker.current.elements.length > 3 ? this.sizeInfo.liHeight * 3 + this.sizeInfo.menuExtras.vert - 2 : 0; + menuHeight = this.sizeInfo.selectOffsetBot - this.sizeInfo.menuExtras.vert; + minHeight = _minHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight; + menuInnerMinHeight = Math.max(_minHeight - menuPadding.vert, 0); + + if (this.$newElement.hasClass(classNames.DROPUP)) { + menuHeight = this.sizeInfo.selectOffsetTop - this.sizeInfo.menuExtras.vert; + } + + maxHeight = menuHeight; + menuInnerHeight = menuHeight - headerHeight - searchHeight - actionsHeight - doneButtonHeight - menuPadding.vert; + } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) { + for (var i = 0; i < this.options.size; i++) { + if (this.selectpicker.current.data[i].type === 'divider') divLength++; + } + + menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding.vert; + menuInnerHeight = menuHeight - menuPadding.vert; + maxHeight = menuHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight; + minHeight = menuInnerMinHeight = ''; + } + + this.$menu.css({ + 'max-height': maxHeight + 'px', + 'overflow': 'hidden', + 'min-height': minHeight + 'px' + }); + + this.$menuInner.css({ + 'max-height': menuInnerHeight + 'px', + 'overflow-y': 'auto', + 'min-height': menuInnerMinHeight + 'px' + }); + + // ensure menuInnerHeight is always a positive number to prevent issues calculating chunkSize in createView + this.sizeInfo.menuInnerHeight = Math.max(menuInnerHeight, 1); + + if (this.selectpicker.current.data.length && this.selectpicker.current.data[this.selectpicker.current.data.length - 1].position > this.sizeInfo.menuInnerHeight) { + this.sizeInfo.hasScrollBar = true; + this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth + this.sizeInfo.scrollBarWidth; + } + + if (this.options.dropdownAlignRight === 'auto') { + this.$menu.toggleClass(classNames.MENURIGHT, this.sizeInfo.selectOffsetLeft > this.sizeInfo.selectOffsetRight && this.sizeInfo.selectOffsetRight < (this.sizeInfo.totalMenuWidth - selectWidth)); + } + + if (this.dropdown && this.dropdown._popper) this.dropdown._popper.update(); + }, + + setSize: function (refresh) { + this.liHeight(refresh); + + if (this.options.header) this.$menu.css('padding-top', 0); + + if (this.options.size !== false) { + var that = this, + $window = $(window); + + this.setMenuSize(); + + if (this.options.liveSearch) { + this.$searchbox + .off('input.setMenuSize propertychange.setMenuSize') + .on('input.setMenuSize propertychange.setMenuSize', function () { + return that.setMenuSize(); + }); + } + + if (this.options.size === 'auto') { + $window + .off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize') + .on('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize', function () { + return that.setMenuSize(); + }); + } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) { + $window.off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize'); + } + } + + this.createView(false, true, refresh); + }, + + setWidth: function () { + var that = this; + + if (this.options.width === 'auto') { + requestAnimationFrame(function () { + that.$menu.css('min-width', '0'); + + that.$element.on('loaded' + EVENT_KEY, function () { + that.liHeight(); + that.setMenuSize(); + + // Get correct width if element is hidden + var $selectClone = that.$newElement.clone().appendTo('body'), + btnWidth = $selectClone.css('width', 'auto').children('button').outerWidth(); + + $selectClone.remove(); + + // Set width to whatever's larger, button title or longest option + that.sizeInfo.selectWidth = Math.max(that.sizeInfo.totalMenuWidth, btnWidth); + that.$newElement.css('width', that.sizeInfo.selectWidth + 'px'); + }); + }); + } else if (this.options.width === 'fit') { + // Remove inline min-width so width can be changed from 'auto' + this.$menu.css('min-width', ''); + this.$newElement.css('width', '').addClass('fit-width'); + } else if (this.options.width) { + // Remove inline min-width so width can be changed from 'auto' + this.$menu.css('min-width', ''); + this.$newElement.css('width', this.options.width); + } else { + // Remove inline min-width/width so width can be changed + this.$menu.css('min-width', ''); + this.$newElement.css('width', ''); + } + // Remove fit-width class if width is changed programmatically + if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') { + this.$newElement[0].classList.remove('fit-width'); + } + }, + + selectPosition: function () { + this.$bsContainer = $('
    '); + + var that = this, + $container = $(this.options.container), + pos, + containerPos, + actualHeight, + getPlacement = function ($element) { + var containerPosition = {}, + // fall back to dropdown's default display setting if display is not manually set + display = that.options.display || ( + // Bootstrap 3 doesn't have $.fn.dropdown.Constructor.Default + $.fn.dropdown.Constructor.Default ? $.fn.dropdown.Constructor.Default.display + : false + ); + + that.$bsContainer.addClass($element.attr('class').replace(/form-control|fit-width/gi, '')).toggleClass(classNames.DROPUP, $element.hasClass(classNames.DROPUP)); + pos = $element.offset(); + + if (!$container.is('body')) { + containerPos = $container.offset(); + containerPos.top += parseInt($container.css('borderTopWidth')) - $container.scrollTop(); + containerPos.left += parseInt($container.css('borderLeftWidth')) - $container.scrollLeft(); + } else { + containerPos = { top: 0, left: 0 }; + } + + actualHeight = $element.hasClass(classNames.DROPUP) ? 0 : $element[0].offsetHeight; + + // Bootstrap 4+ uses Popper for menu positioning + if (version.major < 4 || display === 'static') { + containerPosition.top = pos.top - containerPos.top + actualHeight; + containerPosition.left = pos.left - containerPos.left; + } + + containerPosition.width = $element[0].offsetWidth; + + that.$bsContainer.css(containerPosition); + }; + + this.$button.on('click.bs.dropdown.data-api', function () { + if (that.isDisabled()) { + return; + } + + getPlacement(that.$newElement); + + that.$bsContainer + .appendTo(that.options.container) + .toggleClass(classNames.SHOW, !that.$button.hasClass(classNames.SHOW)) + .append(that.$menu); + }); + + $(window) + .off('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId) + .on('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId, function () { + var isActive = that.$newElement.hasClass(classNames.SHOW); + + if (isActive) getPlacement(that.$newElement); + }); + + this.$element.on('hide' + EVENT_KEY, function () { + that.$menu.data('height', that.$menu.height()); + that.$bsContainer.detach(); + }); + }, + + setOptionStatus: function (selectedOnly) { + var that = this; + + that.noScroll = false; + + if (that.selectpicker.view.visibleElements && that.selectpicker.view.visibleElements.length) { + for (var i = 0; i < that.selectpicker.view.visibleElements.length; i++) { + var liData = that.selectpicker.current.data[i + that.selectpicker.view.position0], + option = liData.option; + + if (option) { + if (selectedOnly !== true) { + that.setDisabled( + liData.index, + liData.disabled + ); + } + + that.setSelected( + liData.index, + option.selected + ); + } + } + } + }, + + /** + * @param {number} index - the index of the option that is being changed + * @param {boolean} selected - true if the option is being selected, false if being deselected + */ + setSelected: function (index, selected) { + var li = this.selectpicker.main.elements[index], + liData = this.selectpicker.main.data[index], + activeIndexIsSet = this.activeIndex !== undefined, + thisIsActive = this.activeIndex === index, + prevActive, + a, + // if current option is already active + // OR + // if the current option is being selected, it's NOT multiple, and + // activeIndex is undefined: + // - when the menu is first being opened, OR + // - after a search has been performed, OR + // - when retainActive is false when selecting a new option (i.e. index of the newly selected option is not the same as the current activeIndex) + keepActive = thisIsActive || (selected && !this.multiple && !activeIndexIsSet); + + liData.selected = selected; + + a = li.firstChild; + + if (selected) { + this.selectedIndex = index; + } + + li.classList.toggle('selected', selected); + + if (keepActive) { + this.focusItem(li, liData); + this.selectpicker.view.currentActive = li; + this.activeIndex = index; + } else { + this.defocusItem(li); + } + + if (a) { + a.classList.toggle('selected', selected); + + if (selected) { + a.setAttribute('aria-selected', true); + } else { + if (this.multiple) { + a.setAttribute('aria-selected', false); + } else { + a.removeAttribute('aria-selected'); + } + } + } + + if (!keepActive && !activeIndexIsSet && selected && this.prevActiveIndex !== undefined) { + prevActive = this.selectpicker.main.elements[this.prevActiveIndex]; + + this.defocusItem(prevActive); + } + }, + + /** + * @param {number} index - the index of the option that is being disabled + * @param {boolean} disabled - true if the option is being disabled, false if being enabled + */ + setDisabled: function (index, disabled) { + var li = this.selectpicker.main.elements[index], + a; + + this.selectpicker.main.data[index].disabled = disabled; + + a = li.firstChild; + + li.classList.toggle(classNames.DISABLED, disabled); + + if (a) { + if (version.major === '4') a.classList.toggle(classNames.DISABLED, disabled); + + if (disabled) { + a.setAttribute('aria-disabled', disabled); + a.setAttribute('tabindex', -1); + } else { + a.removeAttribute('aria-disabled'); + a.setAttribute('tabindex', 0); + } + } + }, + + isDisabled: function () { + return this.$element[0].disabled; + }, + + checkDisabled: function () { + if (this.isDisabled()) { + this.$newElement[0].classList.add(classNames.DISABLED); + this.$button.addClass(classNames.DISABLED).attr('aria-disabled', true); + } else { + if (this.$button[0].classList.contains(classNames.DISABLED)) { + this.$newElement[0].classList.remove(classNames.DISABLED); + this.$button.removeClass(classNames.DISABLED).attr('aria-disabled', false); + } + } + }, + + clickListener: function () { + var that = this, + $document = $(document); + + $document.data('spaceSelect', false); + + this.$button.on('keyup', function (e) { + if (/(32)/.test(e.keyCode.toString(10)) && $document.data('spaceSelect')) { + e.preventDefault(); + $document.data('spaceSelect', false); + } + }); + + this.$newElement.on('show.bs.dropdown', function () { + if (version.major > 3 && !that.dropdown) { + that.dropdown = that.$button.data('bs.dropdown'); + that.dropdown._menu = that.$menu[0]; + } + }); + + this.$button.on('click.bs.dropdown.data-api', function () { + if (!that.$newElement.hasClass(classNames.SHOW)) { + that.setSize(); + } + }); + + function setFocus () { + if (that.options.liveSearch) { + that.$searchbox.trigger('focus'); + } else { + that.$menuInner.trigger('focus'); + } + } + + function checkPopperExists () { + if (that.dropdown && that.dropdown._popper && that.dropdown._popper.state.isCreated) { + setFocus(); + } else { + requestAnimationFrame(checkPopperExists); + } + } + + this.$element.on('shown' + EVENT_KEY, function () { + if (that.$menuInner[0].scrollTop !== that.selectpicker.view.scrollTop) { + that.$menuInner[0].scrollTop = that.selectpicker.view.scrollTop; + } + + if (version.major > 3) { + requestAnimationFrame(checkPopperExists); + } else { + setFocus(); + } + }); + + // ensure posinset and setsize are correct before selecting an option via a click + this.$menuInner.on('mouseenter', 'li a', function (e) { + var hoverLi = this.parentElement, + position0 = that.isVirtual() ? that.selectpicker.view.position0 : 0, + index = Array.prototype.indexOf.call(hoverLi.parentElement.children, hoverLi), + hoverData = that.selectpicker.current.data[index + position0]; + + that.focusItem(hoverLi, hoverData, true); + }); + + this.$menuInner.on('click', 'li a', function (e, retainActive) { + var $this = $(this), + element = that.$element[0], + position0 = that.isVirtual() ? that.selectpicker.view.position0 : 0, + clickedData = that.selectpicker.current.data[$this.parent().index() + position0], + clickedIndex = clickedData.index, + prevValue = getSelectValues(element), + prevIndex = element.selectedIndex, + prevOption = element.options[prevIndex], + triggerChange = true; + + // Don't close on multi choice menu + if (that.multiple && that.options.maxOptions !== 1) { + e.stopPropagation(); + } + + e.preventDefault(); + + // Don't run if the select is disabled + if (!that.isDisabled() && !$this.parent().hasClass(classNames.DISABLED)) { + var option = clickedData.option, + $option = $(option), + state = option.selected, + $optgroup = $option.parent('optgroup'), + $optgroupOptions = $optgroup.find('option'), + maxOptions = that.options.maxOptions, + maxOptionsGrp = $optgroup.data('maxOptions') || false; + + if (clickedIndex === that.activeIndex) retainActive = true; + + if (!retainActive) { + that.prevActiveIndex = that.activeIndex; + that.activeIndex = undefined; + } + + if (!that.multiple) { // Deselect all others if not multi select box + if (prevOption) prevOption.selected = false; + option.selected = true; + that.setSelected(clickedIndex, true); + } else { // Toggle the one we have chosen if we are multi select. + option.selected = !state; + + that.setSelected(clickedIndex, !state); + that.focusedParent.focus(); + + if (maxOptions !== false || maxOptionsGrp !== false) { + var maxReached = maxOptions < getSelectedOptions(element).length, + maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length; + + if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) { + if (maxOptions && maxOptions == 1) { + element.selectedIndex = -1; + option.selected = true; + that.setOptionStatus(true); + } else if (maxOptionsGrp && maxOptionsGrp == 1) { + for (var i = 0; i < $optgroupOptions.length; i++) { + var _option = $optgroupOptions[i]; + _option.selected = false; + that.setSelected(_option.liIndex, false); + } + + option.selected = true; + that.setSelected(clickedIndex, true); + } else { + var maxOptionsText = typeof that.options.maxOptionsText === 'string' ? [that.options.maxOptionsText, that.options.maxOptionsText] : that.options.maxOptionsText, + maxOptionsArr = typeof maxOptionsText === 'function' ? maxOptionsText(maxOptions, maxOptionsGrp) : maxOptionsText, + maxTxt = maxOptionsArr[0].replace('{n}', maxOptions), + maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp), + $notify = $('
    '); + // If {var} is set in array, replace it + /** @deprecated */ + if (maxOptionsArr[2]) { + maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]); + maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]); + } + + option.selected = false; + + that.$menu.append($notify); + + if (maxOptions && maxReached) { + $notify.append($('
    ' + maxTxt + '
    ')); + triggerChange = false; + that.$element.trigger('maxReached' + EVENT_KEY); + } + + if (maxOptionsGrp && maxReachedGrp) { + $notify.append($('
    ' + maxTxtGrp + '
    ')); + triggerChange = false; + that.$element.trigger('maxReachedGrp' + EVENT_KEY); + } + + setTimeout(function () { + that.setSelected(clickedIndex, false); + }, 10); + + $notify[0].classList.add('fadeOut'); + + setTimeout(function () { + $notify.remove(); + }, 1050); + } + } + } + } + + if (!that.multiple || (that.multiple && that.options.maxOptions === 1)) { + that.$button.trigger('focus'); + } else if (that.options.liveSearch) { + that.$searchbox.trigger('focus'); + } + + // Trigger select 'change' + if (triggerChange) { + if (that.multiple || prevIndex !== element.selectedIndex) { + // $option.prop('selected') is current option state (selected/unselected). prevValue is the value of the select prior to being changed. + changedArguments = [option.index, $option.prop('selected'), prevValue]; + that.$element + .triggerNative('change'); + } + } + } + }); + + this.$menu.on('click', 'li.' + classNames.DISABLED + ' a, .' + classNames.POPOVERHEADER + ', .' + classNames.POPOVERHEADER + ' :not(.close)', function (e) { + if (e.currentTarget == this) { + e.preventDefault(); + e.stopPropagation(); + if (that.options.liveSearch && !$(e.target).hasClass('close')) { + that.$searchbox.trigger('focus'); + } else { + that.$button.trigger('focus'); + } + } + }); + + this.$menuInner.on('click', '.divider, .dropdown-header', function (e) { + e.preventDefault(); + e.stopPropagation(); + if (that.options.liveSearch) { + that.$searchbox.trigger('focus'); + } else { + that.$button.trigger('focus'); + } + }); + + this.$menu.on('click', '.' + classNames.POPOVERHEADER + ' .close', function () { + that.$button.trigger('click'); + }); + + this.$searchbox.on('click', function (e) { + e.stopPropagation(); + }); + + this.$menu.on('click', '.actions-btn', function (e) { + if (that.options.liveSearch) { + that.$searchbox.trigger('focus'); + } else { + that.$button.trigger('focus'); + } + + e.preventDefault(); + e.stopPropagation(); + + if ($(this).hasClass('bs-select-all')) { + that.selectAll(); + } else { + that.deselectAll(); + } + }); + + this.$button + .on('focus' + EVENT_KEY, function (e) { + var tabindex = that.$element[0].getAttribute('tabindex'); + + // only change when button is actually focused + if (tabindex !== undefined && e.originalEvent && e.originalEvent.isTrusted) { + // apply select element's tabindex to ensure correct order is followed when tabbing to the next element + this.setAttribute('tabindex', tabindex); + // set element's tabindex to -1 to allow for reverse tabbing + that.$element[0].setAttribute('tabindex', -1); + that.selectpicker.view.tabindex = tabindex; + } + }) + .on('blur' + EVENT_KEY, function (e) { + // revert everything to original tabindex + if (that.selectpicker.view.tabindex !== undefined && e.originalEvent && e.originalEvent.isTrusted) { + that.$element[0].setAttribute('tabindex', that.selectpicker.view.tabindex); + this.setAttribute('tabindex', -1); + that.selectpicker.view.tabindex = undefined; + } + }); + + this.$element + .on('change' + EVENT_KEY, function () { + that.render(); + that.$element.trigger('changed' + EVENT_KEY, changedArguments); + changedArguments = null; + }) + .on('focus' + EVENT_KEY, function () { + if (!that.options.mobile) that.$button[0].focus(); + }); + }, + + liveSearchListener: function () { + var that = this; + + this.$button.on('click.bs.dropdown.data-api', function () { + if (!!that.$searchbox.val()) { + that.$searchbox.val(''); + that.selectpicker.search.previousValue = undefined; + } + }); + + this.$searchbox.on('click.bs.dropdown.data-api focus.bs.dropdown.data-api touchend.bs.dropdown.data-api', function (e) { + e.stopPropagation(); + }); + + this.$searchbox.on('input propertychange', function () { + var searchValue = that.$searchbox[0].value; + + that.selectpicker.search.elements = []; + that.selectpicker.search.data = []; + + if (searchValue) { + var i, + searchMatch = [], + q = searchValue.toUpperCase(), + cache = {}, + cacheArr = [], + searchStyle = that._searchStyle(), + normalizeSearch = that.options.liveSearchNormalize; + + if (normalizeSearch) q = normalizeToBase(q); + + for (var i = 0; i < that.selectpicker.main.data.length; i++) { + var li = that.selectpicker.main.data[i]; + + if (!cache[i]) { + cache[i] = stringSearch(li, q, searchStyle, normalizeSearch); + } + + if (cache[i] && li.headerIndex !== undefined && cacheArr.indexOf(li.headerIndex) === -1) { + if (li.headerIndex > 0) { + cache[li.headerIndex - 1] = true; + cacheArr.push(li.headerIndex - 1); + } + + cache[li.headerIndex] = true; + cacheArr.push(li.headerIndex); + + cache[li.lastIndex + 1] = true; + } + + if (cache[i] && li.type !== 'optgroup-label') cacheArr.push(i); + } + + for (var i = 0, cacheLen = cacheArr.length; i < cacheLen; i++) { + var index = cacheArr[i], + prevIndex = cacheArr[i - 1], + li = that.selectpicker.main.data[index], + liPrev = that.selectpicker.main.data[prevIndex]; + + if (li.type !== 'divider' || (li.type === 'divider' && liPrev && liPrev.type !== 'divider' && cacheLen - 1 !== i)) { + that.selectpicker.search.data.push(li); + searchMatch.push(that.selectpicker.main.elements[index]); + } + } + + that.activeIndex = undefined; + that.noScroll = true; + that.$menuInner.scrollTop(0); + that.selectpicker.search.elements = searchMatch; + that.createView(true); + showNoResults.call(that, searchMatch, searchValue); + } else if (that.selectpicker.search.previousValue) { // for IE11 (#2402) + that.$menuInner.scrollTop(0); + that.createView(false); + } + + that.selectpicker.search.previousValue = searchValue; + }); + }, + + _searchStyle: function () { + return this.options.liveSearchStyle || 'contains'; + }, + + val: function (value) { + var element = this.$element[0]; + + if (typeof value !== 'undefined') { + var prevValue = getSelectValues(element); + + changedArguments = [null, null, prevValue]; + + this.$element + .val(value) + .trigger('changed' + EVENT_KEY, changedArguments); + + if (this.$newElement.hasClass(classNames.SHOW)) { + if (this.multiple) { + this.setOptionStatus(true); + } else { + var liSelectedIndex = (element.options[element.selectedIndex] || {}).liIndex; + + if (typeof liSelectedIndex === 'number') { + this.setSelected(this.selectedIndex, false); + this.setSelected(liSelectedIndex, true); + } + } + } + + this.render(); + + changedArguments = null; + + return this.$element; + } else { + return this.$element.val(); + } + }, + + changeAll: function (status) { + if (!this.multiple) return; + if (typeof status === 'undefined') status = true; + + var element = this.$element[0], + previousSelected = 0, + currentSelected = 0, + prevValue = getSelectValues(element); + + element.classList.add('bs-select-hidden'); + + for (var i = 0, data = this.selectpicker.current.data, len = data.length; i < len; i++) { + var liData = data[i], + option = liData.option; + + if (option && !liData.disabled && liData.type !== 'divider') { + if (liData.selected) previousSelected++; + option.selected = status; + if (status === true) currentSelected++; + } + } + + element.classList.remove('bs-select-hidden'); + + if (previousSelected === currentSelected) return; + + this.setOptionStatus(); + + changedArguments = [null, null, prevValue]; + + this.$element + .triggerNative('change'); + }, + + selectAll: function () { + return this.changeAll(true); + }, + + deselectAll: function () { + return this.changeAll(false); + }, + + toggle: function (e) { + e = e || window.event; + + if (e) e.stopPropagation(); + + this.$button.trigger('click.bs.dropdown.data-api'); + }, + + keydown: function (e) { + var $this = $(this), + isToggle = $this.hasClass('dropdown-toggle'), + $parent = isToggle ? $this.closest('.dropdown') : $this.closest(Selector.MENU), + that = $parent.data('this'), + $items = that.findLis(), + index, + isActive, + liActive, + activeLi, + offset, + updateScroll = false, + downOnTab = e.which === keyCodes.TAB && !isToggle && !that.options.selectOnTab, + isArrowKey = REGEXP_ARROW.test(e.which) || downOnTab, + scrollTop = that.$menuInner[0].scrollTop, + isVirtual = that.isVirtual(), + position0 = isVirtual === true ? that.selectpicker.view.position0 : 0; + + // do nothing if a function key is pressed + if (e.which >= 112 && e.which <= 123) return; + + isActive = that.$newElement.hasClass(classNames.SHOW); + + if ( + !isActive && + ( + isArrowKey || + (e.which == keyCodes.ENTER || e.which == keyCodes.SPACE) || + (e.which >= 48 && e.which <= 57) || + (e.which >= 96 && e.which <= 105) || + (e.which >= 65 && e.which <= 90) + ) + ) { + that.$button.trigger('click.bs.dropdown.data-api'); + + if (that.options.liveSearch) { + that.$searchbox.trigger('focus'); + return; + } + } + + if (e.which === keyCodes.ESCAPE && isActive) { + e.preventDefault(); + that.$button.trigger('click.bs.dropdown.data-api').trigger('focus'); + } + + if (isArrowKey) { // if up or down + if (!$items.length) return; + + liActive = that.selectpicker.main.elements[that.activeIndex]; + index = liActive ? Array.prototype.indexOf.call(liActive.parentElement.children, liActive) : -1; + + if (index !== -1) { + that.defocusItem(liActive); + } + + if (e.which === keyCodes.ARROW_UP) { // up + if (index !== -1) index--; + if (index + position0 < 0) index += $items.length; + + if (!that.selectpicker.view.canHighlight[index + position0]) { + index = that.selectpicker.view.canHighlight.slice(0, index + position0).lastIndexOf(true) - position0; + if (index === -1) index = $items.length - 1; + } + } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down + index++; + if (index + position0 >= that.selectpicker.view.canHighlight.length) index = that.selectpicker.view.firstHighlightIndex; + + if (!that.selectpicker.view.canHighlight[index + position0]) { + index = index + 1 + that.selectpicker.view.canHighlight.slice(index + position0 + 1).indexOf(true); + } + } + + e.preventDefault(); + + var liActiveIndex = position0 + index; + + if (e.which === keyCodes.ARROW_UP) { // up + // scroll to bottom and highlight last option + if (position0 === 0 && index === $items.length - 1) { + that.$menuInner[0].scrollTop = that.$menuInner[0].scrollHeight; + + liActiveIndex = that.selectpicker.current.elements.length - 1; + } else { + activeLi = that.selectpicker.current.data[liActiveIndex]; + offset = activeLi.position - activeLi.height; + + updateScroll = offset < scrollTop; + } + } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down + // scroll to top and highlight first option + if (index === that.selectpicker.view.firstHighlightIndex) { + that.$menuInner[0].scrollTop = 0; + + liActiveIndex = that.selectpicker.view.firstHighlightIndex; + } else { + activeLi = that.selectpicker.current.data[liActiveIndex]; + offset = activeLi.position - that.sizeInfo.menuInnerHeight; + + updateScroll = offset > scrollTop; + } + } + + liActive = that.selectpicker.current.elements[liActiveIndex]; + + that.activeIndex = that.selectpicker.current.data[liActiveIndex].index; + + that.focusItem(liActive); + + that.selectpicker.view.currentActive = liActive; + + if (updateScroll) that.$menuInner[0].scrollTop = offset; + + if (that.options.liveSearch) { + that.$searchbox.trigger('focus'); + } else { + $this.trigger('focus'); + } + } else if ( + (!$this.is('input') && !REGEXP_TAB_OR_ESCAPE.test(e.which)) || + (e.which === keyCodes.SPACE && that.selectpicker.keydown.keyHistory) + ) { + var searchMatch, + matches = [], + keyHistory; + + e.preventDefault(); + + that.selectpicker.keydown.keyHistory += keyCodeMap[e.which]; + + if (that.selectpicker.keydown.resetKeyHistory.cancel) clearTimeout(that.selectpicker.keydown.resetKeyHistory.cancel); + that.selectpicker.keydown.resetKeyHistory.cancel = that.selectpicker.keydown.resetKeyHistory.start(); + + keyHistory = that.selectpicker.keydown.keyHistory; + + // if all letters are the same, set keyHistory to just the first character when searching + if (/^(.)\1+$/.test(keyHistory)) { + keyHistory = keyHistory.charAt(0); + } + + // find matches + for (var i = 0; i < that.selectpicker.current.data.length; i++) { + var li = that.selectpicker.current.data[i], + hasMatch; + + hasMatch = stringSearch(li, keyHistory, 'startsWith', true); + + if (hasMatch && that.selectpicker.view.canHighlight[i]) { + matches.push(li.index); + } + } + + if (matches.length) { + var matchIndex = 0; + + $items.removeClass('active').find('a').removeClass('active'); + + // either only one key has been pressed or they are all the same key + if (keyHistory.length === 1) { + matchIndex = matches.indexOf(that.activeIndex); + + if (matchIndex === -1 || matchIndex === matches.length - 1) { + matchIndex = 0; + } else { + matchIndex++; + } + } + + searchMatch = matches[matchIndex]; + + activeLi = that.selectpicker.main.data[searchMatch]; + + if (scrollTop - activeLi.position > 0) { + offset = activeLi.position - activeLi.height; + updateScroll = true; + } else { + offset = activeLi.position - that.sizeInfo.menuInnerHeight; + // if the option is already visible at the current scroll position, just keep it the same + updateScroll = activeLi.position > scrollTop + that.sizeInfo.menuInnerHeight; + } + + liActive = that.selectpicker.main.elements[searchMatch]; + + that.activeIndex = matches[matchIndex]; + + that.focusItem(liActive); + + if (liActive) liActive.firstChild.focus(); + + if (updateScroll) that.$menuInner[0].scrollTop = offset; + + $this.trigger('focus'); + } + } + + // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu. + if ( + isActive && + ( + (e.which === keyCodes.SPACE && !that.selectpicker.keydown.keyHistory) || + e.which === keyCodes.ENTER || + (e.which === keyCodes.TAB && that.options.selectOnTab) + ) + ) { + if (e.which !== keyCodes.SPACE) e.preventDefault(); + + if (!that.options.liveSearch || e.which !== keyCodes.SPACE) { + that.$menuInner.find('.active a').trigger('click', true); // retain active class + $this.trigger('focus'); + + if (!that.options.liveSearch) { + // Prevent screen from scrolling if the user hits the spacebar + e.preventDefault(); + // Fixes spacebar selection of dropdown items in FF & IE + $(document).data('spaceSelect', true); + } + } + } + }, + + mobile: function () { + // ensure mobile is set to true if mobile function is called after init + this.options.mobile = true; + this.$element[0].classList.add('mobile-device'); + }, + + refresh: function () { + // update options if data attributes have been changed + var config = $.extend({}, this.options, this.$element.data()); + this.options = config; + + this.checkDisabled(); + this.buildData(); + this.setStyle(); + this.render(); + this.buildList(); + this.setWidth(); + + this.setSize(true); + + this.$element.trigger('refreshed' + EVENT_KEY); + }, + + hide: function () { + this.$newElement.hide(); + }, + + show: function () { + this.$newElement.show(); + }, + + remove: function () { + this.$newElement.remove(); + this.$element.remove(); + }, + + destroy: function () { + this.$newElement.before(this.$element).remove(); + + if (this.$bsContainer) { + this.$bsContainer.remove(); + } else { + this.$menu.remove(); + } + + if (this.selectpicker.view.titleOption && this.selectpicker.view.titleOption.parentNode) { + this.selectpicker.view.titleOption.parentNode.removeChild(this.selectpicker.view.titleOption); + } + + this.$element + .off(EVENT_KEY) + .removeData('selectpicker') + .removeClass('bs-select-hidden selectpicker'); + + $(window).off(EVENT_KEY + '.' + this.selectId); + } + }; + + // SELECTPICKER PLUGIN DEFINITION + // ============================== + function Plugin (option) { + // get the args of the outer function.. + var args = arguments; + // The arguments of the function are explicitly re-defined from the argument list, because the shift causes them + // to get lost/corrupted in android 2.3 and IE9 #715 #775 + var _option = option; + + [].shift.apply(args); + + // if the version was not set successfully + if (!version.success) { + // try to retreive it again + try { + version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.'); + } catch (err) { + // fall back to use BootstrapVersion if set + if (Selectpicker.BootstrapVersion) { + version.full = Selectpicker.BootstrapVersion.split(' ')[0].split('.'); + } else { + version.full = [version.major, '0', '0']; + + console.warn( + 'There was an issue retrieving Bootstrap\'s version. ' + + 'Ensure Bootstrap is being loaded before bootstrap-select and there is no namespace collision. ' + + 'If loading Bootstrap asynchronously, the version may need to be manually specified via $.fn.selectpicker.Constructor.BootstrapVersion.', + err + ); + } + } + + version.major = version.full[0]; + version.success = true; + } + + if (version.major === '4') { + // some defaults need to be changed if using Bootstrap 4 + // check to see if they have already been manually changed before forcing them to update + var toUpdate = []; + + if (Selectpicker.DEFAULTS.style === classNames.BUTTONCLASS) toUpdate.push({ name: 'style', className: 'BUTTONCLASS' }); + if (Selectpicker.DEFAULTS.iconBase === classNames.ICONBASE) toUpdate.push({ name: 'iconBase', className: 'ICONBASE' }); + if (Selectpicker.DEFAULTS.tickIcon === classNames.TICKICON) toUpdate.push({ name: 'tickIcon', className: 'TICKICON' }); + + classNames.DIVIDER = 'dropdown-divider'; + classNames.SHOW = 'show'; + classNames.BUTTONCLASS = 'btn-light'; + classNames.POPOVERHEADER = 'popover-header'; + classNames.ICONBASE = ''; + classNames.TICKICON = 'bs-ok-default'; + + for (var i = 0; i < toUpdate.length; i++) { + var option = toUpdate[i]; + Selectpicker.DEFAULTS[option.name] = classNames[option.className]; + } + } + + var value; + var chain = this.each(function () { + var $this = $(this); + if ($this.is('select')) { + var data = $this.data('selectpicker'), + options = typeof _option == 'object' && _option; + + if (!data) { + var dataAttributes = $this.data(); + + for (var dataAttr in dataAttributes) { + if (Object.prototype.hasOwnProperty.call(dataAttributes, dataAttr) && $.inArray(dataAttr, DISALLOWED_ATTRIBUTES) !== -1) { + delete dataAttributes[dataAttr]; + } + } + + var config = $.extend({}, Selectpicker.DEFAULTS, $.fn.selectpicker.defaults || {}, dataAttributes, options); + config.template = $.extend({}, Selectpicker.DEFAULTS.template, ($.fn.selectpicker.defaults ? $.fn.selectpicker.defaults.template : {}), dataAttributes.template, options.template); + $this.data('selectpicker', (data = new Selectpicker(this, config))); + } else if (options) { + for (var i in options) { + if (Object.prototype.hasOwnProperty.call(options, i)) { + data.options[i] = options[i]; + } + } + } + + if (typeof _option == 'string') { + if (data[_option] instanceof Function) { + value = data[_option].apply(data, args); + } else { + value = data.options[_option]; + } + } + } + }); + + if (typeof value !== 'undefined') { + // noinspection JSUnusedAssignment + return value; + } else { + return chain; + } + } + + var old = $.fn.selectpicker; + $.fn.selectpicker = Plugin; + $.fn.selectpicker.Constructor = Selectpicker; + + // SELECTPICKER NO CONFLICT + // ======================== + $.fn.selectpicker.noConflict = function () { + $.fn.selectpicker = old; + return this; + }; + + // get Bootstrap's keydown event handler for either Bootstrap 4 or Bootstrap 3 + function keydownHandler () { + if ($.fn.dropdown) { + // wait to define until function is called in case Bootstrap isn't loaded yet + var bootstrapKeydown = $.fn.dropdown.Constructor._dataApiKeydownHandler || $.fn.dropdown.Constructor.prototype.keydown; + return bootstrapKeydown.apply(this, arguments); + } + } + + $(document) + .off('keydown.bs.dropdown.data-api') + .on('keydown.bs.dropdown.data-api', ':not(.bootstrap-select) > [data-toggle="dropdown"]', keydownHandler) + .on('keydown.bs.dropdown.data-api', ':not(.bootstrap-select) > .dropdown-menu', keydownHandler) + .on('keydown' + EVENT_KEY, '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', Selectpicker.prototype.keydown) + .on('focusin.modal', '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', function (e) { + e.stopPropagation(); + }); + + + // SELECTPICKER DATA-API + // ===================== + $(window).on('load' + EVENT_KEY + '.data-api', function () { + $('.selectpicker').each(function () { + var $selectpicker = $(this); + Plugin.call($selectpicker, $selectpicker.data()); + }) + }); +})(jQuery); + + +})); +//# sourceMappingURL=bootstrap-select.js.map \ No newline at end of file diff --git a/js/bootstrap-select.min.js b/js/bootstrap-select.min.js new file mode 100644 index 00000000..2b572300 --- /dev/null +++ b/js/bootstrap-select.min.js @@ -0,0 +1,9 @@ +/*! + * Bootstrap-select v1.13.18 (https://developer.snapappointments.com/bootstrap-select) + * + * Copyright 2012-2020 SnapAppointments, LLC + * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) + */ + +!function(e,t){void 0===e&&void 0!==window&&(e=window),"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery")):t(e.jQuery)}(this,function(e){!function(P){"use strict";var d=["sanitize","whiteList","sanitizeFn"],r=["background","cite","href","itemtype","longdesc","poster","src","xlink:href"],e={"*":["class","dir","id","lang","role","tabindex","style",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],div:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},l=/^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi,a=/^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i;function v(e,t){var i=e.nodeName.toLowerCase();if(-1!==P.inArray(i,t))return-1===P.inArray(i,r)||Boolean(e.nodeValue.match(l)||e.nodeValue.match(a));for(var s=P(t).filter(function(e,t){return t instanceof RegExp}),n=0,o=s.length;n]+>/g,"")),s&&(a=w(a)),a=a.toUpperCase(),o="contains"===i?0<=a.indexOf(t):a.startsWith(t)))break}return o}function N(e){return parseInt(e,10)||0}P.fn.triggerNative=function(e){var t,i=this[0];i.dispatchEvent?(u?t=new Event(e,{bubbles:!0}):(t=document.createEvent("Event")).initEvent(e,!0,!1),i.dispatchEvent(t)):i.fireEvent?((t=document.createEventObject()).eventType=e,i.fireEvent("on"+e,t)):this.trigger(e)};var f={"\xc0":"A","\xc1":"A","\xc2":"A","\xc3":"A","\xc4":"A","\xc5":"A","\xe0":"a","\xe1":"a","\xe2":"a","\xe3":"a","\xe4":"a","\xe5":"a","\xc7":"C","\xe7":"c","\xd0":"D","\xf0":"d","\xc8":"E","\xc9":"E","\xca":"E","\xcb":"E","\xe8":"e","\xe9":"e","\xea":"e","\xeb":"e","\xcc":"I","\xcd":"I","\xce":"I","\xcf":"I","\xec":"i","\xed":"i","\xee":"i","\xef":"i","\xd1":"N","\xf1":"n","\xd2":"O","\xd3":"O","\xd4":"O","\xd5":"O","\xd6":"O","\xd8":"O","\xf2":"o","\xf3":"o","\xf4":"o","\xf5":"o","\xf6":"o","\xf8":"o","\xd9":"U","\xda":"U","\xdb":"U","\xdc":"U","\xf9":"u","\xfa":"u","\xfb":"u","\xfc":"u","\xdd":"Y","\xfd":"y","\xff":"y","\xc6":"Ae","\xe6":"ae","\xde":"Th","\xfe":"th","\xdf":"ss","\u0100":"A","\u0102":"A","\u0104":"A","\u0101":"a","\u0103":"a","\u0105":"a","\u0106":"C","\u0108":"C","\u010a":"C","\u010c":"C","\u0107":"c","\u0109":"c","\u010b":"c","\u010d":"c","\u010e":"D","\u0110":"D","\u010f":"d","\u0111":"d","\u0112":"E","\u0114":"E","\u0116":"E","\u0118":"E","\u011a":"E","\u0113":"e","\u0115":"e","\u0117":"e","\u0119":"e","\u011b":"e","\u011c":"G","\u011e":"G","\u0120":"G","\u0122":"G","\u011d":"g","\u011f":"g","\u0121":"g","\u0123":"g","\u0124":"H","\u0126":"H","\u0125":"h","\u0127":"h","\u0128":"I","\u012a":"I","\u012c":"I","\u012e":"I","\u0130":"I","\u0129":"i","\u012b":"i","\u012d":"i","\u012f":"i","\u0131":"i","\u0134":"J","\u0135":"j","\u0136":"K","\u0137":"k","\u0138":"k","\u0139":"L","\u013b":"L","\u013d":"L","\u013f":"L","\u0141":"L","\u013a":"l","\u013c":"l","\u013e":"l","\u0140":"l","\u0142":"l","\u0143":"N","\u0145":"N","\u0147":"N","\u014a":"N","\u0144":"n","\u0146":"n","\u0148":"n","\u014b":"n","\u014c":"O","\u014e":"O","\u0150":"O","\u014d":"o","\u014f":"o","\u0151":"o","\u0154":"R","\u0156":"R","\u0158":"R","\u0155":"r","\u0157":"r","\u0159":"r","\u015a":"S","\u015c":"S","\u015e":"S","\u0160":"S","\u015b":"s","\u015d":"s","\u015f":"s","\u0161":"s","\u0162":"T","\u0164":"T","\u0166":"T","\u0163":"t","\u0165":"t","\u0167":"t","\u0168":"U","\u016a":"U","\u016c":"U","\u016e":"U","\u0170":"U","\u0172":"U","\u0169":"u","\u016b":"u","\u016d":"u","\u016f":"u","\u0171":"u","\u0173":"u","\u0174":"W","\u0175":"w","\u0176":"Y","\u0177":"y","\u0178":"Y","\u0179":"Z","\u017b":"Z","\u017d":"Z","\u017a":"z","\u017c":"z","\u017e":"z","\u0132":"IJ","\u0133":"ij","\u0152":"Oe","\u0153":"oe","\u0149":"'n","\u017f":"s"},m=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,g=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\u1ab0-\\u1aff\\u1dc0-\\u1dff]","g");function b(e){return f[e]}function w(e){return(e=e.toString())&&e.replace(m,b).replace(g,"")}var I,x,y,$,S=(I={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},x="(?:"+Object.keys(I).join("|")+")",y=RegExp(x),$=RegExp(x,"g"),function(e){return e=null==e?"":""+e,y.test(e)?e.replace($,E):e});function E(e){return I[e]}var C={32:" ",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",65:"A",66:"B",67:"C",68:"D",69:"E",70:"F",71:"G",72:"H",73:"I",74:"J",75:"K",76:"L",77:"M",78:"N",79:"O",80:"P",81:"Q",82:"R",83:"S",84:"T",85:"U",86:"V",87:"W",88:"X",89:"Y",90:"Z",96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9"},A=27,L=13,D=32,H=9,B=38,R=40,M={success:!1,major:"3"};try{M.full=(P.fn.dropdown.Constructor.VERSION||"").split(" ")[0].split("."),M.major=M.full[0],M.success=!0}catch(e){}var U=0,j=".bs.select",V={DISABLED:"disabled",DIVIDER:"divider",SHOW:"open",DROPUP:"dropup",MENU:"dropdown-menu",MENURIGHT:"dropdown-menu-right",MENULEFT:"dropdown-menu-left",BUTTONCLASS:"btn-default",POPOVERHEADER:"popover-title",ICONBASE:"glyphicon",TICKICON:"glyphicon-ok"},F={MENU:"."+V.MENU},_={div:document.createElement("div"),span:document.createElement("span"),i:document.createElement("i"),subtext:document.createElement("small"),a:document.createElement("a"),li:document.createElement("li"),whitespace:document.createTextNode("\xa0"),fragment:document.createDocumentFragment()};_.noResults=_.li.cloneNode(!1),_.noResults.className="no-results",_.a.setAttribute("role","option"),_.a.className="dropdown-item",_.subtext.className="text-muted",_.text=_.span.cloneNode(!1),_.text.className="text",_.checkMark=_.span.cloneNode(!1);var G=new RegExp(B+"|"+R),q=new RegExp("^"+H+"$|"+A),K={li:function(e,t,i){var s=_.li.cloneNode(!1);return e&&(1===e.nodeType||11===e.nodeType?s.appendChild(e):s.innerHTML=e),void 0!==t&&""!==t&&(s.className=t),null!=i&&s.classList.add("optgroup-"+i),s},a:function(e,t,i){var s=_.a.cloneNode(!0);return e&&(11===e.nodeType?s.appendChild(e):s.insertAdjacentHTML("beforeend",e)),void 0!==t&&""!==t&&s.classList.add.apply(s.classList,t.split(/\s+/)),i&&s.setAttribute("style",i),s},text:function(e,t){var i,s,n=_.text.cloneNode(!1);if(e.content)n.innerHTML=e.content;else{if(n.textContent=e.text,e.icon){var o=_.whitespace.cloneNode(!1);(s=(!0===t?_.i:_.span).cloneNode(!1)).className=this.options.iconBase+" "+e.icon,_.fragment.appendChild(s),_.fragment.appendChild(o)}e.subtext&&((i=_.subtext.cloneNode(!1)).textContent=e.subtext,n.appendChild(i))}if(!0===t)for(;0'},maxOptions:!1,mobile:!1,selectOnTab:!1,dropdownAlignRight:!1,windowPadding:0,virtualScroll:600,display:!1,sanitize:!0,sanitizeFn:null,whiteList:e},Y.prototype={constructor:Y,init:function(){var i=this,e=this.$element.attr("id"),t=this.$element[0],s=t.form;U++,this.selectId="bs-select-"+U,t.classList.add("bs-select-hidden"),this.multiple=this.$element.prop("multiple"),this.autofocus=this.$element.prop("autofocus"),t.classList.contains("show-tick")&&(this.options.showTick=!0),this.$newElement=this.createDropdown(),this.buildData(),this.$element.after(this.$newElement).prependTo(this.$newElement),s&&null===t.form&&(s.id||(s.id="form-"+this.selectId),t.setAttribute("form",s.id)),this.$button=this.$newElement.children("button"),this.$menu=this.$newElement.children(F.MENU),this.$menuInner=this.$menu.children(".inner"),this.$searchbox=this.$menu.find("input"),t.classList.remove("bs-select-hidden"),!0===this.options.dropdownAlignRight&&this.$menu[0].classList.add(V.MENURIGHT),void 0!==e&&this.$button.attr("data-id",e),this.checkDisabled(),this.clickListener(),this.options.liveSearch?(this.liveSearchListener(),this.focusedParent=this.$searchbox[0]):this.focusedParent=this.$menuInner[0],this.setStyle(),this.render(),this.setWidth(),this.options.container?this.selectPosition():this.$element.on("hide"+j,function(){if(i.isVirtual()){var e=i.$menuInner[0],t=e.firstChild.cloneNode(!1);e.replaceChild(t,e.firstChild),e.scrollTop=0}}),this.$menu.data("this",this),this.$newElement.data("this",this),this.options.mobile&&this.mobile(),this.$newElement.on({"hide.bs.dropdown":function(e){i.$element.trigger("hide"+j,e)},"hidden.bs.dropdown":function(e){i.$element.trigger("hidden"+j,e)},"show.bs.dropdown":function(e){i.$element.trigger("show"+j,e)},"shown.bs.dropdown":function(e){i.$element.trigger("shown"+j,e)}}),t.hasAttribute("required")&&this.$element.on("invalid"+j,function(){i.$button[0].classList.add("bs-invalid"),i.$element.on("shown"+j+".invalid",function(){i.$element.val(i.$element.val()).off("shown"+j+".invalid")}).on("rendered"+j,function(){this.validity.valid&&i.$button[0].classList.remove("bs-invalid"),i.$element.off("rendered"+j)}),i.$button.on("blur"+j,function(){i.$element.trigger("focus").trigger("blur"),i.$button.off("blur"+j)})}),setTimeout(function(){i.buildList(),i.$element.trigger("loaded"+j)})},createDropdown:function(){var e=this.multiple||this.options.showTick?" show-tick":"",t=this.multiple?' aria-multiselectable="true"':"",i="",s=this.autofocus?" autofocus":"";M.major<4&&this.$element.parent().hasClass("input-group")&&(i=" input-group-btn");var n,o="",r="",l="",a="";return this.options.header&&(o='
    '+this.options.header+"
    "),this.options.liveSearch&&(r=''),this.multiple&&this.options.actionsBox&&(l='
    "),this.multiple&&this.options.doneButton&&(a='
    "),n='",P(n)},setPositionData:function(){this.selectpicker.view.canHighlight=[],this.selectpicker.view.size=0,this.selectpicker.view.firstHighlightIndex=!1;for(var e=0;e=this.options.virtualScroll||!0===this.options.virtualScroll},createView:function(N,e,t){var A,L,D=this,i=0,H=[];if(this.selectpicker.isSearching=N,this.selectpicker.current=N?this.selectpicker.search:this.selectpicker.main,this.setPositionData(),e)if(t)i=this.$menuInner[0].scrollTop;else if(!D.multiple){var s=D.$element[0],n=(s.options[s.selectedIndex]||{}).liIndex;if("number"==typeof n&&!1!==D.options.size){var o=D.selectpicker.main.data[n],r=o&&o.position;r&&(i=r-(D.sizeInfo.menuInnerHeight+D.sizeInfo.liHeight)/2)}}function l(e,t){var i,s,n,o,r,l,a,c,d=D.selectpicker.current.elements.length,h=[],p=!0,u=D.isVirtual();D.selectpicker.view.scrollTop=e,i=Math.ceil(D.sizeInfo.menuInnerHeight/D.sizeInfo.liHeight*1.5),s=Math.round(d/i)||1;for(var f=0;fd-1?0:D.selectpicker.current.data[d-1].position-D.selectpicker.current.data[D.selectpicker.view.position1-1].position,b.firstChild.style.marginTop=v+"px",b.firstChild.style.marginBottom=g+"px"):(b.firstChild.style.marginTop=0,b.firstChild.style.marginBottom=0),b.firstChild.appendChild(w),!0===u&&D.sizeInfo.hasScrollBar){var C=b.firstChild.offsetWidth;if(t&&CD.sizeInfo.selectWidth)b.firstChild.style.minWidth=D.sizeInfo.menuInnerInnerWidth+"px";else if(C>D.sizeInfo.menuInnerInnerWidth){D.$menu[0].style.minWidth=0;var O=b.firstChild.offsetWidth;O>D.sizeInfo.menuInnerInnerWidth&&(D.sizeInfo.menuInnerInnerWidth=O,b.firstChild.style.minWidth=D.sizeInfo.menuInnerInnerWidth+"px"),D.$menu[0].style.minWidth=""}}}if(D.prevActiveIndex=D.activeIndex,D.options.liveSearch){if(N&&t){var z,T=0;D.selectpicker.view.canHighlight[T]||(T=1+D.selectpicker.view.canHighlight.slice(1).indexOf(!0)),z=D.selectpicker.view.visibleElements[T],D.defocusItem(D.selectpicker.view.currentActive),D.activeIndex=(D.selectpicker.current.data[T]||{}).index,D.focusItem(z)}}else D.$menuInner.trigger("focus")}l(i,!0),this.$menuInner.off("scroll.createView").on("scroll.createView",function(e,t){D.noScroll||l(this.scrollTop,t),D.noScroll=!1}),P(window).off("resize"+j+"."+this.selectId+".createView").on("resize"+j+"."+this.selectId+".createView",function(){D.$newElement.hasClass(V.SHOW)&&l(D.$menuInner[0].scrollTop)})},focusItem:function(e,t,i){if(e){t=t||this.selectpicker.main.data[this.activeIndex];var s=e.firstChild;s&&(s.setAttribute("aria-setsize",this.selectpicker.view.size),s.setAttribute("aria-posinset",t.posinset),!0!==i&&(this.focusedParent.setAttribute("aria-activedescendant",s.id),e.classList.add("active"),s.classList.add("active")))}},defocusItem:function(e){e&&(e.classList.remove("active"),e.firstChild&&e.firstChild.classList.remove("active"))},setPlaceholder:function(){var e=this,t=!1;if(this.options.title&&!this.multiple){this.selectpicker.view.titleOption||(this.selectpicker.view.titleOption=document.createElement("option")),t=!0;var i=this.$element[0],s=!1,n=!this.selectpicker.view.titleOption.parentNode,o=i.selectedIndex,r=i.options[o],l=window.performance&&window.performance.getEntriesByType("navigation"),a=l&&l.length?"back_forward"!==l[0].type:2!==window.performance.navigation.type;n&&(this.selectpicker.view.titleOption.className="bs-title-option",this.selectpicker.view.titleOption.value="",s=!r||0===o&&!1===r.defaultSelected&&void 0===this.$element.data("selected")),!n&&0===this.selectpicker.view.titleOption.index||i.insertBefore(this.selectpicker.view.titleOption,i.firstChild),s&&a?i.selectedIndex=0:"complete"!==document.readyState&&window.addEventListener("pageshow",function(){e.selectpicker.view.displayedValue!==i.value&&e.render()})}return t},buildData:function(){var p=':not([hidden]):not([data-hidden="true"])',u=[],f=0,m=this.setPlaceholder()?1:0;this.options.hideDisabled&&(p+=":not(:disabled)");var e=this.$element[0].querySelectorAll("select > *"+p);function v(e){var t=u[u.length-1];t&&"divider"===t.type&&(t.optID||e.optID)||((e=e||{}).type="divider",u.push(e))}function g(e,t){if((t=t||{}).divider="true"===e.getAttribute("data-divider"),t.divider)v({optID:t.optID});else{var i=u.length,s=e.style.cssText,n=s?S(s):"",o=(e.className||"")+(t.optgroupClass||"");t.optID&&(o="opt "+o),t.optionClass=o.trim(),t.inlineStyle=n,t.text=e.textContent,t.content=e.getAttribute("data-content"),t.tokens=e.getAttribute("data-tokens"),t.subtext=e.getAttribute("data-subtext"),t.icon=e.getAttribute("data-icon"),e.liIndex=i,t.display=t.content||t.text,t.type="option",t.index=i,t.option=e,t.selected=!!e.selected,t.disabled=t.disabled||!!e.disabled,u.push(t)}}function t(e,t){var i=t[e],s=!(e-1 li")},render:function(){var e,t=this,i=this.$element[0],s=this.setPlaceholder()&&0===i.selectedIndex,n=O(i,this.options.hideDisabled),o=n.length,r=this.$button[0],l=r.querySelector(".filter-option-inner-inner"),a=document.createTextNode(this.options.multipleSeparator),c=_.fragment.cloneNode(!1),d=!1;if(r.classList.toggle("bs-placeholder",t.multiple?!o:!z(i,n)),t.multiple||1!==n.length||(t.selectpicker.view.displayedValue=z(i,n)),"static"===this.options.selectedTextFormat)c=K.text.call(this,{text:this.options.title},!0);else if(!1===(this.multiple&&-1!==this.options.selectedTextFormat.indexOf("count")&&1")).length&&o>e[1]||1===e.length&&2<=o))){if(!s){for(var h=0;h option"+m+", optgroup"+m+" option"+m).length,g="function"==typeof this.options.countSelectedText?this.options.countSelectedText(o,v):this.options.countSelectedText;c=K.text.call(this,{text:g.replace("{0}",o.toString()).replace("{1}",v.toString())},!0)}if(null==this.options.title&&(this.options.title=this.$element.attr("title")),c.childNodes.length||(c=K.text.call(this,{text:void 0!==this.options.title?this.options.title:this.options.noneSelectedText},!0)),r.title=c.textContent.replace(/<[^>]*>?/g,"").trim(),this.options.sanitize&&d&&W([c],t.options.whiteList,t.options.sanitizeFn),l.innerHTML="",l.appendChild(c),M.major<4&&this.$newElement[0].classList.contains("bs3-has-addon")){var b=r.querySelector(".filter-expand"),w=l.cloneNode(!0);w.className="filter-expand",b?r.replaceChild(w,b):r.appendChild(w)}this.$element.trigger("rendered"+j)},setStyle:function(e,t){var i,s=this.$button[0],n=this.$newElement[0],o=this.options.style.trim();this.$element.attr("class")&&this.$newElement.addClass(this.$element.attr("class").replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi,"")),M.major<4&&(n.classList.add("bs3"),n.parentNode.classList&&n.parentNode.classList.contains("input-group")&&(n.previousElementSibling||n.nextElementSibling)&&(n.previousElementSibling||n.nextElementSibling).classList.contains("input-group-addon")&&n.classList.add("bs3-has-addon")),i=e?e.trim():o,"add"==t?i&&s.classList.add.apply(s.classList,i.split(" ")):"remove"==t?i&&s.classList.remove.apply(s.classList,i.split(" ")):(o&&s.classList.remove.apply(s.classList,o.split(" ")),i&&s.classList.add.apply(s.classList,i.split(" ")))},liHeight:function(e){if(e||!1!==this.options.size&&!Object.keys(this.sizeInfo).length){var t,i=_.div.cloneNode(!1),s=_.div.cloneNode(!1),n=_.div.cloneNode(!1),o=document.createElement("ul"),r=_.li.cloneNode(!1),l=_.li.cloneNode(!1),a=_.a.cloneNode(!1),c=_.span.cloneNode(!1),d=this.options.header&&0this.sizeInfo.menuExtras.vert&&l+this.sizeInfo.menuExtras.vert+50>this.sizeInfo.selectOffsetBot,!0===this.selectpicker.isSearching&&(a=this.selectpicker.dropup),this.$newElement.toggleClass(V.DROPUP,a),this.selectpicker.dropup=a),"auto"===this.options.size)n=3this.options.size){for(var b=0;bthis.sizeInfo.menuInnerHeight&&(this.sizeInfo.hasScrollBar=!0,this.sizeInfo.totalMenuWidth=this.sizeInfo.menuWidth+this.sizeInfo.scrollBarWidth),"auto"===this.options.dropdownAlignRight&&this.$menu.toggleClass(V.MENURIGHT,this.sizeInfo.selectOffsetLeft>this.sizeInfo.selectOffsetRight&&this.sizeInfo.selectOffsetRightthis.options.size&&i.off("resize"+j+"."+this.selectId+".setMenuSize scroll"+j+"."+this.selectId+".setMenuSize")}this.createView(!1,!0,e)},setWidth:function(){var i=this;"auto"===this.options.width?requestAnimationFrame(function(){i.$menu.css("min-width","0"),i.$element.on("loaded"+j,function(){i.liHeight(),i.setMenuSize();var e=i.$newElement.clone().appendTo("body"),t=e.css("width","auto").children("button").outerWidth();e.remove(),i.sizeInfo.selectWidth=Math.max(i.sizeInfo.totalMenuWidth,t),i.$newElement.css("width",i.sizeInfo.selectWidth+"px")})}):"fit"===this.options.width?(this.$menu.css("min-width",""),this.$newElement.css("width","").addClass("fit-width")):this.options.width?(this.$menu.css("min-width",""),this.$newElement.css("width",this.options.width)):(this.$menu.css("min-width",""),this.$newElement.css("width","")),this.$newElement.hasClass("fit-width")&&"fit"!==this.options.width&&this.$newElement[0].classList.remove("fit-width")},selectPosition:function(){this.$bsContainer=P('
    ');function e(e){var t={},i=r.options.display||!!P.fn.dropdown.Constructor.Default&&P.fn.dropdown.Constructor.Default.display;r.$bsContainer.addClass(e.attr("class").replace(/form-control|fit-width/gi,"")).toggleClass(V.DROPUP,e.hasClass(V.DROPUP)),s=e.offset(),l.is("body")?n={top:0,left:0}:((n=l.offset()).top+=parseInt(l.css("borderTopWidth"))-l.scrollTop(),n.left+=parseInt(l.css("borderLeftWidth"))-l.scrollLeft()),o=e.hasClass(V.DROPUP)?0:e[0].offsetHeight,(M.major<4||"static"===i)&&(t.top=s.top-n.top+o,t.left=s.left-n.left),t.width=e[0].offsetWidth,r.$bsContainer.css(t)}var s,n,o,r=this,l=P(this.options.container);this.$button.on("click.bs.dropdown.data-api",function(){r.isDisabled()||(e(r.$newElement),r.$bsContainer.appendTo(r.options.container).toggleClass(V.SHOW,!r.$button.hasClass(V.SHOW)).append(r.$menu))}),P(window).off("resize"+j+"."+this.selectId+" scroll"+j+"."+this.selectId).on("resize"+j+"."+this.selectId+" scroll"+j+"."+this.selectId,function(){r.$newElement.hasClass(V.SHOW)&&e(r.$newElement)}),this.$element.on("hide"+j,function(){r.$menu.data("height",r.$menu.height()),r.$bsContainer.detach()})},setOptionStatus:function(e){var t=this;if(t.noScroll=!1,t.selectpicker.view.visibleElements&&t.selectpicker.view.visibleElements.length)for(var i=0;i
    ');y[2]&&($=$.replace("{var}",y[2][1"+$+"
    ")),d=!1,C.$element.trigger("maxReached"+j)),g&&w&&(E.append(P("
    "+S+"
    ")),d=!1,C.$element.trigger("maxReachedGrp"+j)),setTimeout(function(){C.setSelected(r,!1)},10),E[0].classList.add("fadeOut"),setTimeout(function(){E.remove()},1050)}}}else c&&(c.selected=!1),h.selected=!0,C.setSelected(r,!0);!C.multiple||C.multiple&&1===C.options.maxOptions?C.$button.trigger("focus"):C.options.liveSearch&&C.$searchbox.trigger("focus"),d&&(!C.multiple&&a===s.selectedIndex||(T=[h.index,p.prop("selected"),l],C.$element.triggerNative("change")))}}),this.$menu.on("click","li."+V.DISABLED+" a, ."+V.POPOVERHEADER+", ."+V.POPOVERHEADER+" :not(.close)",function(e){e.currentTarget==this&&(e.preventDefault(),e.stopPropagation(),C.options.liveSearch&&!P(e.target).hasClass("close")?C.$searchbox.trigger("focus"):C.$button.trigger("focus"))}),this.$menuInner.on("click",".divider, .dropdown-header",function(e){e.preventDefault(),e.stopPropagation(),C.options.liveSearch?C.$searchbox.trigger("focus"):C.$button.trigger("focus")}),this.$menu.on("click","."+V.POPOVERHEADER+" .close",function(){C.$button.trigger("click")}),this.$searchbox.on("click",function(e){e.stopPropagation()}),this.$menu.on("click",".actions-btn",function(e){C.options.liveSearch?C.$searchbox.trigger("focus"):C.$button.trigger("focus"),e.preventDefault(),e.stopPropagation(),P(this).hasClass("bs-select-all")?C.selectAll():C.deselectAll()}),this.$button.on("focus"+j,function(e){var t=C.$element[0].getAttribute("tabindex");void 0!==t&&e.originalEvent&&e.originalEvent.isTrusted&&(this.setAttribute("tabindex",t),C.$element[0].setAttribute("tabindex",-1),C.selectpicker.view.tabindex=t)}).on("blur"+j,function(e){void 0!==C.selectpicker.view.tabindex&&e.originalEvent&&e.originalEvent.isTrusted&&(C.$element[0].setAttribute("tabindex",C.selectpicker.view.tabindex),this.setAttribute("tabindex",-1),C.selectpicker.view.tabindex=void 0)}),this.$element.on("change"+j,function(){C.render(),C.$element.trigger("changed"+j,T),T=null}).on("focus"+j,function(){C.options.mobile||C.$button[0].focus()})},liveSearchListener:function(){var u=this;this.$button.on("click.bs.dropdown.data-api",function(){u.$searchbox.val()&&(u.$searchbox.val(""),u.selectpicker.search.previousValue=void 0)}),this.$searchbox.on("click.bs.dropdown.data-api focus.bs.dropdown.data-api touchend.bs.dropdown.data-api",function(e){e.stopPropagation()}),this.$searchbox.on("input propertychange",function(){var e=u.$searchbox[0].value;if(u.selectpicker.search.elements=[],u.selectpicker.search.data=[],e){var t=[],i=e.toUpperCase(),s={},n=[],o=u._searchStyle(),r=u.options.liveSearchNormalize;r&&(i=w(i));for(var l=0;l=a.selectpicker.view.canHighlight.length&&(t=a.selectpicker.view.firstHighlightIndex),a.selectpicker.view.canHighlight[t+f]||(t=t+1+a.selectpicker.view.canHighlight.slice(t+f+1).indexOf(!0))),e.preventDefault();var m=f+t;e.which===B?0===f&&t===c.length-1?(a.$menuInner[0].scrollTop=a.$menuInner[0].scrollHeight,m=a.selectpicker.current.elements.length-1):d=(o=(n=a.selectpicker.current.data[m]).position-n.height)u+a.sizeInfo.menuInnerHeight),s=a.selectpicker.main.elements[v],a.activeIndex=b[x],a.focusItem(s),s&&s.firstChild.focus(),d&&(a.$menuInner[0].scrollTop=o),r.trigger("focus")}}i&&(e.which===D&&!a.selectpicker.keydown.keyHistory||e.which===L||e.which===H&&a.options.selectOnTab)&&(e.which!==D&&e.preventDefault(),a.options.liveSearch&&e.which===D||(a.$menuInner.find(".active a").trigger("click",!0),r.trigger("focus"),a.options.liveSearch||(e.preventDefault(),P(document).data("spaceSelect",!0))))}},mobile:function(){this.options.mobile=!0,this.$element[0].classList.add("mobile-device")},refresh:function(){var e=P.extend({},this.options,this.$element.data());this.options=e,this.checkDisabled(),this.buildData(),this.setStyle(),this.render(),this.buildList(),this.setWidth(),this.setSize(!0),this.$element.trigger("refreshed"+j)},hide:function(){this.$newElement.hide()},show:function(){this.$newElement.show()},remove:function(){this.$newElement.remove(),this.$element.remove()},destroy:function(){this.$newElement.before(this.$element).remove(),this.$bsContainer?this.$bsContainer.remove():this.$menu.remove(),this.selectpicker.view.titleOption&&this.selectpicker.view.titleOption.parentNode&&this.selectpicker.view.titleOption.parentNode.removeChild(this.selectpicker.view.titleOption),this.$element.off(j).removeData("selectpicker").removeClass("bs-select-hidden selectpicker"),P(window).off(j+"."+this.selectId)}};var J=P.fn.selectpicker;function Q(){if(P.fn.dropdown)return(P.fn.dropdown.Constructor._dataApiKeydownHandler||P.fn.dropdown.Constructor.prototype.keydown).apply(this,arguments)}P.fn.selectpicker=Z,P.fn.selectpicker.Constructor=Y,P.fn.selectpicker.noConflict=function(){return P.fn.selectpicker=J,this},P(document).off("keydown.bs.dropdown.data-api").on("keydown.bs.dropdown.data-api",':not(.bootstrap-select) > [data-toggle="dropdown"]',Q).on("keydown.bs.dropdown.data-api",":not(.bootstrap-select) > .dropdown-menu",Q).on("keydown"+j,'.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input',Y.prototype.keydown).on("focusin.modal",'.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input',function(e){e.stopPropagation()}),P(window).on("load"+j+".data-api",function(){P(".selectpicker").each(function(){var e=P(this);Z.call(e,e.data())})})}(e)}); +//# sourceMappingURL=bootstrap-select.min.js.map \ No newline at end of file diff --git a/js/resources.js b/js/resources.js new file mode 100644 index 00000000..ea1c09b6 --- /dev/null +++ b/js/resources.js @@ -0,0 +1,243 @@ +jQuery(function($){ + function searchResources(){ + $('.oer_resource_posts').html(''); + var loader = '
    '; + $('.oer_resource_posts').html(loader); + var data = { + action: 'search_resources', + } + if ($('.resource-search-filters #keyword').val()!=='') + data.keyword = $('.resource-search-filters #keyword').val(); + if ($('.resource-search-filters #gradeLevel').val()!=='') + data.gradeLevel = $('.resource-search-filters #gradeLevel').val(); + if ($('.resource-search-filters #product').val()!=='') + data.product = $('.resource-search-filters #product').val(); + + $.ajax({ + type: "POST", + url: resources.ajaxurl, + data: data, + success: function(msg){ + $('.oer_resource_posts').html(msg); + } + }); + } + + function moveResourceImage() { + var width = (window.innerWidth > 0) ? window.innerWidth : screen.width; + if (width<768){ + let thumbnail = $('.nalrc-featured-thumbnail'); + $('.nalrc-resource-details .nalrc-resource-desc').after(thumbnail); + } else { + let thumbnail = $('.nalrc-featured-thumbnail'); + $('.nalrc-resource-details').prepend(thumbnail); + } + } + + //multiple select dropdown + var gradeWrapper = $('.resource-search-grade-level .resource-select-wrapper'); + if (gradeWrapper.length){ + gradeWrapper.find('select').selectpicker(); + } + + var resWrapper = $('.resource-search-product .resource-select-wrapper'); + if (resWrapper.length){ + resWrapper.find('select').selectpicker(); + } + + $(document).on('keydown', '.resource-search-grade-level .resource-select-wrapper .bootstrap-select button.dropdown-toggle,.resource-search-product .resource-select-wrapper .bootstrap-select button.dropdown-toggle', function(e){ + var code = e.keyCode || e.which; + if (code==32 || code==13){ + $(this).trigger('click.bs.dropdown.data-api'); + } + }); + + // up and arrow key press + if ($('.resource-select-filter').length){ + var focusedIndex = -1; + var itemFocus = 0; + var optionCount = $('.resource-select-filter .dropdown-menu li').length; + $(document).on('keydown', '.resource-select-filter .dropdown-menu', function(e){ + e.preventDefault(); + var code = e.keyCode || e.which; + if (code==9){ + $(this).closest('.bootstrap-select').find('.selectpicker').selectpicker('toggle'); + filter_index = 0; + } else if (code==38) { + focusedIndex--; + } else if (code==40) { + focusedIndex++; + } else if (code==27) { + itemFocus = 0; + focusedIndex = -1; + } else if (code==32 || code==13){ + $(this).trigger('click'); + focusedIndex = -1; + } + if (code==38 || code==40){ + itemFocus = focusedIndex+1; + $(this).closest('.dropdown-menu').find('li').removeClass('active'); + $(this).closest('.dropdown-menu').find('li a').removeClass('active'); + var curItem = $(this); + var index = $(this).closest('.dropdown-menu').find('li').index(curItem); + $(this).closest('.dropdown-menu').find('ul').scrollTop(index*32); + var next = $(this).closest('.dropdown-menu').find('li:nth-child('+itemFocus+')'); + if (next.length>=0){ + next.addClass('active'); + next.find('a').addClass('active'); + } + $(this).closest('.dropdown-menu').find('li:nth-child('+itemFocus+') a').focus(); + } + }); + } + + /** Topic Search **/ + $('.resource-search-button').on('click', searchResources); + + /** Keyword search **/ + $('.resource-search-keyword #keyword').on('keydown', function(e){ + var code = e.keyCode || e.which; + if (code==13){ + searchResources(); + } + }); + + /** Add Aria Label to Bootstrap Select button **/ + $('.selectpicker').each(function() { + var button = $('button[data-id="'+this.id+'"]').first(); + if(button.length > 0) { + button.attr('aria-label', $(this).attr('aria-label')); + } + }); + + // Keyboard navigation of filter dropdown on Resources page + $(document).on('keydown', '.resource-select-filter button.dropdown-toggle', function(e){ + var code = e.keyCode || e.which; + if (code==13 || code==32){ + $(this).closest('.bootstrap-select').find('.selectpicker').selectpicker('toggle'); + } else if (code==38) { + $(this).closest('.bootstrap-select').find('.dropdown-menu li:last-child a').focus(); + } else if (code==40) { + $(this).closest('.bootstrap-select').find('.dropdown-menu li:first-child a').focus(); + } + }); + + $(document).on('keydown', '.resource-select-filter .dropdown-menu li a', function(e){ + var code = e.keyCode || e.which; + if (code==9){ + $(this).closest('.bootstrap-select').find('.selectpicker').selectpicker('toggle'); + filter_index = 0; + } else if (code==13 || code==32) { + $(this).trigger('click'); + } else if (code==40) { + //console.log($(this).closest('ul.dropdown-menu').find('li.active').index()); + //$(this).closest("ul.dropdown-menu").scrollTop = ($(this).closest('ul.dropdown-menu').find('li.active').index())*32; + } + }); + + $(document).on('click', '.resource-select-wrapper .bootstrap-select .dropdown-toggle', function(e){ + $(this).next('.dropdown-menu').toggleClass('open'); + $(this).next('.dropdown-menu').toggleClass('show'); + $(this).next('.dropdown-menu').find('.inner').toggleClass('open'); + $(this).next('.dropdown-menu').find('.inner').toggleClass('show'); + }); + + document.addEventListener('click', (event) => { + if (!$(event.target).hasClass('dropdown-item') + && !$(event.target).hasClass('dropdown-toggle') + && !$(event.target).hasClass('filter-option-inner-inner')){ + if ($(".resource-select-wrapper .dropdown-menu").hasClass('show')){ + $(".resource-select-wrapper .dropdown-menu").removeClass('show'); + } + } + }, true); + + // Print resource list + if ($('#oer_print_resource_list').length){ + $(document).on('click','#oer_print_resource_list', function(e){ + e.preventDefault(); + var keyword, gradeLevel, product, filter=''; + if ($('.resource-search-filters #keyword').val()!=='') + keyword = $('.resource-search-filters #keyword').val(); + let grades = $('.resource-search-filters #gradeLevel').val(); + if (typeof grades != 'undefined' && grades.length>0) + gradeLevel = $('.resource-search-filters #gradeLevel').val(); + let products = $('.resource-search-filters #product').val(); + if (typeof products != 'undefined' && products.length>0) + product = $('.resource-search-filters #product').val(); + var res_url = window.location.href; + if (keyword){ + console.log(keyword); + filter += '&keyword='+keyword; + } + if (gradeLevel){ + if (Array.isArray(gradeLevel)){ + gradeLevel = gradeLevel.join(","); + } + filter += '&gradelevel='+gradeLevel; + } + if (product){ + console.log(product); + filter += '&product='+product; + } + var printWindow = window.open(res_url+'?action=print&view=list'+filter,'printWindow'); + setTimeout(function(){ + printWindow.print(); + printWindow.onafterprint = printWindow.close; + },500); + }); + $(document).on('keydown','#oer_print_resource_list', function(e){ + var code = e.keyCode || e.which; + if (code==32 || code==13){ + $(this).trigger('click'); + } + }); + } + + // Print resource table + if ($('#oer_print_resource_table').length){ + $(document).on('click','#oer_print_resource_table', function(e){ + e.preventDefault(); + var keyword, gradeLevel, product, filter=''; + if ($('.resource-search-filters #keyword').val()!=='') + keyword = $('.resource-search-filters #keyword').val(); + let grades = $('.resource-search-filters #gradeLevel').val(); + if (typeof grades != 'undefined' && grades.length>0) + gradeLevel = $('.resource-search-filters #gradeLevel').val(); + let products = $('.resource-search-filters #product').val(); + if (typeof products != 'undefined' && products.length>0) + product = $('.resource-search-filters #product').val(); + var res_url = window.location.href; + if (keyword){ + console.log(keyword); + filter += '&keyword='+keyword; + } + if (gradeLevel){ + if (Array.isArray(gradeLevel)){ + gradeLevel = gradeLevel.join(","); + } + filter += '&gradelevel='+gradeLevel; + } + if (product){ + filter += '&product='+product; + } + var res_url = window.location.href; + var printWindow = window.open(res_url+'?action=print&view=table'+filter,'printWindow'); + setTimeout(function(){ + printWindow.print(); + printWindow.onafterprint = printWindow.close; + },500); + }); + $(document).on('keydown','#oer_print_resource_table', function(e){ + var code = e.keyCode || e.which; + if (code==32 || code==13){ + $(this).trigger('click'); + } + }); + } + + /** Move Resource Featured Image below description on small devices **/ + window.addEventListener("resize", moveResourceImage); + + moveResourceImage(); +}); \ No newline at end of file diff --git a/oer_template/archive-resource.php b/oer_template/archive-resource.php index 4d8b9637..8d24610b 100644 --- a/oer_template/archive-resource.php +++ b/oer_template/archive-resource.php @@ -2,7 +2,9 @@ /* * Template Name: Default Archive Resource Template */ - +global $_products; +$printable = false; +$params = []; add_filter( 'body_class','oer_archive_body_classes' ); function oer_archive_body_classes( $classes ) { @@ -10,45 +12,407 @@ function oer_archive_body_classes( $classes ) { return $classes; } + +$allowed_tags = oer_allowed_html(); + +wp_register_script( "resources-script", OER_URL."js/resources.js" ); +wp_enqueue_script( "resources-script" ); +wp_localize_script( "resources-script" , "resources", array("ajaxurl" => admin_url( 'admin-ajax.php' ), "plugin_url" => OER_URL)); +wp_enqueue_style( "resources-style", OER_URL."css/resources.css" ); + get_header(); + +$filter_enabled = empty(get_option('oer_enable_search_filters'))?false:true; +$print_enabled = empty(get_option('oer_enable_print_buttons'))?false:true; + +if (isset($_GET['action']) && $_GET['action']=='print'){ + $printable = true; +} else { + $printable = false; +} + +if (!$printable){ ?>
    -
    -

    ' .post_type_archive_title('', false).'' );?>

    -
    +
    +

    +
    +
    + +
    + +
    + + +
    + +
    +
    +

    +
    +
    +
    +
    + + +
    +
    +
    + +
    +
    +
    + 'resource-grade-level','hide_empty'=>false]); + ?> +
    + +
    +
    +
    + +
    +
    +
    + + +
    +
    + + +
    + +
    + + + +
    - - + -
    +
    - '; - }?> + $col = 'col-md-2'; + echo '
    '.esc_html(get_the_title($post->ID)).' image
    '; + } + $content_col = 'col-md-10'; + + $resource_atts = ""; + ?> -
    -

    - -
    +
    +

    +
    + ID, 'oer_datecreated')[0])): + $resource_atts .= ''.esc_html(get_post_meta($post->ID, 'oer_datecreated')[0]).''; + endif; ?> + ID,'oer_lrtype')[0])): + if (!empty($resource_atts)) + $resource_atts .= ' | '.ucfirst(get_post_meta($post->ID, 'oer_lrtype')[0]).''; + else + $resource_atts .= ''.ucfirst(get_post_meta($post->ID, 'oer_lrtype')[0]).''; + endif; + echo $resource_atts; + ?> +
    - + ID); + $excerpt = oer_get_limited_excerpt($excerpt,150); + echo esc_html(ucfirst($excerpt)); + ?> +
    + ID, 'resource-grade-level' ); + + if (is_array($grade_terms)){ + foreach($grade_terms as $grade){ + $grades[] = $grade->name; + } + } + if (!empty($grades) && oer_grade_levels($grades)!="N/A"): + ?> +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +

    +
    + +
    +

    +
    +
    + + +
    +
    +
    + +
    +
    +
    + + 0 ) : ?> +
    +

    +
    + + + + + + + + + + + + + + +
    + '; + } + + $content_col = 'col-md-10'; + + $resource_atts = ""; + ?> + +
    +

    ID); ?>

    +
    + ID, 'oer_datecreated')[0])): + $resource_atts .= ''.esc_html(get_post_meta($resource->ID, 'oer_datecreated')[0]).''; + endif; ?> + ID,'oer_lrtype')[0])): + if (!empty($resource_atts)) + $resource_atts .= ' | '.ucfirst(get_post_meta($resource->ID, 'oer_lrtype')[0]).''; + else + $resource_atts .= ''.ucfirst(get_post_meta($resource->ID, 'oer_lrtype')[0]).''; + endif; + echo $resource_atts; + ?> +
    + +
    + ID); + $excerpt = oer_get_limited_excerpt($excerpt,150); + echo esc_html(ucfirst($excerpt)); + ?> +
    + ID, 'resource-grade-level' ); + + if (is_array($grade_terms)){ + foreach($grade_terms as $grade){ + $grades[] = $grade->name; + } + } + if (!empty($grades) && oer_grade_levels($grades)!="N/A"): + ?> +
    + +
    + +
    + +
    + +
    +
    +

    +
    + +
    +

    +
    +
    + + +
    +
    +
    + +
    +
    +
    + + 0 ) : ?> + +
    +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ThumbnailTitleDate CreatedResource TypeDescriptionGrade LevelLink
    + ID) ) {?> + + '.__('Resource Screenshot: ').esc_html(get_the_title($resource->ID)).' image'; + } + + $content_col = 'col-md-10'; + + $resource_atts = ""; + ?> + ID); ?>ID, 'oer_datecreated')[0])) + echo esc_html(get_post_meta($resource->ID, 'oer_datecreated')[0]); + ?>ID, 'oer_lrtype')[0]); ?>ID); + $excerpt = oer_get_limited_excerpt($excerpt,150); + echo esc_html(ucfirst($excerpt)); + ?> + + ID, 'resource-grade-level' ); + + if (is_array($grade_terms)){ + foreach($grade_terms as $grade){ + $grades[] = $grade->name; + } + } + echo oer_grade_levels($grades); + ?> +
    @@ -64,4 +428,6 @@ function oer_archive_body_classes( $classes ) {
    + \ No newline at end of file diff --git a/oer_template/search.php b/oer_template/search.php index 14624091..cd3d9989 100644 --- a/oer_template/search.php +++ b/oer_template/search.php @@ -7,7 +7,8 @@ * @since Twenty Sixteen 1.0 */ -get_header(); ?> +get_header(); +?>
    diff --git a/oer_template/single-resource.php b/oer_template/single-resource.php index d47b8527..63ba5bbd 100644 --- a/oer_template/single-resource.php +++ b/oer_template/single-resource.php @@ -237,6 +237,7 @@ function oer_display_default_thumbnail($post){ $root_path = oer_get_root_path(); + $media_type = null; $html = ''; $img_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) , "full" ); @@ -247,7 +248,9 @@ function oer_display_default_thumbnail($post){ $img_width = oer_get_image_width('large'); $img_height = oer_get_image_height('large'); } - $media_type = get_post_meta($post->ID,"oer_mediatype")[0]; + if (get_post_meta($post->ID,"oer_mediatype")){ + $media_type = get_post_meta($post->ID,"oer_mediatype")[0]; + } if(!empty($img_url)) { diff --git a/open-educational-resources.php b/open-educational-resources.php index 43cbf9c5..e2c8e0da 100644 --- a/open-educational-resources.php +++ b/open-educational-resources.php @@ -3,8 +3,8 @@ Plugin Name: WP OER Plugin URI: https://www.wp-oer.com Description: Open Educational Resource management and curation, metadata publishing, and alignment to Common Core State Standards. - Version: 0.9.2 - Requires at least: 4.4 + Version: 0.9.3 + Requires at least: 5.0 Requires PHP: 7.0 Author: Navigation North Author URI: https://www.navigationnorth.com @@ -38,7 +38,7 @@ // Plugin Name and Version define( 'OER_PLUGIN_NAME', 'WP OER Plugin' ); define( 'OER_ADMIN_PLUGIN_NAME', 'WP OER Plugin'); -define( 'OER_VERSION', '0.9.2' ); +define( 'OER_VERSION', '0.9.3' ); define( 'OER_SITE_PATH', ABSPATH ); include_once(OER_PATH.'includes/oer-functions.php'); @@ -51,7 +51,36 @@ include_once(OER_PATH.'widgets/class-subject-area-widget.php'); //define global variable $debug_mode and get value from settings -global $_debug, $_bootstrap, $_fontawesome, $_css, $_css_oer, $_subjectarea, $_search_post_ids, $_w_bootstrap, $_oer_prefix, $oer_session, $_gutenberg, $_use_gutenberg; +global $_debug, $_bootstrap, $_fontawesome, $_css, $_css_oer, $_subjectarea, $_search_post_ids, $_w_bootstrap, $_oer_prefix, $oer_session, $_gutenberg, $_use_gutenberg, $_resources_path, $_products; + +// Product Types +$_products = [ + [ "value" => "Article/Information", "label" => "Article/Information"], + [ "value" => "Assessment", "label" => "Assessment"], + [ "value" => "Audio", "label" => "Audio"], + [ "value" => "Blog", "label" => "Blog" ], + [ "value" => "Calculator", "label" => "Calculator" ], + [ "value" => "Curriculum", "label" => "Curriculum" ], + [ "value" => "Demonstration", "label" => "Demonstration" ], + [ "value" => "Game", "label" => "Game" ], + [ "value" => "Fact Sheet", "label" => "Fact Sheet" ], + [ "value" => "Framework", "label" => "Framework" ], + [ "value" => "Instructional Material", "label" => "Instructional Material" ], + [ "value" => "Interview", "label" => "Interview" ], + [ "value" => "Lecture", "label" => "Lecture" ], + [ "value" => "Lesson Plan", "label" => "Lesson Plan" ], + [ "value" => "Online Course", "label" => "Online Course" ], + [ "value" => "Podcast", "label" => "Podcast" ], + [ "value" => "Presentation", "label" => "Presentation" ], + [ "value" => "Publication", "label" => "Publication" ], + [ "value" => "Research/Evaluation Report", "label" => "Research/Evaluation Report" ], + [ "value" => "Simulation", "label" => "Simulation" ], + [ "value" => "Video", "label" => "Video" ], + [ "value" => "Website", "label" => "Website" ], + [ "value" => "Other", "label" => "Other" ] +]; + +$_resources_path = get_option('oer_configurable_resource_path'); if( ! defined( 'WP_SESSION_COOKIE' ) ) define( 'WP_SESSION_COOKIE', '_oer_session' ); @@ -146,6 +175,10 @@ function oer_create_csv_import_table() update_option( "oer_rewrite_rules", false ); update_option('oer_metadata_firstload', true); update_option('oer_setup', true); + // enable bootstrap by default + update_option('oer_use_bootstrap', true); + // enable fontawesome by default as it is used by the subjects index block + update_option('oer_use_fontawesome', true); //Trigger CPT and Taxonomy creation oer_postcreation(); @@ -560,15 +593,38 @@ function oer_get_default_category_icon($category_name, $hover = false) { add_action('wp_enqueue_scripts', 'oer_front_scripts'); function oer_front_scripts() { - global $_bootstrap, $_fontawesome; - + global $_bootstrap, $_fontawesome, $wp_scripts, $wp_styles; + $bootstrap_enqueued = FALSE; + $fontawesome_enqueued = FALSE; if ($_bootstrap) { - wp_enqueue_style('bootstrap-style', OER_URL.'css/bootstrap.min.css'); - wp_enqueue_script('bootstrap-script', OER_URL.'js/bootstrap.min.js'); + foreach( $wp_scripts->registered as $script ) { + if ((stristr($script->src, 'bootstrap.min.js') !== FALSE or + stristr($script->src, 'bootstrap.js') != FALSE) and + wp_script_is($script->handle, $list = 'enqueued')) { + + $bootstrap_enqueued = TRUE; + break; + } + } + if (!$bootstrap_enqueued){ + wp_enqueue_style('bootstrap-style', OER_URL.'css/bootstrap.min.css'); + wp_enqueue_script('bootstrap-script', OER_URL.'js/bootstrap.min.js'); + } } if ($_fontawesome) { - wp_enqueue_style('fontawesome-style', OER_URL.'css/fontawesome.css'); + foreach( $wp_styles->registered as $style ) { + //var_dump($style); + if ((stristr($style->src, 'fontawesome') !== FALSE or + stristr($style->src, 'font-awesome') != FALSE) and + wp_style_is($style->handle, $list = 'enqueued')) { + $fontawesome_enqueued = TRUE; + break; + } + } + if (!$fontawesome_enqueued){ + wp_enqueue_style('fontawesome-style', OER_URL.'css/fontawesome.css'); + } } } @@ -748,6 +804,92 @@ function oer_settings_page() { ) ); + // Add configurable path section + add_settings_section( + 'oer_configurable_path', + '', + 'oer_path_settings_field_callback', + 'configurable_path_setings' + ); + + // Add configurable path option + add_settings_field( + 'oer_configurable_resource_path', + '', + 'oer_setup_settings_field', + 'configurable_path_setings', + 'oer_configurable_path', + array( + 'uid' => 'oer_configurable_resource_path', + 'type' => 'textbox', + 'class' => 'oer-configurable-resource-path', + 'title' => __( 'Path: ' , OER_SLUG ), + 'description' => __('Enter the relative URL of the resources page without a leading slash(/). (ie. resources)', OER_SLUG) + ) + ); + + //Add Settings field for Resources Page Title + add_settings_field( + 'oer_resources_page_title', + '', + 'oer_setup_settings_field', + 'configurable_path_setings', + 'oer_configurable_path', + array( + 'uid' => 'oer_resources_page_title', + 'type' => 'textbox', + 'class' => 'oer-resources-title', + 'title' => __( 'Title: ', OER_SLUG), + 'description' => __('Enter the title of the resources page.', OER_SLUG) + ) + ); + + //Add Settings field for Resources Page Content + add_settings_field( + 'oer_resources_content', + '', + 'oer_wysiwyg_field', + 'configurable_path_setings', + 'oer_configurable_path', + array( + 'uid' => 'oer_resources_content', + 'type' => 'wysiwyg', + 'class' => 'oer-resources-content bottom-margin', + 'name' => __( 'Content: ', OER_SLUG), + 'description' => __('Enter global resources page content here.', OER_SLUG) + ) + ); + + // Add Enable filter option + add_settings_field( + 'oer_enable_search_filters', + '', + 'oer_setup_settings_field', + 'configurable_path_setings', + 'oer_configurable_path', + array( + 'uid' => 'oer_enable_search_filters', + 'type' => 'checkbox', + 'class' => 'oer-enable-search-filters', + 'name' => __( 'Enable search filter' , OER_SLUG ) + ) + ); + + // Add Enable Print Buttons option + add_settings_field( + 'oer_enable_print_buttons', + '', + 'oer_setup_settings_field', + 'configurable_path_setings', + 'oer_configurable_path', + array( + 'uid' => 'oer_enable_print_buttons', + 'type' => 'checkbox', + 'class' => 'oer-enable-print-buttons', + 'name' => __( 'Enable print buttons' , OER_SLUG ) + ) + ); + register_setting( 'oer_general_settings' , 'oer_disable_screenshots' ); register_setting( 'oer_general_settings' , 'oer_enable_screenshot' ); register_setting( 'oer_general_settings' , 'oer_use_xvfb' ); @@ -755,6 +897,12 @@ function oer_settings_page() { register_setting( 'oer_general_settings' , 'oer_python_install' ); register_setting( 'oer_general_settings' , 'oer_external_screenshots' ); register_setting( 'oer_general_settings' , 'oer_service_url' ); + //register_setting( 'oer_general_settings' , 'oer_nalrc_resource_notice' ); + register_setting( 'oer_general_settings' , 'oer_configurable_resource_path' ); + register_setting( 'oer_general_settings' , 'oer_resources_page_title' ); + register_setting( 'oer_general_settings' , 'oer_resources_content' ); + register_setting( 'oer_general_settings' , 'oer_enable_search_filters' ); + register_setting( 'oer_general_settings' , 'oer_enable_print_buttons' ); } //General settings callback @@ -766,9 +914,21 @@ function oer_embed_settings_callback(){ } +function oer_notice_settings_callback() { + +} + +function oer_path_settings_field_callback() { + +} + + //Initialize Style Settings Tab add_action( 'admin_init' , 'oer_styles_settings' ); function oer_styles_settings(){ + $singular = "Subject Area"; + $plural = "Subject Areas"; + $label = "Subjects"; //Create Styles Section add_settings_section( @@ -806,8 +966,8 @@ function oer_styles_settings(){ 'type' => 'checkbox', 'value' => '1', 'default' => true, - 'name' => __('Display Subjects menu on Subject Area pages', OER_SLUG), - 'description' => __('Lists all subject areas in the left column of Subject Area pages—may conflict with themes using left navigation.', OER_SLUG) + 'name' => __('Display '.$label.' menu on '.$singular.' pages', OER_SLUG), + 'description' => __('Lists all '.strtolower($plural).' in the left column of '.$singular.' pages—may conflict with themes using left navigation.', OER_SLUG) ) ); @@ -838,7 +998,7 @@ function oer_styles_settings(){ 'uid' => 'oer_hide_subject_area_title', 'type' => 'checkbox', 'value' => '1', - 'name' => __('Subject Area pages', OER_SLUG), + 'name' => __($singular.' pages', OER_SLUG), 'pre_html' => __('

    Hide Page Titles

    Some themes have a built-in display of page titles.

    ', OER_SLUG)) ); @@ -940,6 +1100,7 @@ function oer_setup_settings(){ ); //Add Settings field for Import Default Subject Areas + $import_subject_label = "Subject Areas"; add_settings_field( 'oer_import_default_subject_areas', '', @@ -951,8 +1112,8 @@ function oer_setup_settings(){ 'type' => 'checkbox', 'value' => '1', 'default' => true, - 'name' => __('Import Default Subject Areas', OER_SLUG), - 'description' => __('A general listing of the most common subject areas.', OER_SLUG) + 'name' => __('Import Default '.$import_subject_label, OER_SLUG), + 'description' => __('A general listing of the most common '.strtolower($import_subject_label).'.', OER_SLUG) ) ); @@ -1220,9 +1381,9 @@ function oer_setup_settings_field( $arguments ) { $class = ""; $disabled = ""; $allowed_tags = oer_allowed_html(); - + $value = get_option($arguments['uid']); - + if (isset($arguments['indent'])){ echo '
    '; } @@ -1241,7 +1402,9 @@ function oer_setup_settings_field( $arguments ) { $size = 'size="50"'; if (isset($arguments['title'])) $title = $arguments['title']; - echo ''; + if ($title) + echo ''; + echo ''; break; case "checkbox": $display_value = ""; @@ -1249,7 +1412,7 @@ function oer_setup_settings_field( $arguments ) { if ($value=="1" || $value=="on"){ $selected = "checked='checked'"; - $display_value = "value='1'"; + $display_value = "value=1"; } elseif ($value===false){ $selected = ""; if (isset($arguments['default'])) { @@ -1265,7 +1428,7 @@ function oer_setup_settings_field( $arguments ) { if ($arguments['disabled']==true) $disabled = " disabled"; } - + echo ''; break; case "select": @@ -1334,6 +1497,30 @@ function oer_setup_settings_field( $arguments ) { } } +function oer_wysiwyg_field( $arguments ) { + $class = ""; + + $value = get_option($arguments['uid']); + + if (isset($arguments['class'])) { + $class = $arguments['class']; + $class = " class='".$class."' "; + } + + echo ''; + + echo wp_editor( $value, $arguments['uid'], array('textarea_name' => $arguments['uid'], 'textarea_rows' => 10) ); + + //Show Description if specified + if( isset($arguments['description']) ){ + printf( '

    %s

    ', $arguments['description'] ); + } + +} + function oer_setup_radio_field($arguments){ $class=""; @@ -1349,9 +1536,10 @@ function oer_setup_radio_field($arguments){ /** Initialize Subject Area Sidebar widget **/ function oer_widgets_init() { - + $label = "Subject Area"; + register_sidebar( array( - 'name' => 'Subject Area Sidebar', + 'name' => $label.' Sidebar', 'id' => 'subject_area_sidebar', 'before_widget' => '
    ', 'after_widget' => '
    ', @@ -1368,7 +1556,11 @@ function oer_add_body_class($classes) { $cur_theme = wp_get_theme(); $theme_class = $cur_theme->get('Name'); - return array_merge( $classes, array( str_replace( ' ', '-', strtolower($theme_class) ) ) ); + if (isset($_GET['action']) && $_GET['action']=='print'){ + return array_merge( $classes, array( str_replace( ' ', '-', strtolower($theme_class) ) , 'print-preview' ) ); + } else { + return array_merge( $classes, array( str_replace( ' ', '-', strtolower($theme_class) ) ) ); + } } /* Ajax Callback */ @@ -2142,26 +2334,25 @@ function oer_custom_query($search, $wp_query){ $q = $wp_query->query_vars; $n = !empty($q['exact']) ? '' : '%'; - $search = $searchand = ''; + $search_str = $searchand = ''; $terms_relation_type = 'OR'; //Checks each term foreach ((array)$q['search_terms'] as $term ) { - $term = $n . $wpdb->esc_like( $term ) . $n; $OR = ''; - $search .= "{$searchand} ("; + $search_str .= "{$searchand} ("; //Search in title - $search .= $wpdb->prepare("($wpdb->posts.post_title LIKE %s)", $term); - $OR = ' OR '; + $search_str .= $wpdb->remove_placeholder_escape($wpdb->prepare("($wpdb->posts.post_title LIKE %s)", $term)); + $OR = ' OR '; //Search in content - $search .= $OR; - $search .= $wpdb->prepare("($wpdb->posts.post_content LIKE %s)", $term); - $OR = ' OR '; + $search_str .= $OR; + $search_str .= $wpdb->remove_placeholder_escape($wpdb->prepare("($wpdb->posts.post_content LIKE %s)", $term)); + $OR = ' OR '; //Search by meta keys $meta_keys = array( @@ -2180,39 +2371,42 @@ function oer_custom_query($search, $wp_query){ 'oer_publisheremail', 'oer_publishername', 'oer_publisherurl', - 'oer_resourceurl', + //'oer_resourceurl', 'oer_standard', 'oer_standard_alignment', 'oer_userightsurl' ); $meta_key_OR = ''; + foreach ($meta_keys as $key_slug) { - $search .= $OR; - $search .= $wpdb->prepare("$meta_key_OR (pm.meta_key = %s AND pm.meta_value LIKE %s)", $key_slug, $term); - $OR = ''; - $meta_key_OR = ' OR '; - } + $search_str .= $OR; + $search_str .= $wpdb->remove_placeholder_escape($wpdb->prepare("$meta_key_OR (pm.meta_key = %s AND pm.meta_value LIKE %s)", $key_slug, $term)); + $OR = ''; + $meta_key_OR = ' OR '; + } $OR = ' OR '; //Search By Taxonomy $taxonomies = array("post_tag","resource-subject-area"); + $tax_OR = ''; + foreach($taxonomies as $tax) { - $search .= $OR; - $search .= $wpdb->prepare("$tax_OR (tt.taxonomy = %s AND t.name LIKE %s)", $tax, $term); - $OR = ''; - $tax_OR = ' OR '; + $search_str .= $OR; + $search_str .= $wpdb->remove_placeholder_escape($wpdb->prepare("$tax_OR (tt.taxonomy = %s AND t.name LIKE %s)", $tax, $term)); + $OR = ''; + $tax_OR = ' OR '; } - $search .= ")"; + $search_str .= ")"; $searchand = " $terms_relation_type "; } - if ( ! empty( $search ) ) { - $search = " AND ({$search}) "; + if ( ! empty( $search_str ) ) { + $search = " AND ({$search_str}) "; } add_filter('posts_join_request', 'oer_join_table'); @@ -2232,8 +2426,8 @@ function oer_join_table($join){ // Taxomomies join $join .= " LEFT JOIN $wpdb->term_relationships tr ON ($wpdb->posts.ID = tr.object_id) "; - $join .= " LEFT JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) "; - $join .= " LEFT JOIN $wpdb->terms t ON (tt.term_id = t.term_id) "; + $join .= " LEFT JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) "; + $join .= " LEFT JOIN $wpdb->terms t ON (tt.term_id = t.term_id) "; return $join; } @@ -2252,8 +2446,10 @@ function oer_resource_taxonomy_queries( $query ) { } add_action( 'pre_get_posts', 'oer_resource_taxonomy_queries' ); + function oer_custom_search_template($template){ global $wp_query; + if (!$wp_query->is_search) return $template; @@ -2333,6 +2529,7 @@ function oer_add_rewrites() add_rewrite_endpoint( 'substandard', EP_PERMALINK | EP_PAGES ); add_rewrite_endpoint( 'notation', EP_PERMALINK | EP_PAGES ); + $flush_rewrite = get_option('oer_rewrite_rules'); if ($flush_rewrite==false) { $wp_rewrite->init(); @@ -2521,4 +2718,213 @@ function oer_get_root_path() { } return $root_path; +} + +/** Change Tags Label to Keywords for NALRC **/ +function oer_change_tags_labels( $args, $taxonomy ) { + + if ( 'post_tag' === $taxonomy ) { + $args['labels'] = array( + 'name' => esc_html__( 'Educational Tags', OER_SLUG), + 'singular_name' => esc_html__( 'Educational Tag', OER_SLUG ), + 'menu_name' => esc_html__( 'Educational Tags', OER_SLUG ), + 'all_items' => esc_html__( 'All Educational Tags', OER_SLUG ), + 'search_items' => esc_html__( 'Search Educational Tags',OER_SLUG ), + 'add_new_item' => esc_html__( 'Add New Educational Tag', OER_SLUG), + 'edit_item' => esc_html__( 'Edit Educational Tag', OER_SLUG ), + 'update_item' => esc_html__( 'Update Educational Tag', OER_SLUG ), + 'parent_item' => esc_html__( 'Parent Educational Tag',OER_SLUG ), + 'parent_item_colon' => esc_html__( 'Parent Educational Tag:',OER_SLUG ), + 'new_item_name' => esc_html__( 'New Educational Tag',OER_SLUG), + ); + } + + return $args; +} +//add_filter( 'register_taxonomy_args', 'oer_change_tags_labels', 10, 2 ); + +function oer_search_resources(){ + global $wpdb, $oer_session; + $resources = array(); + $resource2 = array(); + $args = array( + 'post_type' => 'resource', + 'post_status' => 'publish', + 'numberposts' => -1, + ); + + $root_path = oer_get_root_path(); + + if (!isset($oer_session)) + $oer_session = OER_WP_Session::get_instance(); + + + try { + // Search by Topic area + if (isset($_POST['gradeLevel'])){ + if (!empty($_POST['gradeLevel'][0])){ + if (!is_array($_POST['gradeLevel'])) + $grades = explode(",",sanitize_text_field($_POST['gradeLevel'])); + else + $grades = array_map('sanitize_text_field',$_POST['gradeLevel']); + $args['tax_query'] = array( + array( + 'taxonomy' => 'resource-grade-level', + 'field' => 'term_id', + 'terms' => $grades + ) + ); + } + } + + // Search by Product Type + if (isset($_POST['product']) && $_POST['product']!==""){ + $args['meta_query'] = array( + array( + 'key' => 'oer_lrtype', + 'value' => array_map('sanitize_text_field',$_POST['product']) + ) + ); + } + + // Search title, description, and tags + if (isset($_POST['keyword']) && $_POST['keyword']!==""){ + for ($i=0;$i<2;$i++){ + if ($i == 0 ){ + $args['s'] = sanitize_text_field($_POST['keyword']); + $resources = get_posts($args); + } else { + if (isset($args['s'])) + unset($args['s']); + $args['tag'] = sanitize_text_field($_POST['keyword']); + $resources2 = get_posts($args); + } + } + $resources = array_merge($resources, $resources2); + } else { + $resources = get_posts($args); + } + + foreach($resources as $resource){ + $resource_atts = ""; + ?> +
    '; + } + ?> + +
    +

    ID)); ?>

    +
    + ID, 'oer_datecreated')[0])): + $resource_atts .= ''.esc_html(get_post_meta($resource->ID, 'oer_datecreated')[0]).''; + endif; ?> + ID,'oer_lrtype')[0])): + if (!empty($resource_atts)) + $resource_atts .= ' | '.ucfirst(get_post_meta($resource->ID, 'oer_lrtype')[0]).''; + else + $resource_atts .= ''.ucfirst(get_post_meta($resource->ID, 'oer_lrtype')[0]).''; + endif; + echo wp_kses_post($resource_atts); + ?> +
    + +
    + ID); + $excerpt = oer_get_limited_excerpt($excerpt,150); + echo esc_html(ucfirst($excerpt)); + ?> +
    + ID, 'resource-grade-level' ); + + if (is_array($grade_terms)){ + foreach($grade_terms as $grade){ + $grades[] = $grade->name; + } + } + if (!empty($grades) && oer_grade_levels($grades)!="N/A"): + ?> +
    + +
    + +
    +
    + getMessage(); + } + die(); +} +add_action('wp_ajax_search_resources', 'oer_search_resources'); +add_action('wp_ajax_nopriv_search_resources', 'oer_search_resources'); + +function oer_filter_resources($params){ + $grades = null; + $products = null; + $args = array( + 'post_type' => 'resource', + 'post_status' => 'publish', + 'numberposts' => -1, + ); + + // Search by Topic area + if (isset($params['gradelevel'])){ + if (!is_array($params['gradelevel'])) + $grades = explode(",",sanitize_text_field($params['gradelevel'])); + else + $grades = array_map('sanitize_text_field',$params['gradelevel']); + $args['tax_query'] = array( + array( + 'taxonomy' => 'resource-grade-level', + 'field' => 'term_id', + 'terms' => $grades + ) + ); + } + + // Search by Product Type + if (isset($params['product'])){ + if (!is_array($params['product'])) + $products = explode(",",sanitize_text_field($params['product'])); + else + $products = array_map('sanitize_text_field',$params['product']); + $args['meta_query'] = array( + array( + 'key' => 'oer_lrtype', + 'value' => $products + ) + ); + } + + // Search title, description, and tags + if (isset($params['keyword'])){ + for ($i=0;$i<2;$i++){ + if ($i == 0 ){ + $args['s'] = sanitize_text_field($params['keyword']); + $resources = get_posts($args); + } else { + if (isset($args['s'])) + unset($args['s']); + $args['tag'] = sanitize_text_field($params['keyword']); + $resources2 = get_posts($args); + } + } + $resources = array_merge($resources, $resources2); + } else { + $resources = get_posts($args); + } + return $resources; } \ No newline at end of file diff --git a/readme.txt b/readme.txt index 34b6ea71..a3f10a7d 100644 --- a/readme.txt +++ b/readme.txt @@ -1,10 +1,10 @@ === WP OER === Contributors: navigationnorth, joehobson, johnpaulbalagolan, josepheneldas, arobotnamedchris Tags: OER, Open Educational Resources, Education, Teaching, Learning -Requires at least: 4.4 -Tested up to: 6.0.2 +Requires at least: 5.0 +Tested up to: 6.2 Requires PHP: 7.0 -Stable tag: 0.9.2 +Stable tag: 0.9.3 License: GPLv3 License URI: https://www.gnu.org/licenses/gpl-3.0.html @@ -41,6 +41,17 @@ No frequently asked questions. 3. Display educational resources on your WordPress website! == Changelog == += 0.9.3 = +* Converted Grade Level field into a taxonomy +* Updated import resources to create a new grade level if not existing +* Added search function to the resources page +* Added function to print resources in a list or table format +* Added path, title, content, enable search filter, and enable print function setting for the Resources page in plugin options +* Enabled FontAwesome and Bootstrap library by default +* PHP 8.1 compatibility +* Block compatibility fixes with WP 6.2 +* Tested up to WP 6.2 + = 0.9.2 = * Fixed the overlapping text on the settings and import pages including the standard list display * Fixed the Resource Block display error when the resource has no selected subject areas diff --git a/samples/resource_import_sample_data.xls b/samples/resource_import_sample_data.xls index 551c510b..a3cdc4e2 100644 Binary files a/samples/resource_import_sample_data.xls and b/samples/resource_import_sample_data.xls differ