From b88e4c78b7b460fd784fa36d99f371d3153b490d Mon Sep 17 00:00:00 2001 From: Mark Johnson Date: Wed, 21 Jan 2026 15:03:49 +0000 Subject: [PATCH] MDL-87264 questions: Add category route --- .upgradenotes/MDL-87264-2026012116303057.yml | 7 + .../amd/build/category.min.js | 2 +- .../amd/build/category.min.js.map | 2 +- .../bank/managecategories/amd/src/category.js | 315 +++++++++++++----- public/question/classes/question_category.php | 89 +++++ public/question/classes/route/api/bank.php | 54 +++ 6 files changed, 386 insertions(+), 83 deletions(-) create mode 100644 .upgradenotes/MDL-87264-2026012116303057.yml create mode 100644 public/question/classes/question_category.php diff --git a/.upgradenotes/MDL-87264-2026012116303057.yml b/.upgradenotes/MDL-87264-2026012116303057.yml new file mode 100644 index 00000000000..75e6faadd91 --- /dev/null +++ b/.upgradenotes/MDL-87264-2026012116303057.yml @@ -0,0 +1,7 @@ +issueNumber: MDL-87264 +notes: + core_question: + - message: >- + Added a new route at `/api/rest/v2/question/categories` for returning a + list of question categories in a particular course module. + type: improved diff --git a/public/question/bank/managecategories/amd/build/category.min.js b/public/question/bank/managecategories/amd/build/category.min.js index 63c870467ac..00f460f7c4c 100644 --- a/public/question/bank/managecategories/amd/build/category.min.js +++ b/public/question/bank/managecategories/amd/build/category.min.js @@ -1,3 +1,3 @@ -define("qbank_managecategories/category",["exports","core/reactive","qbank_managecategories/categorymanager","core/templates","core/modal","core/str","core/local/inplace_editable/events"],(function(_exports,_reactive,_categorymanager,_templates,_modal,_str,_events){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_templates=_interopRequireDefault(_templates),_modal=_interopRequireDefault(_modal);class _default extends _reactive.BaseComponent{create(descriptor){this.name=descriptor.element.id,this.selectors={CATEGORY_LIST:".qbank_managecategories-categorylist",CATEGORY_ITEM:".qbank_managecategories-item[data-categoryid]",CATEGORY_CONTENTS:".qbank_managecategories-item > .container",EDIT_BUTTON:'[data-action="addeditcategory"]',EDITABLE_CATEGORY_NAME:'.inplaceeditable[data-itemtype="categoryname"]',MOVE_BUTTON:'[role="menuitem"][data-actiontype="move"]',CONTEXT:".qbank_managecategories-categorylist[data-contextid]",MODAL_CATEGORY_ITEM:".modal_category_item[data-movingcategoryid]",CONTENT_AREA:".qbank_managecategories-details",CATEGORY_ID:id=>"#category-".concat(id),CONTENT_CONTAINER:id=>"#category-".concat(id," .qbank_managecategories-childlistcontainer"),CHILD_LIST:id=>'ul[data-categoryid="'.concat(id,'"]'),PREVIOUS_SIBLING:sortorder=>':scope > [data-sortorder="'.concat(sortorder,'"]')},this.classes={NO_BOTTOM_PADDING:"pb-0",DRAGHANDLE:"draghandle",DROPTARGET:"qbank_managecategories-droptarget-before"},this.ids={CATEGORY:id=>"category-".concat(id)}}stateReady(){this.initDragDrop(),this.addEventListener(this.getElement(this.selectors.EDIT_BUTTON),"click",_categorymanager.categorymanager.showEditModal);const moveButton=this.getElement(this.selectors.MOVE_BUTTON);this.addEventListener(moveButton,"click",this.showMoveModal),this.addEventListener(this.getElement(),_events.eventTypes.elementUpdated,(e=>{const editable=e.target.closest(this.selectors.EDITABLE_CATEGORY_NAME);_categorymanager.categorymanager.updateCategoryName(editable.dataset.itemid,editable.dataset.value)}))}destroy(){this.deInitDragDrop()}initDragDrop(){this.deInitDragDrop(),this.element.classList.contains(this.classes.DRAGHANDLE)&&(this.getDraggableData=this._getDraggableData),this.dragdrop=new _reactive.DragDrop(this)}deInitDragDrop(){void 0!==this.dragdrop&&(void 0!==this.getDraggableData&&(this.dragdrop.setDraggable(!1),this.getDraggableData=void 0),this.dragdrop.unregister(),this.dragdrop=void 0)}static init(target,selectors){return new this({element:document.querySelector(target),selectors:selectors,reactive:_categorymanager.categorymanager})}_getDraggableData(){return{id:this.getElement().dataset.categoryid}}validateDropData(){return!0}showDropZone(dropData){return!this.getElement().closest(this.selectors.CATEGORY_ID(dropData.id))&&(this.getElement().classList.add(this.classes.DROPTARGET),!0)}hideDropZone(){this.getElement().classList.remove(this.classes.DROPTARGET)}drop(dropData,event){var _precedingSibling;const dropTarget=event.target.closest(this.selectors.CATEGORY_ITEM);if(!dropTarget)return;if(dropTarget.closest(this.selectors.CATEGORY_ID(dropData.id)))return;if(!document.getElementById(this.ids.CATEGORY(dropData.id)))return;const targetParentId=dropTarget.dataset.parent,parentList=dropTarget.closest(this.selectors.CATEGORY_LIST);let precedingSibling;precedingSibling=dropTarget===parentList.firstElementChild?null:dropTarget.previousElementSibling,_categorymanager.categorymanager.moveCategory(dropData.id,targetParentId,null===(_precedingSibling=precedingSibling)||void 0===_precedingSibling?void 0:_precedingSibling.dataset.categoryid)}getWatchers(){return[{watch:"categories[".concat(this.element.dataset.categoryid,"]:updated"),handler:this.updatePosition},{watch:"categories[".concat(this.element.dataset.categoryid,"].templatecontext:created"),handler:this.rerender},{watch:"categories[".concat(this.element.dataset.categoryid,"].templatecontext:updated"),handler:this.rerender},{watch:"categories[".concat(this.element.dataset.categoryid,"].name:updated"),handler:this.updateName},{watch:"categories:created",handler:this.checkChildList}]}async rerender(_ref){let{element:element}=_ref;const{html:html,js:js}=await _templates.default.renderForPromise("qbank_managecategories/category_details",element.templatecontext);return _templates.default.replaceNodeContents(this.getElement(this.selectors.CONTENT_AREA),html,js)}async createChildList(context){const{html:html,js:js}=await _templates.default.renderForPromise("qbank_managecategories/childlist",context),parentContainer=document.querySelector(this.selectors.CONTENT_CONTAINER(context.categoryid));await _templates.default.appendNodeContents(parentContainer,html,js);const childList=document.querySelector(this.selectors.CHILD_LIST(context.categoryid));return childList.closest(this.selectors.CATEGORY_CONTENTS).classList.add(this.classes.NO_BOTTOM_PADDING),childList}async updatePosition(_ref2){let newParent,{element:element}=_ref2;const originParent=document.querySelector(this.selectors.CHILD_LIST(this.getElement().dataset.parent));let previousSibling,nextSibling;var _previousSibling;(parseInt(this.getElement().dataset.parent)!==element.parent?(newParent=document.querySelector(this.selectors.CHILD_LIST(element.parent)),newParent||(newParent=await this.createChildList({categoryid:element.parent})),this.getElement().dataset.parent=element.parent):newParent=this.getElement().parentElement,newParent.firstElementChild&&parseInt(element.sortorder)<=parseInt(newParent.firstElementChild.dataset.sortorder))?nextSibling=newParent.firstElementChild:(previousSibling=newParent.querySelector(this.selectors.PREVIOUS_SIBLING(element.sortorder-1)),nextSibling=null===(_previousSibling=previousSibling)||void 0===_previousSibling?void 0:_previousSibling.nextElementSibling);(newParent!==this.getElement().parentElement||nextSibling!==this.getElement())&&(nextSibling?newParent.insertBefore(this.getElement(),nextSibling):newParent.appendChild(this.getElement())),originParent!==newParent&&this.reactive.stateManager.processUpdates([{name:"categoryLists",action:"put",fields:{id:originParent.dataset.categoryid,childCount:originParent.querySelectorAll(this.selectors.CATEGORY_ITEM).length}},{name:"categoryLists",action:"put",fields:{id:newParent.dataset.categoryid,childCount:newParent.querySelectorAll(this.selectors.CATEGORY_ITEM).length}}]),this.element.dataset.sortorder=element.sortorder;const isDraggable=this.element.classList.contains(this.classes.DRAGHANDLE);isDraggable&&!element.draghandle?(this.element.classList.remove(this.classes.DRAGHANDLE),this.initDragDrop()):!isDraggable&&element.draghandle&&(this.element.classList.add(this.classes.DRAGHANDLE),this.initDragDrop())}createMoveCategoryList(item,movingCategoryId){const categories=[];if(item.children){let precedingSibling=null;if(item.children.forEach((category=>{var _precedingSibling$dat,_precedingSibling2;const categoryId=parseInt(category.dataset.categoryid);if(categoryId===movingCategoryId)return;let child={categoryid:categoryId,movingcategoryid:movingCategoryId,precedingsiblingid:null!==(_precedingSibling$dat=null===(_precedingSibling2=precedingSibling)||void 0===_precedingSibling2?void 0:_precedingSibling2.dataset.categoryid)&&void 0!==_precedingSibling$dat?_precedingSibling$dat:0,parent:category.dataset.parent,categoryname:category.dataset.categoryname,categories:null,current:categoryId===movingCategoryId};const childList=category.querySelector(this.selectors.CATEGORY_LIST);child.categories=childList?this.createMoveCategoryList(childList,movingCategoryId):[{movingcategoryid:movingCategoryId,precedingsiblingid:0,parent:categoryId,categoryname:category.dataset.categoryname,categories:null,newchild:!0}],categories.push(child),precedingSibling=category})),precedingSibling){const precedingId=parseInt(precedingSibling.dataset.categoryid);precedingId!==movingCategoryId&&categories.push({movingcategoryid:movingCategoryId,precedingsiblingid:precedingId,parent:precedingSibling.dataset.parent,categoryname:precedingSibling.dataset.categoryname,categories:null,lastchild:!0})}}return categories}async showMoveModal(e){const item=e.target.closest(this.selectors.MOVE_BUTTON);if(!item)return;if("true"===item.getAttribute("aria-disabled"))return;item.setAttribute("aria-disabled",!0);let moveList={contexts:[]};document.querySelectorAll(this.selectors.CONTEXT).forEach((context=>{const moveContext={contextname:context.dataset.contextname,categories:[],hascategories:!1};moveContext.categories=this.createMoveCategoryList(context,parseInt(item.dataset.categoryid)),moveContext.hascategories=moveContext.categories.length>0,moveList.contexts.push(moveContext)}));const modal=await _modal.default.create({title:(0,_str.get_string)("movecategory","qbank_managecategories",item.dataset.categoryname),body:_templates.default.render("qbank_managecategories/move_context_list",moveList),footer:"",show:!0,large:!0});modal.getBody()[0].addEventListener("click",(e=>{const target=e.target.closest(this.selectors.MODAL_CATEGORY_ITEM);target&&(_categorymanager.categorymanager.moveCategory(target.dataset.movingcategoryid,target.dataset.parent,target.dataset.precedingsiblingid),modal.destroy())})),item.setAttribute("aria-disabled",!1)}async checkChildList(_ref3){let{element:element}=_ref3;return element.parent!==this.getElement().dataset.categoryid||this.getElement(this.selectors.CATEGORY_LIST)?null:this.createChildList({categoryid:element.parent,children:[element.templatecontext]})}updateName(_ref4){let{element:element}=_ref4;this.getElement().dataset.categoryname=element.name}}return _exports.default=_default,_exports.default})); +define("qbank_managecategories/category",["exports","core/reactive","qbank_managecategories/categorymanager","core/templates","core/modal","core/str","core_question/bank_switcher","core/fetch","core/notification","core/url","core/local/inplace_editable/events"],(function(_exports,_reactive,_categorymanager,_templates,_modal,_str,_bank_switcher,_fetch,_notification,CoreUrl,_events){function _getRequireWildcardCache(nodeInterop){if("function"!=typeof WeakMap)return null;var cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_templates=_interopRequireDefault(_templates),_modal=_interopRequireDefault(_modal),_bank_switcher=_interopRequireDefault(_bank_switcher),_fetch=_interopRequireDefault(_fetch),_notification=_interopRequireDefault(_notification),CoreUrl=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if("default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}newObj.default=obj,cache&&cache.set(obj,newObj);return newObj}(CoreUrl);class _default extends _reactive.BaseComponent{create(descriptor){this.name=descriptor.element.id,this.selectors={CATEGORY_LIST:".qbank_managecategories-categorylist",CATEGORY_ITEM:".qbank_managecategories-item[data-categoryid]",CATEGORY_CONTENTS:".qbank_managecategories-item > .container",EDIT_BUTTON:'[data-action="addeditcategory"]',EDITABLE_CATEGORY_NAME:'.inplaceeditable[data-itemtype="categoryname"]',MOVE_BUTTON:'[role="menuitem"][data-actiontype="move"]',CONTEXT:".qbank_managecategories-categorylist[data-contextid]",MODAL_CATEGORY_ITEM:".modal_category_item[data-movingcategoryid]",CONTENT_AREA:".qbank_managecategories-details",CATEGORY_ID:id=>"#category-".concat(id),CONTENT_CONTAINER:id=>"#category-".concat(id," .qbank_managecategories-childlistcontainer"),CHILD_LIST:id=>'ul[data-categoryid="'.concat(id,'"]'),PREVIOUS_SIBLING:sortorder=>':scope > [data-sortorder="'.concat(sortorder,'"]'),SWITCH_QUESTION_BANK:'[data-action="switch-question-bank"]',MOVE_BANK_HEADER:".bank-header"},this.classes={NO_BOTTOM_PADDING:"pb-0",DRAGHANDLE:"draghandle",DROPTARGET:"qbank_managecategories-droptarget-before"},this.ids={CATEGORY:id=>"category-".concat(id)}}stateReady(){this.initDragDrop(),this.addEventListener(this.getElement(this.selectors.EDIT_BUTTON),"click",_categorymanager.categorymanager.showEditModal);const moveButton=this.getElement(this.selectors.MOVE_BUTTON);this.addEventListener(moveButton,"click",this.showMoveModal),this.addEventListener(this.getElement(),_events.eventTypes.elementUpdated,(e=>{const editable=e.target.closest(this.selectors.EDITABLE_CATEGORY_NAME);_categorymanager.categorymanager.updateCategoryName(editable.dataset.itemid,editable.dataset.value)}))}destroy(){this.deInitDragDrop()}initDragDrop(){this.deInitDragDrop(),this.element.classList.contains(this.classes.DRAGHANDLE)&&(this.getDraggableData=this._getDraggableData),this.dragdrop=new _reactive.DragDrop(this)}deInitDragDrop(){void 0!==this.dragdrop&&(void 0!==this.getDraggableData&&(this.dragdrop.setDraggable(!1),this.getDraggableData=void 0),this.dragdrop.unregister(),this.dragdrop=void 0)}static init(target,selectors){return new this({element:document.querySelector(target),selectors:selectors,reactive:_categorymanager.categorymanager})}_getDraggableData(){return{id:this.getElement().dataset.categoryid}}validateDropData(){return!0}showDropZone(dropData){return!this.getElement().closest(this.selectors.CATEGORY_ID(dropData.id))&&(this.getElement().classList.add(this.classes.DROPTARGET),!0)}hideDropZone(){this.getElement().classList.remove(this.classes.DROPTARGET)}drop(dropData,event){var _precedingSibling;const dropTarget=event.target.closest(this.selectors.CATEGORY_ITEM);if(!dropTarget)return;if(dropTarget.closest(this.selectors.CATEGORY_ID(dropData.id)))return;if(!document.getElementById(this.ids.CATEGORY(dropData.id)))return;const targetParentId=dropTarget.dataset.parent,parentList=dropTarget.closest(this.selectors.CATEGORY_LIST);let precedingSibling;precedingSibling=dropTarget===parentList.firstElementChild?null:dropTarget.previousElementSibling,_categorymanager.categorymanager.moveCategory(dropData.id,targetParentId,null===(_precedingSibling=precedingSibling)||void 0===_precedingSibling?void 0:_precedingSibling.dataset.categoryid)}getWatchers(){return[{watch:"categories[".concat(this.element.dataset.categoryid,"]:updated"),handler:this.updatePosition},{watch:"categories[".concat(this.element.dataset.categoryid,"].templatecontext:created"),handler:this.rerender},{watch:"categories[".concat(this.element.dataset.categoryid,"].templatecontext:updated"),handler:this.rerender},{watch:"categories[".concat(this.element.dataset.categoryid,"].name:updated"),handler:this.updateName},{watch:"categories:created",handler:this.checkChildList}]}async rerender(_ref){let{element:element}=_ref;const{html:html,js:js}=await _templates.default.renderForPromise("qbank_managecategories/category_details",element.templatecontext);return _templates.default.replaceNodeContents(this.getElement(this.selectors.CONTENT_AREA),html,js)}async createChildList(context){const{html:html,js:js}=await _templates.default.renderForPromise("qbank_managecategories/childlist",context),parentContainer=document.querySelector(this.selectors.CONTENT_CONTAINER(context.categoryid));await _templates.default.appendNodeContents(parentContainer,html,js);const childList=document.querySelector(this.selectors.CHILD_LIST(context.categoryid));return childList.closest(this.selectors.CATEGORY_CONTENTS).classList.add(this.classes.NO_BOTTOM_PADDING),childList}async updatePosition(_ref2){let newParent,{element:element}=_ref2;const originParent=document.querySelector(this.selectors.CHILD_LIST(this.getElement().dataset.parent));if(element.contextid===_categorymanager.categorymanager.state.page.contextid){let previousSibling,nextSibling;var _previousSibling;if(parseInt(this.getElement().dataset.parent)!==element.parent?(newParent=document.querySelector(this.selectors.CHILD_LIST(element.parent)),newParent||(newParent=await this.createChildList({categoryid:element.parent})),this.getElement().dataset.parent=element.parent):newParent=this.getElement().parentElement,newParent.firstElementChild&&parseInt(element.sortorder)<=parseInt(newParent.firstElementChild.dataset.sortorder))nextSibling=newParent.firstElementChild;else previousSibling=newParent.querySelector(this.selectors.PREVIOUS_SIBLING(element.sortorder-1)),nextSibling=null===(_previousSibling=previousSibling)||void 0===_previousSibling?void 0:_previousSibling.nextElementSibling;(newParent!==this.getElement().parentElement||nextSibling!==this.getElement())&&(nextSibling?newParent.insertBefore(this.getElement(),nextSibling):newParent.appendChild(this.getElement()))}else this.getElement().remove();originParent!==newParent&&this.reactive.stateManager.processUpdates([{name:"categoryLists",action:"put",fields:{id:originParent.dataset.categoryid,childCount:originParent.querySelectorAll(this.selectors.CATEGORY_ITEM).length}},{name:"categoryLists",action:"put",fields:{id:newParent.dataset.categoryid,childCount:newParent.querySelectorAll(this.selectors.CATEGORY_ITEM).length}}]),this.element.dataset.sortorder=element.sortorder;const isDraggable=this.element.classList.contains(this.classes.DRAGHANDLE);isDraggable&&!element.draghandle?(this.element.classList.remove(this.classes.DRAGHANDLE),this.initDragDrop()):!isDraggable&&element.draghandle&&(this.element.classList.add(this.classes.DRAGHANDLE),this.initDragDrop())}getCategoryDataFromElements(element){const categories=[];return element.children&&element.children.forEach((category=>{let child={categoryId:category.dataset.categoryid,parentId:category.dataset.parent,categoryName:category.dataset.categoryname,children:null};const childList=category.querySelector(this.selectors.CATEGORY_LIST);childList&&(child.children=this.getCategoryDataFromElements(childList)),categories.push(child)})),categories}getCategoryDataFromRecords(record){const categories=[];if(record.children)for(const childId in record.children){const category=record.children[childId];let child={categoryId:parseInt(category.id),parentId:parseInt(category.parent),categoryName:category.name,children:null};category.children&&(child.children=this.getCategoryDataFromRecords(category)),categories.push(child)}return categories}createMoveCategoryList(categoryData,movingCategoryId){const categories=[];if(categoryData){let precedingSibling=null;categoryData.forEach((category=>{var _precedingSibling$cat,_precedingSibling2;if(category.categoryId===movingCategoryId)return;let child={categoryid:category.categoryId,movingcategoryid:movingCategoryId,precedingsiblingid:null!==(_precedingSibling$cat=null===(_precedingSibling2=precedingSibling)||void 0===_precedingSibling2?void 0:_precedingSibling2.categoryId)&&void 0!==_precedingSibling$cat?_precedingSibling$cat:0,parent:category.parentId,categoryname:category.categoryName,categories:null,current:category.categoryId===movingCategoryId};category.children?child.categories=this.createMoveCategoryList(category.children,movingCategoryId):child.categories=[{movingcategoryid:movingCategoryId,precedingsiblingid:0,parent:category.categoryId,categoryname:category.categoryName,categories:null,newchild:!0}],categories.push(child),precedingSibling=category})),precedingSibling&&precedingSibling.categoryId!==movingCategoryId&&categories.push({movingcategoryid:movingCategoryId,precedingsiblingid:precedingSibling.categoryId,parent:precedingSibling.parentId,categoryname:precedingSibling.categoryName,categories:null,lastchild:!0})}return categories}async showMoveModal(e){const item=e.target.closest(this.selectors.MOVE_BUTTON);if(!item)return;if("true"===item.getAttribute("aria-disabled"))return;item.setAttribute("aria-disabled",!0);const contextElement=document.querySelector(this.selectors.CONTEXT),categoryData=this.getCategoryDataFromElements(contextElement),moveContext={contextname:contextElement.dataset.contextname,contextid:contextElement.dataset.contextid,cmid:_categorymanager.categorymanager.state.page.cmid,categories:[],hascategories:!1},movingCategoryId=parseInt(item.dataset.categoryid);moveContext.categories=this.createMoveCategoryList(categoryData,movingCategoryId),moveContext.hascategories=moveContext.categories.length>0;const moveCategory=(0,_str.get_string)("movecategory","qbank_managecategories",item.dataset.categoryname),modal=await _modal.default.create({title:moveCategory,body:_templates.default.render("qbank_managecategories/move_context_list",moveContext),footer:"",show:!0,large:!0}),switcher=new _bank_switcher.default;modal.getBody()[0].addEventListener("click",(async e=>{const categoryItem=e.target.closest(this.selectors.MODAL_CATEGORY_ITEM),moveHeader=e.currentTarget.querySelector(this.selectors.MOVE_BANK_HEADER);if(categoryItem){if(_categorymanager.categorymanager.moveCategory(categoryItem.dataset.movingcategoryid,categoryItem.dataset.parent,categoryItem.dataset.precedingsiblingid),moveHeader.dataset.cmid!==_categorymanager.categorymanager.state.page.cmid){const url=CoreUrl.relativeUrl("/question/bank/managecategories/category.php",{cmid:moveHeader.dataset.cmid}),message=await(0,_str.get_string)("categorymovedto","qbank_managecategories",{url:url,name:moveHeader.textContent});_notification.default.addNotification({message:message,type:"info"})}return void modal.destroy()}if(e.target.closest(this.selectors.SWITCH_QUESTION_BANK)){const pageState=_categorymanager.categorymanager.state.page;try{const contextId=parseInt(contextElement.dataset.contextid);await switcher.show(modal,pageState.courseid,contextId,parseInt(moveHeader.dataset.cmid),pageState.cmid)}catch(ex){_notification.default.exception(ex)}}})),modal.getModal()[0].addEventListener("bankSwitched",(async e=>{try{const params={coursemodule:e.detail.cmid},categoriesResponse=await _fetch.default.performGet("core_question","categories",{params:params}),{context:context,categories:categories}=await categoriesResponse.json();for(const id in categories){const category=categories[id];if(category.parent>0){const parentitem=categories[category.parent];parentitem.hasOwnProperty("children")||(parentitem.children={}),categories[category.parent].children[category.id]=category}}let topCategory;for(const id in categories)0===parseInt(categories[id].parent)&&(topCategory=categories[id]);const categoryData=this.getCategoryDataFromRecords(topCategory),moveContext={contextname:context.prefixedname,contextid:context.prefixedname,cmid:e.detail.cmid,categories:[],hascategories:!1};moveContext.categories=this.createMoveCategoryList(categoryData,movingCategoryId),moveContext.hascategories=moveContext.categories.length>0,modal.setBody(_templates.default.render("qbank_managecategories/move_context_list",moveContext)),await modal.getBodyPromise(),modal.setTitle(moveCategory),modal.setFooter("")}catch(ex){_notification.default.alert((0,_str.get_string)("error","error"),ex)}})),item.setAttribute("aria-disabled",!1)}async checkChildList(_ref3){let{element:element}=_ref3;return element.parent!==this.getElement().dataset.categoryid||this.getElement(this.selectors.CATEGORY_LIST)?null:this.createChildList({categoryid:element.parent,children:[element.templatecontext]})}updateName(_ref4){let{element:element}=_ref4;this.getElement().dataset.categoryname=element.name}}return _exports.default=_default,_exports.default})); //# sourceMappingURL=category.min.js.map \ No newline at end of file diff --git a/public/question/bank/managecategories/amd/build/category.min.js.map b/public/question/bank/managecategories/amd/build/category.min.js.map index 1219d473151..af630c260ca 100644 --- a/public/question/bank/managecategories/amd/build/category.min.js.map +++ b/public/question/bank/managecategories/amd/build/category.min.js.map @@ -1 +1 @@ -{"version":3,"file":"category.min.js","sources":["../src/category.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * The category component.\n *\n * @module qbank_managecategories/category\n * @class qbank_managecategories/category\n */\n\nimport {BaseComponent, DragDrop} from 'core/reactive';\nimport {categorymanager} from 'qbank_managecategories/categorymanager';\nimport Templates from 'core/templates';\nimport Modal from \"core/modal\";\nimport {get_string as getString} from \"core/str\";\nimport {eventTypes as inplaceEditableEventTypes} from 'core/local/inplace_editable/events';\n\nexport default class extends BaseComponent {\n\n create(descriptor) {\n this.name = descriptor.element.id;\n this.selectors = {\n CATEGORY_LIST: '.qbank_managecategories-categorylist',\n CATEGORY_ITEM: '.qbank_managecategories-item[data-categoryid]',\n CATEGORY_CONTENTS: '.qbank_managecategories-item > .container',\n EDIT_BUTTON: '[data-action=\"addeditcategory\"]',\n EDITABLE_CATEGORY_NAME: '.inplaceeditable[data-itemtype=\"categoryname\"]',\n MOVE_BUTTON: '[role=\"menuitem\"][data-actiontype=\"move\"]',\n CONTEXT: '.qbank_managecategories-categorylist[data-contextid]',\n MODAL_CATEGORY_ITEM: '.modal_category_item[data-movingcategoryid]',\n CONTENT_AREA: '.qbank_managecategories-details',\n CATEGORY_ID: id => `#category-${id}`,\n CONTENT_CONTAINER: id => `#category-${id} .qbank_managecategories-childlistcontainer`,\n CHILD_LIST: id => `ul[data-categoryid=\"${id}\"]`,\n PREVIOUS_SIBLING: sortorder => `:scope > [data-sortorder=\"${sortorder}\"]`,\n };\n this.classes = {\n NO_BOTTOM_PADDING: 'pb-0',\n DRAGHANDLE: 'draghandle',\n DROPTARGET: 'qbank_managecategories-droptarget-before',\n };\n this.ids = {\n CATEGORY: id => `category-${id}`,\n };\n }\n\n stateReady() {\n this.initDragDrop();\n this.addEventListener(this.getElement(this.selectors.EDIT_BUTTON), 'click', categorymanager.showEditModal);\n const moveButton = this.getElement(this.selectors.MOVE_BUTTON);\n this.addEventListener(moveButton, 'click', this.showMoveModal);\n this.addEventListener(this.getElement(), inplaceEditableEventTypes.elementUpdated, (e) => {\n const editable = e.target.closest(this.selectors.EDITABLE_CATEGORY_NAME);\n categorymanager.updateCategoryName(editable.dataset.itemid, editable.dataset.value);\n });\n }\n\n destroy() {\n // The draggable element must be unregistered.\n this.deInitDragDrop();\n }\n\n /**\n * Remove any existing DragDrop component, and create a new one.\n */\n initDragDrop() {\n this.deInitDragDrop();\n // If the element is currently draggable, register the getDraggableData method.\n if (this.element.classList.contains(this.classes.DRAGHANDLE)) {\n this.getDraggableData = this._getDraggableData;\n }\n this.dragdrop = new DragDrop(this);\n }\n\n /**\n * If the DragDrop component is currently registered, unregister it.\n */\n deInitDragDrop() {\n if (this.dragdrop !== undefined) {\n if (this.getDraggableData !== undefined) {\n this.dragdrop.setDraggable(false);\n this.getDraggableData = undefined;\n }\n this.dragdrop.unregister();\n this.dragdrop = undefined;\n }\n }\n\n /**\n * Static method to create a component instance.\n *\n * @param {string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n * @return {Component}\n */\n static init(target, selectors) {\n return new this({\n element: document.querySelector(target),\n selectors,\n reactive: categorymanager,\n });\n }\n\n /**\n * Return the category ID from the component's element.\n *\n * This method is referenced as getDraggableData when the component can be dragged.\n *\n * @return {{id: string}}\n * @private\n */\n _getDraggableData() {\n return {\n id: this.getElement().dataset.categoryid\n };\n }\n\n validateDropData() {\n return true;\n }\n\n /**\n * Highlight the top border of the category item.\n *\n * @param {Object} dropData\n */\n showDropZone(dropData) {\n if (this.getElement().closest(this.selectors.CATEGORY_ID(dropData.id))) {\n // Can't drop onto itself or its own child.\n return false;\n }\n this.getElement().classList.add(this.classes.DROPTARGET);\n return true;\n }\n\n /**\n * Remove highlighting.\n */\n hideDropZone() {\n this.getElement().classList.remove(this.classes.DROPTARGET);\n }\n\n /**\n * Find the new position of the dropped category, and trigger the move.\n *\n * @param {Object} dropData The category being moved.\n * @param {Event} event The drop event.\n */\n drop(dropData, event) {\n const dropTarget = event.target.closest(this.selectors.CATEGORY_ITEM);\n\n if (!dropTarget) {\n return;\n }\n\n if (dropTarget.closest(this.selectors.CATEGORY_ID(dropData.id))) {\n // Can't drop onto your own child.\n return;\n }\n\n const source = document.getElementById(this.ids.CATEGORY(dropData.id));\n\n if (!source) {\n return;\n }\n\n const targetParentId = dropTarget.dataset.parent;\n const parentList = dropTarget.closest(this.selectors.CATEGORY_LIST);\n let precedingSibling;\n\n if (dropTarget === parentList.firstElementChild) {\n // Dropped at the top of the list.\n precedingSibling = null;\n } else {\n precedingSibling = dropTarget.previousElementSibling;\n }\n\n // Insert the category after the target category\n categorymanager.moveCategory(dropData.id, targetParentId, precedingSibling?.dataset.categoryid);\n }\n\n getWatchers() {\n return [\n // After any update to this category, move it to the new position.\n {watch: `categories[${this.element.dataset.categoryid}]:updated`, handler: this.updatePosition},\n // When the template context is added or updated, re-render the content.\n {watch: `categories[${this.element.dataset.categoryid}].templatecontext:created`, handler: this.rerender},\n {watch: `categories[${this.element.dataset.categoryid}].templatecontext:updated`, handler: this.rerender},\n // When the name is updated, update it in the element data set.\n {watch: `categories[${this.element.dataset.categoryid}].name:updated`, handler: this.updateName},\n // When a new category is created, check whether we need to add a child list to this category.\n {watch: `categories:created`, handler: this.checkChildList},\n ];\n }\n\n /**\n * Re-render the category content.\n *\n * @param {Object} args\n * @param {Element} args.element\n * @return {Promise}\n */\n async rerender({element}) {\n const {html, js} = await Templates.renderForPromise(\n 'qbank_managecategories/category_details',\n element.templatecontext\n );\n return Templates.replaceNodeContents(this.getElement(this.selectors.CONTENT_AREA), html, js);\n }\n\n /**\n * Render and append a new child list.\n *\n * @param {Object} context Template context, must include at least categoryid.\n * @return {Promise}\n */\n async createChildList(context) {\n const {html, js} = await Templates.renderForPromise(\n 'qbank_managecategories/childlist',\n context,\n );\n const parentContainer = document.querySelector(this.selectors.CONTENT_CONTAINER(context.categoryid));\n await Templates.appendNodeContents(parentContainer, html, js);\n const childList = document.querySelector(this.selectors.CHILD_LIST(context.categoryid));\n childList.closest(this.selectors.CATEGORY_CONTENTS).classList.add(this.classes.NO_BOTTOM_PADDING);\n return childList;\n }\n\n /**\n * Move a category to its new position.\n *\n * A category may change its parent, sortorder and draghandle independently or at the same time. This method will resolve those\n * changes and move the element to the new position. If the parent doesn't already have a child list, one will be created.\n *\n * If the parent has changed, this will also update the state with the new child count of the old and new parents.\n *\n * @param {Object} args\n * @param {Object} args.element\n * @return {Promise}\n */\n async updatePosition({element}) {\n // Move to a new parent category.\n let newParent;\n const originParent = document.querySelector(this.selectors.CHILD_LIST(this.getElement().dataset.parent));\n if (parseInt(this.getElement().dataset.parent) !== element.parent) {\n newParent = document.querySelector(this.selectors.CHILD_LIST(element.parent));\n if (!newParent) {\n // The target category doesn't have a child list yet. We'd better create one.\n newParent = await this.createChildList({categoryid: element.parent});\n }\n this.getElement().dataset.parent = element.parent;\n } else {\n newParent = this.getElement().parentElement;\n }\n\n // Move to a new position within the parent.\n let previousSibling;\n let nextSibling;\n if (newParent.firstElementChild && parseInt(element.sortorder) <= parseInt(newParent.firstElementChild.dataset.sortorder)) {\n // Move to the top of the list.\n nextSibling = newParent.firstElementChild;\n } else {\n // Move later in the list.\n previousSibling = newParent.querySelector(this.selectors.PREVIOUS_SIBLING(element.sortorder - 1));\n nextSibling = previousSibling?.nextElementSibling;\n }\n\n // Check if this has actually moved, or if it's just having its sortorder updated due to another element moving.\n const moved = (newParent !== this.getElement().parentElement || nextSibling !== this.getElement());\n\n if (moved) {\n if (nextSibling) {\n // Move to the specified position in the list.\n newParent.insertBefore(this.getElement(), nextSibling);\n } else {\n // Move to the end of the list (may also be the top of the list is empty).\n newParent.appendChild(this.getElement());\n }\n }\n if (originParent !== newParent) {\n // Update child count of old and new parent.\n this.reactive.stateManager.processUpdates([\n {\n name: 'categoryLists',\n action: 'put',\n fields: {\n id: originParent.dataset.categoryid,\n childCount: originParent.querySelectorAll(this.selectors.CATEGORY_ITEM).length\n }\n },\n {\n name: 'categoryLists',\n action: 'put',\n fields: {\n id: newParent.dataset.categoryid,\n childCount: newParent.querySelectorAll(this.selectors.CATEGORY_ITEM).length\n }\n }\n ]);\n }\n\n this.element.dataset.sortorder = element.sortorder;\n\n // Enable/disable dragging.\n const isDraggable = this.element.classList.contains(this.classes.DRAGHANDLE);\n if (isDraggable && !element.draghandle) {\n this.element.classList.remove(this.classes.DRAGHANDLE);\n this.initDragDrop();\n } else if (!isDraggable && element.draghandle) {\n this.element.classList.add(this.classes.DRAGHANDLE);\n this.initDragDrop();\n }\n }\n\n /**\n * Recursively create a list of all valid destinations for a current category within a parent category.\n *\n * @param {Element} item\n * @param {Number} movingCategoryId\n * @return {Array}\n */\n createMoveCategoryList(item, movingCategoryId) {\n const categories = [];\n if (item.children) {\n let precedingSibling = null;\n item.children.forEach(category => {\n const categoryId = parseInt(category.dataset.categoryid);\n // Don't create a target for the category that's moving.\n if (categoryId === movingCategoryId) {\n return;\n }\n // Create a target to move before this child.\n let child = {\n categoryid: categoryId,\n movingcategoryid: movingCategoryId,\n precedingsiblingid: precedingSibling?.dataset.categoryid ?? 0,\n parent: category.dataset.parent,\n categoryname: category.dataset.categoryname,\n categories: null,\n current: categoryId === movingCategoryId,\n };\n const childList = category.querySelector(this.selectors.CATEGORY_LIST);\n if (childList) {\n // If the child has its own children, recursively make a list of those.\n child.categories = this.createMoveCategoryList(childList, movingCategoryId);\n } else {\n // Otherwise, create a target to move as a new child of this one.\n child.categories = [\n {\n movingcategoryid: movingCategoryId,\n precedingsiblingid: 0,\n parent: categoryId,\n categoryname: category.dataset.categoryname,\n categories: null,\n newchild: true,\n }\n ];\n }\n categories.push(child);\n precedingSibling = category;\n });\n if (precedingSibling) {\n const precedingId = parseInt(precedingSibling.dataset.categoryid);\n if (precedingId !== movingCategoryId) {\n // If this is the last child of its parent, also create a target to move the category after this one.\n categories.push({\n movingcategoryid: movingCategoryId,\n precedingsiblingid: precedingId,\n parent: precedingSibling.dataset.parent,\n categoryname: precedingSibling.dataset.categoryname,\n categories: null,\n lastchild: true,\n });\n }\n }\n }\n return categories;\n }\n\n /**\n * Displays a modal containing links to move the category to a new location.\n *\n * @param {Event} e Button click event.\n */\n async showMoveModal(e) {\n // Return if it is not menu item.\n const item = e.target.closest(this.selectors.MOVE_BUTTON);\n if (!item) {\n return;\n }\n // Return if it is disabled.\n if (item.getAttribute('aria-disabled') === 'true') {\n return;\n }\n\n // Prevent addition click on the item.\n item.setAttribute('aria-disabled', true);\n\n // Build the list of move links.\n let moveList = {contexts: []};\n const contexts = document.querySelectorAll(this.selectors.CONTEXT);\n contexts.forEach(context => {\n const moveContext = {\n contextname: context.dataset.contextname,\n categories: [],\n hascategories: false,\n };\n moveContext.categories = this.createMoveCategoryList(context, parseInt(item.dataset.categoryid));\n moveContext.hascategories = moveContext.categories.length > 0;\n moveList.contexts.push(moveContext);\n });\n\n const modal = await Modal.create({\n title: getString('movecategory', 'qbank_managecategories', item.dataset.categoryname),\n body: Templates.render('qbank_managecategories/move_context_list', moveList),\n footer: '',\n show: true,\n large: true,\n });\n // Show modal and add click event for list items.\n modal.getBody()[0].addEventListener('click', e => {\n const target = e.target.closest(this.selectors.MODAL_CATEGORY_ITEM);\n if (!target) {\n return;\n }\n categorymanager.moveCategory(target.dataset.movingcategoryid, target.dataset.parent, target.dataset.precedingsiblingid);\n modal.destroy();\n });\n item.setAttribute('aria-disabled', false);\n }\n\n /**\n * Check and add a child list if needed.\n *\n * Check whether the category that has just been added has this category as its parent. If it does,\n * check that this category has a child list, and if not, add one.\n *\n * @param {Object} args\n * @param {Element} args.element The new category.\n * @return {Promise}\n */\n async checkChildList({element}) {\n if (element.parent !== this.getElement().dataset.categoryid) {\n return null; // Not for me.\n }\n let childList = this.getElement(this.selectors.CATEGORY_LIST);\n if (childList) {\n return null; // List already exists, it will handle adding the new category.\n }\n // Render and add a new child list containing the new category.\n return this.createChildList({\n categoryid: element.parent,\n children: [\n element.templatecontext,\n ]\n });\n }\n\n /**\n * Update the name in the category item element's data, for building move targets.\n *\n * @param {Object} args\n * @param {Object} args.element\n */\n updateName({element}) {\n this.getElement().dataset.categoryname = element.name;\n }\n}\n"],"names":["BaseComponent","create","descriptor","name","element","id","selectors","CATEGORY_LIST","CATEGORY_ITEM","CATEGORY_CONTENTS","EDIT_BUTTON","EDITABLE_CATEGORY_NAME","MOVE_BUTTON","CONTEXT","MODAL_CATEGORY_ITEM","CONTENT_AREA","CATEGORY_ID","CONTENT_CONTAINER","CHILD_LIST","PREVIOUS_SIBLING","sortorder","classes","NO_BOTTOM_PADDING","DRAGHANDLE","DROPTARGET","ids","CATEGORY","stateReady","initDragDrop","addEventListener","this","getElement","categorymanager","showEditModal","moveButton","showMoveModal","inplaceEditableEventTypes","elementUpdated","e","editable","target","closest","updateCategoryName","dataset","itemid","value","destroy","deInitDragDrop","classList","contains","getDraggableData","_getDraggableData","dragdrop","DragDrop","undefined","setDraggable","unregister","document","querySelector","reactive","categoryid","validateDropData","showDropZone","dropData","add","hideDropZone","remove","drop","event","dropTarget","getElementById","targetParentId","parent","parentList","precedingSibling","firstElementChild","previousElementSibling","moveCategory","_precedingSibling","getWatchers","watch","handler","updatePosition","rerender","updateName","checkChildList","html","js","Templates","renderForPromise","templatecontext","replaceNodeContents","context","parentContainer","appendNodeContents","childList","newParent","originParent","previousSibling","nextSibling","parseInt","createChildList","parentElement","_previousSibling","nextElementSibling","insertBefore","appendChild","stateManager","processUpdates","action","fields","childCount","querySelectorAll","length","isDraggable","draghandle","createMoveCategoryList","item","movingCategoryId","categories","children","forEach","category","categoryId","child","movingcategoryid","precedingsiblingid","_precedingSibling2","categoryname","current","newchild","push","precedingId","lastchild","getAttribute","setAttribute","moveList","contexts","moveContext","contextname","hascategories","modal","Modal","title","body","render","footer","show","large","getBody"],"mappings":"uhBA6B6BA,wBAEzBC,OAAOC,iBACEC,KAAOD,WA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B,aAAa,iBAAiB,OAG/BC,SAAW,CAACC,SAAU,IACThF,SAASuD,iBAAiBlF,KAAKxB,UAAUO,SACjD4G,SAAQ7B,gBACP8C,YAAc,CAChBC,YAAa/C,QAAQjD,QAAQgG,YAC7BpB,WAAY,GACZqB,eAAe,GAEnBF,YAAYnB,WAAazF,KAAKsF,uBAAuBxB,QAASQ,SAASiB,KAAK1E,QAAQiB,aACpF8E,YAAYE,cAAgBF,YAAYnB,WAAWN,OAAS,EAC5DuB,SAASC,SAASN,KAAKO,sBAGrBG,YAAcC,eAAM7I,OAAO,CAC7B8I,OAAO,mBAAU,eAAgB,yBAA0B1B,KAAK1E,QAAQqF,cACxEgB,KAAMxD,mBAAUyD,OAAO,2CAA4CT,UACnEU,OAAQ,GACRC,MAAM,EACNC,OAAO,IAGXP,MAAMQ,UAAU,GAAGxH,iBAAiB,SAASS,UACnCE,OAASF,EAAEE,OAAOC,QAAQX,KAAKxB,UAAUQ,qBAC1C0B,0CAGWqC,aAAarC,OAAOG,QAAQkF,iBAAkBrF,OAAOG,QAAQ6B,OAAQhC,OAAOG,QAAQmF,oBACpGe,MAAM/F,cAEVuE,KAAKkB,aAAa,iBAAiB,mCAalBnI,QAACA,sBACdA,QAAQoE,SAAW1C,KAAKC,aAAaY,QAAQiB,YAGjC9B,KAAKC,WAAWD,KAAKxB,UAAUC,eAFpC,KAOJuB,KAAKuE,gBAAgB,CACxBzC,WAAYxD,QAAQoE,OACpBgD,SAAU,CACNpH,QAAQsF,mBAWpBN,sBAAWhF,QAACA,oBACH2B,aAAaY,QAAQqF,aAAe5H,QAAQD"} \ No newline at end of file +{"version":3,"file":"category.min.js","sources":["../src/category.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * The category component.\n *\n * @module qbank_managecategories/category\n * @class qbank_managecategories/category\n */\n\nimport {BaseComponent, DragDrop} from 'core/reactive';\nimport {categorymanager} from 'qbank_managecategories/categorymanager';\nimport Templates from 'core/templates';\nimport Modal from \"core/modal\";\nimport {get_string as getString} from \"core/str\";\nimport BankSwitcher from 'core_question/bank_switcher';\nimport Fetch from 'core/fetch';\nimport Notification from 'core/notification';\nimport * as CoreUrl from 'core/url';\nimport {eventTypes as inplaceEditableEventTypes} from 'core/local/inplace_editable/events';\n\nexport default class extends BaseComponent {\n\n create(descriptor) {\n this.name = descriptor.element.id;\n this.selectors = {\n CATEGORY_LIST: '.qbank_managecategories-categorylist',\n CATEGORY_ITEM: '.qbank_managecategories-item[data-categoryid]',\n CATEGORY_CONTENTS: '.qbank_managecategories-item > .container',\n EDIT_BUTTON: '[data-action=\"addeditcategory\"]',\n EDITABLE_CATEGORY_NAME: '.inplaceeditable[data-itemtype=\"categoryname\"]',\n MOVE_BUTTON: '[role=\"menuitem\"][data-actiontype=\"move\"]',\n CONTEXT: '.qbank_managecategories-categorylist[data-contextid]',\n MODAL_CATEGORY_ITEM: '.modal_category_item[data-movingcategoryid]',\n CONTENT_AREA: '.qbank_managecategories-details',\n CATEGORY_ID: id => `#category-${id}`,\n CONTENT_CONTAINER: id => `#category-${id} .qbank_managecategories-childlistcontainer`,\n CHILD_LIST: id => `ul[data-categoryid=\"${id}\"]`,\n PREVIOUS_SIBLING: sortorder => `:scope > [data-sortorder=\"${sortorder}\"]`,\n SWITCH_QUESTION_BANK: '[data-action=\"switch-question-bank\"]',\n MOVE_BANK_HEADER: '.bank-header',\n };\n this.classes = {\n NO_BOTTOM_PADDING: 'pb-0',\n DRAGHANDLE: 'draghandle',\n DROPTARGET: 'qbank_managecategories-droptarget-before',\n };\n this.ids = {\n CATEGORY: id => `category-${id}`,\n };\n }\n\n stateReady() {\n this.initDragDrop();\n this.addEventListener(this.getElement(this.selectors.EDIT_BUTTON), 'click', categorymanager.showEditModal);\n const moveButton = this.getElement(this.selectors.MOVE_BUTTON);\n this.addEventListener(moveButton, 'click', this.showMoveModal);\n this.addEventListener(this.getElement(), inplaceEditableEventTypes.elementUpdated, (e) => {\n const editable = e.target.closest(this.selectors.EDITABLE_CATEGORY_NAME);\n categorymanager.updateCategoryName(editable.dataset.itemid, editable.dataset.value);\n });\n }\n\n destroy() {\n // The draggable element must be unregistered.\n this.deInitDragDrop();\n }\n\n /**\n * Remove any existing DragDrop component, and create a new one.\n */\n initDragDrop() {\n this.deInitDragDrop();\n // If the element is currently draggable, register the getDraggableData method.\n if (this.element.classList.contains(this.classes.DRAGHANDLE)) {\n this.getDraggableData = this._getDraggableData;\n }\n this.dragdrop = new DragDrop(this);\n }\n\n /**\n * If the DragDrop component is currently registered, unregister it.\n */\n deInitDragDrop() {\n if (this.dragdrop !== undefined) {\n if (this.getDraggableData !== undefined) {\n this.dragdrop.setDraggable(false);\n this.getDraggableData = undefined;\n }\n this.dragdrop.unregister();\n this.dragdrop = undefined;\n }\n }\n\n /**\n * Static method to create a component instance.\n *\n * @param {string} target the DOM main element or its ID\n * @param {object} selectors optional css selector overrides\n * @return {Component}\n */\n static init(target, selectors) {\n return new this({\n element: document.querySelector(target),\n selectors,\n reactive: categorymanager,\n });\n }\n\n /**\n * Return the category ID from the component's element.\n *\n * This method is referenced as getDraggableData when the component can be dragged.\n *\n * @return {{id: string}}\n * @private\n */\n _getDraggableData() {\n return {\n id: this.getElement().dataset.categoryid\n };\n }\n\n validateDropData() {\n return true;\n }\n\n /**\n * Highlight the top border of the category item.\n *\n * @param {Object} dropData\n */\n showDropZone(dropData) {\n if (this.getElement().closest(this.selectors.CATEGORY_ID(dropData.id))) {\n // Can't drop onto itself or its own child.\n return false;\n }\n this.getElement().classList.add(this.classes.DROPTARGET);\n return true;\n }\n\n /**\n * Remove highlighting.\n */\n hideDropZone() {\n this.getElement().classList.remove(this.classes.DROPTARGET);\n }\n\n /**\n * Find the new position of the dropped category, and trigger the move.\n *\n * @param {Object} dropData The category being moved.\n * @param {Event} event The drop event.\n */\n drop(dropData, event) {\n const dropTarget = event.target.closest(this.selectors.CATEGORY_ITEM);\n\n if (!dropTarget) {\n return;\n }\n\n if (dropTarget.closest(this.selectors.CATEGORY_ID(dropData.id))) {\n // Can't drop onto your own child.\n return;\n }\n\n const source = document.getElementById(this.ids.CATEGORY(dropData.id));\n\n if (!source) {\n return;\n }\n\n const targetParentId = dropTarget.dataset.parent;\n const parentList = dropTarget.closest(this.selectors.CATEGORY_LIST);\n let precedingSibling;\n\n if (dropTarget === parentList.firstElementChild) {\n // Dropped at the top of the list.\n precedingSibling = null;\n } else {\n precedingSibling = dropTarget.previousElementSibling;\n }\n\n // Insert the category after the target category\n categorymanager.moveCategory(dropData.id, targetParentId, precedingSibling?.dataset.categoryid);\n }\n\n getWatchers() {\n return [\n // After any update to this category, move it to the new position.\n {watch: `categories[${this.element.dataset.categoryid}]:updated`, handler: this.updatePosition},\n // When the template context is added or updated, re-render the content.\n {watch: `categories[${this.element.dataset.categoryid}].templatecontext:created`, handler: this.rerender},\n {watch: `categories[${this.element.dataset.categoryid}].templatecontext:updated`, handler: this.rerender},\n // When the name is updated, update it in the element data set.\n {watch: `categories[${this.element.dataset.categoryid}].name:updated`, handler: this.updateName},\n // When a new category is created, check whether we need to add a child list to this category.\n {watch: `categories:created`, handler: this.checkChildList},\n ];\n }\n\n /**\n * Re-render the category content.\n *\n * @param {Object} args\n * @param {Element} args.element\n * @return {Promise}\n */\n async rerender({element}) {\n const {html, js} = await Templates.renderForPromise(\n 'qbank_managecategories/category_details',\n element.templatecontext\n );\n return Templates.replaceNodeContents(this.getElement(this.selectors.CONTENT_AREA), html, js);\n }\n\n /**\n * Render and append a new child list.\n *\n * @param {Object} context Template context, must include at least categoryid.\n * @return {Promise}\n */\n async createChildList(context) {\n const {html, js} = await Templates.renderForPromise(\n 'qbank_managecategories/childlist',\n context,\n );\n const parentContainer = document.querySelector(this.selectors.CONTENT_CONTAINER(context.categoryid));\n await Templates.appendNodeContents(parentContainer, html, js);\n const childList = document.querySelector(this.selectors.CHILD_LIST(context.categoryid));\n childList.closest(this.selectors.CATEGORY_CONTENTS).classList.add(this.classes.NO_BOTTOM_PADDING);\n return childList;\n }\n\n /**\n * Move a category to its new position.\n *\n * A category may change its parent, sortorder and draghandle independently or at the same time. This method will resolve those\n * changes and move the element to the new position. If the parent doesn't already have a child list, one will be created.\n *\n * If the parent has changed, this will also update the state with the new child count of the old and new parents.\n *\n * @param {Object} args\n * @param {Object} args.element\n * @return {Promise}\n */\n async updatePosition({element}) {\n // Move to a new parent category.\n let newParent;\n const originParent = document.querySelector(this.selectors.CHILD_LIST(this.getElement().dataset.parent));\n if (element.contextid === categorymanager.state.page.contextid) {\n if (parseInt(this.getElement().dataset.parent) !== element.parent) {\n newParent = document.querySelector(this.selectors.CHILD_LIST(element.parent));\n if (!newParent) {\n // The target category doesn't have a child list yet. We'd better create one.\n newParent = await this.createChildList({categoryid: element.parent});\n }\n this.getElement().dataset.parent = element.parent;\n } else {\n newParent = this.getElement().parentElement;\n }\n\n // Move to a new position within the parent.\n let previousSibling;\n let nextSibling;\n if (\n newParent.firstElementChild &&\n parseInt(element.sortorder) <= parseInt(newParent.firstElementChild.dataset.sortorder)\n ) {\n // Move to the top of the list.\n nextSibling = newParent.firstElementChild;\n } else {\n // Move later in the list.\n previousSibling = newParent.querySelector(this.selectors.PREVIOUS_SIBLING(element.sortorder - 1));\n nextSibling = previousSibling?.nextElementSibling;\n }\n\n // Check if this has actually moved, or if it's just having its sortorder updated due to another element moving.\n const moved = (newParent !== this.getElement().parentElement || nextSibling !== this.getElement());\n\n if (moved) {\n if (nextSibling) {\n // Move to the specified position in the list.\n newParent.insertBefore(this.getElement(), nextSibling);\n } else {\n // Move to the end of the list (may also be the top of the list is empty).\n newParent.appendChild(this.getElement());\n }\n }\n } else {\n // The category was moved to a different context, it should no longer appear on this page.\n this.getElement().remove();\n }\n\n if (originParent !== newParent) {\n // Update child count of old and new parent.\n this.reactive.stateManager.processUpdates([\n {\n name: 'categoryLists',\n action: 'put',\n fields: {\n id: originParent.dataset.categoryid,\n childCount: originParent.querySelectorAll(this.selectors.CATEGORY_ITEM).length\n }\n },\n {\n name: 'categoryLists',\n action: 'put',\n fields: {\n id: newParent.dataset.categoryid,\n childCount: newParent.querySelectorAll(this.selectors.CATEGORY_ITEM).length\n }\n }\n ]);\n }\n\n this.element.dataset.sortorder = element.sortorder;\n\n // Enable/disable dragging.\n const isDraggable = this.element.classList.contains(this.classes.DRAGHANDLE);\n if (isDraggable && !element.draghandle) {\n this.element.classList.remove(this.classes.DRAGHANDLE);\n this.initDragDrop();\n } else if (!isDraggable && element.draghandle) {\n this.element.classList.add(this.classes.DRAGHANDLE);\n this.initDragDrop();\n }\n }\n\n /**\n * Get the abstract category data from the elements on the page.\n *\n * @param {Element} element The category element from the page.\n * @return {Array} List of categories containing categoryId, parentId, categoryName, and a nested array of children.\n */\n getCategoryDataFromElements(element) {\n const categories = [];\n if (element.children) {\n element.children.forEach(category => {\n // Add this category to the list.\n let child = {\n categoryId: category.dataset.categoryid,\n parentId: category.dataset.parent,\n categoryName: category.dataset.categoryname,\n children: null,\n };\n const childList = category.querySelector(this.selectors.CATEGORY_LIST);\n if (childList) {\n // If the child has its own children, recursively make a list of those.\n child.children = this.getCategoryDataFromElements(childList);\n }\n categories.push(child);\n });\n }\n return categories;\n }\n\n /**\n * Get the abstract category data from the records retrieved from the web service.\n *\n * @param {Object} record The category record.\n * @return {Array} List of categories containing categoryId, parentId, categoryName, and a nested array of children.\n */\n getCategoryDataFromRecords(record) {\n const categories = [];\n if (record.children) {\n for (const childId in record.children) {\n const category = record.children[childId];\n // Add this category to the list.\n let child = {\n categoryId: parseInt(category.id),\n parentId: parseInt(category.parent),\n categoryName: category.name,\n children: null,\n };\n if (category.children) {\n // If the child has its own children, recursively make a list of those.\n child.children = this.getCategoryDataFromRecords(category);\n }\n categories.push(child);\n }\n }\n return categories;\n }\n\n /**\n * Recursively create a list of all valid destinations for a current category within a parent category.\n *\n * @param {Object} categoryData\n * @param {Number} movingCategoryId\n * @return {Array}\n */\n createMoveCategoryList(categoryData, movingCategoryId) {\n const categories = [];\n if (categoryData) {\n let precedingSibling = null;\n categoryData.forEach(category => {\n // Don't create a target for the category that's moving.\n if (category.categoryId === movingCategoryId) {\n return;\n }\n // Create a target to move before this child.\n let child = {\n categoryid: category.categoryId,\n movingcategoryid: movingCategoryId,\n precedingsiblingid: precedingSibling?.categoryId ?? 0,\n parent: category.parentId,\n categoryname: category.categoryName,\n categories: null,\n current: category.categoryId === movingCategoryId,\n };\n if (category.children) {\n // If the child has its own children, recursively make a list of those.\n child.categories = this.createMoveCategoryList(category.children, movingCategoryId);\n } else {\n // Otherwise, create a target to move as a new child of this one.\n child.categories = [\n {\n movingcategoryid: movingCategoryId,\n precedingsiblingid: 0,\n parent: category.categoryId,\n categoryname: category.categoryName,\n categories: null,\n newchild: true,\n }\n ];\n }\n categories.push(child);\n precedingSibling = category;\n });\n if (precedingSibling) {\n if (precedingSibling.categoryId !== movingCategoryId) {\n // If this is the last child of its parent, also create a target to move the category after this one.\n categories.push({\n movingcategoryid: movingCategoryId,\n precedingsiblingid: precedingSibling.categoryId,\n parent: precedingSibling.parentId,\n categoryname: precedingSibling.categoryName,\n categories: null,\n lastchild: true,\n });\n }\n }\n }\n return categories;\n }\n\n /**\n * Displays a modal containing links to move the category to a new location.\n *\n * @param {Event} e Button click event.\n */\n async showMoveModal(e) {\n // Return if it is not menu item.\n const item = e.target.closest(this.selectors.MOVE_BUTTON);\n if (!item) {\n return;\n }\n // Return if it is disabled.\n if (item.getAttribute('aria-disabled') === 'true') {\n return;\n }\n\n // Prevent addition click on the item.\n item.setAttribute('aria-disabled', true);\n\n // Build the list of move links.\n const contextElement = document.querySelector(this.selectors.CONTEXT);\n const categoryData = this.getCategoryDataFromElements(contextElement);\n\n const moveContext = {\n contextname: contextElement.dataset.contextname,\n contextid: contextElement.dataset.contextid,\n cmid: categorymanager.state.page.cmid,\n categories: [],\n hascategories: false,\n };\n const movingCategoryId = parseInt(item.dataset.categoryid);\n moveContext.categories = this.createMoveCategoryList(categoryData, movingCategoryId);\n moveContext.hascategories = moveContext.categories.length > 0;\n\n const moveCategory = getString('movecategory', 'qbank_managecategories', item.dataset.categoryname);\n const modal = await Modal.create({\n title: moveCategory,\n body: Templates.render('qbank_managecategories/move_context_list', moveContext),\n footer: '',\n show: true,\n large: true,\n });\n const switcher = new BankSwitcher();\n // Show modal and add click event for list items and bank switcher.\n modal.getBody()[0].addEventListener('click', async(e) => {\n const categoryItem = e.target.closest(this.selectors.MODAL_CATEGORY_ITEM);\n const moveHeader = e.currentTarget.querySelector(this.selectors.MOVE_BANK_HEADER);\n if (categoryItem) {\n categorymanager.moveCategory(\n categoryItem.dataset.movingcategoryid,\n categoryItem.dataset.parent,\n categoryItem.dataset.precedingsiblingid,\n );\n if (moveHeader.dataset.cmid !== categorymanager.state.page.cmid) {\n const url = CoreUrl.relativeUrl(\n '/question/bank/managecategories/category.php',\n {cmid: moveHeader.dataset.cmid}\n );\n const message = await getString(\n 'categorymovedto',\n 'qbank_managecategories',\n {url, name: moveHeader.textContent},\n );\n Notification.addNotification({message: message, type: 'info'});\n }\n modal.destroy();\n return;\n }\n const switchButton = e.target.closest(this.selectors.SWITCH_QUESTION_BANK);\n if (switchButton) {\n const pageState = categorymanager.state.page;\n try {\n const contextId = parseInt(contextElement.dataset.contextid);\n await switcher.show(modal, pageState.courseid, contextId, parseInt(moveHeader.dataset.cmid), pageState.cmid);\n } catch (ex) {\n Notification.exception(ex);\n }\n }\n });\n modal.getModal()[0].addEventListener('bankSwitched', async(e) => {\n try {\n const params = {coursemodule: e.detail.cmid};\n const categoriesResponse = await Fetch.performGet(\n 'core_question',\n 'categories',\n {params},\n );\n const {context, categories} = await categoriesResponse.json();\n // Convert the list of categories into a nested tree.\n for (const id in categories) {\n const category = categories[id];\n if (category.parent > 0) {\n const parentitem = categories[category.parent];\n if (!parentitem.hasOwnProperty('children')) {\n parentitem.children = {};\n }\n categories[category.parent].children[category.id] = category;\n }\n }\n // Get the top category with all the others nested below.\n let topCategory;\n for (const id in categories) {\n if (parseInt(categories[id].parent) === 0) {\n topCategory = categories[id];\n }\n }\n const categoryData = this.getCategoryDataFromRecords(topCategory);\n const moveContext = {\n contextname: context.prefixedname,\n contextid: context.prefixedname,\n cmid: e.detail.cmid,\n categories: [],\n hascategories: false,\n };\n moveContext.categories = this.createMoveCategoryList(categoryData, movingCategoryId);\n moveContext.hascategories = moveContext.categories.length > 0;\n modal.setBody(\n Templates.render('qbank_managecategories/move_context_list', moveContext),\n );\n await modal.getBodyPromise();\n modal.setTitle(moveCategory);\n modal.setFooter('');\n } catch (ex) {\n Notification.alert(getString('error', 'error'), ex);\n }\n });\n item.setAttribute('aria-disabled', false);\n }\n\n /**\n * Check and add a child list if needed.\n *\n * Check whether the category that has just been added has this category as its parent. If it does,\n * check that this category has a child list, and if not, add one.\n *\n * @param {Object} args\n * @param {Element} args.element The new category.\n * @return {Promise}\n */\n async checkChildList({element}) {\n if (element.parent !== this.getElement().dataset.categoryid) {\n return null; // Not for me.\n }\n let childList = this.getElement(this.selectors.CATEGORY_LIST);\n if (childList) {\n return null; // List already exists, it will handle adding the new category.\n }\n // Render and add a new child list containing the new category.\n return this.createChildList({\n categoryid: element.parent,\n children: [\n element.templatecontext,\n ]\n });\n }\n\n /**\n * Update the name in the category item element's data, for building move targets.\n *\n * @param {Object} args\n * @param {Object} args.element\n */\n updateName({element}) {\n this.getElement().dataset.categoryname = element.name;\n }\n}\n"],"names":["BaseComponent","create","descriptor","name","element","id","selectors","CATEGORY_LIST","CATEGORY_ITEM","CATEGORY_CONTENTS","EDIT_BUTTON","EDITABLE_CATEGORY_NAME","MOVE_BUTTON","CONTEXT","MODAL_CATEGORY_ITEM","CONTENT_AREA","CATEGORY_ID","CONTENT_CONTAINER","CHILD_LIST","PREVIOUS_SIBLING","sortorder","SWITCH_QUESTION_BANK","MOVE_BANK_HEADER","classes","NO_BOTTOM_PADDING","DRAGHANDLE","DROPTARGET","ids","CATEGORY","stateReady","initDragDrop","addEventListener","this","getElement","categorymanager","showEditModal","moveButton","showMoveModal","inplaceEditableEventTypes","elementUpdated","e","editable","target","closest","updateCategoryName","dataset","itemid","value","destroy","deInitDragDrop","classList","contains","getDraggableData","_getDraggableData","dragdrop","DragDrop","undefined","setDraggable","unregister","document","querySelector","reactive","categoryid","validateDropData","showDropZone","dropData","add","hideDropZone","remove","drop","event","dropTarget","getElementById","targetParentId","parent","parentList","precedingSibling","firstElementChild","previousElementSibling","moveCategory","_precedingSibling","getWatchers","watch","handler","updatePosition","rerender","updateName","checkChildList","html","js","Templates","renderForPromise","templatecontext","replaceNodeContents","context","parentContainer","appendNodeContents","childList","newParent","originParent","contextid","state","page","previousSibling","nextSibling","parseInt","createChildList","parentElement","_previousSibling","nextElementSibling","insertBefore","appendChild","stateManager","processUpdates","action","fields","childCount","querySelectorAll","length","isDraggable","draghandle","getCategoryDataFromElements","categories","children","forEach","category","child","categoryId","parentId","categoryName","categoryname","push","getCategoryDataFromRecords","record","childId","createMoveCategoryList","categoryData","movingCategoryId","movingcategoryid","precedingsiblingid","_precedingSibling2","current","newchild","lastchild","item","getAttribute","setAttribute","contextElement","moveContext","contextname","cmid","hascategories","modal","Modal","title","body","render","footer","show","large","switcher","BankSwitcher","getBody","async","categoryItem","moveHeader","currentTarget","url","CoreUrl","relativeUrl","message","textContent","addNotification","type","pageState","contextId","courseid","ex","exception","getModal","params","coursemodule","detail","categoriesResponse","Fetch","performGet","json","parentitem","hasOwnProperty","topCategory","prefixedname","setBody","getBodyPromise","setTitle","setFooter","alert"],"mappings":"8sDAiC6BA,wBAEzBC,OAAOC,iBACEC,KAAOD,WAAWE,QAAQC,QAC1BC,UAAY,CACbC,c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nE,WAAWrH,WAG3BmI,aAAexG,KAAKoG,2BAA2ByD,aAC/CzC,YAAc,CAChBC,YAAavD,QAAQgG,aACrB1F,UAAWN,QAAQgG,aACnBxC,KAAM9G,EAAE8I,OAAOhC,KACf5B,WAAY,GACZ6B,eAAe,GAEnBH,YAAY1B,WAAa1F,KAAKuG,uBAAuBC,aAAcC,kBACnEW,YAAYG,cAAgBH,YAAY1B,WAAWJ,OAAS,EAC5DkC,MAAMuC,QACFrG,mBAAUkE,OAAO,2CAA4CR,oBAE3DI,MAAMwC,iBACZxC,MAAMyC,SAASlH,cACfyE,MAAM0C,UAAU,IAClB,MAAOjB,0BACQkB,OAAM,mBAAU,QAAS,SAAUlB,QAGxDjC,KAAKE,aAAa,iBAAiB,mCAalB9I,QAACA,sBACdA,QAAQsE,SAAW1C,KAAKC,aAAaY,QAAQiB,YAGjC9B,KAAKC,WAAWD,KAAK1B,UAAUC,eAFpC,KAOJyB,KAAK0E,gBAAgB,CACxB5C,WAAY1D,QAAQsE,OACpBiD,SAAU,CACNvH,QAAQwF,mBAWpBN,sBAAWlF,QAACA,oBACH6B,aAAaY,QAAQqF,aAAe9H,QAAQD"} \ No newline at end of file diff --git a/public/question/bank/managecategories/amd/src/category.js b/public/question/bank/managecategories/amd/src/category.js index f46fe1f8b21..a620347f2ce 100644 --- a/public/question/bank/managecategories/amd/src/category.js +++ b/public/question/bank/managecategories/amd/src/category.js @@ -25,6 +25,10 @@ import {categorymanager} from 'qbank_managecategories/categorymanager'; import Templates from 'core/templates'; import Modal from "core/modal"; import {get_string as getString} from "core/str"; +import BankSwitcher from 'core_question/bank_switcher'; +import Fetch from 'core/fetch'; +import Notification from 'core/notification'; +import * as CoreUrl from 'core/url'; import {eventTypes as inplaceEditableEventTypes} from 'core/local/inplace_editable/events'; export default class extends BaseComponent { @@ -45,6 +49,8 @@ export default class extends BaseComponent { CONTENT_CONTAINER: id => `#category-${id} .qbank_managecategories-childlistcontainer`, CHILD_LIST: id => `ul[data-categoryid="${id}"]`, PREVIOUS_SIBLING: sortorder => `:scope > [data-sortorder="${sortorder}"]`, + SWITCH_QUESTION_BANK: '[data-action="switch-question-bank"]', + MOVE_BANK_HEADER: '.bank-header', }; this.classes = { NO_BOTTOM_PADDING: 'pb-0', @@ -254,41 +260,50 @@ export default class extends BaseComponent { // Move to a new parent category. let newParent; const originParent = document.querySelector(this.selectors.CHILD_LIST(this.getElement().dataset.parent)); - if (parseInt(this.getElement().dataset.parent) !== element.parent) { - newParent = document.querySelector(this.selectors.CHILD_LIST(element.parent)); - if (!newParent) { - // The target category doesn't have a child list yet. We'd better create one. - newParent = await this.createChildList({categoryid: element.parent}); - } - this.getElement().dataset.parent = element.parent; - } else { - newParent = this.getElement().parentElement; - } - - // Move to a new position within the parent. - let previousSibling; - let nextSibling; - if (newParent.firstElementChild && parseInt(element.sortorder) <= parseInt(newParent.firstElementChild.dataset.sortorder)) { - // Move to the top of the list. - nextSibling = newParent.firstElementChild; - } else { - // Move later in the list. - previousSibling = newParent.querySelector(this.selectors.PREVIOUS_SIBLING(element.sortorder - 1)); - nextSibling = previousSibling?.nextElementSibling; - } - - // Check if this has actually moved, or if it's just having its sortorder updated due to another element moving. - const moved = (newParent !== this.getElement().parentElement || nextSibling !== this.getElement()); - - if (moved) { - if (nextSibling) { - // Move to the specified position in the list. - newParent.insertBefore(this.getElement(), nextSibling); + if (element.contextid === categorymanager.state.page.contextid) { + if (parseInt(this.getElement().dataset.parent) !== element.parent) { + newParent = document.querySelector(this.selectors.CHILD_LIST(element.parent)); + if (!newParent) { + // The target category doesn't have a child list yet. We'd better create one. + newParent = await this.createChildList({categoryid: element.parent}); + } + this.getElement().dataset.parent = element.parent; } else { - // Move to the end of the list (may also be the top of the list is empty). - newParent.appendChild(this.getElement()); + newParent = this.getElement().parentElement; } + + // Move to a new position within the parent. + let previousSibling; + let nextSibling; + if ( + newParent.firstElementChild && + parseInt(element.sortorder) <= parseInt(newParent.firstElementChild.dataset.sortorder) + ) { + // Move to the top of the list. + nextSibling = newParent.firstElementChild; + } else { + // Move later in the list. + previousSibling = newParent.querySelector(this.selectors.PREVIOUS_SIBLING(element.sortorder - 1)); + nextSibling = previousSibling?.nextElementSibling; + } + + // Check if this has actually moved, or if it's just having its sortorder updated due to another element moving. + const moved = (newParent !== this.getElement().parentElement || nextSibling !== this.getElement()); + + if (moved) { + if (nextSibling) { + // Move to the specified position in the list. + newParent.insertBefore(this.getElement(), nextSibling); + } else { + // Move to the end of the list (may also be the top of the list is empty). + newParent.appendChild(this.getElement()); + } + } + } else { + // The category was moved to a different context, it should no longer appear on this page. + this.getElement().remove(); } + if (originParent !== newParent) { // Update child count of old and new parent. this.reactive.stateManager.processUpdates([ @@ -325,44 +340,106 @@ export default class extends BaseComponent { } /** - * Recursively create a list of all valid destinations for a current category within a parent category. + * Create a list of category data from the elements on the page. * - * @param {Element} item - * @param {Number} movingCategoryId - * @return {Array} + * This will find the category list item elements on the page and extract the category ID, parent ID, and name from the dataset + * of each element, with any child categories nested underneath. This list can then be passed to createMoveCategoryList to + * create a tree of move targets. + * + * @param {Element} element The category element from the page. + * @return {Array} List of categories containing categoryId, parentId, categoryName, and a nested array of children. */ - createMoveCategoryList(item, movingCategoryId) { + getCategoryDataFromElements(element) { const categories = []; - if (item.children) { - let precedingSibling = null; - item.children.forEach(category => { - const categoryId = parseInt(category.dataset.categoryid); - // Don't create a target for the category that's moving. - if (categoryId === movingCategoryId) { - return; - } - // Create a target to move before this child. + if (element.children) { + element.children.forEach(category => { + // Add this category to the list. let child = { - categoryid: categoryId, - movingcategoryid: movingCategoryId, - precedingsiblingid: precedingSibling?.dataset.categoryid ?? 0, - parent: category.dataset.parent, - categoryname: category.dataset.categoryname, - categories: null, - current: categoryId === movingCategoryId, + categoryId: category.dataset.categoryid, + parentId: category.dataset.parent, + categoryName: category.dataset.categoryname, + children: null, }; const childList = category.querySelector(this.selectors.CATEGORY_LIST); if (childList) { // If the child has its own children, recursively make a list of those. - child.categories = this.createMoveCategoryList(childList, movingCategoryId); + child.children = this.getCategoryDataFromElements(childList); + } + categories.push(child); + }); + } + return categories; + } + + /** + * Get the category data from the records retrieved from the web service. + * + * This will process the list of category records and extract the category ID, parent ID, and name from each, + * with any child categories nested underneath. This list can then be passed to createMoveCategoryList to + * create a tree of move targets. + * + * @param {Object} record The category record. + * @return {Array} List of categories containing categoryId, parentId, categoryName, and a nested array of children. + */ + getCategoryDataFromRecords(record) { + const categories = []; + if (record.children) { + for (const childId in record.children) { + const category = record.children[childId]; + // Add this category to the list. + let child = { + categoryId: parseInt(category.id), + parentId: parseInt(category.parent), + categoryName: category.name, + children: null, + }; + if (category.children) { + // If the child has its own children, recursively make a list of those. + child.children = this.getCategoryDataFromRecords(category); + } + categories.push(child); + } + } + return categories; + } + + /** + * Recursively create a list of all valid destinations for a current category within a parent category. + * + * @param {Object} categoryData A list of category data from getCategoryDataFromElements() or getCategoryDataFromRecords(). + * @param {Number} movingCategoryId The ID of the category currently being moved. + * @return {Array} + */ + createMoveCategoryList(categoryData, movingCategoryId) { + const categories = []; + if (categoryData) { + let precedingSibling = null; + categoryData.forEach(category => { + // Don't create a target for the category that's moving. + if (category.categoryId === movingCategoryId) { + return; + } + // Create a target to move before this child. + let child = { + categoryid: category.categoryId, + movingcategoryid: movingCategoryId, + precedingsiblingid: precedingSibling?.categoryId ?? 0, + parent: category.parentId, + categoryname: category.categoryName, + categories: null, + current: category.categoryId === movingCategoryId, + }; + if (category.children) { + // If the child has its own children, recursively make a list of those. + child.categories = this.createMoveCategoryList(category.children, movingCategoryId); } else { // Otherwise, create a target to move as a new child of this one. child.categories = [ { movingcategoryid: movingCategoryId, precedingsiblingid: 0, - parent: categoryId, - categoryname: category.dataset.categoryname, + parent: category.categoryId, + categoryname: category.categoryName, categories: null, newchild: true, } @@ -372,14 +449,13 @@ export default class extends BaseComponent { precedingSibling = category; }); if (precedingSibling) { - const precedingId = parseInt(precedingSibling.dataset.categoryid); - if (precedingId !== movingCategoryId) { + if (precedingSibling.categoryId !== movingCategoryId) { // If this is the last child of its parent, also create a target to move the category after this one. categories.push({ movingcategoryid: movingCategoryId, - precedingsiblingid: precedingId, - parent: precedingSibling.dataset.parent, - categoryname: precedingSibling.dataset.categoryname, + precedingsiblingid: precedingSibling.categoryId, + parent: precedingSibling.parentId, + categoryname: precedingSibling.categoryName, categories: null, lastchild: true, }); @@ -409,34 +485,111 @@ export default class extends BaseComponent { item.setAttribute('aria-disabled', true); // Build the list of move links. - let moveList = {contexts: []}; - const contexts = document.querySelectorAll(this.selectors.CONTEXT); - contexts.forEach(context => { - const moveContext = { - contextname: context.dataset.contextname, - categories: [], - hascategories: false, - }; - moveContext.categories = this.createMoveCategoryList(context, parseInt(item.dataset.categoryid)); - moveContext.hascategories = moveContext.categories.length > 0; - moveList.contexts.push(moveContext); - }); + const contextElement = document.querySelector(this.selectors.CONTEXT); + const categoryData = this.getCategoryDataFromElements(contextElement); + const moveContext = { + contextname: contextElement.dataset.contextname, + contextid: contextElement.dataset.contextid, + cmid: categorymanager.state.page.cmid, + categories: [], + hascategories: false, + }; + const movingCategoryId = parseInt(item.dataset.categoryid); + moveContext.categories = this.createMoveCategoryList(categoryData, movingCategoryId); + moveContext.hascategories = moveContext.categories.length > 0; + + const moveCategory = getString('movecategory', 'qbank_managecategories', item.dataset.categoryname); const modal = await Modal.create({ - title: getString('movecategory', 'qbank_managecategories', item.dataset.categoryname), - body: Templates.render('qbank_managecategories/move_context_list', moveList), + title: moveCategory, + body: Templates.render('qbank_managecategories/move_context_list', moveContext), footer: '', show: true, large: true, }); - // Show modal and add click event for list items. - modal.getBody()[0].addEventListener('click', e => { - const target = e.target.closest(this.selectors.MODAL_CATEGORY_ITEM); - if (!target) { + const switcher = new BankSwitcher(); + // Show modal and add click event for list items and bank switcher. + modal.getBody()[0].addEventListener('click', async(e) => { + const categoryItem = e.target.closest(this.selectors.MODAL_CATEGORY_ITEM); + const moveHeader = e.currentTarget.querySelector(this.selectors.MOVE_BANK_HEADER); + if (categoryItem) { + categorymanager.moveCategory( + categoryItem.dataset.movingcategoryid, + categoryItem.dataset.parent, + categoryItem.dataset.precedingsiblingid, + ); + if (moveHeader.dataset.cmid !== categorymanager.state.page.cmid) { + const url = CoreUrl.relativeUrl( + '/question/bank/managecategories/category.php', + {cmid: moveHeader.dataset.cmid} + ); + const message = await getString( + 'categorymovedto', + 'qbank_managecategories', + {url, name: moveHeader.textContent}, + ); + Notification.addNotification({message: message, type: 'info'}); + } + modal.destroy(); return; } - categorymanager.moveCategory(target.dataset.movingcategoryid, target.dataset.parent, target.dataset.precedingsiblingid); - modal.destroy(); + const switchButton = e.target.closest(this.selectors.SWITCH_QUESTION_BANK); + if (switchButton) { + const pageState = categorymanager.state.page; + try { + const contextId = parseInt(contextElement.dataset.contextid); + await switcher.show(modal, pageState.courseid, contextId, parseInt(moveHeader.dataset.cmid), pageState.cmid); + } catch (ex) { + Notification.exception(ex); + } + } + }); + modal.getModal()[0].addEventListener('bankSwitched', async(e) => { + try { + const params = {coursemodule: e.detail.cmid}; + const categoriesResponse = await Fetch.performGet( + 'core_question', + 'categories', + {params}, + ); + const {context, categories} = await categoriesResponse.json(); + // Convert the list of categories into a nested tree. + for (const id in categories) { + const category = categories[id]; + if (category.parent > 0) { + const parentitem = categories[category.parent]; + if (!parentitem.hasOwnProperty('children')) { + parentitem.children = {}; + } + categories[category.parent].children[category.id] = category; + } + } + // Get the top category with all the others nested below. + let topCategory; + for (const id in categories) { + if (parseInt(categories[id].parent) === 0) { + topCategory = categories[id]; + } + } + const categoryData = this.getCategoryDataFromRecords(topCategory); + const moveContext = { + contextname: context.prefixedname, + contextid: context.prefixedname, + cmid: e.detail.cmid, + categories: [], + hascategories: false, + }; + moveContext.categories = this.createMoveCategoryList(categoryData, movingCategoryId); + moveContext.hascategories = moveContext.categories.length > 0; + modal.setBody( + Templates.render('qbank_managecategories/move_context_list', moveContext), + ); + await modal.getBodyPromise(); + modal.setTitle(moveCategory); + modal.setFooter(''); + } catch (ex) { + Notification.alert(getString('error', 'error'), ex); + } }); item.setAttribute('aria-disabled', false); } diff --git a/public/question/classes/question_category.php b/public/question/classes/question_category.php new file mode 100644 index 00000000000..6e466b47a30 --- /dev/null +++ b/public/question/classes/question_category.php @@ -0,0 +1,89 @@ +. + +namespace core_question; + +use core\context; +use JsonSerializable; +use stdClass; + +/** + * A simple value object representing a question category. + * + * When serialised to JSON for output via routes, this the name and intro will be formatted. + * + * @package core_question + * @copyright 2026 onwards Catalyst IT EU {@link https://catalyst-eu.net} + * @author Mark Johnson + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class question_category implements JsonSerializable { + /** + * Set properties and format strings. + * + * @param int $id The category ID + * @param string $name The raw category name, this will be formatted. + * @param int $contextid The module context ID the category belongs to. + * @param string $info The category's info, this with be formatted according to $infoformat. + * @param string $infoformat The format for $info. + * @param string $stamp Generated identifier for this category. + * @param int $parent Parent category ID. + * @param int $sortorder Category sort order within its parent. + * @param int $idnumber ID number. + */ + public function __construct( + /** @var int $id The category ID */ + public int $id, + /** @var string $name The raw category name, this will be formatted. */ + public string $name, + /** @var int $contextid The module context ID the category belongs to. */ + public int $contextid, + /** @var string $info The category's info, this with be formatted according to $infoformat. */ + public string $info, + /** @var string $infoformat The format for $info. */ + public string $infoformat, + /** @var string $stamp Generated identifier for this category. */ + public string $stamp, + /** @var int $parent Parent category ID. */ + public int $parent, + /** @var int $sortorder Category sort order within its parent. */ + public int $sortorder, + /** @var int $idnumber ID number. */ + public int $idnumber, + ) { + } + + /** + * Returns the properties with formatted 'name' and 'info' + * + * This is used when encoding the object for output, for example via web service routes. + * + * @return stdClass + */ + public function jsonSerialize(): stdClass { + $context = context::instance_by_id($this->contextid); + return (object) [ + 'id' => $this->id, + 'name' => format_string($this->name, ['context' => $context]), + 'contextid' => $this->contextid, + 'info' => format_text($this->info, $this->infoformat, ['context' => $context]), + 'stamp' => $this->stamp, + 'parent' => $this->parent, + 'sortorder' => $this->sortorder, + 'idnumber' => $this->idnumber, + ]; + } +} diff --git a/public/question/classes/route/api/bank.php b/public/question/classes/route/api/bank.php index 64f256f6361..cec4e0683d5 100644 --- a/public/question/classes/route/api/bank.php +++ b/public/question/classes/route/api/bank.php @@ -33,6 +33,8 @@ use core\router\schema\response\payload_response; use core\router\schema\response\response; use core_question\local\bank\formatted_bank; use core_question\local\bank\question_bank_helper; +use core_question\output\question_category_selector; +use core_question\question_category; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; @@ -179,4 +181,56 @@ class bank { ); } + #[route( + path: '/categories', // Resolves to /api/rest/v2/question/categories. + queryparams: [ + new query_coursemodule(), + ], + responses: [ + new response( + statuscode: 200, + description: 'OK', + content: [ + new json_media_type( + schema: new schema_object( + content: [ + 'context' => new array_of_strings(param::ALPHA, param::TEXT), + 'categories' => new array_of_things(question_category::class), + ], + ), + ), + ], + ), + ], + )] + /** + * Return a list of question categories with names and info formatted for output. + * + * @param ServerRequestInterface $request + * @param ResponseInterface $response + * @param module $coursemodulecontext The module context. + * @param question_category_selector $categoryselector Injected dependency. + * @return payload_response The course module context id and name, and a list of question categories in that context. + */ + public function categories( + ServerRequestInterface $request, + ResponseInterface $response, + module $coursemodulecontext, + question_category_selector $categoryselector, + ): payload_response { + require_login(); + $categories = $categoryselector->get_categories_for_contexts($coursemodulecontext->id, top: true); + return new payload_response( + request: $request, + response: $response, + payload: [ + 'context' => [ + 'id' => $coursemodulecontext->id, + 'name' => $coursemodulecontext->get_context_name(false), + 'prefixedname' => $coursemodulecontext->get_context_name(), + ], + 'categories' => $categories, + ], + ); + } }