blob: d53b51574f5c1cf4a0c65df2ad2ac27874b74755 [file] [log] [blame]
Copybara854996b2021-09-07 19:36:02 +00001/* Copyright 2016 The Chromium Authors. All Rights Reserved.
2 *
3 * Use of this source code is governed by a BSD-style
4 * license that can be found in the LICENSE file or at
5 * https://developers.google.com/open-source/licenses/bsd
6 */
7/* eslint-disable no-var */
8/* eslint-disable prefer-const */
9
10/**
11 * This file contains JS functions that support various issue editing
12 * features of Monorail. These editing features include: selecting
13 * issues on the issue list page, adding attachments, expanding and
14 * collapsing the issue editing form, and starring issues.
15 *
16 * Browser compatability: IE6, IE7, FF1.0+, Safari.
17 */
18
19
20/**
21 * Here are some string constants that are used repeatedly in the code.
22 */
23let TKR_SELECTED_CLASS = 'selected';
24let TKR_UNDEF_CLASS = 'undef';
25let TKR_NOVEL_CLASS = 'novel';
26let TKR_EXCL_CONFICT_CLASS = 'exclconflict';
27let TKR_QUESTION_MARK_CLASS = 'questionmark';
28let TKR_ATTACHPROMPT_ID = 'attachprompt';
29let TKR_ATTACHAFILE_ID = 'attachafile';
30let TKR_ATTACHMAXSIZE_ID = 'attachmaxsize';
31let TKR_CURRENT_TEMPLATE_INDEX_ID = 'current_template_index';
32let TKR_PROMPT_MEMBERS_ONLY_CHECKBOX_ID = 'members_only_checkbox';
33let TKR_PROMPT_SUMMARY_EDITOR_ID = 'summary_editor';
34let TKR_PROMPT_SUMMARY_MUST_BE_EDITED_CHECKBOX_ID =
35 'summary_must_be_edited_checkbox';
36let TKR_PROMPT_CONTENT_EDITOR_ID = 'content_editor';
37let TKR_PROMPT_STATUS_EDITOR_ID = 'status_editor';
38let TKR_PROMPT_OWNER_EDITOR_ID = 'owner_editor';
39let TKR_PROMPT_ADMIN_NAMES_EDITOR_ID = 'admin_names_editor';
40let TKR_OWNER_DEFAULTS_TO_MEMBER_CHECKBOX_ID =
41 'owner_defaults_to_member_checkbox';
42let TKR_OWNER_DEFAULTS_TO_MEMBER_AREA_ID =
43 'owner_defaults_to_member_area';
44let TKR_COMPONENT_REQUIRED_CHECKBOX_ID =
45 'component_required_checkbox';
46let TKR_PROMPT_COMPONENTS_EDITOR_ID = 'components_editor';
47let TKR_FIELD_EDITOR_ID_PREFIX = 'tmpl_custom_';
48let TKR_PROMPT_LABELS_EDITOR_ID_PREFIX = 'label';
49let TKR_CONFIRMAREA_ID = 'confirmarea';
50let TKR_DISCARD_YOUR_CHANGES = 'Discard your changes?';
51// Note, users cannot enter '<'.
52let TKR_DELETED_PROMPT_NAME = '<DELETED>';
53// Display warning if labels contain the following prefixes.
54// The following list is the same as tracker_constants.RESERVED_PREFIXES except
55// for the 'hotlist' prefix. 'hostlist' will be added when it comes a full
56// feature and when projects that use 'Hostlist-*' labels are transitioned off.
57let TKR_LABEL_RESERVED_PREFIXES = [
58 'id', 'project', 'reporter', 'summary', 'status', 'owner', 'cc',
59 'attachments', 'attachment', 'component', 'opened', 'closed',
60 'modified', 'is', 'has', 'blockedon', 'blocking', 'blocked', 'mergedinto',
61 'stars', 'starredby', 'description', 'comment', 'commentby', 'label',
62 'rank', 'explicit_status', 'derived_status', 'explicit_owner',
63 'derived_owner', 'explicit_cc', 'derived_cc', 'explicit_label',
64 'derived_label', 'last_comment_by', 'exact_component',
65 'explicit_component', 'derived_component'];
66
67
68/**
69 * Appends a given child element to the DOM based on parameters.
70 * @param {HTMLElement} parentEl
71 * @param {string} tag
72 * @param {string} optClassName
73 * @param {string} optID
74 * @param {string} optText
75 * @param {string} optStyle
76*/
77function TKR_createChild(parentEl, tag, optClassName, optID, optText, optStyle) {
78 let el = document.createElement(tag);
79 if (optClassName) el.classList.add(optClassName);
80 if (optID) el.id = optID;
81 if (optText) el.textContent = optText;
82 if (optStyle) el.setAttribute('style', optStyle);
83 parentEl.appendChild(el);
84 return el;
85}
86
87/**
88 * Select all the issues on the issue list page.
89 */
90function TKR_selectAllIssues() {
91 TKR_selectIssues(true);
92}
93
94
95/**
96 * Function to deselect all the issues on the issue list page.
97 */
98function TKR_selectNoneIssues() {
99 TKR_selectIssues(false);
100}
101
102
103/**
104 * Function to select or deselect all the issues on the issue list page.
105 * @param {boolean} checked True means select issues, False means deselect.
106 */
107function TKR_selectIssues(checked) {
108 let table = $('resultstable');
109 for (let r = 0; r < table.rows.length; ++r) {
110 let row = table.rows[r];
111 let firstCell = row.cells[0];
112 if (firstCell.tagName == 'TD') {
113 for (let e = 0; e < firstCell.childNodes.length; ++e) {
114 let element = firstCell.childNodes[e];
115 if (element.tagName == 'INPUT' && element.type == 'checkbox') {
116 element.checked = checked ? 'checked' : '';
117 if (checked) {
118 row.classList.add(TKR_SELECTED_CLASS);
119 } else {
120 row.classList.remove(TKR_SELECTED_CLASS);
121 }
122 }
123 }
124 }
125 }
126}
127
128
129/**
130 * The ID number to append to the next dynamically created file upload field.
131 */
132let TKR_nextFileID = 1;
133
134
135/**
136 * Function to dynamically create a new attachment upload field add
137 * insert it into the page DOM.
138 * @param {string} id The id of the parent HTML element.
139 *
140 * TODO(lukasperaza): use different nextFileID for separate forms on same page,
141 * e.g. issue update form and issue description update form
142 */
143function TKR_addAttachmentFields(id, attachprompt_id,
144 attachafile_id, attachmaxsize_id) {
145 if (TKR_nextFileID >= 16) {
146 return;
147 }
148 if (typeof attachprompt_id === 'undefined') {
149 attachprompt_id = TKR_ATTACHPROMPT_ID;
150 }
151 if (typeof attachafile_id === 'undefined') {
152 attachafile_id = TKR_ATTACHAFILE_ID;
153 }
154 if (typeof attachmaxsize_id === 'undefined') {
155 attachmaxsize_id = TKR_ATTACHMAXSIZE_ID;
156 }
157 let el = $(id);
158 el.style.marginTop = '4px';
159 let div = document.createElement('div');
160 var id = 'file' + TKR_nextFileID;
161 let label = TKR_createChild(div, 'label', null, null, 'Attach file:');
162 label.setAttribute('for', id);
163 let input = TKR_createChild(
164 div, 'input', null, id, null, 'width:auto;margin-left:17px');
165 input.setAttribute('type', 'file');
166 input.name = id;
167 let removeLink = TKR_createChild(
168 div, 'a', null, null, 'Remove', 'font-size:x-small');
169 removeLink.href = '#';
170 removeLink.addEventListener('click', function(event) {
171 let target = event.target;
172 $(attachafile_id).focus();
173 target.parentNode.parentNode.removeChild(target.parentNode);
174 event.preventDefault();
175 });
176 el.appendChild(div);
177 el.querySelector('input').focus();
178 ++TKR_nextFileID;
179 if (TKR_nextFileID < 16) {
180 $(attachafile_id).textContent = 'Attach another file';
181 } else {
182 $(attachprompt_id).style.display = 'none';
183 }
184 $(attachmaxsize_id).style.display = '';
185}
186
187
188/**
189 * Function to display the form so that the user can update an issue.
190 */
191function TKR_openIssueUpdateForm() {
192 TKR_showHidden($('makechangesarea'));
193 TKR_goToAnchor('makechanges');
194 TKR_forceProperTableWidth();
195 window.setTimeout(
196 function() {
197 document.getElementById('addCommentTextArea').focus();
198 },
199 100);
200}
201
202
203/**
204 * The index of the template that is currently selected for editing
205 * on the administration page for issues.
206 */
207let TKR_currentTemplateIndex = 0;
208
209
210/**
211 * Array of field IDs that are defined in the current project, set by call to setFieldIDs().
212 */
213let TKR_fieldIDs = [];
214
215
216function TKR_setFieldIDs(fieldIDs) {
217 TKR_fieldIDs = fieldIDs;
218}
219
220
221/**
222 * This function displays the appropriate template text in a text field.
223 * It is called after the user has selected one template to view/edit.
224 * @param {Element} widget The list widget containing the list of templates.
225 */
226function TKR_selectTemplate(widget) {
227 TKR_showHidden($('edit_panel'));
228 TKR_currentTemplateIndex = widget.value;
229 $(TKR_CURRENT_TEMPLATE_INDEX_ID).value = TKR_currentTemplateIndex;
230
231 let content_editor = $(TKR_PROMPT_CONTENT_EDITOR_ID);
232 TKR_makeDefined(content_editor);
233
234 let can_edit = $('can_edit_' + TKR_currentTemplateIndex).value == 'yes';
235 let disabled = can_edit ? '' : 'disabled';
236
237 $(TKR_PROMPT_MEMBERS_ONLY_CHECKBOX_ID).disabled = disabled;
238 $(TKR_PROMPT_MEMBERS_ONLY_CHECKBOX_ID).checked = $(
239 'members_only_' + TKR_currentTemplateIndex).value == 'yes';
240 $(TKR_PROMPT_SUMMARY_EDITOR_ID).disabled = disabled;
241 $(TKR_PROMPT_SUMMARY_EDITOR_ID).value = $(
242 'summary_' + TKR_currentTemplateIndex).value;
243 $(TKR_PROMPT_SUMMARY_MUST_BE_EDITED_CHECKBOX_ID).disabled = disabled;
244 $(TKR_PROMPT_SUMMARY_MUST_BE_EDITED_CHECKBOX_ID).checked = $(
245 'summary_must_be_edited_' + TKR_currentTemplateIndex).value == 'yes';
246 content_editor.disabled = disabled;
247 content_editor.value = $('content_' + TKR_currentTemplateIndex).value;
248 $(TKR_PROMPT_STATUS_EDITOR_ID).disabled = disabled;
249 $(TKR_PROMPT_STATUS_EDITOR_ID).value = $(
250 'status_' + TKR_currentTemplateIndex).value;
251 $(TKR_PROMPT_OWNER_EDITOR_ID).disabled = disabled;
252 $(TKR_PROMPT_OWNER_EDITOR_ID).value = $(
253 'owner_' + TKR_currentTemplateIndex).value;
254 $(TKR_OWNER_DEFAULTS_TO_MEMBER_CHECKBOX_ID).disabled = disabled;
255 $(TKR_OWNER_DEFAULTS_TO_MEMBER_CHECKBOX_ID).checked = $(
256 'owner_defaults_to_member_' + TKR_currentTemplateIndex).value == 'yes';
257 $(TKR_COMPONENT_REQUIRED_CHECKBOX_ID).disabled = disabled;
258 $(TKR_COMPONENT_REQUIRED_CHECKBOX_ID).checked = $(
259 'component_required_' + TKR_currentTemplateIndex).value == 'yes';
260 $(TKR_OWNER_DEFAULTS_TO_MEMBER_AREA_ID).disabled = disabled;
261 $(TKR_OWNER_DEFAULTS_TO_MEMBER_AREA_ID).style.display =
262 $(TKR_PROMPT_OWNER_EDITOR_ID).value ? 'none' : '';
263 $(TKR_PROMPT_COMPONENTS_EDITOR_ID).disabled = disabled;
264 $(TKR_PROMPT_COMPONENTS_EDITOR_ID).value = $(
265 'components_' + TKR_currentTemplateIndex).value;
266
267 // Blank out all custom field editors first, then fill them in during the next loop.
268 for (var i = 0; i < TKR_fieldIDs.length; i++) {
269 let fieldEditor = $(TKR_FIELD_EDITOR_ID_PREFIX + TKR_fieldIDs[i]);
270 let holder = $('field_value_' + TKR_currentTemplateIndex + '_' + TKR_fieldIDs[i]);
271 if (fieldEditor) {
272 fieldEditor.disabled = disabled;
273 fieldEditor.value = holder ? holder.value : '';
274 }
275 }
276
277 var i = 0;
278 while ($(TKR_PROMPT_LABELS_EDITOR_ID_PREFIX + i)) {
279 $(TKR_PROMPT_LABELS_EDITOR_ID_PREFIX + i).disabled = disabled;
280 $(TKR_PROMPT_LABELS_EDITOR_ID_PREFIX + i).value =
281 $('label_' + TKR_currentTemplateIndex + '_' + i).value;
282 i++;
283 }
284
285 $(TKR_PROMPT_ADMIN_NAMES_EDITOR_ID).disabled = disabled;
286 $(TKR_PROMPT_ADMIN_NAMES_EDITOR_ID).value = $(
287 'admin_names_' + TKR_currentTemplateIndex).value;
288
289 let numNonDeletedTemplates = 0;
290 for (var i = 0; i < TKR_templateNames.length; i++) {
291 if (TKR_templateNames[i] != TKR_DELETED_PROMPT_NAME) {
292 numNonDeletedTemplates++;
293 }
294 }
295 if ($('delbtn')) {
296 if (numNonDeletedTemplates > 1) {
297 $('delbtn').disabled='';
298 } else { // Don't allow the last template to be deleted.
299 $('delbtn').disabled='disabled';
300 }
301 }
302}
303
304
305var TKR_templateNames = []; // Exported in tracker-onload.js
306
307
308/**
309 * Create a new issue template and add the needed form fields to the DOM.
310 */
311function TKR_newTemplate() {
312 let newIndex = TKR_templateNames.length;
313 let templateName = prompt('Name of new template?', '');
314 templateName = templateName.replace(
315 /[&<>"]/g, '', // " help emacs highlighting
316 );
317 if (!templateName) return;
318
319 for (let i = 0; i < TKR_templateNames.length; i++) {
320 if (templateName == TKR_templateNames[i]) {
321 alert('Please choose a unique name.');
322 return;
323 }
324 }
325
326 TKR_addTemplateHiddenFields(newIndex, templateName);
327 TKR_templateNames.push(templateName);
328
329 let templateOption = TKR_createChild(
330 $('template_menu'), 'option', null, null, templateName);
331 templateOption.value = newIndex;
332 templateOption.selected = 'selected';
333
334 let developerOption = TKR_createChild(
335 $('default_template_for_developers'), 'option', null, null, templateName);
336 developerOption.value = templateName;
337
338 let userOption = TKR_createChild(
339 $('default_template_for_users'), 'option', null, null, templateName);
340 userOption.value = templateName;
341
342 TKR_selectTemplate($('template_menu'));
343}
344
345
346/**
347 * Private function to append HTML for new hidden form fields
348 * for a new issue template to the issue admin form.
349 */
350function TKR_addTemplateHiddenFields(templateIndex, templateName) {
351 let parentEl = $('adminTemplates');
352 TKR_appendHiddenField(
353 parentEl, 'template_id_' + templateIndex, 'template_id_' + templateIndex, '0');
354 TKR_appendHiddenField(parentEl, 'name_' + templateIndex,
355 'name_' + templateIndex, templateName);
356 TKR_appendHiddenField(parentEl, 'members_only_' + templateIndex);
357 TKR_appendHiddenField(parentEl, 'summary_' + templateIndex);
358 TKR_appendHiddenField(parentEl, 'summary_must_be_edited_' + templateIndex);
359 TKR_appendHiddenField(parentEl, 'content_' + templateIndex);
360 TKR_appendHiddenField(parentEl, 'status_' + templateIndex);
361 TKR_appendHiddenField(parentEl, 'owner_' + templateIndex);
362 TKR_appendHiddenField(
363 parentEl, 'owner_defaults_to_member_' + templateIndex,
364 'owner_defaults_to_member_' + templateIndex, 'yes');
365 TKR_appendHiddenField(parentEl, 'component_required_' + templateIndex);
366 TKR_appendHiddenField(parentEl, 'components_' + templateIndex);
367
368 var i = 0;
369 while ($('label_0_' + i)) {
370 TKR_appendHiddenField(parentEl, 'label_' + templateIndex,
371 'label_' + templateIndex + '_' + i);
372 i++;
373 }
374
375 for (var i = 0; i < TKR_fieldIDs.length; i++) {
376 let fieldId = 'field_value_' + templateIndex + '_' + TKR_fieldIDs[i];
377 TKR_appendHiddenField(parentEl, fieldId, fieldId);
378 }
379
380 TKR_appendHiddenField(parentEl, 'admin_names_' + templateIndex);
381 TKR_appendHiddenField(
382 parentEl, 'can_edit_' + templateIndex, 'can_edit_' + templateIndex,
383 'yes');
384}
385
386
387/**
388 * Utility function to append string parts for one hidden field
389 * to the given array.
390 */
391function TKR_appendHiddenField(parentEl, name, opt_id, opt_value) {
392 let input = TKR_createChild(parentEl, 'input', null, opt_id || name);
393 input.setAttribute('type', 'hidden');
394 input.name = name;
395 input.value = opt_value || '';
396}
397
398
399/**
400 * Delete the currently selected issue template, and mark its hidden
401 * form field as deleted so that they will be ignored when submitted.
402 */
403function TKR_deleteTemplate() {
404 // Mark the current template name as deleted.
405 TKR_templateNames.splice(
406 TKR_currentTemplateIndex, 1, TKR_DELETED_PROMPT_NAME);
407 $('name_' + TKR_currentTemplateIndex).value = TKR_DELETED_PROMPT_NAME;
408 _toggleHidden($('edit_panel'));
409 $('delbtn').disabled = 'disabled';
410 TKR_rebuildTemplateMenu();
411 TKR_rebuildDefaultTemplateMenu('default_template_for_developers');
412 TKR_rebuildDefaultTemplateMenu('default_template_for_users');
413}
414
415/**
416 * Utility function to rebuild the template menu on the issue admin page.
417 */
418function TKR_rebuildTemplateMenu() {
419 let parentEl = $('template_menu');
420 while (parentEl.childNodes.length) {
421 parentEl.removeChild(parentEl.childNodes[0]);
422 }
423 for (let i = 0; i < TKR_templateNames.length; i++) {
424 if (TKR_templateNames[i] != TKR_DELETED_PROMPT_NAME) {
425 let option = TKR_createChild(
426 parentEl, 'option', null, null, TKR_templateNames[i]);
427 option.value = i;
428 }
429 }
430}
431
432
433/**
434 * Utility function to rebuild a default template drop-down.
435 */
436function TKR_rebuildDefaultTemplateMenu(menuID) {
437 let defaultTemplateName = $(menuID).value;
438 let parentEl = $(menuID);
439 while (parentEl.childNodes.length) {
440 parentEl.removeChild(parentEl.childNodes[0]);
441 }
442 for (let i = 0; i < TKR_templateNames.length; i++) {
443 if (TKR_templateNames[i] != TKR_DELETED_PROMPT_NAME) {
444 let option = TKR_createChild(
445 parentEl, 'option', null, null, TKR_templateNames[i]);
446 option.values = TKR_templateNames[i];
447 if (defaultTemplateName == TKR_templateNames[i]) {
448 option.setAttribute('selected', 'selected');
449 }
450 }
451 }
452}
453
454
455/**
456 * Change the issue template to the specified one.
457 * TODO(jrobbins): move to an AJAX implementation that would not reload page.
458 *
459 * @param {string} projectName The name of the current project.
460 * @param {string} templateName The name of the template to switch to.
461 */
462function TKR_switchTemplate(projectName, templateName) {
463 let ok = true;
464 if (TKR_isDirty()) {
465 ok = confirm('Switching to a different template will lose the text you entered.');
466 }
467 if (ok) {
468 TKR_initialFormValues = TKR_currentFormValues();
469 window.location = '/p/' + projectName +
470 '/issues/entry?template=' + templateName;
471 }
472}
473
474/**
475 * Function to remove a CSS class and initial tip from a text widget.
476 * Some text fields or text areas display gray textual tips to help the user
477 * make use of those widgets. When the user focuses on the field, the tip
478 * disappears and is made ready for user input (in the normal text color).
479 * @param {Element} el The form field that had the gray text tip.
480 */
481function TKR_makeDefined(el) {
482 if (el.classList.contains(TKR_UNDEF_CLASS)) {
483 el.classList.remove(TKR_UNDEF_CLASS);
484 el.value = '';
485 }
486}
487
488
489/**
490 * Save the contents of the visible issue template text area into a hidden
491 * text field for later submission.
492 * Called when the user has edited the text of a issue template.
493 */
494function TKR_saveTemplate() {
495 if (TKR_currentTemplateIndex) {
496 $('members_only_' + TKR_currentTemplateIndex).value =
497 $(TKR_PROMPT_MEMBERS_ONLY_CHECKBOX_ID).checked ? 'yes' : '';
498 $('summary_' + TKR_currentTemplateIndex).value =
499 $(TKR_PROMPT_SUMMARY_EDITOR_ID).value;
500 $('summary_must_be_edited_' + TKR_currentTemplateIndex).value =
501 $(TKR_PROMPT_SUMMARY_MUST_BE_EDITED_CHECKBOX_ID).checked ? 'yes' : '';
502 $('content_' + TKR_currentTemplateIndex).value =
503 $(TKR_PROMPT_CONTENT_EDITOR_ID).value;
504 $('status_' + TKR_currentTemplateIndex).value =
505 $(TKR_PROMPT_STATUS_EDITOR_ID).value;
506 $('owner_' + TKR_currentTemplateIndex).value =
507 $(TKR_PROMPT_OWNER_EDITOR_ID).value;
508 $('owner_defaults_to_member_' + TKR_currentTemplateIndex).value =
509 $(TKR_OWNER_DEFAULTS_TO_MEMBER_CHECKBOX_ID).checked ? 'yes' : '';
510 $('component_required_' + TKR_currentTemplateIndex).value =
511 $(TKR_COMPONENT_REQUIRED_CHECKBOX_ID).checked ? 'yes' : '';
512 $('components_' + TKR_currentTemplateIndex).value =
513 $(TKR_PROMPT_COMPONENTS_EDITOR_ID).value;
514 $(TKR_OWNER_DEFAULTS_TO_MEMBER_AREA_ID).style.display =
515 $(TKR_PROMPT_OWNER_EDITOR_ID).value ? 'none' : '';
516
517 for (var i = 0; i < TKR_fieldIDs.length; i++) {
518 let fieldID = TKR_fieldIDs[i];
519 let fieldEditor = $(TKR_FIELD_EDITOR_ID_PREFIX + fieldID);
520 if (fieldEditor) {
521 _saveFieldValue(fieldID, fieldEditor.value);
522 }
523 }
524
525 var i = 0;
526 while ($('label_' + TKR_currentTemplateIndex + '_' + i)) {
527 $('label_' + TKR_currentTemplateIndex + '_' + i).value =
528 $(TKR_PROMPT_LABELS_EDITOR_ID_PREFIX + i).value;
529 i++;
530 }
531
532 $('admin_names_' + TKR_currentTemplateIndex).value =
533 $(TKR_PROMPT_ADMIN_NAMES_EDITOR_ID).value;
534 }
535}
536
537
538function _saveFieldValue(fieldID, val) {
539 let fieldValId = 'field_value_' + TKR_currentTemplateIndex + '_' + fieldID;
540 $(fieldValId).value = val;
541}
542
543
544/**
545 * This is a json string encoding of an array of form values after the initial
546 * page load. It is used for comparison on page unload to prompt the user
547 * before abandoning changes. It is initialized in TKR_onload().
548*/
549let TKR_initialFormValues;
550
551
552/**
553 * Returns a json string encoding of an array of all the values from user
554 * input fields of interest (omits search box, e.g.)
555 */
556function TKR_currentFormValues() {
557 let inputs = document.querySelectorAll('input, textarea, select, checkbox');
558 let values = [];
559
560 for (i = 0; i < inputs.length; i++) {
561 // Don't include blank inputs. This prevents a popup if the user
562 // clicks "add a row" for new labels but doesn't actually enter any
563 // text into them. Also ignore search box contents.
564 if (inputs[i].value && !inputs[i].hasAttribute('ignore-dirty') &&
565 inputs[i].name != 'token') {
566 values.push(inputs[i].value);
567 }
568 }
569
570 return JSON.stringify(values);
571}
572
573
574/**
575 * This function returns true if the user has made any edits to fields of
576 * interest.
577 */
578function TKR_isDirty() {
579 return TKR_initialFormValues != TKR_currentFormValues();
580}
581
582
583/**
584 * The user has clicked the 'Discard' button on the issue update form.
585 * If the form has been edited, ask if they are sure about discarding
586 * before then navigating to the given URL. This can go up to some
587 * other page, or reload the current page with a fresh form.
588 * @param {string} nextUrl The page to show after discarding.
589 */
590function TKR_confirmDiscardUpdate(nextUrl) {
591 if (!TKR_isDirty() || confirm(TKR_DISCARD_YOUR_CHANGES)) {
592 document.location = nextUrl;
593 }
594}
595
596
597/**
598 * The user has clicked the 'Discard' button on the issue entry form.
599 * If the form has been edited, this function asks if they are sure about
600 * discarding before doing it.
601 * @param {Element} discardButton The 'Discard' button.
602 */
603function TKR_confirmDiscardEntry(discardButton) {
604 if (!TKR_isDirty() || confirm(TKR_DISCARD_YOUR_CHANGES)) {
605 TKR_go('list');
606 }
607}
608
609
610/**
611 * Normally, we show 2 rows of label editing fields when updating an issue.
612 * However, if the issue has more than that many labels already, we make sure to
613 * show them all.
614 */
615function TKR_exposeExistingLabelFields() {
616 if ($('label3').value ||
617 $('label4').value ||
618 $('label5').value) {
619 if ($('addrow1')) {
620 _showID('LF_row2');
621 _hideID('addrow1');
622 }
623 }
624 if ($('label6').value ||
625 $('label7').value ||
626 $('label8').value) {
627 _showID('LF_row3');
628 _hideID('addrow2');
629 }
630 if ($('label9').value ||
631 $('label10').value ||
632 $('label11').value) {
633 _showID('LF_row4');
634 _hideID('addrow3');
635 }
636 if ($('label12').value ||
637 $('label13').value ||
638 $('label14').value) {
639 _showID('LF_row5');
640 _hideID('addrow4');
641 }
642 if ($('label15').value ||
643 $('label16').value ||
644 $('label17').value) {
645 _showID('LF_row6');
646 _hideID('addrow5');
647 }
648 if ($('label18').value ||
649 $('label19').value ||
650 $('label20').value) {
651 _showID('LF_row7');
652 _hideID('addrow6');
653 }
654 if ($('label21').value ||
655 $('label22').value ||
656 $('label23').value) {
657 _showID('LF_row8');
658 _hideID('addrow7');
659 }
660}
661
662
663/**
664 * Flag to indicate when the user has not yet caused any input events.
665 * We use this to clear the placeholder in the new issue summary field
666 * exactly once.
667 */
668let TKR_firstEvent = true;
669
670
671/**
672 * This is called in response to almost any user input event on the
673 * issue entry page. If the placeholder in the new issue sumary field has
674 * not yet been cleared, then this function clears it.
675 */
676function TKR_clearOnFirstEvent(initialSummary) {
677 if (TKR_firstEvent && $('summary').value == initialSummary) {
678 TKR_firstEvent = false;
679 $('summary').value = TKR_keepJustSummaryPrefixes($('summary').value);
680 }
681}
682
683/**
684 * Clear the summary, except for any prefixes of the form "[bracketed text]"
685 * or "keyword:". If there were any, add a trailing space. This is useful
686 * to people who like to encode issue classification info in the summary line.
687 */
688function TKR_keepJustSummaryPrefixes(s) {
689 let matches = s.match(/^(\[[^\]]+\])+|^(\S+:\s*)+/);
690 if (matches == null) {
691 return '';
692 }
693
694 let prefix = matches[0];
695 if (prefix.substr(prefix.length - 1) != ' ') {
696 prefix += ' ';
697 }
698 return prefix;
699}
700
701/**
702 * An array of label <input>s that start with reserved prefixes.
703 */
704let TKR_labelsWithReservedPrefixes = [];
705
706/**
707 * An array of label <input>s that are equal to reserved words.
708 */
709let TKR_labelsConflictingWithReserved = [];
710
711/**
712 * An array of novel issue status values entered by the user on the
713 * current page. 'Novel' means that they are not well known and are
714 * likely to be typos. Note that this list will always have zero or
715 * one element, but a list is used for consistency with the list of
716 * novel labels.
717 */
718let TKR_novelStatuses = [];
719
720/**
721 * An array of novel issue label values entered by the user on the
722 * current page. 'Novel' means that they are not well known and are
723 * likely to be typos.
724 */
725let TKR_novelLabels = [];
726
727/**
728 * A boolean that indicates whether the entered owner value is valid or not.
729 */
730let TKR_invalidOwner = false;
731
732/**
733 * The user has changed the issue status text field. This function
734 * checks whether it is a well-known status value. If not, highlight it
735 * as a potential typo.
736 * @param {Element} textField The issue status text field.
737 * @return Always returns true to indicate that the browser should
738 * continue to process the user input event normally.
739 */
740function TKR_confirmNovelStatus(textField) {
741 let v = textField.value.trim().toLowerCase();
742 let isNovel = (v !== '');
743 let wellKnown = TKR_statusWords;
744 for (let i = 0; i < wellKnown.length && isNovel; ++i) {
745 let wk = wellKnown[i];
746 if (v == wk.toLowerCase()) {
747 isNovel = false;
748 }
749 }
750 if (isNovel) {
751 if (TKR_novelStatuses.indexOf(textField) == -1) {
752 TKR_novelStatuses.push(textField);
753 }
754 textField.classList.add(TKR_NOVEL_CLASS);
755 } else {
756 if (TKR_novelStatuses.indexOf(textField) != -1) {
757 TKR_novelStatuses.splice(TKR_novelStatuses.indexOf(textField), 1);
758 }
759 textField.classList.remove(TKR_NOVEL_CLASS);
760 }
761 TKR_updateConfirmBeforeSubmit();
762 return true;
763}
764
765
766/**
767 * The user has changed a issue label text field. This function checks
768 * whether it is a well-known label value. If not, highlight it as a
769 * potential typo.
770 * @param {Element} textField An issue label text field.
771 * @return Always returns true to indicate that the browser should
772 * continue to process the user input event normally.
773 *
774 * TODO(jrobbins): code duplication with function above.
775 */
776function TKR_confirmNovelLabel(textField) {
777 let v = textField.value.trim().toLowerCase();
778 if (v.search('-') == 0) {
779 v = v.substr(1);
780 }
781 let isNovel = (v !== '');
782 if (v.indexOf('?') > -1) {
783 isNovel = false; // We don't count labels that the user must edit anyway.
784 }
785 let wellKnown = TKR_labelWords;
786 for (var i = 0; i < wellKnown.length && isNovel; ++i) {
787 let wk = wellKnown[i];
788 if (v == wk.toLowerCase()) {
789 isNovel = false;
790 }
791 }
792
793 let containsReservedPrefix = false;
794 var textFieldWarningDisplayed = TKR_labelsWithReservedPrefixes.indexOf(textField) != -1;
795 for (var i = 0; i < TKR_LABEL_RESERVED_PREFIXES.length; ++i) {
796 if (v.startsWith(TKR_LABEL_RESERVED_PREFIXES[i] + '-')) {
797 if (!textFieldWarningDisplayed) {
798 TKR_labelsWithReservedPrefixes.push(textField);
799 }
800 containsReservedPrefix = true;
801 break;
802 }
803 }
804 if (!containsReservedPrefix && textFieldWarningDisplayed) {
805 TKR_labelsWithReservedPrefixes.splice(
806 TKR_labelsWithReservedPrefixes.indexOf(textField), 1);
807 }
808
809 let conflictsWithReserved = false;
810 var textFieldWarningDisplayed =
811 TKR_labelsConflictingWithReserved.indexOf(textField) != -1;
812 for (var i = 0; i < TKR_LABEL_RESERVED_PREFIXES.length; ++i) {
813 if (v == TKR_LABEL_RESERVED_PREFIXES[i]) {
814 if (!textFieldWarningDisplayed) {
815 TKR_labelsConflictingWithReserved.push(textField);
816 }
817 conflictsWithReserved = true;
818 break;
819 }
820 }
821 if (!conflictsWithReserved && textFieldWarningDisplayed) {
822 TKR_labelsConflictingWithReserved.splice(
823 TKR_labelsConflictingWithReserved.indexOf(textField), 1);
824 }
825
826 if (isNovel) {
827 if (TKR_novelLabels.indexOf(textField) == -1) {
828 TKR_novelLabels.push(textField);
829 }
830 textField.classList.add(TKR_NOVEL_CLASS);
831 } else {
832 if (TKR_novelLabels.indexOf(textField) != -1) {
833 TKR_novelLabels.splice(TKR_novelLabels.indexOf(textField), 1);
834 }
835 textField.classList.remove(TKR_NOVEL_CLASS);
836 }
837 TKR_updateConfirmBeforeSubmit();
838 return true;
839}
840
841/**
842 * Dictionary { prefix:[textField,...], ...} for all the prefixes of any
843 * text that has been entered into any label field. This is used to find
844 * duplicate labels and multiple labels that share an single exclusive
845 * prefix (e.g., Priority).
846 */
847let TKR_usedPrefixes = {};
848
849/**
850 * This is a prefix to the HTML ids of each label editing field.
851 * It varied by page, so it is set in the HTML page. Needed to initialize
852 * our validation across label input text fields.
853 */
854let TKR_labelFieldIDPrefix = '';
855
856/**
857 * Initialize the set of all used labels on forms that allow users to
858 * enter issue labels. Some labels are supplied in the HTML page
859 * itself, and we do not want to offer duplicates of those.
860 */
861function TKR_prepLabelAC() {
862 let i = 0;
863 while ($('label'+i)) {
864 TKR_validateLabel($('label'+i));
865 i++;
866 }
867}
868
869/**
870 * Reads the owner field and determines if the current value is a valid member.
871 */
872function TKR_prepOwnerField(validOwners) {
873 if ($('owneredit')) {
874 currentOwner = $('owneredit').value;
875 if (currentOwner == '') {
876 // Empty owner field is not an invalid owner.
877 invalidOwner = false;
878 return;
879 }
880 invalidOwner = true;
881 for (let i = 0; i < validOwners.length; i++) {
882 let owner = validOwners[i].name;
883 if (currentOwner == owner) {
884 invalidOwner = false;
885 break;
886 }
887 }
888 TKR_invalidOwner = invalidOwner;
889 }
890}
891
892/**
893 * Keep track of which label prefixes have been used so that
894 * we can not offer the same label twice and so that we can highlight
895 * multiple labels that share an exclusive prefix.
896 */
897function TKR_updateUsedPrefixes(textField) {
898 if (textField.oldPrefix != undefined) {
899 DeleteArrayElement(TKR_usedPrefixes[textField.oldPrefix], textField);
900 }
901
902 let prefix = textField.value.split('-')[0].toLowerCase();
903 if (TKR_usedPrefixes[prefix] == undefined) {
904 TKR_usedPrefixes[prefix] = [textField];
905 } else {
906 TKR_usedPrefixes[prefix].push(textField);
907 }
908 textField.oldPrefix = prefix;
909}
910
911/**
912 * Go through all the label entry fields in our prefix-oriented
913 * data structure and highlight any that are part of a conflict
914 * (multiple labels with the same exclusive prefix). Unhighlight
915 * any label text entry fields that are not in conflict. And, display
916 * a warning message to encourage the user to correct the conflict.
917 */
918function TKR_highlightExclusiveLabelPrefixConflicts() {
919 let conflicts = [];
920 for (let prefix in TKR_usedPrefixes) {
921 let textFields = TKR_usedPrefixes[prefix];
922 if (textFields == undefined || textFields.length == 0) {
923 delete TKR_usedPrefixes[prefix];
924 } else if (textFields.length > 1 &&
925 FindInArray(TKR_exclPrefixes, prefix) != -1) {
926 conflicts.push(prefix);
927 for (var i = 0; i < textFields.length; i++) {
928 var tf = textFields[i];
929 tf.classList.add(TKR_EXCL_CONFICT_CLASS);
930 }
931 } else {
932 for (var i = 0; i < textFields.length; i++) {
933 var tf = textFields[i];
934 tf.classList.remove(TKR_EXCL_CONFICT_CLASS);
935 }
936 }
937 }
938 if (conflicts.length > 0) {
939 let severity = TKR_restrict_to_known ? 'Error' : 'Warning';
940 let confirm_area = $(TKR_CONFIRMAREA_ID);
941 if (confirm_area) {
942 $('confirmmsg').textContent = (severity +
943 ': Multiple values for: ' + conflicts.join(', '));
944 confirm_area.className = TKR_EXCL_CONFICT_CLASS;
945 confirm_area.style.display = '';
946 }
947 }
948}
949
950/**
951 * Keeps track of any label text fields that have a value that
952 * is bad enough to prevent submission of the form. When this
953 * list is non-empty, the submit button gets disabled.
954 */
955let TKR_labelsBlockingSubmit = [];
956
957/**
958 * Look for any "?" characters in the label and, if found,
959 * make the label text red, prevent form submission, and
960 * display on-page help to tell the user to edit those labels.
961 * @param {Element} textField An issue label text field.
962 */
963function TKR_highlightQuestionMarks(textField) {
964 let tfIndex = TKR_labelsBlockingSubmit.indexOf(textField);
965 if (textField.value.indexOf('?') > -1 && tfIndex == -1) {
966 TKR_labelsBlockingSubmit.push(textField);
967 textField.classList.add(TKR_QUESTION_MARK_CLASS);
968 } else if (textField.value.indexOf('?') == -1 && tfIndex > -1) {
969 TKR_labelsBlockingSubmit.splice(tfIndex, 1);
970 textField.classList.remove(TKR_QUESTION_MARK_CLASS);
971 }
972
973 let block_submit_msg = $('blocksubmitmsg');
974 if (block_submit_msg) {
975 if (TKR_labelsBlockingSubmit.length > 0) {
976 block_submit_msg.textContent = 'You must edit labels that contain "?".';
977 } else {
978 block_submit_msg.textContent = '';
979 }
980 }
981}
982
983/**
984 * The user has edited a label. Display a warning if the label is
985 * not a well known label, or if there are multiple labels that
986 * share an exclusive prefix.
987 * @param {Element} textField An issue label text field.
988 */
989function TKR_validateLabel(textField) {
990 if (textField == undefined) return;
991 TKR_confirmNovelLabel(textField);
992 TKR_updateUsedPrefixes(textField);
993 TKR_highlightExclusiveLabelPrefixConflicts();
994 TKR_highlightQuestionMarks(textField);
995}
996
997// TODO(jrobbins): what about typos in owner and cc list?
998
999/**
1000 * If there are any novel status or label values, we display a message
1001 * that explains that to the user so that they can catch any typos before
1002 * submitting them. If the project is restricting input to only the
1003 * well-known statuses and labels, then show these as an error instead.
1004 * In that case, on-page JS will prevent submission.
1005 */
1006function TKR_updateConfirmBeforeSubmit() {
1007 let severity = TKR_restrict_to_known ? 'Error' : 'Note';
1008 let novelWord = TKR_restrict_to_known ? 'undefined' : 'uncommon';
1009 let msg = '';
1010 let labels = TKR_novelLabels.map(function(item) {
1011 return item.value;
1012 });
1013 if (TKR_novelStatuses.length > 0 && TKR_novelLabels.length > 0) {
1014 msg = severity + ': You are using an ' + novelWord + ' status and ' + novelWord + ' label(s): ' + labels.join(', ') + '.'; // TODO: i18n
1015 } else if (TKR_novelStatuses.length > 0) {
1016 msg = severity + ': You are using an ' + novelWord + ' status value.';
1017 } else if (TKR_novelLabels.length > 0) {
1018 msg = severity + ': You are using ' + novelWord + ' label(s): ' + labels.join(', ') + '.';
1019 }
1020
1021 for (var i = 0; i < TKR_labelsWithReservedPrefixes.length; ++i) {
1022 msg += '\nNote: The label ' + TKR_labelsWithReservedPrefixes[i].value +
1023 ' starts with a reserved word. This is not recommended.';
1024 }
1025 for (var i = 0; i < TKR_labelsConflictingWithReserved.length; ++i) {
1026 msg += '\nNote: The label ' + TKR_labelsConflictingWithReserved[i].value +
1027 ' conflicts with a reserved word. This is not recommended.';
1028 }
1029 // Display the owner is no longer a member note only if an owner error is not
1030 // already shown on the page.
1031 if (TKR_invalidOwner && !$('ownererror')) {
1032 msg += '\nNote: Current owner is no longer a project member.';
1033 }
1034
1035 let confirm_area = $(TKR_CONFIRMAREA_ID);
1036 if (confirm_area) {
1037 $('confirmmsg').textContent = msg;
1038 if (msg != '') {
1039 confirm_area.className = TKR_NOVEL_CLASS;
1040 confirm_area.style.display = '';
1041 } else {
1042 confirm_area.style.display = 'none';
1043 }
1044 }
1045}
1046
1047
1048/**
1049 * The user has selected a command from the 'Actions...' menu
1050 * on the issue list. This function checks the selected value and carry
1051 * out the requested action.
1052 * @param {Element} actionsMenu The 'Actions...' <select> form element.
1053 */
1054function TKR_handleListActions(actionsMenu) {
1055 switch (actionsMenu.value) {
1056 case 'bulk':
1057 TKR_HandleBulkEdit();
1058 break;
1059 case 'colspec':
1060 TKR_closeAllPopups(actionsMenu);
1061 _showID('columnspec');
1062 _hideID('addissuesspec');
1063 break;
1064 case 'flagspam':
1065 TKR_flagSpam(true);
1066 break;
1067 case 'unflagspam':
1068 TKR_flagSpam(false);
1069 break;
1070 case 'addtohotlist':
1071 TKR_addToHotlist();
1072 break;
1073 case 'addissues':
1074 _showID('addissuesspec');
1075 _hideID('columnspec');
1076 setCurrentColSpec();
1077 break;
1078 case 'removeissues':
1079 HTL_removeIssues();
1080 break;
1081 case 'issuesperpage':
1082 break;
1083 }
1084 actionsMenu.value = 'moreactions';
1085}
1086
1087
1088async function TKR_handleDetailActions(localId) {
1089 let moreActions = $('more_actions');
1090
1091 if (moreActions.value == 'delete') {
1092 $('copy_issue_form_fragment').style.display = 'none';
1093 $('move_issue_form_fragment').style.display = 'none';
1094 let ok = confirm(
1095 'Normally, you should just close issues by setting their status ' +
1096 'to a closed value.\n' +
1097 'Are you sure you want to delete this issue?');
1098 if (ok) {
1099 await window.prpcClient.call('monorail.Issues', 'DeleteIssue', {
1100 issueRef: {
1101 projectName: window.CS_env.projectName,
1102 localId: localId,
1103 },
1104 delete: true,
1105 });
1106 location.reload(true);
1107 return;
1108 }
1109 }
1110
1111 if (moreActions.value == 'move') {
1112 $('move_issue_form_fragment').style.display = '';
1113 $('copy_issue_form_fragment').style.display = 'none';
1114 return;
1115 }
1116 if (moreActions.value == 'copy') {
1117 $('copy_issue_form_fragment').style.display = '';
1118 $('move_issue_form_fragment').style.display = 'none';
1119 return;
1120 }
1121
1122 // If no action was taken, reset the dropdown to the 'More actions...' item.
1123 moreActions.value = '0';
1124}
1125
1126/**
1127 * The user has selected the "Flag as spam..." menu item.
1128 */
1129async function TKR_flagSpam(isSpam) {
1130 const selectedIssueRefs = [];
1131 issueRefs.forEach((issueRef) => {
1132 const checkbox = $('cb_' + issueRef.id);
1133 if (checkbox && checkbox.checked) {
1134 selectedIssueRefs.push({
1135 projectName: issueRef.project_name,
1136 localId: issueRef.id,
1137 });
1138 }
1139 });
1140 if (selectedIssueRefs.length > 0) {
1141 if (!confirm((isSpam ? 'Flag' : 'Un-flag') +
1142 ' all selected issues as spam?')) {
1143 return;
1144 }
1145 await window.prpcClient.call('monorail.Issues', 'FlagIssues', {
1146 issueRefs: selectedIssueRefs,
1147 flag: isSpam,
1148 });
1149 location.reload(true);
1150 } else {
1151 alert('Please select some issues to flag as spam');
1152 }
1153}
1154
1155function TKR_addToHotlist() {
1156 const selectedIssueRefs = GetSelectedIssuesRefs();
1157 if (selectedIssueRefs.length > 0) {
1158 window.__hotlists_dialog.ShowUpdateHotlistDialog();
1159 } else {
1160 alert('Please select some issues to add to a hotlist');
1161 }
1162}
1163
1164
1165function GetSelectedIssuesRefs() {
1166 let selectedIssueRefs = [];
1167 for (let i = 0; i < issueRefs.length; i++) {
1168 let checkbox = document.getElementById('cb_' + issueRefs[i]['id']);
1169 if (checkbox == null) {
1170 checkbox = document.getElementById(
1171 'cb_' + issueRefs[i]['project_name'] + ':' + issueRefs[i]['id']);
1172 }
1173 if (checkbox && checkbox.checked) {
1174 selectedIssueRefs.push(issueRefs[i]);
1175 }
1176 }
1177 return selectedIssueRefs;
1178}
1179
1180function onResponseUpdateUI(modifiedHotlists, remainingHotlists) {
1181 const list = $('user-hotlists-list');
1182 while (list.firstChild) {
1183 list.removeChild(list.firstChild);
1184 }
1185 remainingHotlists.forEach((hotlist) => {
1186 const name = hotlist[0];
1187 const userId = hotlist[1];
1188 const url = `/u/${userId}/hotlists/${name}`;
1189 const hotlistLink = document.createElement('a');
1190 hotlistLink.setAttribute('href', url);
1191 hotlistLink.textContent = name;
1192 list.appendChild(hotlistLink);
1193 list.appendChild(document.createElement('br'));
1194 });
1195 $('user-hotlists').style.display = 'block';
1196 onAddIssuesResponse(modifiedHotlists);
1197}
1198
1199function onAddIssuesResponse(modifiedHotlists) {
1200 const hotlistNames = modifiedHotlists.map((hotlist) => hotlist[0]).join(', ');
1201 $('notice').textContent = 'Successfully updated ' + hotlistNames;
1202 $('update-issues-hotlists').style.display = 'none';
1203 $('alert-table').style.display = 'table';
1204}
1205
1206function onAddIssuesFailure(reason) {
1207 $('notice').textContent =
1208 'Some hotlists were not updated: ' + reason.description;
1209 $('update-issues-hotlists').style.display = 'none';
1210 $('alert-table').style.display = 'table';
1211}
1212
1213/**
1214 * The user has selected the "Bulk Edit..." menu item. Go to a page that
1215 * offers the ability to edit all selected issues.
1216 */
1217// TODO(jrobbins): cross-project bulk edit
1218function TKR_HandleBulkEdit() {
1219 let selectedIssueRefs = GetSelectedIssuesRefs();
1220 let selectedLocalIDs = [];
1221 for (let i = 0; i < selectedIssueRefs.length; i++) {
1222 selectedLocalIDs.push(selectedIssueRefs[i]['id']);
1223 }
1224 if (selectedLocalIDs.length > 0) {
1225 let selectedLocalIDString = selectedLocalIDs.join(',');
1226 let url = 'bulkedit?ids=' + selectedLocalIDString;
1227 TKR_go(url + _ctxArgs);
1228 } else {
1229 alert('Please select some issues to edit');
1230 }
1231}
1232
1233/**
1234 * Clears the selected status value when the 'clear' operator is chosen.
1235 */
1236function TKR_ignoreWidgetIfOpIsClear(selectEl, inputID) {
1237 if (selectEl.value == 'clear') {
1238 document.getElementById(inputID).value = '';
1239 }
1240}
1241
1242/**
1243 * Array of original labels on the served page, so that we can notice
1244 * when the used submits a form that has any Restrict-* labels removed.
1245 */
1246let TKR_allOrigLabels = [];
1247
1248
1249/**
1250 * Prevent users from easily entering "+1" comments.
1251 */
1252function TKR_checkPlusOne() {
1253 let c = $('addCommentTextArea').value;
1254 let instructions = (
1255 '\nPlease use the star icon instead.\n' +
1256 'Stars show your interest without annoying other users.');
1257 if (new RegExp('^\\s*[-+]+[0-9]+\\s*.{0,30}$', 'm').test(c) &&
1258 c.length < 150) {
1259 alert('This looks like a "+1" comment.' + instructions);
1260 return false;
1261 }
1262 if (new RegExp('^\\s*me too.{0,30}$', 'i').test(c)) {
1263 alert('This looks like a "me too" comment.' + instructions);
1264 return false;
1265 }
1266 return true;
1267}
1268
1269
1270/**
1271 * If the user removes Restrict-* labels, ask them if they are sure.
1272 */
1273function TKR_checkUnrestrict(prevent_restriction_removal) {
1274 let removedRestrictions = [];
1275
1276 for (let i = 0; i < TKR_allOrigLabels.length; ++i) {
1277 let origLabel = TKR_allOrigLabels[i];
1278 if (origLabel.indexOf('Restrict-') == 0) {
1279 let found = false;
1280 let j = 0;
1281 while ($('label' + j)) {
1282 let newLabel = $('label' + j).value;
1283 if (newLabel == origLabel) {
1284 found = true;
1285 break;
1286 }
1287 j++;
1288 }
1289 if (!found) {
1290 removedRestrictions.push(origLabel);
1291 }
1292 }
1293 }
1294
1295 if (removedRestrictions.length == 0) {
1296 return true;
1297 }
1298
1299 if (prevent_restriction_removal) {
1300 let msg = 'You may not remove restriction labels.';
1301 alert(msg);
1302 return false;
1303 }
1304
1305 let instructions = (
1306 'You are removing these restrictions:\n ' +
1307 removedRestrictions.join('\n ') +
1308 '\nThis may allow more people to access this issue.' +
1309 '\nAre you sure?');
1310 return confirm(instructions);
1311}
1312
1313
1314/**
1315 * Add a column to a list view by updating the colspec form element and
1316 * submiting an invisible <form> to load a new page that includes the column.
1317 * @param {string} colname The name of the column to start showing.
1318 */
1319function TKR_addColumn(colname) {
1320 let colspec = TKR_getColspecElement();
1321 colspec.value = colspec.value + ' ' + colname;
1322 $('colspecform').submit();
1323}
1324
1325
1326/**
1327 * Allow members to shift-click to select multiple issues. This keeps
1328 * track of the last row that the user clicked a checkbox on.
1329 */
1330let TKR_lastSelectedRow = undefined;
1331
1332
1333/**
1334 * Return true if an event had the shift-key pressed.
1335 * @param {Event} evt The mouse click event.
1336 */
1337function TKR_hasShiftKey(evt) {
1338 evt = (evt) ? evt : (window.event) ? window.event : '';
1339 if (evt) {
1340 if (evt.modifiers) {
1341 return evt.modifiers & Event.SHIFT_MASK;
1342 } else {
1343 return evt.shiftKey;
1344 }
1345 }
1346 return false;
1347}
1348
1349
1350/**
1351 * Select one row: check the checkbox and use highlight color.
1352 * @param {Element} row the row containing the checkbox that the user clicked.
1353 * @param {boolean} checked True if the user checked the box.
1354 */
1355function TKR_rangeSelectRow(row, checked) {
1356 if (!row) {
1357 return;
1358 }
1359 if (checked) {
1360 row.classList.add('selected');
1361 } else {
1362 row.classList.remove('selected');
1363 }
1364
1365 let td = row.firstChild;
1366 while (td && td.tagName != 'TD') {
1367 td = td.nextSibling;
1368 }
1369 if (!td) {
1370 return;
1371 }
1372
1373 let checkbox = td.firstChild;
1374 while (checkbox && checkbox.tagName != 'INPUT') {
1375 checkbox = checkbox.nextSibling;
1376 }
1377 if (!checkbox) {
1378 return;
1379 }
1380
1381 checkbox.checked = checked;
1382}
1383
1384
1385/**
1386 * If the user shift-clicked a checkbox, (un)select a range.
1387 * @param {Event} evt The mouse click event.
1388 * @param {Element} el The checkbox that was clicked.
1389 */
1390function TKR_checkRangeSelect(evt, el) {
1391 let clicked_row = el.parentNode.parentNode.rowIndex;
1392 if (clicked_row == TKR_lastSelectedRow) {
1393 return;
1394 }
1395 if (TKR_hasShiftKey(evt) && TKR_lastSelectedRow != undefined) {
1396 let results_table = $('resultstable');
1397 let delta = (clicked_row > TKR_lastSelectedRow) ? 1 : -1;
1398 for (let i = TKR_lastSelectedRow; i != clicked_row; i += delta) {
1399 TKR_rangeSelectRow(results_table.rows[i], el.checked);
1400 }
1401 }
1402 TKR_lastSelectedRow = clicked_row;
1403}
1404
1405
1406/**
1407 * Make a link to a given issue that includes context parameters that allow
1408 * the user to see the same list columns, sorting, query, and pagination state
1409 * if they ever navigate up to the list again.
1410 * @param {{issue_url: string}} issueRef The dict with info about an issue,
1411 * including a url to the issue detail page.
1412 */
1413function TKR_makeIssueLink(issueRef) {
1414 return '/p/' + issueRef['project_name'] + '/issues/detail?id=' + issueRef['id'] + _ctxArgs;
1415}
1416
1417
1418/**
1419 * Hide or show a list column in the case where we already have the
1420 * data for that column on the page.
1421 * @param {number} colIndex index of the column that is being shown or hidden.
1422 */
1423function TKR_toggleColumnUpdate(colIndex) {
1424 let shownCols = TKR_getColspecElement().value.split(' ');
1425 let filteredCols = [];
1426 for (let i=0; i< shownCols.length; i++) {
1427 if (_allColumnNames[colIndex] != shownCols[i].toLowerCase()) {
1428 filteredCols.push(shownCols[i]);
1429 }
1430 }
1431
1432 TKR_getColspecElement().value = filteredCols.join(' ');
1433 TKR_toggleColumn('hide_col_' + colIndex);
1434 _ctxArgs = _formatContextQueryArgs();
1435 window.history.replaceState({}, '', '?' + _ctxArgs);
1436}
1437
1438
1439/**
1440 * Convert a column into a groupby clause by removing it from the column spec
1441 * and adding it to the groupby spec, then reloading the page.
1442 * @param {number} colIndex index of the column that is being shown or hidden.
1443 */
1444function TKR_addGroupBy(colIndex) {
1445 let colName = _allColumnNames[colIndex];
1446 let shownCols = TKR_getColspecElement().value.split(' ');
1447 let filteredCols = [];
1448 for (var i=0; i < shownCols.length; i++) {
1449 if (shownCols[i] && colName != shownCols[i].toLowerCase()) {
1450 filteredCols.push(shownCols[i]);
1451 }
1452 }
1453
1454 TKR_getColspecElement().value = filteredCols.join(' ');
1455
1456 let groupSpec = $('groupbyspec');
1457 let shownGroupings = groupSpec.value.split(' ');
1458 let filteredGroupings = [];
1459 for (i=0; i < shownGroupings.length; i++) {
1460 if (shownGroupings[i] && colName != shownGroupings[i].toLowerCase()) {
1461 filteredGroupings.push(shownGroupings[i]);
1462 }
1463 }
1464 filteredGroupings.push(colName);
1465 groupSpec.value = filteredGroupings.join(' ');
1466 $('colspecform').submit();
1467}
1468
1469
1470/**
1471 * Add a multi-valued custom field editing widget.
1472 */
1473function TKR_addMultiFieldValueWidget(
1474 el, field_id, field_type, opt_validate_1, opt_validate_2, field_phase_name) {
1475 let widget = document.createElement('INPUT');
1476 widget.name = (field_phase_name && (
1477 field_phase_name != '')) ? `custom_${field_id}_${field_phase_name}` :
1478 `custom_${field_id}`;
1479 if (field_type == 'str' || field_type =='url') {
1480 widget.size = 90;
1481 }
1482 if (field_type == 'user') {
1483 widget.style = 'width:12em';
1484 widget.classList.add('userautocomplete');
1485 widget.classList.add('customfield');
1486 widget.classList.add('multivalued');
1487 widget.addEventListener('focus', function(event) {
1488 _acrob(null);
1489 _acof(event);
1490 });
1491 }
1492 if (field_type == 'int' || field_type == 'date') {
1493 widget.style.textAlign = 'right';
1494 widget.style.width = '12em';
1495 widget.min = opt_validate_1;
1496 widget.max = opt_validate_2;
1497 }
1498 if (field_type == 'int') {
1499 widget.type = 'number';
1500 } else if (field_type == 'date') {
1501 widget.type = 'date';
1502 }
1503
1504 el.parentNode.insertBefore(widget, el);
1505
1506 let del_button = document.createElement('U');
1507 del_button.onclick = function(event) {
1508 _removeMultiFieldValueWidget(event.target);
1509 };
1510 del_button.textContent = 'X';
1511 el.parentNode.insertBefore(del_button, el);
1512}
1513
1514
1515function TKR_removeMultiFieldValueWidget(el) {
1516 let target = el.previousSibling;
1517 while (target && target.tagName != 'INPUT') {
1518 target = target.previousSibling;
1519 }
1520 if (target) {
1521 el.parentNode.removeChild(target);
1522 }
1523 el.parentNode.removeChild(el); // the X itself
1524}
1525
1526
1527/**
1528 * Trim trailing commas and spaces off <INPUT type="email" multiple> fields
1529 * before submitting the form.
1530 */
1531function TKR_trimCommas() {
1532 let ccField = $('memberccedit');
1533 if (ccField) {
1534 ccField.value = ccField.value.replace(/,\s*$/, '');
1535 }
1536 ccField = $('memberenter');
1537 if (ccField) {
1538 ccField.value = ccField.value.replace(/,\s*$/, '');
1539 }
1540}
1541
1542
1543/**
1544 * Identify which issues have been checkedboxed for removal from hotlist.
1545 */
1546function HTL_removeIssues() {
1547 let selectedLocalIDs = [];
1548 for (let i = 0; i < issueRefs.length; i++) {
1549 issueRef = issueRefs[i]['project_name']+':'+issueRefs[i]['id'];
1550 let checkbox = document.getElementById('cb_' + issueRef);
1551 if (checkbox && checkbox.checked) {
1552 selectedLocalIDs.push(issueRef);
1553 }
1554 }
1555
1556 if (selectedLocalIDs.length > 0) {
1557 if (!confirm('Remove all selected issues?')) {
1558 return;
1559 }
1560 let selectedLocalIDString = selectedLocalIDs.join(',');
1561 $('bulk_remove_local_ids').value = selectedLocalIDString;
1562 $('bulk_remove_value').value = 'true';
1563 setCurrentColSpec();
1564
1565 let form = $('bulkremoveissues');
1566 form.submit();
1567 } else {
1568 alert('Please select some issues to remove');
1569 }
1570}
1571
1572function setCurrentColSpec() {
1573 $('current_col_spec').value = TKR_getColspecElement().value;
1574}
1575
1576
1577async function saveNote(textBox, hotlistID) {
1578 const projectName = textBox.getAttribute('projectname');
1579 const localId = textBox.getAttribute('localid');
1580 await window.prpcClient.call(
1581 'monorail.Features', 'UpdateHotlistIssueNote', {
1582 hotlistRef: {
1583 hotlistId: hotlistID,
1584 },
1585 issueRef: {
1586 projectName: textBox.getAttribute('projectname'),
1587 localId: textBox.getAttribute('localid'),
1588 },
1589 note: textBox.value,
1590 });
1591 $(`itemnote_${projectName}_${localId}`).value = textBox.value;
1592}
1593
1594// TODO(jojwang): monorail:4291, integrate this into autocomplete process
1595// to prevent calling ListStatuses twice.
1596/**
1597 * Load the status select element with possible project statuses.
1598 */
1599function TKR_loadStatusSelect(projectName, selectId, selected, isBulkEdit=false) {
1600 const projectRequestMessage = {
1601 project_name: projectName};
1602 const statusesPromise = window.prpcClient.call(
1603 'monorail.Projects', 'ListStatuses', projectRequestMessage);
1604 statusesPromise.then((statusesResponse) => {
1605 const jsonData = TKR_convertStatuses(statusesResponse);
1606 const statusSelect = document.getElementById(selectId);
1607 // An initial option with value='selected' had to be added in HTML
1608 // to prevent TKR_isDirty() from registering a change in the select input
1609 // even when the user has not selected a different value.
1610 // That option needs to be removed otherwise, screenreaders will announce
1611 // its existence.
1612 while (statusSelect.firstChild) {
1613 statusSelect.removeChild(statusSelect.firstChild);
1614 }
1615 // Add unrecognized status (can be empty status) to open statuses.
1616 let selectedFound = false;
1617 jsonData.open.concat(jsonData.closed).forEach((status) => {
1618 if (status.name === selected) {
1619 selectedFound = true;
1620 }
1621 });
1622 if (!selectedFound) {
1623 jsonData.open.unshift({name: selected});
1624 }
1625 // Add open statuses.
1626 if (jsonData.open.length > 0) {
1627 const openGroup =
1628 statusSelect.appendChild(createStatusGroup('Open', jsonData.open, selected, isBulkEdit));
1629 }
1630 if (jsonData.closed.length > 0) {
1631 statusSelect.appendChild(createStatusGroup('Closed', jsonData.closed, selected));
1632 }
1633 });
1634}
1635
1636function createStatusGroup(groupName, options, selected, isBulkEdit=false) {
1637 const groupElement = document.createElement('optgroup');
1638 groupElement.label = groupName;
1639 options.forEach((option) => {
1640 const opt = document.createElement('option');
1641 opt.value = option.name;
1642 opt.selected = (selected === option.name) ? true : false;
1643 // Special case for when opt represents an empty status.
1644 if (opt.value === '') {
1645 if (isBulkEdit) {
1646 opt.textContent = '--- (no change)';
1647 opt.setAttribute('aria-label', 'no change');
1648 } else {
1649 opt.textContent = '--- (empty status)';
1650 opt.setAttribute('aria-label', 'empty status');
1651 }
1652 } else {
1653 opt.textContent = option.doc ? `${option.name} = ${option.doc}` : option.name;
1654 }
1655 groupElement.appendChild(opt);
1656 });
1657 return groupElement;
1658}
1659
1660/**
1661 * Generate DOM for a filter rules preview section.
1662 */
1663function renderFilterRulesSection(section_id, heading, value_why_list) {
1664 let section = $(section_id);
1665 while (section.firstChild) {
1666 section.removeChild(section.firstChild);
1667 }
1668 if (value_why_list.length == 0) return false;
1669
1670 section.appendChild(document.createTextNode(heading + ': '));
1671 for (let i = 0; i < value_why_list.length; ++i) {
1672 if (i > 0) {
1673 section.appendChild(document.createTextNode(', '));
1674 }
1675 let value = value_why_list[i].value;
1676 let why = value_why_list[i].why;
1677 let span = section.appendChild(
1678 document.createElement('span'));
1679 span.textContent = value;
1680 if (why) span.setAttribute('title', why);
1681 }
1682 return true;
1683}
1684
1685
1686/**
1687 * Generate DOM for a filter rules preview section bullet list.
1688 */
1689function renderFilterRulesListSection(section_id, heading, value_why_list) {
1690 let section = $(section_id);
1691 while (section.firstChild) {
1692 section.removeChild(section.firstChild);
1693 }
1694 if (value_why_list.length == 0) return false;
1695
1696 section.appendChild(document.createTextNode(heading + ': '));
1697 let bulletList = document.createElement('ul');
1698 section.appendChild(bulletList);
1699 for (let i = 0; i < value_why_list.length; ++i) {
1700 let listItem = document.createElement('li');
1701 bulletList.appendChild(listItem);
1702 let value = value_why_list[i].value;
1703 let why = value_why_list[i].why;
1704 let span = listItem.appendChild(
1705 document.createElement('span'));
1706 span.textContent = value;
1707 if (why) span.setAttribute('title', why);
1708 }
1709 return true;
1710}
1711
1712
1713/**
1714 * Ask server to do a presubmit check and then display and warnings
1715 * as the user edits an issue.
1716 */
1717function TKR_presubmit() {
1718 const issue_form = (
1719 document.forms.create_issue_form || document.forms.issue_update_form);
1720 if (!issue_form) {
1721 return;
1722 }
1723
1724 const inputs = issue_form.querySelectorAll(
1725 'input:not([type="file"]), textarea, select');
1726 if (!inputs) {
1727 return;
1728 }
1729
1730 const valuesByName = new Map();
1731 for (const key in inputs) {
1732 if (!inputs.hasOwnProperty(key)) {
1733 continue;
1734 }
1735 const input = inputs[key];
1736 if (input.type === 'checkbox' && !input.checked) {
1737 continue;
1738 }
1739 if (!valuesByName.has(input.name)) {
1740 valuesByName.set(input.name, []);
1741 }
1742 valuesByName.get(input.name).push(input.value);
1743 }
1744
1745 const issueDelta = TKR_buildIssueDelta(valuesByName);
1746 const issueRef = {project_name: window.CS_env.projectName};
1747 if (valuesByName.has('id')) {
1748 issueRef.local_id = valuesByName.get('id')[0];
1749 }
1750
1751 const presubmitMessage = {
1752 issue_ref: issueRef,
1753 issue_delta: issueDelta,
1754 };
1755 const presubmitPromise = window.prpcClient.call(
1756 'monorail.Issues', 'PresubmitIssue', presubmitMessage);
1757
1758 presubmitPromise.then((response) => {
1759 $('owner_avail_state').style.display = (
1760 response.ownerAvailabilityState ? '' : 'none');
1761 $('owner_avail_state').className = (
1762 'availability_' + response.ownerAvailabilityState);
1763 $('owner_availability').textContent = response.ownerAvailability;
1764
1765 let derived_labels;
1766 if (response.derivedLabels) {
1767 derived_labels = renderFilterRulesSection(
1768 'preview_filterrules_labels', 'Labels', response.derivedLabels);
1769 }
1770 let derived_owner_email;
1771 if (response.derivedOwners) {
1772 derived_owner_email = renderFilterRulesSection(
1773 'preview_filterrules_owner', 'Owner', response.derivedOwners[0]);
1774 }
1775 let derived_cc_emails;
1776 if (response.derivedCcs) {
1777 derived_cc_emails = renderFilterRulesSection(
1778 'preview_filterrules_ccs', 'Cc', response.derivedCcs);
1779 }
1780 let warnings;
1781 if (response.warnings) {
1782 warnings = renderFilterRulesListSection(
1783 'preview_filterrules_warnings', 'Warnings', response.warnings);
1784 }
1785 let errors;
1786 if (response.errors) {
1787 errors = renderFilterRulesListSection(
1788 'preview_filterrules_errors', 'Errors', response.errors);
1789 }
1790
1791 if (derived_labels || derived_owner_email || derived_cc_emails ||
1792 warnings || errors) {
1793 $('preview_filterrules_area').style.display = '';
1794 } else {
1795 $('preview_filterrules_area').style.display = 'none';
1796 }
1797 });
1798}
1799
1800function HTL_deleteHotlist(form) {
1801 if (confirm('Are you sure you want to delete this hotlist? This cannot be undone.')) {
1802 $('delete').value = 'true';
1803 form.submit();
1804 }
1805}
1806
1807function HTL_toggleIssuesShown(toggleIssuesButton) {
1808 const can = toggleIssuesButton.value;
1809 const hotlist_name = $('hotlist_name').value;
1810 let url = `${hotlist_name}?can=${can}`;
1811 const hidden_cols = $('colcontrol').classList.value;
1812 if (window.location.href.includes('&colspec') || hidden_cols) {
1813 const colSpecElement =
1814 TKR_getColspecElement(); // eslint-disable-line new-cap
1815 let sort = '';
1816 if ($('sort')) {
1817 sort = $('sort').value.split(' ').join('+');
1818 url += `&sort=${sort}`;
1819 }
1820 url += colSpecElement ? `&colspec=${colSpecElement.value}` : '';
1821 }
1822 TKR_go(url);
1823}