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