From 38fe5cc384e9165ce96c70a17eb9fed53d6af3ca Mon Sep 17 00:00:00 2001 From: Jayce Birrell Date: Tue, 22 Jul 2025 08:52:21 +0930 Subject: [PATCH] MDL-85698 core: combo box informs screen reader users --- lang/en/moodle.php | 3 ++ .../comboboxsearch/search_combobox.min.js | 4 +- .../comboboxsearch/search_combobox.min.js.map | 2 +- lib/amd/src/comboboxsearch/search_combobox.js | 51 +++++++++++++++++++ lib/templates/comboboxsearch.mustache | 2 + 5 files changed, 59 insertions(+), 3 deletions(-) diff --git a/lang/en/moodle.php b/lang/en/moodle.php index 5cf4c0670c8..f32ef90bae8 100644 --- a/lang/en/moodle.php +++ b/lang/en/moodle.php @@ -1451,6 +1451,7 @@ $string['moveselectedcategoriesto'] = 'Move selected categories to'; $string['moveselectedcoursesto'] = 'Move selected courses to...'; $string['movetoanotherfolder'] = 'Move to another folder'; $string['moveup'] = 'Move up'; +$string['multipleitemsfound'] = 'There are {$a} items found.'; $string['mustconfirm'] = 'You need to confirm your account'; $string['mustchangepassword'] = 'The new password must be different than the current one'; $string['mycourses'] = 'My courses'; @@ -1537,6 +1538,7 @@ $string['nograde'] = 'No grade'; $string['nohelpforactivityorresource'] = 'There is currently no help associated with this resource or activity'; $string['nochange'] = 'No change'; $string['noimagesyet'] = 'No images have been uploaded to your course yet'; +$string['noitemsfound'] = 'No items found.'; $string['nologsfound'] = 'No logs have been found'; $string['nomatchingusers'] = 'No users match \'{$a}\''; $string['nomorecourses'] = 'No more matching courses could be found'; @@ -1611,6 +1613,7 @@ $string['numyears'] = '{$a} years'; $string['ok'] = 'OK'; $string['oldpassword'] = 'Current password'; $string['olduserdirectory'] = 'This is the OLD users directory, and is no longer needed. You may safely delete it. The files it contains have been copied to the NEW user directory.'; +$string['oneitemfound'] = 'There is 1 item found.'; $string['opendrawerblocks'] = 'Open block drawer'; $string['opendrawerindex'] = 'Open course index'; $string['opensinnewwindow'] = 'Opens in new window'; diff --git a/lib/amd/build/comboboxsearch/search_combobox.min.js b/lib/amd/build/comboboxsearch/search_combobox.min.js index 2b194381fe7..94ff99fb432 100644 --- a/lib/amd/build/comboboxsearch/search_combobox.min.js +++ b/lib/amd/build/comboboxsearch/search_combobox.min.js @@ -1,10 +1,10 @@ -define("core/comboboxsearch/search_combobox",["exports","jquery","core/utils","core/pending"],(function(_exports,_jquery,_utils,_pending){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj} +define("core/comboboxsearch/search_combobox",["exports","jquery","core/utils","core/pending","core/str"],(function(_exports,_jquery,_utils,_pending,_str){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj} /** * The class that manages the state of the search within a combobox. * * @module core/comboboxsearch/search_combobox * @copyright 2023 Mathew May * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_pending=_interopRequireDefault(_pending);return _exports.default=class{constructor(){var _this$searchInput$val,_this$searchInput;_defineProperty(this,"selectors",{component:this.componentSelector(),toggle:'[data-toggle="dropdown"]',instance:'[data-region="instance"]',input:'[data-action="search"]',clearSearch:'[data-action="clearsearch"]',dropdown:this.dropdownSelector(),resultitems:'[role="option"]',viewall:"#select-all",combobox:'[role="combobox"]'}),_defineProperty(this,"matchedResults",[]),_defineProperty(this,"searchTerm",""),_defineProperty(this,"preppedSearchTerm",null),_defineProperty(this,"resultNodes",[]),_defineProperty(this,"currentNode",null),_defineProperty(this,"currentViewAll",null),_defineProperty(this,"dataset",null),_defineProperty(this,"datasetSize",0),_defineProperty(this,"component",document.querySelector(this.selectors.component)),_defineProperty(this,"instance",this.component.dataset.instance),_defineProperty(this,"toggle",this.component.querySelector(this.selectors.toggle)),_defineProperty(this,"searchInput",this.component.querySelector(this.selectors.input)),_defineProperty(this,"searchDropdown",this.component.querySelector(this.selectors.dropdown)),_defineProperty(this,"clearSearchButton",this.component.querySelector(this.selectors.clearSearch)),_defineProperty(this,"combobox",this.component.querySelector(this.selectors.combobox)),_defineProperty(this,"$component",(0,_jquery.default)(this.component)),this.setSearchTerms(null!==(_this$searchInput$val=null===(_this$searchInput=this.searchInput)||void 0===_this$searchInput?void 0:_this$searchInput.value)&&void 0!==_this$searchInput$val?_this$searchInput$val:""),this.registerClickHandlers(),null!==this.searchInput&&(this.registerInputHandlers(),this.registerChangeHandlers()),""!==this.getSearchTerm()&&this.clearSearchButton.classList.remove("d-none")}fetchDataset(){throw new Error("fetchDataset() must be implemented in ".concat(this.constructor.name))}filterDataset(dataset){throw new Error("filterDataset(".concat(dataset,") must be implemented in ").concat(this.constructor.name))}filterMatchDataset(){throw new Error("filterMatchDataset() must be implemented in ".concat(this.constructor.name))}renderDropdown(){throw new Error("renderDropdown() must be implemented in ".concat(this.constructor.name))}componentSelector(){throw new Error("componentSelector() must be implemented in ".concat(this.constructor.name))}dropdownSelector(){throw new Error("dropdownSelector() must be implemented in ".concat(this.constructor.name))}triggerSelector(){window.console.warning("triggerSelector() is deprecated. Consider using this.selectors.toggle")}async getDataset(){return this.dataset||(this.dataset=await this.fetchDataset()),this.datasetSize=this.dataset.length,this.dataset}getDatasetSize(){return this.datasetSize}getMatchedResults(){return this.matchedResults}setMatchedResults(result){this.matchedResults=result}getSearchTerm(){return this.searchTerm}getPreppedSearchTerm(){return this.preppedSearchTerm}setSearchTerms(result){this.searchTerm=result,this.preppedSearchTerm=result.toLowerCase()}getHTMLElements(){return this.updateNodes(),{searchDropdown:this.searchDropdown,currentViewAll:this.currentViewAll,searchInput:this.searchInput,clearSearchButton:this.clearSearchButton,trigger:this.component.querySelector(this.selectors.trigger)}}closeSearch(){let clear=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.toggleDropdown(),clear&&(this.clearSearchButton.classList.add("d-none"),this.setSearchTerms(""),this.searchInput.value="")}searchResultsVisible(){const{searchDropdown:searchDropdown}=this.getHTMLElements();return null!==searchDropdown.offsetParent}toggleDropdown(){arguments.length>0&&void 0!==arguments[0]&&arguments[0]?(0,_jquery.default)(this.toggle).dropdown("show"):(0,_jquery.default)(this.toggle).dropdown("hide")}updateNodes(){this.resultNodes=[...this.component.querySelectorAll(this.selectors.resultitems)],this.currentNode=this.resultNodes.find((r=>r.id===document.activeElement.id)),this.currentViewAll=this.component.querySelector(this.selectors.viewall),this.clearSearchButton=this.component.querySelector(this.selectors.clearSearch),this.searchInput=this.component.querySelector(this.selectors.input),this.searchDropdown=this.component.querySelector(this.selectors.dropdown)}registerClickHandlers(){this.component.addEventListener("click",this.clickHandler.bind(this))}registerChangeHandlers(){this.component.querySelector("#".concat(this.combobox.dataset.inputElement)).addEventListener("change",this.changeHandler.bind(this))}registerInputHandlers(){this.searchInput.addEventListener("input",(0,_utils.debounce)((async()=>{if(this.getSearchTerm()===this.searchInput.value&&this.searchResultsVisible())return void window.console.warn("Search term matches input value - skipping");this.setSearchTerms(this.searchInput.value);const pendingPromise=new _pending.default;""===this.getSearchTerm()?(this.toggleDropdown(),this.clearSearchButton.classList.add("d-none"),await this.filterrenderpipe()):(this.clearSearchButton.classList.remove("d-none"),await this.renderAndShow()),pendingPromise.resolve()}),300,{pending:!0}))}async filterrenderpipe(){this.updateNodes(),this.setMatchedResults(await this.filterDataset(await this.getDataset())),this.filterMatchDataset(),await this.renderDropdown()}async renderAndShow(){this.setMatchedResults(await this.filterDataset(await this.getDataset())),await this.filterMatchDataset(),await this.renderDropdown(),this.toggleDropdown(!0)}async clickHandler(e){this.updateNodes(),e.target.closest(this.selectors.clearSearch)&&(this.closeSearch(!0),this.searchInput.focus(),this.searchInput.removeAttribute("aria-activedescendant")),""!==this.getSearchTerm()&&!this.getHTMLElements().searchDropdown.classList.contains("show")&&e.target.closest(this.selectors.input)&&await this.renderAndShow()}changeHandler(e){}},_exports.default})); + */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_pending=_interopRequireDefault(_pending);return _exports.default=class{constructor(){var _this$searchInput$val,_this$searchInput;_defineProperty(this,"selectors",{component:this.componentSelector(),toggle:'[data-toggle="dropdown"]',instance:'[data-region="instance"]',input:'[data-action="search"]',clearSearch:'[data-action="clearsearch"]',dropdown:this.dropdownSelector(),resultitems:'[role="option"]',viewall:"#select-all",combobox:'[role="combobox"]'}),_defineProperty(this,"matchedResults",[]),_defineProperty(this,"searchTerm",""),_defineProperty(this,"preppedSearchTerm",null),_defineProperty(this,"resultNodes",[]),_defineProperty(this,"currentNode",null),_defineProperty(this,"currentViewAll",null),_defineProperty(this,"dataset",null),_defineProperty(this,"datasetSize",0),_defineProperty(this,"component",document.querySelector(this.selectors.component)),_defineProperty(this,"instance",this.component.dataset.instance),_defineProperty(this,"toggle",this.component.querySelector(this.selectors.toggle)),_defineProperty(this,"searchInput",this.component.querySelector(this.selectors.input)),_defineProperty(this,"searchDropdown",this.component.querySelector(this.selectors.dropdown)),_defineProperty(this,"clearSearchButton",this.component.querySelector(this.selectors.clearSearch)),_defineProperty(this,"combobox",this.component.querySelector(this.selectors.combobox)),_defineProperty(this,"$component",(0,_jquery.default)(this.component)),this.setSearchTerms(null!==(_this$searchInput$val=null===(_this$searchInput=this.searchInput)||void 0===_this$searchInput?void 0:_this$searchInput.value)&&void 0!==_this$searchInput$val?_this$searchInput$val:""),this.registerClickHandlers(),null!==this.searchInput&&(this.registerInputHandlers(),this.registerChangeHandlers()),""!==this.getSearchTerm()&&this.clearSearchButton.classList.remove("d-none")}fetchDataset(){throw new Error("fetchDataset() must be implemented in ".concat(this.constructor.name))}filterDataset(dataset){throw new Error("filterDataset(".concat(dataset,") must be implemented in ").concat(this.constructor.name))}filterMatchDataset(){throw new Error("filterMatchDataset() must be implemented in ".concat(this.constructor.name))}renderDropdown(){throw new Error("renderDropdown() must be implemented in ".concat(this.constructor.name))}componentSelector(){throw new Error("componentSelector() must be implemented in ".concat(this.constructor.name))}dropdownSelector(){throw new Error("dropdownSelector() must be implemented in ".concat(this.constructor.name))}triggerSelector(){window.console.warning("triggerSelector() is deprecated. Consider using this.selectors.toggle")}async getDataset(){return this.dataset||(this.dataset=await this.fetchDataset()),this.datasetSize=this.dataset.length,this.dataset}getDatasetSize(){return this.datasetSize}getMatchedResults(){return this.matchedResults}setMatchedResults(result){this.matchedResults=result}getSearchTerm(){return this.searchTerm}getPreppedSearchTerm(){return this.preppedSearchTerm}setSearchTerms(result){this.searchTerm=result,this.preppedSearchTerm=result.toLowerCase()}getHTMLElements(){return this.updateNodes(),{searchDropdown:this.searchDropdown,currentViewAll:this.currentViewAll,searchInput:this.searchInput,clearSearchButton:this.clearSearchButton,trigger:this.component.querySelector(this.selectors.trigger)}}closeSearch(){let clear=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.toggleDropdown(),clear&&(this.clearSearchButton.classList.add("d-none"),this.setSearchTerms(""),this.searchInput.value="")}searchResultsVisible(){const{searchDropdown:searchDropdown}=this.getHTMLElements();return null!==searchDropdown.offsetParent}toggleDropdown(){arguments.length>0&&void 0!==arguments[0]&&arguments[0]?(0,_jquery.default)(this.toggle).dropdown("show"):(0,_jquery.default)(this.toggle).dropdown("hide")}updateNodes(){this.resultNodes=[...this.component.querySelectorAll(this.selectors.resultitems)],this.currentNode=this.resultNodes.find((r=>r.id===document.activeElement.id)),this.currentViewAll=this.component.querySelector(this.selectors.viewall),this.clearSearchButton=this.component.querySelector(this.selectors.clearSearch),this.searchInput=this.component.querySelector(this.selectors.input),this.searchDropdown=this.component.querySelector(this.selectors.dropdown)}registerClickHandlers(){this.component.addEventListener("click",this.clickHandler.bind(this))}registerChangeHandlers(){this.component.querySelector("#".concat(this.combobox.dataset.inputElement)).addEventListener("change",this.changeHandler.bind(this))}registerInputHandlers(){this.searchInput.addEventListener("input",(0,_utils.debounce)((async()=>{if(this.getSearchTerm()===this.searchInput.value&&this.searchResultsVisible())return void window.console.warn("Search term matches input value - skipping");this.setSearchTerms(this.searchInput.value);const pendingPromise=new _pending.default;""===this.getSearchTerm()?(this.toggleDropdown(),this.clearSearchButton.classList.add("d-none"),await this.filterrenderpipe()):(this.clearSearchButton.classList.remove("d-none"),await this.renderAndShow()),pendingPromise.resolve()}),300,{pending:!0}))}async filterrenderpipe(){this.updateNodes(),this.setMatchedResults(await this.filterDataset(await this.getDataset())),this.filterMatchDataset(),await this.renderDropdown(),await this.updateLiveRegion()}async renderAndShow(){this.setMatchedResults(await this.filterDataset(await this.getDataset())),await this.filterMatchDataset(),await this.renderDropdown(),this.toggleDropdown(!0),await this.updateLiveRegion()}async clickHandler(e){this.updateNodes(),e.target.closest(this.selectors.clearSearch)&&(this.closeSearch(!0),this.searchInput.focus(),this.searchInput.removeAttribute("aria-activedescendant")),""!==this.getSearchTerm()&&!this.getHTMLElements().searchDropdown.classList.contains("show")&&e.target.closest(this.selectors.input)&&await this.renderAndShow()}changeHandler(e){}async updateLiveRegion(){var _this$searchDropdown;if(null===(_this$searchDropdown=this.searchDropdown)||void 0===_this$searchDropdown||!_this$searchDropdown.id)return;const idParts=this.searchDropdown.id.split("-");if(idParts.length<3)return;const[,instanceId,id]=idParts,liveRegion=document.getElementById("combobox-status-".concat(instanceId,"-").concat(id));if(!liveRegion)return;const resultCount=this.getMatchedResults().length;let message;message=0===resultCount?await(0,_str.get_string)("noitemsfound","core"):1===resultCount?await(0,_str.get_string)("oneitemfound","core"):await(0,_str.get_string)("multipleitemsfound","core",resultCount),liveRegion.textContent=message,this.liveRegionTimeout&&clearTimeout(this.liveRegionTimeout),this.liveRegionTimeout=setTimeout((()=>{liveRegion.textContent="",this.liveRegionTimeout=null}),4e3)}},_exports.default})); //# sourceMappingURL=search_combobox.min.js.map \ No newline at end of file diff --git a/lib/amd/build/comboboxsearch/search_combobox.min.js.map b/lib/amd/build/comboboxsearch/search_combobox.min.js.map index 61b42bbc2e1..73f638f637b 100644 --- a/lib/amd/build/comboboxsearch/search_combobox.min.js.map +++ b/lib/amd/build/comboboxsearch/search_combobox.min.js.map @@ -1 +1 @@ -{"version":3,"file":"search_combobox.min.js","sources":["../../src/comboboxsearch/search_combobox.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\nimport $ from 'jquery';\nimport {debounce} from 'core/utils';\nimport Pending from 'core/pending';\n\n/**\n * The class that manages the state of the search within a combobox.\n *\n * @module core/comboboxsearch/search_combobox\n * @copyright 2023 Mathew May \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nexport default class {\n // Define our standard lookups.\n selectors = {\n component: this.componentSelector(),\n toggle: '[data-toggle=\"dropdown\"]',\n instance: '[data-region=\"instance\"]',\n input: '[data-action=\"search\"]',\n clearSearch: '[data-action=\"clearsearch\"]',\n dropdown: this.dropdownSelector(),\n resultitems: '[role=\"option\"]',\n viewall: '#select-all',\n combobox: '[role=\"combobox\"]',\n };\n\n // The results from the called filter function.\n matchedResults = [];\n\n // What did the user search for?\n searchTerm = '';\n\n // What the user searched for as a lowercase.\n preppedSearchTerm = null;\n\n // The DOM nodes after the dropdown render.\n resultNodes = [];\n\n // Where does the user currently have focus?\n currentNode = null;\n\n // The current node for the view all link.\n currentViewAll = null;\n\n dataset = null;\n\n datasetSize = 0;\n\n // DOM nodes that persist.\n component = document.querySelector(this.selectors.component);\n instance = this.component.dataset.instance;\n toggle = this.component.querySelector(this.selectors.toggle);\n searchInput = this.component.querySelector(this.selectors.input);\n searchDropdown = this.component.querySelector(this.selectors.dropdown);\n clearSearchButton = this.component.querySelector(this.selectors.clearSearch);\n combobox = this.component.querySelector(this.selectors.combobox);\n $component = $(this.component);\n\n constructor() {\n // If we have a search input, try to get the value otherwise fallback.\n this.setSearchTerms(this.searchInput?.value ?? '');\n // Begin handling the base search component.\n this.registerClickHandlers();\n\n // Conditionally set up the input handler since we don't know exactly how we were called.\n // If the combobox is rendered later, then you'll need to call this.registerInputHandlers() manually.\n // An example of this is the collapse columns in the gradebook.\n if (this.searchInput !== null) {\n this.registerInputHandlers();\n this.registerChangeHandlers();\n }\n\n // If we have a search term, show the clear button.\n if (this.getSearchTerm() !== '') {\n this.clearSearchButton.classList.remove('d-none');\n }\n }\n\n /**\n * Stub out a required function.\n */\n fetchDataset() {\n throw new Error(`fetchDataset() must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n * @param {Array} dataset\n */\n filterDataset(dataset) {\n throw new Error(`filterDataset(${dataset}) must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n */\n filterMatchDataset() {\n throw new Error(`filterMatchDataset() must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n */\n renderDropdown() {\n throw new Error(`renderDropdown() must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n */\n componentSelector() {\n throw new Error(`componentSelector() must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n */\n dropdownSelector() {\n throw new Error(`dropdownSelector() must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n * @deprecated since Moodle 4.4\n */\n triggerSelector() {\n window.console.warning('triggerSelector() is deprecated. Consider using this.selectors.toggle');\n }\n\n /**\n * Return the dataset that we will be searching upon.\n *\n * @returns {Promise}\n */\n async getDataset() {\n if (!this.dataset) {\n this.dataset = await this.fetchDataset();\n }\n this.datasetSize = this.dataset.length;\n return this.dataset;\n }\n\n /**\n * Return the size of the dataset.\n *\n * @returns {number}\n */\n getDatasetSize() {\n return this.datasetSize;\n }\n\n /**\n * Return the results of the filter upon the dataset.\n *\n * @returns {Array}\n */\n getMatchedResults() {\n return this.matchedResults;\n }\n\n /**\n * Given a filter has been run across the dataset, store the matched results.\n *\n * @param {Array} result\n */\n setMatchedResults(result) {\n this.matchedResults = result;\n }\n\n /**\n * Get the value that the user entered.\n *\n * @returns {string}\n */\n getSearchTerm() {\n return this.searchTerm;\n }\n\n /**\n * Get the transformed search value.\n *\n * @returns {string}\n */\n getPreppedSearchTerm() {\n return this.preppedSearchTerm;\n }\n\n /**\n * When a user searches for something, set our variable to manage it.\n *\n * @param {string} result\n */\n setSearchTerms(result) {\n this.searchTerm = result;\n this.preppedSearchTerm = result.toLowerCase();\n }\n\n /**\n * Return an object containing a handfull of dom nodes that we sometimes need the value of.\n *\n * @returns {object}\n */\n getHTMLElements() {\n this.updateNodes();\n return {\n searchDropdown: this.searchDropdown,\n currentViewAll: this.currentViewAll,\n searchInput: this.searchInput,\n clearSearchButton: this.clearSearchButton,\n trigger: this.component.querySelector(this.selectors.trigger),\n };\n }\n\n /**\n * When called, close the dropdown and reset the input field attributes.\n *\n * @param {Boolean} clear Conditionality clear the input box.\n */\n closeSearch(clear = false) {\n this.toggleDropdown();\n if (clear) {\n // Hide the \"clear\" search button search bar.\n this.clearSearchButton.classList.add('d-none');\n // Clear the entered search query in the search bar and hide the search results container.\n this.setSearchTerms('');\n this.searchInput.value = \"\";\n }\n }\n\n /**\n * Check whether search results are currently visible.\n *\n * @returns {Boolean}\n */\n searchResultsVisible() {\n const {searchDropdown} = this.getHTMLElements();\n // If a Node is not visible, then the offsetParent is null.\n return searchDropdown.offsetParent !== null;\n }\n\n /**\n * When called, update the dropdown fields.\n *\n * @param {Boolean} on Flag to toggle hiding or showing values.\n */\n toggleDropdown(on = false) {\n if (on) {\n $(this.toggle).dropdown('show');\n } else {\n $(this.toggle).dropdown('hide');\n }\n }\n\n /**\n * These class members change when a new result set is rendered. So update for fresh data.\n */\n updateNodes() {\n this.resultNodes = [...this.component.querySelectorAll(this.selectors.resultitems)];\n this.currentNode = this.resultNodes.find(r => r.id === document.activeElement.id);\n this.currentViewAll = this.component.querySelector(this.selectors.viewall);\n this.clearSearchButton = this.component.querySelector(this.selectors.clearSearch);\n this.searchInput = this.component.querySelector(this.selectors.input);\n this.searchDropdown = this.component.querySelector(this.selectors.dropdown);\n }\n\n /**\n * Register clickable event listeners.\n */\n registerClickHandlers() {\n // Register click events within the component.\n this.component.addEventListener('click', this.clickHandler.bind(this));\n }\n\n /**\n * Register change event listeners.\n */\n registerChangeHandlers() {\n const valueElement = this.component.querySelector(`#${this.combobox.dataset.inputElement}`);\n valueElement.addEventListener('change', this.changeHandler.bind(this));\n }\n\n /**\n * Register input event listener for the text input area.\n */\n registerInputHandlers() {\n // Register & handle the text input.\n this.searchInput.addEventListener('input', debounce(async() => {\n if (this.getSearchTerm() === this.searchInput.value && this.searchResultsVisible()) {\n window.console.warn(`Search term matches input value - skipping`);\n // The debounce canhappen multiple times quickly. GRrargh\n return;\n }\n this.setSearchTerms(this.searchInput.value);\n\n const pendingPromise = new Pending();\n if (this.getSearchTerm() === '') {\n this.toggleDropdown();\n this.clearSearchButton.classList.add('d-none');\n await this.filterrenderpipe();\n } else {\n this.clearSearchButton.classList.remove('d-none');\n await this.renderAndShow();\n }\n pendingPromise.resolve();\n }, 300, {pending: true}));\n }\n\n /**\n * Update any changeable nodes, filter and then render the result.\n *\n * @returns {Promise}\n */\n async filterrenderpipe() {\n this.updateNodes();\n this.setMatchedResults(await this.filterDataset(await this.getDataset()));\n this.filterMatchDataset();\n await this.renderDropdown();\n }\n\n /**\n * A combo method to take the matching fields and render out the results.\n *\n * @returns {Promise}\n */\n async renderAndShow() {\n // User has given something for us to filter against.\n this.setMatchedResults(await this.filterDataset(await this.getDataset()));\n await this.filterMatchDataset();\n // Replace the dropdown node contents and show the results.\n await this.renderDropdown();\n // Set the dropdown to open.\n this.toggleDropdown(true);\n }\n\n /**\n * The handler for when a user interacts with the component.\n *\n * @param {MouseEvent} e The triggering event that we are working with.\n */\n async clickHandler(e) {\n this.updateNodes();\n // The \"clear search\" button is triggered.\n if (e.target.closest(this.selectors.clearSearch)) {\n this.closeSearch(true);\n this.searchInput.focus();\n // Remove aria-activedescendant when the available options change.\n this.searchInput.removeAttribute('aria-activedescendant');\n }\n // User may have accidentally clicked off the dropdown and wants to reopen it.\n if (\n this.getSearchTerm() !== ''\n && !this.getHTMLElements().searchDropdown.classList.contains('show')\n && e.target.closest(this.selectors.input)\n ) {\n await this.renderAndShow();\n }\n }\n\n /**\n * The handler for when a user changes the value of the component (selects an option from the dropdown).\n *\n * @param {Event} e The change event.\n */\n // eslint-disable-next-line no-unused-vars\n changeHandler(e) {\n // Components may override this method to do something.\n }\n}\n"],"names":["constructor","component","this","componentSelector","toggle","instance","input","clearSearch","dropdown","dropdownSelector","resultitems","viewall","combobox","document","querySelector","selectors","dataset","setSearchTerms","searchInput","_this$searchInput","value","registerClickHandlers","registerInputHandlers","registerChangeHandlers","getSearchTerm","clearSearchButton","classList","remove","fetchDataset","Error","name","filterDataset","filterMatchDataset","renderDropdown","triggerSelector","window","console","warning","datasetSize","length","getDatasetSize","getMatchedResults","matchedResults","setMatchedResults","result","searchTerm","getPreppedSearchTerm","preppedSearchTerm","toLowerCase","getHTMLElements","updateNodes","searchDropdown","currentViewAll","trigger","closeSearch","clear","toggleDropdown","add","searchResultsVisible","offsetParent","resultNodes","querySelectorAll","currentNode","find","r","id","activeElement","addEventListener","clickHandler","bind","inputElement","changeHandler","async","warn","pendingPromise","Pending","filterrenderpipe","renderAndShow","resolve","pending","getDataset","e","target","closest","focus","removeAttribute","contains"],"mappings":";;;;;;;qMAyEIA,2FA5CY,CACRC,UAAWC,KAAKC,oBAChBC,OAAQ,2BACRC,SAAU,2BACVC,MAAO,yBACPC,YAAa,8BACbC,SAAUN,KAAKO,mBACfC,YAAa,kBACbC,QAAS,cACTC,SAAU,4DAIG,sCAGJ,6CAGO,yC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CASb7B,mBACAP,wBAAwBzC,KAAK6B,oBAAoB7B,KAAK8E,oBACtDhD,2BACC9B,KAAK+B,4CAUNU,wBAAwBzC,KAAK6B,oBAAoB7B,KAAK8E,qBACrD9E,KAAK8B,2BAEL9B,KAAK+B,sBAENuB,gBAAe,sBAQLyB,QACV/B,cAED+B,EAAEC,OAAOC,QAAQjF,KAAKa,UAAUR,oBAC3B+C,aAAY,QACZpC,YAAYkE,aAEZlE,YAAYmE,gBAAgB,0BAIR,KAAzBnF,KAAKsB,kBACDtB,KAAK+C,kBAAkBE,eAAezB,UAAU4D,SAAS,SAC1DL,EAAEC,OAAOC,QAAQjF,KAAKa,UAAUT,cAE7BJ,KAAK2E,gBAUnBN,cAAcU"} \ No newline at end of file +{"version":3,"file":"search_combobox.min.js","sources":["../../src/comboboxsearch/search_combobox.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\nimport $ from 'jquery';\nimport {debounce} from 'core/utils';\nimport Pending from 'core/pending';\nimport {get_string as getString} from 'core/str';\n\n\n/**\n * The class that manages the state of the search within a combobox.\n *\n * @module core/comboboxsearch/search_combobox\n * @copyright 2023 Mathew May \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nexport default class {\n // Define our standard lookups.\n selectors = {\n component: this.componentSelector(),\n toggle: '[data-toggle=\"dropdown\"]',\n instance: '[data-region=\"instance\"]',\n input: '[data-action=\"search\"]',\n clearSearch: '[data-action=\"clearsearch\"]',\n dropdown: this.dropdownSelector(),\n resultitems: '[role=\"option\"]',\n viewall: '#select-all',\n combobox: '[role=\"combobox\"]',\n };\n\n // The results from the called filter function.\n matchedResults = [];\n\n // What did the user search for?\n searchTerm = '';\n\n // What the user searched for as a lowercase.\n preppedSearchTerm = null;\n\n // The DOM nodes after the dropdown render.\n resultNodes = [];\n\n // Where does the user currently have focus?\n currentNode = null;\n\n // The current node for the view all link.\n currentViewAll = null;\n\n dataset = null;\n\n datasetSize = 0;\n\n // DOM nodes that persist.\n component = document.querySelector(this.selectors.component);\n instance = this.component.dataset.instance;\n toggle = this.component.querySelector(this.selectors.toggle);\n searchInput = this.component.querySelector(this.selectors.input);\n searchDropdown = this.component.querySelector(this.selectors.dropdown);\n clearSearchButton = this.component.querySelector(this.selectors.clearSearch);\n combobox = this.component.querySelector(this.selectors.combobox);\n $component = $(this.component);\n\n constructor() {\n // If we have a search input, try to get the value otherwise fallback.\n this.setSearchTerms(this.searchInput?.value ?? '');\n // Begin handling the base search component.\n this.registerClickHandlers();\n\n // Conditionally set up the input handler since we don't know exactly how we were called.\n // If the combobox is rendered later, then you'll need to call this.registerInputHandlers() manually.\n // An example of this is the collapse columns in the gradebook.\n if (this.searchInput !== null) {\n this.registerInputHandlers();\n this.registerChangeHandlers();\n }\n\n // If we have a search term, show the clear button.\n if (this.getSearchTerm() !== '') {\n this.clearSearchButton.classList.remove('d-none');\n }\n }\n\n /**\n * Stub out a required function.\n */\n fetchDataset() {\n throw new Error(`fetchDataset() must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n * @param {Array} dataset\n */\n filterDataset(dataset) {\n throw new Error(`filterDataset(${dataset}) must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n */\n filterMatchDataset() {\n throw new Error(`filterMatchDataset() must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n */\n renderDropdown() {\n throw new Error(`renderDropdown() must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n */\n componentSelector() {\n throw new Error(`componentSelector() must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n */\n dropdownSelector() {\n throw new Error(`dropdownSelector() must be implemented in ${this.constructor.name}`);\n }\n\n /**\n * Stub out a required function.\n * @deprecated since Moodle 4.4\n */\n triggerSelector() {\n window.console.warning('triggerSelector() is deprecated. Consider using this.selectors.toggle');\n }\n\n /**\n * Return the dataset that we will be searching upon.\n *\n * @returns {Promise}\n */\n async getDataset() {\n if (!this.dataset) {\n this.dataset = await this.fetchDataset();\n }\n this.datasetSize = this.dataset.length;\n return this.dataset;\n }\n\n /**\n * Return the size of the dataset.\n *\n * @returns {number}\n */\n getDatasetSize() {\n return this.datasetSize;\n }\n\n /**\n * Return the results of the filter upon the dataset.\n *\n * @returns {Array}\n */\n getMatchedResults() {\n return this.matchedResults;\n }\n\n /**\n * Given a filter has been run across the dataset, store the matched results.\n *\n * @param {Array} result\n */\n setMatchedResults(result) {\n this.matchedResults = result;\n }\n\n /**\n * Get the value that the user entered.\n *\n * @returns {string}\n */\n getSearchTerm() {\n return this.searchTerm;\n }\n\n /**\n * Get the transformed search value.\n *\n * @returns {string}\n */\n getPreppedSearchTerm() {\n return this.preppedSearchTerm;\n }\n\n /**\n * When a user searches for something, set our variable to manage it.\n *\n * @param {string} result\n */\n setSearchTerms(result) {\n this.searchTerm = result;\n this.preppedSearchTerm = result.toLowerCase();\n }\n\n /**\n * Return an object containing a handfull of dom nodes that we sometimes need the value of.\n *\n * @returns {object}\n */\n getHTMLElements() {\n this.updateNodes();\n return {\n searchDropdown: this.searchDropdown,\n currentViewAll: this.currentViewAll,\n searchInput: this.searchInput,\n clearSearchButton: this.clearSearchButton,\n trigger: this.component.querySelector(this.selectors.trigger),\n };\n }\n\n /**\n * When called, close the dropdown and reset the input field attributes.\n *\n * @param {Boolean} clear Conditionality clear the input box.\n */\n closeSearch(clear = false) {\n this.toggleDropdown();\n if (clear) {\n // Hide the \"clear\" search button search bar.\n this.clearSearchButton.classList.add('d-none');\n // Clear the entered search query in the search bar and hide the search results container.\n this.setSearchTerms('');\n this.searchInput.value = \"\";\n }\n }\n\n /**\n * Check whether search results are currently visible.\n *\n * @returns {Boolean}\n */\n searchResultsVisible() {\n const {searchDropdown} = this.getHTMLElements();\n // If a Node is not visible, then the offsetParent is null.\n return searchDropdown.offsetParent !== null;\n }\n\n /**\n * When called, update the dropdown fields.\n *\n * @param {Boolean} on Flag to toggle hiding or showing values.\n */\n toggleDropdown(on = false) {\n if (on) {\n $(this.toggle).dropdown('show');\n } else {\n $(this.toggle).dropdown('hide');\n }\n }\n\n /**\n * These class members change when a new result set is rendered. So update for fresh data.\n */\n updateNodes() {\n this.resultNodes = [...this.component.querySelectorAll(this.selectors.resultitems)];\n this.currentNode = this.resultNodes.find(r => r.id === document.activeElement.id);\n this.currentViewAll = this.component.querySelector(this.selectors.viewall);\n this.clearSearchButton = this.component.querySelector(this.selectors.clearSearch);\n this.searchInput = this.component.querySelector(this.selectors.input);\n this.searchDropdown = this.component.querySelector(this.selectors.dropdown);\n }\n\n /**\n * Register clickable event listeners.\n */\n registerClickHandlers() {\n // Register click events within the component.\n this.component.addEventListener('click', this.clickHandler.bind(this));\n }\n\n /**\n * Register change event listeners.\n */\n registerChangeHandlers() {\n const valueElement = this.component.querySelector(`#${this.combobox.dataset.inputElement}`);\n valueElement.addEventListener('change', this.changeHandler.bind(this));\n }\n\n /**\n * Register input event listener for the text input area.\n */\n registerInputHandlers() {\n // Register & handle the text input.\n this.searchInput.addEventListener('input', debounce(async() => {\n if (this.getSearchTerm() === this.searchInput.value && this.searchResultsVisible()) {\n window.console.warn(`Search term matches input value - skipping`);\n // The debounce canhappen multiple times quickly. GRrargh\n return;\n }\n this.setSearchTerms(this.searchInput.value);\n\n const pendingPromise = new Pending();\n if (this.getSearchTerm() === '') {\n this.toggleDropdown();\n this.clearSearchButton.classList.add('d-none');\n await this.filterrenderpipe();\n } else {\n this.clearSearchButton.classList.remove('d-none');\n await this.renderAndShow();\n }\n pendingPromise.resolve();\n }, 300, {pending: true}));\n }\n\n /**\n * Update any changeable nodes, filter and then render the result.\n *\n * @returns {Promise}\n */\n async filterrenderpipe() {\n this.updateNodes();\n this.setMatchedResults(await this.filterDataset(await this.getDataset()));\n this.filterMatchDataset();\n await this.renderDropdown();\n await this.updateLiveRegion();\n }\n\n /**\n * A combo method to take the matching fields and render out the results.\n *\n * @returns {Promise}\n */\n async renderAndShow() {\n // User has given something for us to filter against.\n this.setMatchedResults(await this.filterDataset(await this.getDataset()));\n await this.filterMatchDataset();\n // Replace the dropdown node contents and show the results.\n await this.renderDropdown();\n // Set the dropdown to open.\n this.toggleDropdown(true);\n await this.updateLiveRegion();\n }\n\n /**\n * The handler for when a user interacts with the component.\n *\n * @param {MouseEvent} e The triggering event that we are working with.\n */\n async clickHandler(e) {\n this.updateNodes();\n // The \"clear search\" button is triggered.\n if (e.target.closest(this.selectors.clearSearch)) {\n this.closeSearch(true);\n this.searchInput.focus();\n // Remove aria-activedescendant when the available options change.\n this.searchInput.removeAttribute('aria-activedescendant');\n }\n // User may have accidentally clicked off the dropdown and wants to reopen it.\n if (\n this.getSearchTerm() !== ''\n && !this.getHTMLElements().searchDropdown.classList.contains('show')\n && e.target.closest(this.selectors.input)\n ) {\n await this.renderAndShow();\n }\n }\n\n /**\n * The handler for when a user changes the value of the component (selects an option from the dropdown).\n *\n * @param {Event} e The change event.\n */\n // eslint-disable-next-line no-unused-vars\n changeHandler(e) {\n // Components may override this method to do something.\n }\n\n /**\n * Updates the screen reader live region with the result count.\n */\n async updateLiveRegion() {\n if (!this.searchDropdown?.id) {\n return;\n }\n\n const idParts = this.searchDropdown.id.split('-');\n\n if (idParts.length < 3) {\n return;\n }\n const [, instanceId, id] = idParts; // E.g. dialog-12-34 only want the last two parts.\n const liveRegion = document.getElementById(`combobox-status-${instanceId}-${id}`);\n\n if (!liveRegion) {\n return;\n }\n\n const resultCount = this.getMatchedResults().length;\n let message;\n if (resultCount === 0) {\n message = await getString('noitemsfound', 'core');\n } else if (resultCount === 1) {\n message = await getString('oneitemfound', 'core');\n } else {\n message = await getString('multipleitemsfound', 'core', resultCount);\n }\n\n liveRegion.textContent = message;\n\n // Reset previous timeout if it exists.\n if (this.liveRegionTimeout) {\n clearTimeout(this.liveRegionTimeout);\n }\n\n // Clear the feedback message after 4 seconds. This is similar to the default timeout of toast messages\n // before disappearing from view. It is important to clear the message to prevent screen reader users from navigating\n // into this region and avoiding confusion.\n this.liveRegionTimeout = setTimeout(() => {\n liveRegion.textContent = '';\n this.liveRegionTimeout = null;\n }, 4000);\n }\n\n}\n"],"names":["constructor","component","this","componentSelector","toggle","instance","input","clearSearch","dropdown","dropdownSelector","resultitems","viewall","combobox","document","querySelector","selectors","dataset","setSearchTerms","searchInput","_this$searchInput","value","registerClickHandlers","registerInputHandlers","registerChangeHandlers","getSearchTerm","clearSearchButton","classList","remove","fetchDataset","Error","name","filterDataset","filterMatchDataset","renderDropdown","triggerSelector","window","console","warning","datasetSize","length","getDatasetSize","getMatchedResults","matchedResults","setMatchedResults","result","searchTerm","getPreppedSearchTerm","preppedSearchTerm","toLowerCase","getHTMLElements","updateNodes","searchDropdown","currentViewAll","trigger","closeSearch","clear","toggleDropdown","add","searchResultsVisible","offsetParent","resultNodes","querySelectorAll","currentNode","find","r","id","activeElement","addEventListener","clickHandler","bind","inputElement","changeHandler","async","warn","pendingPromise","Pending","filterrenderpipe","renderAndShow","resolve","pending","getDataset","updateLiveRegion","e","target","closest","focus","removeAttribute","contains","_this$searchDropdown","idParts","split","instanceId","liveRegion","getElementById","resultCount","message","textContent","liveRegionTimeout","clearTimeout","setTimeout"],"mappings":";;;;;;;qMA2EIA,2FA5CY,CACRC,UAAWC,KAAKC,oBAChBC,OAAQ,2BACRC,SAAU,2BACVC,MAAO,yBACPC,YAAa,8BACbC,SAAUN,KAAKO,mBACfC,YAAa,kBACbC,QAAS,cACTC,SAAU,4DAIG,sCAGJ,6CAGO,yCAGN,uCAGA,4CAGG,qCAEP,yCAEI,oCAGFC,SAASC,cAAcZ,KA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hD,2BACC9B,KAAK+B,uBACL/B,KAAK+E,8CAUNtC,wBAAwBzC,KAAK6B,oBAAoB7B,KAAK8E,qBACrD9E,KAAK8B,2BAEL9B,KAAK+B,sBAENuB,gBAAe,SACdtD,KAAK+E,sCAQIC,QACVhC,cAEDgC,EAAEC,OAAOC,QAAQlF,KAAKa,UAAUR,oBAC3B+C,aAAY,QACZpC,YAAYmE,aAEZnE,YAAYoE,gBAAgB,0BAIR,KAAzBpF,KAAKsB,kBACDtB,KAAK+C,kBAAkBE,eAAezB,UAAU6D,SAAS,SAC1DL,EAAEC,OAAOC,QAAQlF,KAAKa,UAAUT,cAE7BJ,KAAK2E,gBAUnBN,cAAcW,sFAQLhF,KAAKiD,iDAALqC,qBAAqBvB,gBAIpBwB,QAAUvF,KAAKiD,eAAec,GAAGyB,MAAM,QAEzCD,QAAQlD,OAAS,gBAGZoD,WAAY1B,IAAMwB,QACrBG,WAAa/E,SAASgF,yCAAkCF,uBAAc1B,SAEvE2B,wBAICE,YAAc5F,KAAKuC,oBAAoBF,WACzCwD,QAEAA,QADgB,IAAhBD,kBACgB,mBAAU,eAAgB,QACnB,IAAhBA,kBACS,mBAAU,eAAgB,cAE1B,mBAAU,qBAAsB,OAAQA,aAG5DF,WAAWI,YAAcD,QAGrB7F,KAAK+F,mBACLC,aAAahG,KAAK+F,wBAMjBA,kBAAoBE,YAAW,KAChCP,WAAWI,YAAc,QACpBC,kBAAoB,OAC1B"} \ No newline at end of file diff --git a/lib/amd/src/comboboxsearch/search_combobox.js b/lib/amd/src/comboboxsearch/search_combobox.js index 8094e298051..f3ded646b32 100644 --- a/lib/amd/src/comboboxsearch/search_combobox.js +++ b/lib/amd/src/comboboxsearch/search_combobox.js @@ -16,6 +16,8 @@ import $ from 'jquery'; import {debounce} from 'core/utils'; import Pending from 'core/pending'; +import {get_string as getString} from 'core/str'; + /** * The class that manages the state of the search within a combobox. @@ -330,6 +332,7 @@ export default class { this.setMatchedResults(await this.filterDataset(await this.getDataset())); this.filterMatchDataset(); await this.renderDropdown(); + await this.updateLiveRegion(); } /** @@ -345,6 +348,7 @@ export default class { await this.renderDropdown(); // Set the dropdown to open. this.toggleDropdown(true); + await this.updateLiveRegion(); } /** @@ -380,4 +384,51 @@ export default class { changeHandler(e) { // Components may override this method to do something. } + + /** + * Updates the screen reader live region with the result count. + */ + async updateLiveRegion() { + if (!this.searchDropdown?.id) { + return; + } + + const idParts = this.searchDropdown.id.split('-'); + + if (idParts.length < 3) { + return; + } + const [, instanceId, id] = idParts; // E.g. dialog-12-34 only want the last two parts. + const liveRegion = document.getElementById(`combobox-status-${instanceId}-${id}`); + + if (!liveRegion) { + return; + } + + const resultCount = this.getMatchedResults().length; + let message; + if (resultCount === 0) { + message = await getString('noitemsfound', 'core'); + } else if (resultCount === 1) { + message = await getString('oneitemfound', 'core'); + } else { + message = await getString('multipleitemsfound', 'core', resultCount); + } + + liveRegion.textContent = message; + + // Reset previous timeout if it exists. + if (this.liveRegionTimeout) { + clearTimeout(this.liveRegionTimeout); + } + + // Clear the feedback message after 4 seconds. This is similar to the default timeout of toast messages + // before disappearing from view. It is important to clear the message to prevent screen reader users from navigating + // into this region and avoiding confusion. + this.liveRegionTimeout = setTimeout(() => { + liveRegion.textContent = ''; + this.liveRegionTimeout = null; + }, 4000); + } + } diff --git a/lib/templates/comboboxsearch.mustache b/lib/templates/comboboxsearch.mustache index f53533cdb42..f074256354a 100644 --- a/lib/templates/comboboxsearch.mustache +++ b/lib/templates/comboboxsearch.mustache @@ -90,3 +90,5 @@ + +