[TASK] Migrate Toolbar/ClearCacheMenu to TypeScript
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Resources / Private / TypeScript / Toolbar / ClearCacheMenu.ts
1 /*
2 * This file is part of the TYPO3 CMS project.
3 *
4 * It is free software; you can redistribute it and/or modify it under
5 * the terms of the GNU General Public License, either version 2
6 * of the License, or any later version.
7 *
8 * For the full copyright and license information, please read the
9 * LICENSE.txt file that was distributed with this source code.
10 *
11 * The TYPO3 project - inspiring people to share!
12 */
13
14 import * as $ from 'jquery';
15 import Icons = require('../Icons');
16 import Notification = require('../Notification');
17 import Viewport = require('../Viewport');
18
19 enum Identifiers {
20 containerSelector = '#typo3-cms-backend-backend-toolbaritems-clearcachetoolbaritem',
21 menuItemSelector = 'a.toolbar-cache-flush-action',
22 toolbarIconSelector = '.toolbar-item-icon .t3js-icon'
23 }
24
25 /**
26 * Module: TYPO3/CMS/Backend/Toolbar/ClearCacheMenu
27 * main functionality for clearing caches via the top bar
28 * reloading the clear cache icon
29 */
30 class ClearCacheMenu {
31 constructor() {
32 Viewport.Topbar.Toolbar.registerEvent(this.initializeEvents);
33 }
34
35 /**
36 * Registers listeners for the icons inside the dropdown to trigger
37 * the clear cache call
38 */
39 private initializeEvents = (): void => {
40 $(Identifiers.containerSelector).on('click', Identifiers.menuItemSelector, (evt: JQueryEventObject): void => {
41 evt.preventDefault();
42 const ajaxUrl = $(evt.currentTarget).attr('href');
43 if (ajaxUrl) {
44 this.clearCache(ajaxUrl);
45 }
46 });
47 }
48
49 /**
50 * Calls TYPO3 to clear a cache, then changes the topbar icon
51 * to a spinner. Restores the original topbar icon when the request completed.
52 *
53 * @param {string} ajaxUrl The URL to load
54 */
55 private clearCache(ajaxUrl: string): void {
56 // Close clear cache menu
57 $(Identifiers.containerSelector).removeClass('open');
58
59 const $toolbarItemIcon = $(Identifiers.toolbarIconSelector, Identifiers.containerSelector);
60 const $existingIcon = $toolbarItemIcon.clone();
61
62 Icons.getIcon('spinner-circle-light', Icons.sizes.small).done((spinner: string): void => {
63 $toolbarItemIcon.replaceWith(spinner);
64 });
65
66 $.ajax({
67 url: ajaxUrl,
68 type: 'post',
69 cache: false,
70 complete: (jqXHRObject: JQueryXHR, status: string): void => {
71 $(Identifiers.toolbarIconSelector, Identifiers.containerSelector).replaceWith($existingIcon);
72 if (status !== 'success' || jqXHRObject.responseText !== '') {
73 Notification.error(
74 'An error occurred',
75 'An error occurred while clearing the cache. It is likely not all caches were cleared as expected.'
76 );
77 }
78 }
79 });
80 }
81 }
82
83 export = new ClearCacheMenu();