MDL-79064 core: Improve Native promise support

As we migrate to primarily using natives promises, we should make it
easier to use and consume them.

This change:
- updates core/str to add new methods for:
  - getString
  - getStrings
- accept Native promises into Modal setters
This commit is contained in:
Andrew Nicols
2023-08-29 10:57:06 +08:00
parent 9bfcd77d51
commit fe80eecc44
6 changed files with 101 additions and 35 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -7,6 +7,6 @@ define("core/str",["exports","jquery","core/ajax","core/localstorage"],(function
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since 2.9
*
*/Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.get_strings=_exports.get_string=_exports.cache_strings=void 0,_jquery=_interopRequireDefault(_jquery),_ajax=_interopRequireDefault(_ajax),_localstorage=_interopRequireDefault(_localstorage);let promiseCache=[];_exports.get_string=(key,component,param,lang)=>get_strings([{key:key,component:component,param:param,lang:lang}]).then((results=>results[0]));const get_strings=requests=>{let requestData=[];const pageLang=(0,_jquery.default)("html").attr("lang").replace(/-/g,"_"),stringPromises=requests.map((request=>{let{component:component,key:key,param:param,lang:lang=pageLang}=request;component||(component="core");const cacheKey=(_ref=>{let{key:key,component:component,lang:lang=pageLang}=_ref;return"core_str/".concat(key,"/").concat(component,"/").concat(lang)})({key:key,component:component,lang:lang}),buildReturn=promise=>(promiseCache[cacheKey]=promise,promise);if(component in M.str&&key in M.str[component])return buildReturn(new Promise((resolve=>{resolve(M.util.get_string(key,component,param,lang))})));const cached=_localstorage.default.get(cacheKey);return cached?(M.str[component]={...M.str[component],[key]:cached},buildReturn(new Promise((resolve=>{resolve(M.util.get_string(key,component,param,lang))})))):cacheKey in promiseCache?buildReturn(promiseCache[cacheKey]).then((()=>M.util.get_string(key,component,param,lang))):buildReturn(new Promise(((resolve,reject)=>{requestData.push({methodname:"core_get_string",args:{stringid:key,stringparams:[],component:component,lang:lang},done:str=>{M.str[component]={...M.str[component],[key]:str},_localstorage.default.set(cacheKey,str),resolve(M.util.get_string(key,component,param,lang))},fail:reject})})))}));return requestData.length&&_ajax.default.call(requestData,!0,!1,!1,0,M.cfg.langrev),_jquery.default.when.apply(_jquery.default,stringPromises).then((function(){for(var _len=arguments.length,strings=new Array(_len),_key=0;_key<_len;_key++)strings[_key]=arguments[_key];return strings}))};_exports.get_strings=get_strings;_exports.cache_strings=strings=>{const defaultLang=(0,_jquery.default)("html").attr("lang").replace(/-/g,"_");strings.forEach((_ref2=>{let{key:key,component:component,value:value,lang:lang=defaultLang}=_ref2;const cacheKey=["core_str",key,component,lang].join("/");component in M.str&&key in M.str[component]||(component in M.str||(M.str[component]={}),M.str[component][key]=value),_localstorage.default.get(cacheKey)||_localstorage.default.set(cacheKey,value),cacheKey in promiseCache||(promiseCache[cacheKey]=_jquery.default.Deferred().resolve(value).promise())}))}}));
*/Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.get_strings=_exports.get_string=_exports.getStrings=_exports.getString=_exports.cache_strings=void 0,_jquery=_interopRequireDefault(_jquery),_ajax=_interopRequireDefault(_ajax),_localstorage=_interopRequireDefault(_localstorage);let promiseCache=[];_exports.get_string=(key,component,param,lang)=>get_strings([{key:key,component:component,param:param,lang:lang}]).then((results=>results[0]));_exports.getString=(key,component,param,lang)=>getRequestedStrings([{key:key,component:component,param:param,lang:lang}])[0];_exports.getStrings=requests=>Promise.all(getRequestedStrings(requests));const getRequestedStrings=requests=>{let requestData=[];const pageLang=(0,_jquery.default)("html").attr("lang").replace(/-/g,"_"),stringPromises=requests.map((request=>{let{component:component,key:key,param:param,lang:lang=pageLang}=request;component||(component="core");const cacheKey=(_ref=>{let{key:key,component:component,lang:lang=pageLang}=_ref;return"core_str/".concat(key,"/").concat(component,"/").concat(lang)})({key:key,component:component,lang:lang}),buildReturn=promise=>(promiseCache[cacheKey]=promise,promise);if(component in M.str&&key in M.str[component])return buildReturn(new Promise((resolve=>{resolve(M.util.get_string(key,component,param,lang))})));const cached=_localstorage.default.get(cacheKey);return cached?(M.str[component]={...M.str[component],[key]:cached},buildReturn(new Promise((resolve=>{resolve(M.util.get_string(key,component,param,lang))})))):cacheKey in promiseCache?buildReturn(promiseCache[cacheKey]).then((()=>M.util.get_string(key,component,param,lang))):buildReturn(new Promise(((resolve,reject)=>{requestData.push({methodname:"core_get_string",args:{stringid:key,stringparams:[],component:component,lang:lang},done:str=>{M.str[component]={...M.str[component],[key]:str},_localstorage.default.set(cacheKey,str),resolve(M.util.get_string(key,component,param,lang))},fail:reject})})))}));return requestData.length&&_ajax.default.call(requestData,!0,!1,!1,0,M.cfg.langrev),stringPromises},get_strings=requests=>_jquery.default.when.apply(_jquery.default,getRequestedStrings(requests)).then((function(){for(var _len=arguments.length,strings=new Array(_len),_key=0;_key<_len;_key++)strings[_key]=arguments[_key];return strings}));_exports.get_strings=get_strings;_exports.cache_strings=strings=>{const defaultLang=(0,_jquery.default)("html").attr("lang").replace(/-/g,"_");strings.forEach((_ref2=>{let{key:key,component:component,value:value,lang:lang=defaultLang}=_ref2;const cacheKey=["core_str",key,component,lang].join("/");component in M.str&&key in M.str[component]||(component in M.str||(M.str[component]={}),M.str[component][key]=value),_localstorage.default.get(cacheKey)||_localstorage.default.set(cacheKey,value),cacheKey in promiseCache||(promiseCache[cacheKey]=_jquery.default.Deferred().resolve(value).promise())}))}}));
//# sourceMappingURL=str.min.js.map
File diff suppressed because one or more lines are too long
+12 -11
View File
@@ -977,20 +977,21 @@ export default class Modal {
* @return {Promise}
*/
asyncSet(value, setFunction) {
var p = value;
if (typeof value !== 'object' || !value.hasOwnProperty('then')) {
p = $.Deferred();
p.resolve(value);
}
const getWrappedValue = (value) => {
if (value instanceof Promise) {
return $.when(value);
}
p.then((content) => {
setFunction(content);
if (typeof value !== 'object' || !value.hasOwnProperty('then')) {
return $.Deferred().resolve(value);
}
return;
})
.catch(Notification.exception);
return value;
};
return p;
return getWrappedValue(value)
.then((content) => setFunction(content))
.catch(Notification.exception);
}
/**
+85 -20
View File
@@ -26,6 +26,15 @@ import $ from 'jquery';
import Ajax from 'core/ajax';
import LocalStorage from 'core/localstorage';
/**
* @typedef StringRequest
* @type {object}
* @param {string} requests.key The string identifer to fetch
* @param {string} [requests.component='core'] The componet to fetch from
* @param {string} [requests.lang] The language to fetch a string for. Defaults to current page language.
* @param {object|string} [requests.param] The param for variable expansion in the string.
*/
// Module cache for the promises so that we don't make multiple
// unnecessary requests.
let promiseCache = [];
@@ -38,21 +47,17 @@ let promiseCache = [];
* If the string has previously been cached, then the Promise will be resolved immediately, otherwise it will be fetched
* from the server and resolved when available.
*
* @method get_string
* @param {string} key The language string key
* @param {string} component The language string component
* @param {string} param The param for variable expansion in the string.
* @param {string} lang The users language - if not passed it is deduced.
* @return {Promise}
* @return {jQuery.Promise} A jQuery Promise containing the translated string
*
* @example <caption>Fetching a string</caption>
*
* import {get_string as getString} from 'core/str';
* get_string('cannotfindteacher', 'error')
* .then(str => {
* window.console.log(str); // Cannot find teacher
* })
* .catch();
* .then((str) => window.console.log(str)); // Cannot find teacher
*/
// eslint-disable-next-line camelcase
export const get_string = (key, component, param, lang) => {
@@ -60,24 +65,41 @@ export const get_string = (key, component, param, lang) => {
.then(results => results[0]);
};
/**
* Return a Promise that resolves to a string.
*
* If the string has previously been cached, then the Promise will be resolved immediately, otherwise it will be fetched
* from the server and resolved when available.
*
* @param {string} key The language string key
* @param {string} component The language string component
* @param {string} param The param for variable expansion in the string.
* @param {string} lang The users language - if not passed it is deduced.
* @return {Promise} A native Promise containing the translated string
*
* @example <caption>Fetching a string</caption>
*
* import {getString} from 'core/str';
*
* getString('cannotfindteacher', 'error')
* .then((str) => window.console.log(str)); // Cannot find teacher
*/
export const getString = (key, component, param, lang) => getRequestedStrings([{key, component, param, lang}])[0];
// eslint-disable-next-line camelcase
/**
* Make a batch request to load a set of strings.
*
* Any missing string will be fetched from the server.
* The Promise will only be resolved once all strings are available, or an attempt has been made to fetch them.
*
* @method get_strings
* @param {Object[]} requests List of strings to fetch
* @param {string} requests.key The string identifer to fetch
* @param {string} [requests.component='core'] The componet to fetch from
* @param {string} [requests.lang] The language to fetch a string for. Defaults to current page language.
* @param {object|string} [requests.param] The param for variable expansion in the string.
* @return {Promise[]}
* @param {Array.<StringRequest>} requests List of strings to fetch
* @return {Promise[]} An array of native promises containing the translated strings
*
* @example <caption>Fetching a set of strings</caption>
*
* import {get_strings as getStrings} from 'core/str';
* get_strings([
* import {getStrings} from 'core/str';
* getStrings([
* {
* key: 'cannotfindteacher',
* component: 'error',
@@ -95,11 +117,17 @@ export const get_string = (key, component, param, lang) => {
* window.console.log(cannotFindTeacher); // Cannot find teacher
* window.console.log(yes); // Yes
* window.console.log(no); // No
* })
* .catch();
* });
*/
// eslint-disable-next-line camelcase
export const get_strings = (requests) => {
export const getStrings = (requests) => Promise.all(getRequestedStrings(requests));
/**
* Internal function to perform the string requests.
*
* @param {Array.<StringRequest>} requests List of strings to fetch
* @returns {Promise<string>}
*/
const getRequestedStrings = (requests) => {
let requestData = [];
const pageLang = $('html').attr('lang').replace(/-/g, '_');
@@ -174,9 +202,46 @@ export const get_strings = (requests) => {
Ajax.call(requestData, true, false, false, 0, M.cfg.langrev);
}
return stringPromises;
};
/**
* Make a batch request to load a set of strings.
*
* Any missing string will be fetched from the server.
* The Promise will only be resolved once all strings are available, or an attempt has been made to fetch them.
*
* @param {Array.<StringRequest>} requests List of strings to fetch
* @return {Promise[]} An array of native promises containing the translated strings
*
* @example <caption>Fetching a set of strings</caption>
*
* import {getStrings} from 'core/str';
* get_strings([
* {
* key: 'cannotfindteacher',
* component: 'error',
* },
* {
* key: 'yes',
* component: 'core',
* },
* {
* key: 'no',
* component: 'core',
* },
* ])
* .then((cannotFindTeacher, yes, no) => {
* window.console.log(cannotFindTeacher); // Cannot find teacher
* window.console.log(yes); // Yes
* window.console.log(no); // No
* });
*/
// eslint-disable-next-line camelcase
export const get_strings = (requests) => {
// We need to use jQuery here because some calling code uses the
// .done handler instead of the .then handler.
return $.when.apply($, stringPromises)
return $.when.apply($, getRequestedStrings(requests))
.then((...strings) => strings);
};