Localization.ts 14.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

14
import $ from 'jquery';
15
16
17
import {AjaxResponse} from 'TYPO3/CMS/Core/Ajax/AjaxResponse';
import {SeverityEnum} from './Enum/Severity';
import AjaxRequest = require('TYPO3/CMS/Core/Ajax/AjaxRequest');
18
import Icons = require('./Icons');
19
import Wizard = require('./Wizard');
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

type LanguageRecord = {
  uid: number;
  title: string;
  flagIcon: string;
};

type SummaryColumns = {
  columns: { [key: number]: string };
  columnList: Array<number>;
};

type SummaryColPosRecord = {
  uid: number;
  title: string;
  icon: string;
};

type SummaryRecord = {
  columns: SummaryColumns;
  records: Array<Array<SummaryColPosRecord>>;
};

class Localization {
  private triggerButton: string = '.t3js-localize';
  private localizationMode: string = null;
  private sourceLanguage: number = null;
  private records: Array<any> = [];

  constructor() {
    $((): void => {
      this.initialize();
    });
  }

  private initialize(): void {
    const me = this;
57
58
    Icons.getIcon('actions-localize', Icons.sizes.large).then((localizeIconMarkup: string): void => {
      Icons.getIcon('actions-edit-copy', Icons.sizes.large).then((copyIconMarkup: string): void => {
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
        $(me.triggerButton).removeClass('disabled');

        $(document).on('click', me.triggerButton, (e: JQueryEventObject): void => {
          e.preventDefault();

          const $triggerButton = $(e.currentTarget);
          const actions: Array<string> = [];
          let slideStep1: string = '';

          if ($triggerButton.data('allowTranslate')) {
            actions.push(
              '<div class="row">'
              + '<div class="btn-group col-sm-3">'
              + '<label class="btn btn-block btn-default t3js-localization-option" data-helptext=".t3js-helptext-translate">'
              + localizeIconMarkup
              + '<input type="radio" name="mode" id="mode_translate" value="localize" style="display: none">'
              + '<br>Translate</label>'
              + '</div>'
              + '<div class="col-sm-9">'
              + '<p class="t3js-helptext t3js-helptext-translate text-muted">' + TYPO3.lang['localize.educate.translate'] + '</p>'
              + '</div>'
80
              + '</div>',
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
            );
          }

          if ($triggerButton.data('allowCopy')) {
            actions.push(
              '<div class="row">'
              + '<div class="col-sm-3 btn-group">'
              + '<label class="btn btn-block btn-default t3js-localization-option" data-helptext=".t3js-helptext-copy">'
              + copyIconMarkup
              + '<input type="radio" name="mode" id="mode_copy" value="copyFromLanguage" style="display: none">'
              + '<br>Copy</label>'
              + '</div>'
              + '<div class="col-sm-9">'
              + '<p class="t3js-helptext t3js-helptext-copy text-muted">' + TYPO3.lang['localize.educate.copy'] + '</p>'
              + '</div>'
96
              + '</div>',
97
98
99
            );
          }

100
101
102
103
104
105
106
107
108
109
          if ($triggerButton.data('allowTranslate') === 0 && $triggerButton.data('allowCopy') === 0) {
            actions.push(
              '<div class="row">'
              + '<div class="col-sm-12">'
              + '<div class="alert alert-warning">'
              + '<div class="media">'
              + '<div class="media-left">'
              + '<span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-exclamation fa-stack-1x"></i></span>'
              + '</div>'
              + '<div class="media-body">'
110
              + '<p class="alert-message">' + TYPO3.lang['localize.educate.noTranslate'] + '</p>'
111
112
113
114
115
116
117
118
              + '</div>'
              + '</div>'
              + '</div>'
              + '</div>'
              + '</div>',
            );
          }

119
          slideStep1 += '<div data-bs-toggle="buttons">' + actions.join('<hr>') + '</div>';
120
121
122
123
124
125
          Wizard.addSlide(
            'localize-choose-action',
            TYPO3.lang['localize.wizard.header_page']
              .replace('{0}', $triggerButton.data('page'))
              .replace('{1}', $triggerButton.data('languageName')),
            slideStep1,
126
            SeverityEnum.info,
127
128
129
130
131
132
133
          );
          Wizard.addSlide(
            'localize-choose-language',
            TYPO3.lang['localize.view.chooseLanguage'],
            '',
            SeverityEnum.info,
            ($slide: JQuery): void => {
134
              Icons.getIcon('spinner-circle-dark', Icons.sizes.large).then((markup: string): void => {
135
136
137
138
                $slide.html('<div class="text-center">' + markup + '</div>');

                this.loadAvailableLanguages(
                  parseInt($triggerButton.data('pageId'), 10),
139
                  parseInt($triggerButton.data('languageId'), 10),
140
141
                ).then(async (response: AjaxResponse): Promise<void> => {
                  const result: Array<LanguageRecord> = await response.resolve();
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
                  if (result.length === 1) {
                    // We only have one result, auto select the record and continue
                    this.sourceLanguage = result[0].uid;
                    Wizard.unlockNextStep().trigger('click');
                    return;
                  }

                  Wizard.getComponent().on('click', '.t3js-language-option', (optionEvt: JQueryEventObject): void => {
                    const $me = $(optionEvt.currentTarget);
                    const $radio = $me.find('input[type="radio"]');

                    this.sourceLanguage = $radio.val();
                    console.log('Localization.ts@132', this.sourceLanguage);
                    Wizard.unlockNextStep();
                  });

158
                  const $languageButtons = $('<div />', {class: 'row', 'data-bs-toggle': 'buttons'});
159
160
161
162
163
164
165
166
167
168
169
170
171

                  for (const languageObject of result) {
                    $languageButtons.append(
                      $('<div />', {class: 'col-sm-4'}).append(
                        $('<label />', {class: 'btn btn-default btn-block t3js-language-option option'})
                          .text(' ' + languageObject.title)
                          .prepend(languageObject.flagIcon)
                          .prepend(
                            $('<input />', {
                              type: 'radio',
                              name: 'language',
                              id: 'language' + languageObject.uid,
                              value: languageObject.uid,
172
173
                              style: 'display: none;',
                            },
174
                            ),
175
176
                          ),
                      ),
177
178
179
180
181
                    );
                  }
                  $slide.empty().append($languageButtons);
                });
              });
182
            },
183
184
185
186
187
188
          );
          Wizard.addSlide(
            'localize-summary',
            TYPO3.lang['localize.view.summary'],
            '',
            SeverityEnum.info, ($slide: JQuery): void => {
189
              Icons.getIcon('spinner-circle-dark', Icons.sizes.large).then((markup: string): void => {
190
191
192
193
                $slide.html('<div class="text-center">' + markup + '</div>');
              });
              this.getSummary(
                parseInt($triggerButton.data('pageId'), 10),
194
                parseInt($triggerButton.data('languageId'), 10),
195
196
              ).then(async (response: AjaxResponse): Promise<void> => {
                const result: SummaryRecord = await response.resolve();
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
                $slide.empty();
                this.records = [];

                const columns = result.columns.columns;
                const columnList = result.columns.columnList;

                columnList.forEach((colPos: number): void => {
                  if (typeof result.records[colPos] === 'undefined') {
                    return;
                  }

                  const column = columns[colPos];
                  const $row = $('<div />', {class: 'row'});

                  result.records[colPos].forEach((record: SummaryColPosRecord): void => {
                    const label = ' (' + record.uid + ') ' + record.title;
                    this.records.push(record.uid);

                    $row.append(
                      $('<div />', {'class': 'col-sm-6'}).append(
                        $('<div />', {'class': 'input-group'}).append(
                          $('<span />', {'class': 'input-group-addon'}).append(
                            $('<input />', {
                              type: 'checkbox',
                              'class': 't3js-localization-toggle-record',
                              id: 'record-uid-' + record.uid,
                              checked: 'checked',
                              'data-uid': record.uid,
225
226
                              'aria-label': label,
                            }),
227
228
229
                          ),
                          $('<label />', {
                            'class': 'form-control',
230
231
232
233
                            for: 'record-uid-' + record.uid,
                          }).text(label).prepend(record.icon),
                        ),
                      ),
234
235
236
237
238
                    );
                  });

                  $slide.append(
                    $('<fieldset />', {
239
                      'class': 'localization-fieldset',
240
241
242
243
244
                    }).append(
                      $('<label />').text(column).prepend(
                        $('<input />', {
                          'class': 't3js-localization-toggle-column',
                          type: 'checkbox',
245
246
                          checked: 'checked',
                        }),
247
                      ),
248
249
                      $row,
                    ),
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
                  );
                });

                Wizard.unlockNextStep();

                Wizard.getComponent().on('change', '.t3js-localization-toggle-record', (cmpEvt: JQueryEventObject): void => {
                  const $me = $(cmpEvt.currentTarget);
                  const uid = $me.data('uid');
                  const $parent = $me.closest('fieldset');
                  const $columnCheckbox = $parent.find('.t3js-localization-toggle-column');

                  if ($me.is(':checked')) {
                    this.records.push(uid);
                  } else {
                    const index = this.records.indexOf(uid);
                    if (index > -1) {
                      this.records.splice(index, 1);
                    }
                  }

                  const $allChildren = $parent.find('.t3js-localization-toggle-record');
                  const $checkedChildren = $parent.find('.t3js-localization-toggle-record:checked');

                  $columnCheckbox.prop('checked', $checkedChildren.length > 0);
                  $columnCheckbox.prop('indeterminate', $checkedChildren.length > 0 && $checkedChildren.length < $allChildren.length);

                  if (this.records.length > 0) {
                    Wizard.unlockNextStep();
                  } else {
                    Wizard.lockNextStep();
                  }
281
                }).on('change', '.t3js-localization-toggle-column', (toggleEvt: JQueryEventObject): void => {
282
283
284
285
286
287
288
                  const $me = $(toggleEvt.currentTarget);
                  const $children = $me.closest('fieldset').find('.t3js-localization-toggle-record');

                  $children.prop('checked', $me.is(':checked'));
                  $children.trigger('change');
                });
              });
289
            },
290
291
292
293
294
295
          );

          Wizard.addFinalProcessingSlide((): void => {
            this.localizeRecords(
              parseInt($triggerButton.data('pageId'), 10),
              parseInt($triggerButton.data('languageId'), 10),
296
              this.records,
297
            ).then((): void => {
298
299
300
              Wizard.dismiss();
              document.location.reload();
            });
301
          }).then((): void => {
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
            Wizard.show();

            Wizard.getComponent().on('click', '.t3js-localization-option', (optionEvt: JQueryEventObject): void => {
              const $me = $(optionEvt.currentTarget);
              const $radio = $me.find('input[type="radio"]');

              if ($me.data('helptext')) {
                const $container = $(optionEvt.delegateTarget);
                $container.find('.t3js-helptext').addClass('text-muted');
                $container.find($me.data('helptext')).removeClass('text-muted');
              }
              this.localizationMode = $radio.val();
              Wizard.unlockNextStep();
            });
          });
        });
      });
    });
  }

  /**
   * Load available languages from page
   *
   * @param {number} pageId
   * @param {number} languageId
327
   * @returns {Promise<AjaxResponse>}
328
   */
329
330
331
332
333
  private loadAvailableLanguages(pageId: number, languageId: number): Promise<AjaxResponse> {
    return new AjaxRequest(TYPO3.settings.ajaxUrls.page_languages).withQueryArguments({
      pageId: pageId,
      languageId: languageId,
    }).get();
334
335
336
337
338
339
340
  }

  /**
   * Get summary for record processing
   *
   * @param {number} pageId
   * @param {number} languageId
341
   * @returns {Promise<AjaxResponse>}
342
   */
343
344
345
346
347
348
  private getSummary(pageId: number, languageId: number): Promise<AjaxResponse> {
    return new AjaxRequest(TYPO3.settings.ajaxUrls.records_localize_summary).withQueryArguments({
      pageId: pageId,
      destLanguageId: languageId,
      languageId: this.sourceLanguage,
    }).get();
349
350
351
352
353
354
355
356
  }

  /**
   * Localize records
   *
   * @param {number} pageId
   * @param {number} languageId
   * @param {Array<number>} uidList
357
   * @returns {Promise<AjaxResponse>}
358
   */
359
360
361
362
363
364
365
366
  private localizeRecords(pageId: number, languageId: number, uidList: Array<number>): Promise<AjaxResponse> {
    return new AjaxRequest(TYPO3.settings.ajaxUrls.records_localize).withQueryArguments({
      pageId: pageId,
      srcLanguageId: this.sourceLanguage,
      destLanguageId: languageId,
      action: this.localizationMode,
      uidList: uidList,
    }).get();
367
368
369
370
  }
}

export = new Localization();