lib/amd/src/paged_content_factory.js

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