Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
/* global ns */
2
/**
3
 * Construct a form from library semantics.
4
 */
5
ns.Form = function (library, startLanguages, defaultLanguage) {
6
  var self = this;
7
 
8
  this.params = {};
9
  this.passReadies = false;
10
  this.commonFields = {};
11
 
12
  this.$form = ns.$('' +
13
    '<div class="h5peditor-form">' +
14
      '<div class="tree"></div>' +
15
      '<div class="common collapsed hidden">' +
16
        '<div class="fields">' +
17
          '<p class="desc">' +
18
            ns.t('core', 'commonFieldsDescription') +
19
          '</p>' +
20
          '<div class="h5peditor-language-switcher">' +
21
            '<label class="language-label" for="h5peditor-language-switcher">' + ns.t('core', 'language') + ':</label>' +
22
            '<select id="h5peditor-language-switcher">' +
23
              '<option value="-">' + ns.t('core', 'noLanguagesSupported') + '</option>' +
24
            '</select>' +
25
          '</div>' +
26
          '<div class="h5peditor-language-notice">' +
27
            '<div class="first"></div>' +
28
            '<div class="last"></div>' +
29
          '</div>' +
30
        '</div>' +
31
      '</div>' +
32
    '</div>'
33
  );
34
  this.$common = this.$form.find('.common > .fields');
35
 
36
  if (ns.FullscreenBar !== undefined) {
37
    // Exception from rules
38
    if (library.indexOf('H5P.CoursePresentation') === -1 &&
39
        library.indexOf('H5P.BranchingScenario') === -1 &&
40
        library.indexOf('H5P.InteractiveVideo') === -1) {
41
      ns.FullscreenBar(this.$form, library);
42
    }
43
  }
44
 
45
  // Add title expand/collapse button
46
  self.$commonButton = ns.$('<div/>', {
47
    'class': 'h5peditor-label',
48
    'aria-expanded': 'false',
49
    title: ns.t('core', 'expandCollapse'),
50
    role: 'button',
51
    tabIndex: 0,
52
    html: '<span class="icon"></span>' + ns.t('core', 'commonFields'),
53
    on: {
54
      click: function () {
55
        toggleCommonFields();
56
      },
57
      keypress: function (event) {
58
        if ((event.charCode || event.keyCode) === 32) {
59
          toggleCommonFields();
60
          event.preventDefault();
61
        }
62
      }
63
    },
64
    prependTo: this.$common.parent()
65
  });
66
 
67
  // Alternate background colors
68
  this.zebra = "odd";
69
 
70
  // Locate the language switcher DOM element
71
  const $switcher = this.$form.find('.h5peditor-language-switcher select');
72
  const $notice = this.$form.find('.h5peditor-language-notice');
73
  const loadedLibs = [];
74
  const languages = {};
75
  ns.defaultLanguage = ns.contentLanguage;
76
  if (defaultLanguage) {
77
    ns.defaultLanguage = defaultLanguage;
78
  }
79
 
80
  /**
81
   * Toggle common fields group visibility
82
   */
83
  const toggleCommonFields = function () {
84
    const expandedValue = self.$common.parent().hasClass('collapsed')
85
      ? 'true' : 'false';
86
    self.$commonButton.attr('aria-expanded', expandedValue);
87
    self.$common.parent().toggleClass('collapsed');
88
  };
89
 
90
  /**
91
   * Create options DOM elements
92
   *
93
   * @private
94
   * @return {string}
95
   */
96
  const createOptions = function () {
97
    let options = '';
98
    for (let code in languages) {
99
      let label = ns.supportedLanguages[code] ? ns.supportedLanguages[code] : code.toLocaleUpperCase();
100
      options += '<option value="' + code + '"' + (code === ns.defaultLanguage ? ' selected' : '') + '>' + label + '</option>';
101
    }
102
    return options;
103
  };
104
 
105
  /**
106
   * Figure out if all loaded libraries supports the chosen language code
107
   *
108
   * @private
109
   * @param {string} code
110
   * @return {boolean}
111
   */
112
  const isSupportedByAll = function (code) {
113
    return (languages[code].length === loadedLibs.length);
114
  };
115
 
116
  /**
117
   * This function does something different than the other functions.
118
   *
119
   * @private
120
   * @param {string} lang Global value not used to avoid it changing while loading
121
   */
122
  const updateCommonFields = function (lang) {
123
    const libs = languages[lang];
124
    for (let lib in ns.libraryCache) {
125
 
126
      // Update common fields
127
      if (ns.renderableCommonFields[lib] && ns.renderableCommonFields[lib].fields) {
128
        for (let j = 0; j < ns.renderableCommonFields[lib].fields.length; j++) {
129
          const field = ns.renderableCommonFields[lib].fields[j];
130
 
131
          // Determine translation to use
132
          const translation = ns.libraryCache[lib].translation[lang];
133
 
134
          if (field.instance === undefined || translation === undefined) {
135
            continue; // Skip
136
          }
137
 
138
          // Find the correct translation for the field
139
          const fieldTranslation = findFieldDefaultTranslation(field.field, ns.libraryCache[lib].semantics, translation);
140
 
141
          // Extract the default values from the translation
142
          const defaultValue = getDefaultValue(fieldTranslation, field.field);
143
 
144
          // Update the widget
145
          field.instance.forceValue(defaultValue);
146
        }
147
      }
148
 
149
      if (ns.libraryCache[lib].translation[lang] !== undefined) {
150
        // Update semantics, so that the next time something is inserted it will get the same language
151
        ns.updateCommonFieldsDefault(ns.libraryCache[lib].semantics, ns.libraryCache[lib].translation[lang]);
152
      }
153
    }
154
  };
155
 
156
  /**
157
   * Recursivly search for the field's translations
158
   *
159
   * @private
160
   * @param {Object} field The field we're looking for
161
   * @param {Array} semantics The fields tree to search amongst
162
   * @param {Array} translation The translation tree to search and return from
163
   * @return {Object} The translation if found
164
   */
165
  const findFieldDefaultTranslation = function (field, semantics, translation) {
166
    for (let i = 0; i < semantics.length; i++) {
167
      if (semantics[i] === field) {
168
        return translation[i];
169
      }
170
      if (semantics[i].fields !== undefined && semantics[i].fields.length &&
171
          translation[i].fields !== undefined && translation[i].fields.length) {
172
        const found1 = findFieldDefaultTranslation(field, semantics[i].fields, translation[i].fields);
173
        if (found1 !== undefined) {
174
          return found1;
175
        }
176
      }
177
      if (semantics[i].field !== undefined && translation[i].field !== undefined) {
178
        const found2 = findFieldDefaultTranslation(field, [semantics[i].field], [translation[i].field]);
179
        if (found2 !== undefined) {
180
          return found2;
181
        }
182
      }
183
    }
184
  };
185
 
186
  /**
187
   * Recursivly format a default value for a field.
188
   *
189
   * @private
190
   * @param {Object} translation The translation field to extract the default values from
191
   * @param {Object} field Needed for field naming
192
   * @return {Object} The default value
193
   */
194
  const getDefaultValue = function (translation, field) {
195
    if (translation.default !== undefined) {
196
      return translation.default;
197
    }
198
    if (translation.fields !== undefined && translation.fields.length) {
199
      if (translation.fields.length === 1) {
200
        return getDefaultValue(translation.fields[0], field.fields[0]);
201
      }
202
      const values = {};
203
      for (let i = 0; i < translation.fields.length; i++) {
204
        values[field.fields[i].name] = getDefaultValue(translation.fields[i], field.fields[i]);
205
      }
206
      return values;
207
    }
208
    if (translation.field !== undefined) {
209
      return getDefaultValue(translation.field, field.field);
210
    }
211
  };
212
 
213
  /**
214
   * Prepares and loads all the missing translations from the server.
215
   *
216
   * @param {string} lang Global value not used to avoid it changing while loading
217
   * @param {function} done Callback
218
   */
219
  const loadTranslations = function (lang, done) {
220
    // Figure out what we actually need to load
221
    const loadLibs = [];
222
    for (let li in ns.libraryCache) {
223
      if (ns.libraryCache[li] === 0 || ns.libraryCache[li].translation[lang] === undefined) {
224
        loadLibs.push(li);
225
      }
226
    }
227
 
228
    if (loadLibs.length) {
229
      ns.$.post(
230
        ns.getAjaxUrl('translations', { language: lang }),
231
        { libraries: loadLibs },
232
        function (res) {
233
          for (let lib in res.data) {
234
            ns.libraryCache[lib].translation[lang] = JSON.parse(res.data[lib]).semantics;
235
          }
236
          done();
237
        }
238
      );
239
    }
240
    else {
241
      done(); // Continue without loading anything
242
    }
243
  }
244
 
245
  /**
246
   * Add new languages for content type.
247
   *
248
   * @param {string} lib uberName
249
   * @param {Array} langs
250
   */
251
  self.addLanguages = function (lib, langs) {
252
    // Update language counters
253
    for (let i = 0; i < langs.length; i++) {
254
      const code = langs[i];
255
      if (languages[code] === undefined) {
256
        languages[code] = [lib];
257
      }
258
      else {
259
        languages[code].push(lib);
260
      }
261
    }
262
    loadedLibs.push(lib);
263
 
264
    // Update
265
    $switcher.html(createOptions());
266
  };
267
 
268
  /**
269
   * Remove languages for content type.
270
   *
271
   * @param {string} lib uberName
272
   * @param {Array} langs
273
   */
274
  self.removeLanguages = function (lib, langs) {
275
    // Update language counters
276
    for (let i = 0; i < langs.length; i++) {
277
      const code = langs[i];
278
      if (languages[code] !== undefined) {
279
        if (languages[code].length === 1) {
280
          delete languages[code];
281
        }
282
        else {
283
          languages[code].splice(languages[code].indexOf(lib), 1);
284
        }
285
      }
286
    }
287
    loadedLibs.splice(loadedLibs.indexOf(lib), 1);
288
 
289
    // Update
290
    $switcher.html(createOptions());
291
  };
292
 
293
  // Handle switching language and loading new translations
294
  $switcher.change(function (e) {
295
    // Create confirmation dialog
296
    const confirmDialog = new H5P.ConfirmationDialog({
297
      headerText: ns.t('core', 'changeLanguage', {':language': (ns.supportedLanguages[this.value] ? ns.supportedLanguages[this.value] : this.value.toLocaleUpperCase())}),
298
      dialogText: ns.t('core', 'thisWillPotentially'),
299
    }).appendTo(document.body);
300
    confirmDialog.on('confirmed', function () {
301
      const lang = ns.defaultLanguage = $switcher.val();
302
      const humanLang = (ns.supportedLanguages[lang] ? ns.supportedLanguages[lang] : lang.toLocaleUpperCase());
303
 
304
      // Update chosen default language for main content and sub-content
305
      self.metadata.defaultLanguage = lang;
306
      self.params = self.setSubContentDefaultLanguage(self.params, lang);
307
 
308
      // Figure out if all libraries were supported
309
      if (!isSupportedByAll(lang)) {
310
        // Show a warning message
311
        $notice.children('.first').html(ns.t('core', 'notAllTextsChanged', {':language': humanLang}));
312
        $notice.children('.last').html(ns.t('core', 'contributeTranslations', {':language': humanLang, ':url': 'https://h5p.org/contributing#translating'}));
313
        $notice.addClass('show');
314
      }
315
      else {
316
        // Hide a warning message
317
        $notice.removeClass('show');
318
      }
319
 
320
      $switcher.prop('disabled', 'disabled');
321
      loadTranslations(lang, function () {
322
        // Do the actualy update of the field values
323
        updateCommonFields(lang);
324
        $switcher.prop('disabled', false);
325
      });
326
    });
327
    confirmDialog.on('canceled', function () {
328
      $switcher.val(ns.defaultLanguage);
329
    });
330
    // Show
331
    confirmDialog.show($switcher.offset().top);
332
  });
333
 
334
  // Add initial langauges for content type
335
  self.addLanguages(library, startLanguages);
336
};
337
 
338
/**
339
 * Recursively traverse params and sets default language for each sub-content
340
 *
341
 * @param {Object|Array} params Parameters
342
 * @param {string} lang Default language that will be set
343
 *
344
 * @return {Object|Array} Parameters with default language set for sub-content
345
 */
346
ns.Form.prototype.setSubContentDefaultLanguage = function (params, lang) {
347
  if (!params) {
348
    return params;
349
  }
350
 
351
  const self = this;
352
 
353
  if (Array.isArray(params)) {
354
    for (let i; i < params.length; i++) {
355
      params[i] = self.setSubContentDefaultLanguage(params[i], lang);
356
    }
357
  }
358
  else if (typeof params === 'object') {
359
    if (params.metadata) {
360
      params.metadata.defaultLanguage = lang;
361
    }
362
 
363
    for (let parameter in params) {
364
      if (!params.hasOwnProperty(parameter)) {
365
        continue;
366
      }
367
      params[parameter] = this.setSubContentDefaultLanguage(
368
        params[parameter],
369
        lang
370
      );
371
    }
372
  }
373
 
374
  return params;
375
};
376
 
377
/**
378
 * Replace the given element with our form.
379
 *
380
 * @param {jQuery} $element
381
 * @returns {undefined}
382
 */
383
ns.Form.prototype.replace = function ($element) {
384
  $element.replaceWith(this.$form);
385
  this.offset = this.$form.offset();
386
  // Prevent inputs and selects in an h5peditor form from submitting the main
387
  // framework form.
388
  this.$form.on('keydown', 'input,select', function (event) {
389
    if (event.keyCode === 13) {
390
      // Prevent enter key from submitting form.
391
      return false;
392
    }
393
  });
394
};
395
 
396
/**
397
 * Remove the current form.
398
 */
399
ns.Form.prototype.remove = function () {
400
  ns.removeChildren(this.metadataForm.children);
401
  ns.removeChildren(this.children);
402
  ns.renderableCommonFields = {}; // Reset all common fields
403
  this.$form.remove();
404
};
405
 
406
/**
407
 * Wrapper for processing the semantics.
408
 *
409
 * @param {Array} semantics
410
 * @param {Object} defaultParams
411
 * @returns {undefined}
412
 */
413
ns.Form.prototype.processSemantics = function (semantics, defaultParams, metadata) {
414
  this.metadata = (metadata ? metadata : defaultParams.metadata || {});
415
 
416
  // Set language initially used
417
  if (!this.metadata.defaultLanguage) {
418
    this.metadata.defaultLanguage = ns.defaultLanguage;
419
  }
420
 
421
  if (ns.enableMetadata(this.currentLibrary)) {
422
    this.metadataForm = new ns.MetadataForm(this, this.metadata, this.$form.children('.tree'), true);
423
  }
424
  else {
425
    this.metadataForm = H5PEditor.MetadataForm.createLegacyForm(this.metadata, this.$form.children('.tree'));
426
 
427
    // This fixes CSS overrides done by some old custom editors
428
    switch (this.currentLibrary.split(' ')[0]) {
429
      case 'H5P.InteractiveVideo':
430
      case 'H5P.DragQuestion':
431
      case 'H5P.ImageHotspotQuestion':
432
        this.metadataForm.getExtraTitleField().$item.css('padding', '20px 20px 0 20px');
433
        break;
434
 
435
      case 'H5P.CoursePresentation':
436
        this.metadataForm.getExtraTitleField().$item.css('padding-bottom', '1em');
437
        break;
438
    }
439
  }
440
 
441
  // Overriding this.params with {} will lead to old content not being editable for now
442
  this.params = (defaultParams.params ? defaultParams.params : defaultParams);
443
 
444
  // Create real children
445
  ns.processSemanticsChunk(semantics, this.params, this.$form.children('.tree'), this);
446
};
447
 
448
/**
449
 * Collect functions to execute once the tree is complete.
450
 *
451
 * @param {function} ready
452
 * @returns {undefined}
453
 */
454
ns.Form.prototype.ready = function (ready) {
455
  this.readies.push(ready);
456
};