-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathEditorController.js
2648 lines (2284 loc) · 95.4 KB
/
EditorController.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ---------------------------------------------------------------------
*
* GLPI - Gestionnaire Libre de Parc Informatique
*
* http://glpi-project.org
*
* @copyright 2015-2025 Teclib' and contributors.
* @copyright 2003-2014 by the INDEPNET Development Team.
* @licence https://www.gnu.org/licenses/gpl-3.0.html
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* ---------------------------------------------------------------------
*/
/* global _, tinymce_editor_configs, getUUID, getRealInputWidth, sortable, tinymce, glpi_toast_info, glpi_toast_error, bootstrap, setupAjaxDropdown, setupAdaptDropdown, setHasUnsavedChanges, hasUnsavedChanges */
import { GlpiFormConditionEditorController } from './ConditionEditorController.js';
/**
* Client code to handle users actions on the form_editor template
*/
export class GlpiFormEditorController
{
/**
* Target form editor (jquery selector)
* @type {string}
*/
#target;
/**
* Is this form a draft?
* @type {boolean}
*/
#is_draft;
/**
* Default question type to use when creating a new question
* @type {string}
*/
#defaultQuestionType;
/**
* Templates container (jquery selector)
* @type {string}
*/
#templates;
/**
* Options for each question type
* @type {Object}
*/
#options;
/**
* Subtypes options for each question type
* @type {Object}
*/
#question_subtypes_options;
/**
* @type {array<GlpiFormConditionEditorController>}
*/
#conditions_editors_controllers;
/**
* @type {boolean}
*/
#do_preview_after_save = false;
/**
* Create a new GlpiFormEditorController instance for the given target.
* The target must be a valid form.
*
* @param {string} target
* @param {boolean} is_draft
* @param {string} defaultQuestionType
* @param {string} templates
*/
constructor(target, is_draft, defaultQuestionType, templates) {
this.#target = target;
this.#is_draft = is_draft;
this.#defaultQuestionType = defaultQuestionType;
this.#templates = templates;
this.#options = {};
this.#question_subtypes_options = {};
this.#conditions_editors_controllers = [];
// Validate target
if ($(this.#target).prop("tagName") != "FORM") {
throw new Error("Target must be a valid form");
}
// Validate default question type
if (this.#getQuestionTemplate(this.#defaultQuestionType).length == 0) {
throw new Error(`Invalid default question type: ${defaultQuestionType}`);
}
// Adjust container height and init handlers
this.#adjustContainerHeight();
this.#initEventHandlers();
this.#refreshUX();
// Adjust dynamics inputs size
$(this.#target)
.find("[data-glpi-form-editor-dynamic-input]")
.each((index, input) => {
this.#computeDynamicInputSize(input);
});
// Enable sortable on questions
this.#enableSortable(
$(this.#target).find("[data-glpi-form-editor-blocks]")
);
// Focus the form's name input if there are no questions
if (this.#getQuestionsCount() === 0) {
$(this.#target)
.find("[data-glpi-form-editor-form-details-name]")[0]
.select();
}
this.computeState();
// Some radios wont be displayed correclty as checked as they share the same name.
// This is fixed by re-checking them after the state has been computed.
// Not sure if there is a better solution for this, it doesn't feel great.
this.#refreshCheckedInputs();
}
/**
* Init event handlers for each possible editors actions (identified by the
* "data-glpi-form-editor-on-xxx" data attributes) and external events.
*/
#initEventHandlers() {
// Register throttled version of the adjustContainerHeight() function
const adjust_container_height_throttled = _.throttle(
() => this.#adjustContainerHeight(),
100
);
// Compute correct height when the window is resized
$(window).on('resize', () => adjust_container_height_throttled());
// Handle ajax controller submit event
$(this.#target).on(
"glpi-ajax-controller-submit-success",
() => this.#handleBackendUpdateResponse()
);
// Handle clicks inside the form editor, remove the active item
$(document)
.on(
'click',
'[data-glpi-form-editor]',
() => {
$('.simulate-focus').removeClass('simulate-focus');
}
);
// Handle tinymce change event
$(document)
.on(
'tinyMCEChange',
(e, original_event) => this.#handleTinyMCEChange(original_event)
);
// Handle tinymce click event
$(document)
.on(
'tinyMCEClick',
(e, original_event) => this.#handleTinyMCEClick(original_event)
);
// Handle visiblity editor dropdowns
// The dropdown content will be re-rendered each time it is opened.
// This ensure the selectable data is always up to date (i.e. the
// question selector has up to date questions names, contains all newly
// added questions and do not include deleted questions).
$(document)
.on(
'show.bs.dropdown',
'[data-glpi-form-editor-visibility-dropdown]',
(e) => this.#renderVisibilityEditor(
$(e.target)
.parent()
.find('[data-glpi-conditions-editor-container]')
),
);
// Compute state before submitting the form
$(this.#target).on('submit', (event) => {
try {
this.computeState();
} catch (e) {
// Do not submit the form if the state isn't computed
event.preventDefault();
event.stopPropagation();
glpi_toast_error(__("An unexpected error occurred"));
throw e;
}
});
// Handle form submit success event
$(this.#target).on('glpi-ajax-controller-submit-success', () => {
const save_and_preview_button = $(this.#target).find(
'[data-glpi-form-editor-save-and-preview-action]'
);
// Reset unsaved changes
this.#updatePreviewButton();
// Check if a preview action was queued
if (this.#do_preview_after_save) {
// Open the preview page in a new tab
window.open(
save_and_preview_button.data('glpi-form-editor-preview-url'),
'_blank'
);
this.#do_preview_after_save = false;
}
});
$(document).on('glpiFormChangeEvent', () => {
this.#updatePreviewButton();
});
// Handle conditions strategy changes
document.addEventListener('updated_strategy', (e) => {
this.#updateVisibilityBadge(
$(e.detail.container).closest(
'[data-glpi-form-editor-block],[data-glpi-form-editor-section-details]'
),
e.detail.strategy
);
});
// Register handlers for each possible editor actions using custom
// data attributes
const events = ["click", "change", "input"];
events.forEach((event) => {
const attribute = `data-glpi-form-editor-on-${event}`;
$(document)
.on(event, `${this.#target} [${attribute}]`, (e) => {
// Get action and a jQuery wrapper for the target
const target = $(e.currentTarget);
const action = target.attr(attribute);
try {
this.#handleEditorAction(action, target, e);
} catch (e) {
glpi_toast_error(__("An unexpected error occurred"));
throw e;
}
});
});
}
/**
* Register new options for the given question type.
*
* @param {string} type Question type
* @param {Object} options Options for the question type
*/
registerQuestionTypeOptions(type, options) {
this.#options[type] = options;
}
/**
* Register new subtypes options for the given question type.
*
* @param {string} type Question type
* @param {Object} options Subtypes options for the question type
*/
registerQuestionSubTypesOptions(type, options) {
this.#question_subtypes_options[type] = options;
}
/**
* Handle backend response
*/
#handleBackendUpdateResponse() {
// Item can no longer be draft after the first backend update
if (this.#is_draft) {
this.#removeDraftStatus();
}
}
/**
* This method should be the unique entry point for any action on the editor.
*
* @param {string} action Action to perform
* @param {jQuery} target Element that triggered the action
* @param {Event} event Event
*/
#handleEditorAction(action, target, event) {
/**
* Some unsaved changes are not tracked by the native `data-track-changes`
* attribute.
*
* By default, any editor actions will be considered as unsaved changes.
*
* Actions that do not represent an actual data change must manually
* set this variable to `false`.
* This make sure we don't forget to track changes when needed.
*/
let unsaved_changes = true;
// Events should only be handled here once.
event.stopPropagation();
switch (action) {
// Mark the target item as active
case "set-active":
this.#setActiveItem(target);
unsaved_changes = false;
break;
// Add a question
case "add-question":
this.#addQuestion(
target.closest(`
[data-glpi-form-editor-active-form],
[data-glpi-form-editor-active-section],
[data-glpi-form-editor-active-horizontal-blocks],
[data-glpi-form-editor-active-question],
[data-glpi-form-editor-active-comment],
[data-glpi-form-editor-horizontal-block-placeholder]
`),
);
break;
// Delete the target question
case "delete-question":
this.#deleteQuestion(
target.closest("[data-glpi-form-editor-question]")
);
break;
// Toggle mandatory class on the target question
case "toggle-mandatory-question":
this.#toggleMandatoryClass(
target.closest("[data-glpi-form-editor-question]"),
target.prop("checked")
);
break;
// Compute the ideal width of the given input based on its content
case "compute-dynamic-input":
this.#computeDynamicInputSize(target[0]);
break;
// Change the type category of the target question
case "change-question-type-category":
this.#changeQuestionTypeCategory(
target.closest("[data-glpi-form-editor-question]"),
target.val()
);
break;
// Change the type of the target question
case "change-question-type":
this.#changeQuestionType(
target.closest("[data-glpi-form-editor-question]"),
target.val()
);
break;
case "change-question-sub-type":
this.#changeQuestionSubType(
target.closest("[data-glpi-form-editor-question]"),
target.val()
);
break;
// Add a section at the end of the form
case "add-section":
this.#addSection(
target.closest(`
[data-glpi-form-editor-active-form],
[data-glpi-form-editor-active-section],
[data-glpi-form-editor-active-horizontal-blocks],
[data-glpi-form-editor-active-question],
[data-glpi-form-editor-active-comment]
`),
);
break;
// Delete the target section
case "delete-section":
this.#deleteSection(
target.closest("[data-glpi-form-editor-section]")
);
break;
// Build the "move section modal" content
case "build-move-section-modal-content":
this.#buildMoveSectionModalContent();
unsaved_changes = false;
break;
// Reorder the sections based on the "move section modal" content
case "reorder-sections":
this.#reorderSections();
break;
// Merge current section with the previous section
case "merge-with-previous-section":
this.#mergeWithPreviousSection(
target.closest("[data-glpi-form-editor-section]")
);
break;
// Collapse/uncollapse target section
case "collapse-section":
this.#collaspeSection(
target.closest("[data-glpi-form-editor-section]")
);
break;
// Duplicate target section
case "duplicate-section":
this.#duplicateSection(
target.closest("[data-glpi-form-editor-section]")
);
break;
// Duplicate target question
case "duplicate-question":
this.#duplicateQuestion(
target.closest("[data-glpi-form-editor-question]")
);
break;
// Duplicate target comment
case "duplicate-comment":
this.#duplicateComment(
target.closest("[data-glpi-form-editor-comment]")
);
break;
// No specific instructions for these events.
// They must still be kept here as they benefits from the common code
// like refreshUX().
case "question-sort-update":
break;
// Add a comment
case "add-comment":
this.#addComment(
target.closest(`
[data-glpi-form-editor-active-form],
[data-glpi-form-editor-active-section],
[data-glpi-form-editor-active-horizontal-blocks],
[data-glpi-form-editor-active-question],
[data-glpi-form-editor-active-comment],
[data-glpi-form-editor-horizontal-block-placeholder]
`),
);
break;
// Delete the target comment
case "delete-comment":
this.#deleteComment(
target.closest("[data-glpi-form-editor-comment]")
);
break;
case "show-visibility-dropdown":
this.#showVisibilityDropdown(
target.closest('[data-glpi-form-editor-block],[data-glpi-form-editor-section-details]')
);
break;
case "add-horizontal-layout":
this.#addHorizontalLayout(
target.closest(`
[data-glpi-form-editor-active-form],
[data-glpi-form-editor-active-section],
[data-glpi-form-editor-active-horizontal-blocks],
[data-glpi-form-editor-active-question],
[data-glpi-form-editor-active-comment]
`)
);
break;
case "delete-horizontal-layout":
this.#deleteHorizontalLayout(
target.closest("[data-glpi-form-editor-horizontal-blocks-container]")
);
break;
case "add-horizontal-layout-slot":
this.#addHorizontalLayoutSlot(
target.closest("[data-glpi-form-editor-horizontal-blocks]")
);
break;
case "remove-horizontal-layout-slot":
this.#removeHorizontalLayoutSlot(
target.closest("[data-glpi-form-editor-horizontal-block-placeholder]")
);
break;
case "copy-uuid":
this.#copyQuestionUuidToClipboard(
target.closest('[data-glpi-form-editor-question')
);
break;
case "queue-preview":
this.#do_preview_after_save = true;
break;
// Unknown action
default:
throw new Error(`Unknown action: ${action}`);
}
if (unsaved_changes) {
setHasUnsavedChanges(true);
}
// Refresh all dynamic UX components after every action.
// It is a bit less effecient than refreshing only the needed components
// per action, but it is much simpler and safer.
this.#refreshUX();
}
/**
* Compute the state of the form editor (= inputs names and values).
* Must be executed after each actions.
*/
computeState() {
const global_block_indices = { 'question': 0, 'comment': 0 };
// Find all sections
const sections = $(this.#target).find("[data-glpi-form-editor-section]");
sections.each((s_index, section) => {
// Compute state for each sections
this.#formatInputsNames(
$(section).find("[data-glpi-form-editor-section-details]"),
'section',
s_index
);
this.#setSectionRank($(section), s_index);
this.#setUuid($(section));
// Find all items for this section (both questions and comments)
const items = $(section).find('[data-glpi-form-editor-section-blocks]').children("[data-glpi-form-editor-block], [data-glpi-form-editor-horizontal-blocks-container]");
items.each((vertical_rank, item) => {
let blocks = $(item);
const is_horizontal_block = $(item).is("[data-glpi-form-editor-horizontal-blocks-container]");
// If the item is a horizontal block, we need to find all questions and comments
if (is_horizontal_block) {
blocks = $(item).find("[data-glpi-form-editor-block], [data-glpi-form-editor-horizontal-block-placeholder]");
}
blocks.each((horizontal_rank, block) => {
if ($(block).is("[data-glpi-form-editor-horizontal-block-placeholder]")) {
return;
}
// Determine the type of the block
const itemType = $(block).is("[data-glpi-form-editor-question]") ? 'question' : 'comment';
// Compute state for each block
this.#formatInputsNames(
$(block),
itemType,
global_block_indices[itemType]
);
this.#setQuestionRank($(block), vertical_rank, is_horizontal_block ? horizontal_rank : null);
this.#setUuid($(block));
this.#setParentSection($(block), $(section));
// Increment the index for this item type
global_block_indices[itemType]++;
});
});
});
}
/**
* Refresh all UX items that may be modified by mulitple actions.
*/
#refreshUX() {
this.#updateAddSectionActionVisiblity();
this.#addFakeDivToEmptySections();
this.#updateSectionCountLabels();
this.#updateSectionsDetailsVisiblity();
this.#updateMergeSectionActionVisibility();
}
/**
* Must not be called directly, use computeState() instead.
*
* Inputs names of questions and sections must be formatted to match the
* expected format, which is:
* - Sections: _sections[section_index][field]
* - Questions: _questions[question_index][field]
* - Comment blocks: _comments[comment_index][field]
*
* @param {jQuery} item Section or question form container
* @param {string} type Item type: "question" or "section"
* @param {number} item_index Item index
*/
#formatInputsNames(item, type, item_index) {
// Find all inputs for this section
const inputs = item.find("input[name], select[name], textarea[name]");
// Find all section inputs and update their names to match the
// "_section[section_index][field]" format
inputs.each((index, input) => {
const name = $(input).attr("name");
// Input was never parsed before, store its original name
if (!$(input).data("glpi-form-editor-original-name")) {
$(input).attr("data-glpi-form-editor-original-name", name);
}
// Format input name
let field = $(input).data("glpi-form-editor-original-name");
let base_input_index = "";
if (type === "section") {
// The input is for the section itself
base_input_index = `_sections[${item_index}]`;
} else if (type === "question") {
// The input is for a question
base_input_index = `_questions[${item_index}]`;
// Check if the input is an option (has the data-glpi-form-editor-specific-question-extra-data attribute)
const is_option = $(input).attr("data-glpi-form-editor-specific-question-extra-data") !== undefined;
if (is_option) {
base_input_index += `[extra_data]`;
}
} else if (type === "comment") {
// The input is for a comment block
base_input_index = `_comments[${item_index}]`;
} else if (type === "temp") {
// We need to format the input name temporarily
base_input_index = `_temp[${item_index}]`;
} else {
throw new Error(`Unknown item type: ${type}`);
}
// Update input name
let postfix = "";
const postfix_pattern = new RegExp(/\[([\w-[\]]*)\]$/, 'g');
if (typeof field === 'string' && postfix_pattern.test(field)) {
postfix = field.match(postfix_pattern);
field = field.replace(postfix, "");
}
$(input).attr(
"name",
`${base_input_index}[${field}]${postfix}`
);
});
}
/**
* Must not be called directly, use computeState() instead.
*
* Set the rank of the given item
*
* @param {item} section Section
* @param {number} rank Rank of the item
*/
#setSectionRank(section, rank) {
this.#setItemInput(section, "rank", rank);
}
/**
* Must not be called directly, use computeState() instead.
*
* Set the rank of the given item
*
* @param {item} question Question
* @param {number} vertical_rank Vertical rank of the item
* @param {number|null} horizontal_rank Horizontal rank of the item
*/
#setQuestionRank(question, vertical_rank, horizontal_rank = null) {
this.#setItemInput(question, "vertical_rank", vertical_rank);
this.#setItemInput(question, "horizontal_rank", horizontal_rank);
// Disable horizontal rank input if the question is not in a horizontal block
const horizontal_rank_input = question.find("input[name='horizontal_rank'], input[data-glpi-form-editor-original-name='horizontal_rank']");
horizontal_rank_input.prop("disabled", horizontal_rank === null);
}
/**
* Must not be called directly, use computeState() instead.
*
* Generate a UUID for each newly created questions and sections.
* This UUID will be used by the backend to handle updates for news items.
*
* @param {jQuery} item Section or question
*/
#setUuid(item) {
const uuid = this.#getItemInput(item, "uuid");
if (uuid == '') {
// Replace by UUID
this.#setItemInput(item, "uuid", getUUID());
}
}
/**
* Must not be called directly, use computeState() instead.
*
* Set the parent section of the given question.
*
* @param {jQuery} question Target question
* @param {jQuery} section Parent section
*
*/
#setParentSection(question, section) {
const uuid = this.#getItemInput(section, "uuid");
this.#setItemInput(question, "forms_sections_uuid", uuid);
}
/**
* Handle tinymce change event
* @param {Object} e Event data
*/
#handleTinyMCEChange(e) {
// Check if the change is related to a question description
const description_container = $(e.target.container)
.closest("[data-glpi-form-editor-question-description]");
if (description_container.length > 0) {
// This is a question description, mark as extra details if empty
this.#markQuestionDescriptionAsExtraDetailsIfEmpty(
description_container,
e.level.content
);
}
}
/**
* Handle tinymce click event
* @param {Object} e Event data
*/
#handleTinyMCEClick(e) {
// The event target expose its relevant textarea in a `data-id` property
const id = $(e.target).closest("#tinymce").data("id");
const textarea = $(`#${id}`);
// Handle 'set-active' action for clicks inside tinymce
this.#setActiveItem(
textarea
.closest('[data-glpi-form-editor-on-click="set-active"]')
);
}
/**
* Adjust height using javascript
* This is the only reliable way to make our content use the remaining
* height of the page as the parent container doesn't define a height
*/
#adjustContainerHeight() {
// Get window and editor height
const window_height = document.body.offsetHeight;
const editor_height = $(this.#target).offset().top;
// Border added at the bottom of the page, must be taken into account
const tab_content_border = 1;
// Compute and apply ideal height
let height = (window_height - editor_height - tab_content_border);
if ($("#debug-toolbar").length > 0) {
// If the debug toolbar is present, we need to take it into account
const debug_toolbar_height = $("#debug-toolbar").height();
height -= debug_toolbar_height;
}
$(this.#target).css('height', `${height}`);
}
/**
* Update UX to reflect the fact that the form is no longer a draft.
*/
#removeDraftStatus() {
// Turn the "Add" button into "Save"
const add_button = $('#main-form button[name=update]');
add_button
.find('.ti-plus')
.removeClass('ti-plus')
.addClass('ti-device-floppy');
add_button.find('.add-label').text(__('Save'));
add_button.prop("title", __('Save'));
// Show the delete button
const del_button = $('#main-form button[name=delete]');
del_button.removeClass('d-none');
// Mark as no longer a draft to avoid running this code again
this.#is_draft = false;
}
/**
* Mark question description as extra details if empty.
*
* @param {jQuery} container
* @param {Object} content
*/
#markQuestionDescriptionAsExtraDetailsIfEmpty(container, content) {
// Compute raw text length
const div = document.createElement("div");
div.innerHTML = content;
const raw_text = div.textContent || div.innerText || "";
const length = raw_text.length;
// Mark as secondary data if empty
if (length == 0) {
container
.attr("data-glpi-form-editor-question-extra-details", "");
} else {
container
.removeAttr("data-glpi-form-editor-question-extra-details");
}
}
/**
* Set the current active item.
* An active item may have additionnal fields displayed, allowing more
* complex customization.
*
* There can only be a single active item at once.
*
* A null value may be passed if there are no active item.
*
* @param {jQuery|null} item_container
*/
#setActiveItem(item_container) {
const possible_active_items = ['form', 'section', 'question', 'comment', 'horizontal-blocks', 'horizontal-block-placeholder'];
// Remove current active item
possible_active_items.forEach((type) => {
$(this.#target)
.find(`[data-glpi-form-editor-active-${type}]`)
.filter((index, element) => {
if (type === 'form' || type === 'section') {
return true;
}
return item_container !== null
&& !$(element).is(item_container)
&& $(element).has(item_container).length === 0;
})
.removeAttr(`data-glpi-form-editor-active-${type}`);
});
/**
* Delay the activation of the new item to avoid a rendering bug.
* I can't explain it, but without this delay,
* the elements contained in a horizontal layout do not collapse.
*/
setTimeout(() => {
// Set new active item if specified
if (item_container !== null) {
possible_active_items.forEach((type) => {
// Can be set active from the container itself or the sub "details" container
if (item_container.data(`glpi-form-editor-${type}-details`) !== undefined) {
item_container
.closest(`[data-glpi-form-editor-${type}]`)
.attr(`data-glpi-form-editor-active-${type}`, "");
} else if (item_container.data(`glpi-form-editor-${type}`) !== undefined) {
item_container
.attr(`data-glpi-form-editor-active-${type}`, "");
}
});
// An item can't be active if its parent section is collapsed
const section = item_container.closest("[data-glpi-form-editor-section]");
if (section.hasClass("section-collapsed")) {
return;
}
item_container.addClass("active");
const horizontal_blocks = item_container.closest("section[data-glpi-form-editor-horizontal-blocks]");
if (horizontal_blocks.length > 0) {
// Set active the horizontal container
horizontal_blocks.closest("section[data-glpi-form-editor-horizontal-blocks-container]")
.attr("data-glpi-form-editor-active-horizontal-blocks", "");
}
}
});
}
/**
* Add a block next to the target.
* @param {jQuery} target
* @param {jQuery} template
* @returns
*/
#addBlock(target, template) {
let destination;
let action;
// Find the context using the target
if (
target.data('glpi-form-editor-question') !== undefined
|| target.data('glpi-form-editor-comment') !== undefined
) {
// Adding a new block after an existing question
destination = target;
action = "after";
} else if (target.data('glpi-form-editor-section') !== undefined) {
// Adding a block at the start of a section
destination = target
.closest("[data-glpi-form-editor-section]")
.find("[data-glpi-form-editor-section-blocks]");
action = "prepend";
} else if (target.data('glpi-form-editor-form') !== undefined) {
// Add a block at the end of the form
destination = $(this.#target)
.find("[data-glpi-form-editor-section]:last-child")
.find("[data-glpi-form-editor-section-blocks]:last-child");
action = "append";
} else if (target.data('glpi-form-editor-horizontal-blocks-container') !== undefined) {
// Adding a new block after an existing horizontal block
destination = target;
action = "after";
} else if (target.data('glpi-form-editor-horizontal-blocks') !== undefined) {
// Adding a block at the end of a horizontal block
destination = target;
action = "append";
} else if (target.data('glpi-form-editor-horizontal-block-placeholder') !== undefined) {
// Adding a block just after the horizontal layout placeholder
destination = target;
action = "after";
// Remove the placeholder just after adding the block
setTimeout(() => this.#removeHorizontalLayoutSlot(target), 0);
} else {
throw new Error('Unexpected target');
}
// Insert the new template into the questions area of the current section
return this.#copy_template(
template,
destination,
action
);
}
/**
* Add a question at the end of the form
* @param {jQuery} target Current position in the form
*/
#addQuestion(target) {
// Get template content
const template = this.#getQuestionTemplate(
this.#defaultQuestionType
).children();
const new_question = this.#addBlock(target, template);
// Mark as active
this.#setActiveItem(new_question);
// Focus question's name
new_question
.find("[data-glpi-form-editor-question-details-name]")[0]
.focus();
// Compute dynamic inputs size
new_question.find("[data-glpi-form-editor-dynamic-input]").each((index, input) => {
this.#computeDynamicInputSize(input);
});
// Enable sortable on the new question
this.#enableSortable(new_question);