MDL-63793 block_myoverview: Persist the user's paging limit preference
[moodle.git] / lib / amd / src / paged_content_factory.js
CommitLineData
4ab09853
RW
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
17 * Factory to create a paged content widget.
18 *
19 * @module core/paged_content_factory
20 * @copyright 2018 Ryan Wyllie <ryan@moodle.com>
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 */
23define(
24[
25 'jquery',
26 'core/templates',
27 'core/notification',
fd955097
P
28 'core/paged_content',
29 'core/paged_content_events',
11988d74
P
30 'core/pubsub',
31 'core/ajax'
4ab09853
RW
32],
33function(
34 $,
35 Templates,
36 Notification,
fd955097
P
37 PagedContent,
38 PagedContentEvents,
11988d74
P
39 PubSub,
40 Ajax
4ab09853
RW
41) {
42 var TEMPLATES = {
43 PAGED_CONTENT: 'core/paged_content'
44 };
45
2c13ae01
RW
46 var DEFAULT = {
47 ITEMS_PER_PAGE_SINGLE: 25,
48 ITEMS_PER_PAGE_ARRAY: [25, 50, 100, 0],
49 MAX_PAGES: 3
50 };
51
4ab09853 52 /**
2c13ae01
RW
53 * Get the default context to render the paged content mustache
54 * template.
4ab09853 55 *
2c13ae01 56 * @return {object}
4ab09853 57 */
2c13ae01
RW
58 var getDefaultTemplateContext = function() {
59 return {
60 pagingbar: false,
61 pagingdropdown: false,
62 skipjs: true,
63 ignorecontrolwhileloading: true,
64 controlplacementbottom: false
4ab09853 65 };
2c13ae01
RW
66 };
67
68 /**
69 * Get the default context to render the paging bar mustache template.
70 *
71 * @return {object}
72 */
73 var getDefaultPagingBarTemplateContext = function() {
74 return {
75 showitemsperpageselector: false,
76 itemsperpage: 35,
77 previous: true,
78 next: true,
79 activepagenumber: 1,
80 hidecontrolonsinglepage: true,
81 pages: []
82 };
83 };
84
85 /**
86 * Calculate the number of pages required for the given number of items and
87 * how many of each item should appear on a page.
88 *
89 * @param {Number} numberOfItems How many items in total.
90 * @param {Number} itemsPerPage How many items will be shown per page.
91 * @return {Number} The number of pages required.
92 */
93 var calculateNumberOfPages = function(numberOfItems, itemsPerPage) {
94 var numberOfPages = 1;
95
96 if (numberOfItems > 0) {
97 var partial = numberOfItems % itemsPerPage;
98
99 if (partial) {
100 numberOfItems -= partial;
101 numberOfPages = (numberOfItems / itemsPerPage) + 1;
102 } else {
103 numberOfPages = numberOfItems / itemsPerPage;
104 }
105 }
106
107 return numberOfPages;
108 };
109
110 /**
111 * Build the context for the paging bar template when we have a known number
112 * of items.
113 *
114 * @param {Number} numberOfItems How many items in total.
115 * @param {Number} itemsPerPage How many items will be shown per page.
116 * @return {object} Mustache template
117 */
118 var buildPagingBarTemplateContextKnownLength = function(numberOfItems, itemsPerPage) {
119 if (itemsPerPage === null) {
120 itemsPerPage = DEFAULT.ITEMS_PER_PAGE_SINGLE;
121 }
122
123 if ($.isArray(itemsPerPage)) {
124 // If we're given a total number of pages then we don't support a variable
125 // set of items per page so just use the first one.
126 itemsPerPage = itemsPerPage[0];
127 }
128
129 var context = getDefaultPagingBarTemplateContext();
130 context.itemsperpage = itemsPerPage;
131 var numberOfPages = calculateNumberOfPages(numberOfItems, itemsPerPage);
4ab09853
RW
132
133 for (var i = 1; i <= numberOfPages; i++) {
134 var page = {
135 number: i,
136 page: "" + i,
137 };
138
139 // Make the first page active by default.
140 if (i === 1) {
141 page.active = true;
142 }
143
144 context.pages.push(page);
145 }
146
147 return context;
148 };
149
150 /**
2c13ae01
RW
151 * Convert the itemsPerPage value into a format applicable for the mustache template.
152 * The given value can be either a single integer or an array of integers / objects.
153 *
154 * E.g.
155 * In: [5, 10]
156 * out: [{value: 5, active: true}, {value: 10, active: false}]
157 *
158 * In: [5, {value: 10, active: true}]
159 * Out: [{value: 5, active: false}, {value: 10, active: true}]
160 *
161 * In: [{value: 5, active: false}, {value: 10, active: true}]
162 * Out: [{value: 5, active: false}, {value: 10, active: true}]
163 *
164 * @param {int|int[]} itemsPerPage Options for number of items per page.
165 * @return {int|array}
166 */
167 var buildItemsPerPagePagingBarContext = function(itemsPerPage) {
168 if ($.isArray(itemsPerPage)) {
169 // Convert the array into a format accepted by the template.
170 var context = itemsPerPage.map(function(num) {
171 if (typeof num === 'number') {
172 // If the item is just a plain number then convert it into
173 // an object with value and active keys.
174 return {
175 value: num,
176 active: false
177 };
178 } else {
179 // Otherwise we assume the caller has specified things correctly.
180 return num;
181 }
182 });
183
184 var activeItems = context.filter(function(item) {
185 return item.active;
186 });
187
188 // Default the first item to active if one hasn't been specified.
189 if (!activeItems.length) {
190 context[0].active = true;
191 }
192
193 return context;
194 } else {
195 return itemsPerPage;
196 }
197 };
198
199 /**
200 * Build the context for the paging bar template when we have an unknown
201 * number of items.
202 *
203 * @param {Number} itemsPerPage How many items will be shown per page.
204 * @return {object} Mustache template
205 */
206 var buildPagingBarTemplateContextUnknownLength = function(itemsPerPage) {
207 if (itemsPerPage === null) {
208 itemsPerPage = DEFAULT.ITEMS_PER_PAGE_ARRAY;
209 }
210
211 var context = getDefaultPagingBarTemplateContext();
212 context.itemsperpage = buildItemsPerPagePagingBarContext(itemsPerPage);
213 context.showitemsperpageselector = $.isArray(itemsPerPage);
214
215 return context;
216 };
217
218 /**
219 * Build the context to render the paging bar template with based on the number
220 * of pages to show.
221 *
222 * @param {int|null} numberOfItems How many items are there total.
223 * @param {int|null} itemsPerPage How many items will be shown per page.
224 * @return {object} The template context.
225 */
226 var buildPagingBarTemplateContext = function(numberOfItems, itemsPerPage) {
227 if (numberOfItems) {
228 return buildPagingBarTemplateContextKnownLength(numberOfItems, itemsPerPage);
229 } else {
230 return buildPagingBarTemplateContextUnknownLength(itemsPerPage);
231 }
232 };
233
234 /**
235 * Build the context to render the paging dropdown template based on the number
4ab09853
RW
236 * of pages to show and items per page.
237 *
238 * This control is rendered with a gradual increase of the items per page to
239 * limit the number of pages in the dropdown. Each page will show twice as much
240 * as the previous page (except for the first two pages).
241 *
2c13ae01
RW
242 * By default there will only be 4 pages shown (including the "All" option) unless
243 * a different number of pages is defined using the maxPages config value.
244 *
4ab09853 245 * For example:
4ab09853
RW
246 * Items per page = 25
247 * Would render a dropdown will 4 options:
248 * 25
249 * 50
250 * 100
251 * All
252 *
2c13ae01 253 * @param {Number} itemsPerPage How many items will be shown per page.
4ab09853
RW
254 * @param {object} config Configuration options provided by the client.
255 * @return {object} The template context.
256 */
2c13ae01
RW
257 var buildPagingDropdownTemplateContext = function(itemsPerPage, config) {
258 if (itemsPerPage === null) {
259 itemsPerPage = DEFAULT.ITEMS_PER_PAGE_SINGLE;
260 }
261
262 if ($.isArray(itemsPerPage)) {
263 // If we're given an array for the items per page, rather than a number,
264 // then just use that as the options for the dropdown.
265 return {
266 options: itemsPerPage
267 };
268 }
269
4ab09853
RW
270 var context = {
271 options: []
272 };
273
274 var totalItems = 0;
275 var lastIncrease = 0;
2c13ae01 276 var maxPages = DEFAULT.MAX_PAGES;
4ab09853
RW
277
278 if (config.hasOwnProperty('maxPages')) {
279 maxPages = config.maxPages;
280 }
281
282 for (var i = 1; i <= maxPages; i++) {
283 var itemCount = 0;
284
285 if (i <= 2) {
286 itemCount = itemsPerPage;
287 lastIncrease = itemsPerPage;
288 } else {
289 lastIncrease = lastIncrease * 2;
290 itemCount = lastIncrease;
291 }
292
293 totalItems += itemCount;
294 var option = {
295 itemcount: itemCount,
296 content: totalItems
297 };
298
299 // Make the first option active by default.
300 if (i === 1) {
301 option.active = true;
302 }
303
304 context.options.push(option);
305 }
306
307 return context;
308 };
309
310 /**
311 * Build the context to render the paged content template with based on the number
312 * of pages to show, items per page, and configuration option.
313 *
314 * By default the code will render a paging bar for the paging controls unless
315 * otherwise specified in the provided config.
316 *
2c13ae01
RW
317 * @param {int|null} numberOfItems Total number of items.
318 * @param {int|null|array} itemsPerPage How many items will be shown per page.
4ab09853
RW
319 * @param {object} config Configuration options provided by the client.
320 * @return {object} The template context.
321 */
2c13ae01
RW
322 var buildTemplateContext = function(numberOfItems, itemsPerPage, config) {
323 var context = getDefaultTemplateContext();
324
325 if (config.hasOwnProperty('ignoreControlWhileLoading')) {
326 context.ignorecontrolwhileloading = config.ignoreControlWhileLoading;
327 }
328
329 if (config.hasOwnProperty('controlPlacementBottom')) {
330 context.controlplacementbottom = config.controlPlacementBottom;
331 }
332
333 if (config.hasOwnProperty('hideControlOnSinglePage')) {
334 context.hidecontrolonsinglepage = config.hideControlOnSinglePage;
335 }
336
337 if (config.hasOwnProperty('ariaLabels')) {
338 context.arialabels = config.ariaLabels;
339 }
4ab09853
RW
340
341 if (config.hasOwnProperty('dropdown') && config.dropdown) {
2c13ae01 342 context.pagingdropdown = buildPagingDropdownTemplateContext(itemsPerPage, config);
4ab09853 343 } else {
2c13ae01 344 context.pagingbar = buildPagingBarTemplateContext(numberOfItems, itemsPerPage);
4ab09853
RW
345 }
346
347 return context;
348 };
349
350 /**
2c13ae01
RW
351 * Create a paged content widget where the complete list of items is not loaded
352 * up front but will instead be loaded by an ajax request (or similar).
4ab09853 353 *
2c13ae01
RW
354 * The client code must provide a callback function which loads and renders the
355 * items for each page. See PagedContent.init for more details.
356 *
357 * The function will return a deferred that is resolved with a jQuery object
358 * for the HTML content and a string for the JavaScript.
359 *
360 * The current list of configuration options available are:
361 * dropdown {bool} True to render the page control as a dropdown (paging bar is default).
362 * maxPages {Number} The maximum number of pages to show in the dropdown (only works with dropdown option)
363 * ignoreControlWhileLoading {bool} Disable the pagination controls while loading a page (default to true)
364 * controlPlacementBottom {bool} Render controls under paged content (default to false)
365 *
366 * @param {function} renderPagesContentCallback Callback for loading and rendering the items.
367 * @param {object} config Configuration options provided by the client.
368 * @return {promise} Resolved with jQuery HTML and string JS.
4ab09853 369 */
2c13ae01
RW
370 var create = function(renderPagesContentCallback, config) {
371 return createWithTotalAndLimit(null, null, renderPagesContentCallback, config);
372 };
4ab09853 373
2c13ae01
RW
374 /**
375 * Create a paged content widget where the complete list of items is not loaded
376 * up front but will instead be loaded by an ajax request (or similar).
377 *
378 * The client code must provide a callback function which loads and renders the
379 * items for each page. See PagedContent.init for more details.
380 *
381 * The function will return a deferred that is resolved with a jQuery object
382 * for the HTML content and a string for the JavaScript.
383 *
384 * The current list of configuration options available are:
385 * dropdown {bool} True to render the page control as a dropdown (paging bar is default).
386 * maxPages {Number} The maximum number of pages to show in the dropdown (only works with dropdown option)
387 * ignoreControlWhileLoading {bool} Disable the pagination controls while loading a page (default to true)
388 * controlPlacementBottom {bool} Render controls under paged content (default to false)
389 *
390 * @param {int|array|null} itemsPerPage How many items will be shown per page.
391 * @param {function} renderPagesContentCallback Callback for loading and rendering the items.
392 * @param {object} config Configuration options provided by the client.
393 * @return {promise} Resolved with jQuery HTML and string JS.
394 */
fd955097
P
395 var createWithLimit = function(itemsPerPage, renderPagesContentCallback, config) {
396 return createWithTotalAndLimit(null, itemsPerPage, renderPagesContentCallback, config);
4ab09853
RW
397 };
398
399 /**
400 * Create a paged content widget where the complete list of items is not loaded
401 * up front but will instead be loaded by an ajax request (or similar).
402 *
403 * The client code must provide a callback function which loads and renders the
404 * items for each page. See PagedContent.init for more details.
405 *
406 * The function will return a deferred that is resolved with a jQuery object
407 * for the HTML content and a string for the JavaScript.
408 *
409 * The current list of configuration options available are:
410 * dropdown {bool} True to render the page control as a dropdown (paging bar is default).
2c13ae01
RW
411 * maxPages {Number} The maximum number of pages to show in the dropdown (only works with dropdown option)
412 * ignoreControlWhileLoading {bool} Disable the pagination controls while loading a page (default to true)
413 * controlPlacementBottom {bool} Render controls under paged content (default to false)
4ab09853 414 *
2c13ae01
RW
415 * @param {int|null} numberOfItems How many items are there in total.
416 * @param {int|array|null} itemsPerPage How many items will be shown per page.
4ab09853
RW
417 * @param {function} renderPagesContentCallback Callback for loading and rendering the items.
418 * @param {object} config Configuration options provided by the client.
419 * @return {promise} Resolved with jQuery HTML and string JS.
420 */
fd955097 421 var createWithTotalAndLimit = function(numberOfItems, itemsPerPage, renderPagesContentCallback, config) {
2c13ae01 422 config = config || {};
4ab09853
RW
423
424 var deferred = $.Deferred();
2c13ae01 425 var templateContext = buildTemplateContext(numberOfItems, itemsPerPage, config);
4ab09853
RW
426
427 Templates.render(TEMPLATES.PAGED_CONTENT, templateContext)
428 .then(function(html, js) {
429 html = $(html);
11988d74
P
430 var id = html.attr('id');
431
432 // Set the id to the custom namespace provided
433 if (config.hasOwnProperty('eventNamespace')) {
434 id = config.eventNamespace;
435 }
4ab09853
RW
436
437 var container = html;
4ab09853 438
11988d74
P
439 PagedContent.init(container, renderPagesContentCallback, id);
440
441 registerEvents(id, config);
4ab09853
RW
442
443 deferred.resolve(html, js);
444 return;
445 })
446 .fail(function(exception) {
447 deferred.reject(exception);
448 })
449 .fail(Notification.exception);
450
2c13ae01 451 return deferred.promise();
4ab09853
RW
452 };
453
454 /**
455 * Create a paged content widget where the complete list of items is loaded
456 * up front.
457 *
458 * The client code must provide a callback function which renders the
459 * items for each page. The callback will be provided with an array where each
460 * value in the array is a the list of items to render for the page.
461 *
462 * The function will return a deferred that is resolved with a jQuery object
463 * for the HTML content and a string for the JavaScript.
464 *
465 * The current list of configuration options available are:
466 * dropdown {bool} True to render the page control as a dropdown (paging bar is default).
2c13ae01
RW
467 * maxPages {Number} The maximum number of pages to show in the dropdown (only works with dropdown option)
468 * ignoreControlWhileLoading {bool} Disable the pagination controls while loading a page (default to true)
469 * controlPlacementBottom {bool} Render controls under paged content (default to false)
4ab09853
RW
470 *
471 * @param {array} contentItems The list of items to paginate.
2c13ae01 472 * @param {Number} itemsPerPage How many items will be shown per page.
4ab09853
RW
473 * @param {function} renderContentCallback Callback for rendering the items for the page.
474 * @param {object} config Configuration options provided by the client.
475 * @return {promise} Resolved with jQuery HTML and string JS.
476 */
477 var createFromStaticList = function(contentItems, itemsPerPage, renderContentCallback, config) {
478 if (typeof config == 'undefined') {
479 config = {};
480 }
481
482 var numberOfItems = contentItems.length;
2c13ae01 483 return createWithTotalAndLimit(numberOfItems, itemsPerPage, function(pagesData) {
4ab09853
RW
484 var contentToRender = [];
485 pagesData.forEach(function(pageData) {
486 var begin = pageData.offset;
487 var end = pageData.limit ? begin + pageData.limit : numberOfItems;
488 var items = contentItems.slice(begin, end);
489 contentToRender.push(items);
490 });
491
492 return renderContentCallback(contentToRender);
493 }, config);
494 };
495
fd955097
P
496 /**
497 * Reset the last page number for the generated paged-content
498 * This is used when we need a way to update the last page number outside of the getters callback
499 *
500 * @param {String} id ID of the paged content container
501 * @param {Int} lastPageNumber The last page number
502 */
503 var resetLastPageNumber = function(id, lastPageNumber) {
504 PubSub.publish(id + PagedContentEvents.ALL_ITEMS_LOADED, lastPageNumber);
505 };
506
11988d74
P
507 /**
508 * Generate the callback handler for the page limit persistence functionality
509 *
510 * @param {String} persistentLimitKey
511 * @return {callback}
512 */
513 var generateLimitHandler = function(persistentLimitKey) {
514 var callback = function(limit) {
515 var args = {
516 preferences: [
517 {
518 type: persistentLimitKey,
519 value: limit
520 }
521 ]
522 };
523
524 var request = {
525 methodname: 'core_user_update_user_preferences',
526 args: args
527 };
528
529 Ajax.call([request]);
530 };
531
532 return callback;
533 };
534
535 /**
536 * Set up any events based on config key values
537 *
538 * @param {string} namespace The namespace for this component
539 * @param {object} config Config options passed to the factory
540 */
541 var registerEvents = function(namespace, config) {
542 if (config.hasOwnProperty('persistentLimitKey')) {
543 PubSub.subscribe(namespace + PagedContentEvents.SET_ITEMS_PER_PAGE_LIMIT,
544 generateLimitHandler(config.persistentLimitKey));
545 }
546 };
547
4ab09853 548 return {
2c13ae01
RW
549 create: create,
550 createWithLimit: createWithLimit,
551 createWithTotalAndLimit: createWithTotalAndLimit,
552 createFromStaticList: createFromStaticList,
553 // Backwards compatibility just in case anyone was using this.
fd955097
P
554 createFromAjax: createWithTotalAndLimit,
555 resetLastPageNumber: resetLastPageNumber
4ab09853
RW
556 };
557});