/* globals wipPrefixes, issuesTribute, emojiTribute */ /* exported timeAddManual, toggleStopwatch, cancelStopwatch, initHeatmap */ /* exported toggleDeadlineForm, setDeadline, updateDeadline, deleteDependencyModal, cancelCodeComment, onOAuthLoginClick */ function htmlEncode(text) { return jQuery('
').text(text).html(); } let csrf; let suburl; let previewFileModes; let simpleMDEditor; let codeMirrorEditor; // Disable Dropzone auto-discover because it's manually initialized if (typeof (Dropzone) !== 'undefined') { Dropzone.autoDiscover = false; } function initCommentPreviewTab($form) { const $tabMenu = $form.find('.tabular.menu'); $tabMenu.find('.item').tab(); $tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`).click(function () { const $this = $(this); $.post($this.data('url'), { _csrf: csrf, mode: 'gfm', context: $this.data('context'), text: $form.find(`.tab.segment[data-tab="${$tabMenu.data('write')}"] textarea`).val() }, (data) => { const $previewPanel = $form.find(`.tab.segment[data-tab="${$tabMenu.data('preview')}"]`); $previewPanel.html(data); emojify.run($previewPanel[0]); $('pre code', $previewPanel[0]).each(function () { hljs.highlightBlock(this); }); }); }); buttonsClickOnEnter(); } function initEditPreviewTab($form) { const $tabMenu = $form.find('.tabular.menu'); $tabMenu.find('.item').tab(); const $previewTab = $tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`); if ($previewTab.length) { previewFileModes = $previewTab.data('preview-file-modes').split(','); $previewTab.click(function () { const $this = $(this); $.post($this.data('url'), { _csrf: csrf, mode: 'gfm', context: $this.data('context'), text: $form.find(`.tab.segment[data-tab="${$tabMenu.data('write')}"] textarea`).val() }, (data) => { const $previewPanel = $form.find(`.tab.segment[data-tab="${$tabMenu.data('preview')}"]`); $previewPanel.html(data); emojify.run($previewPanel[0]); $('pre code', $previewPanel[0]).each(function () { hljs.highlightBlock(this); }); }); }); } } function initEditDiffTab($form) { const $tabMenu = $form.find('.tabular.menu'); $tabMenu.find('.item').tab(); $tabMenu.find(`.item[data-tab="${$tabMenu.data('diff')}"]`).click(function () { const $this = $(this); $.post($this.data('url'), { _csrf: csrf, context: $this.data('context'), content: $form.find(`.tab.segment[data-tab="${$tabMenu.data('write')}"] textarea`).val() }, (data) => { const $diffPreviewPanel = $form.find(`.tab.segment[data-tab="${$tabMenu.data('diff')}"]`); $diffPreviewPanel.html(data); emojify.run($diffPreviewPanel[0]); }); }); } function initEditForm() { if ($('.edit.form').length === 0) { return; } initEditPreviewTab($('.edit.form')); initEditDiffTab($('.edit.form')); } function initBranchSelector() { const $selectBranch = $('.ui.select-branch'); const $branchMenu = $selectBranch.find('.reference-list-menu'); $branchMenu.find('.item:not(.no-select)').click(function () { const selectedValue = $(this).data('id'); $($(this).data('id-selector')).val(selectedValue); $selectBranch.find('.ui .branch-name').text(selectedValue); }); $selectBranch.find('.reference.column').click(function () { $selectBranch.find('.scrolling.reference-list-menu').css('display', 'none'); $selectBranch.find('.reference .text').removeClass('black'); $($(this).data('target')).css('display', 'block'); $(this).find('.text').addClass('black'); return false; }); } function updateIssuesMeta(url, action, issueIds, elementId) { return new Promise(((resolve) => { $.ajax({ type: 'POST', url, data: { _csrf: csrf, action, issue_ids: issueIds, id: elementId }, success: resolve }); })); } function initRepoStatusChecker() { const migrating = $('#repo_migrating'); $('#repo_migrating_failed').hide(); if (migrating) { const repo_name = migrating.attr('repo'); if (typeof repo_name === 'undefined') { return; } $.ajax({ type: 'GET', url: `${suburl}/${repo_name}/status`, data: { _csrf: csrf, }, complete(xhr) { if (xhr.status === 200) { if (xhr.responseJSON) { if (xhr.responseJSON.status === 0) { window.location.reload(); return; } setTimeout(() => { initRepoStatusChecker(); }, 2000); return; } } $('#repo_migrating_progress').hide(); $('#repo_migrating_failed').show(); } }); } } function initReactionSelector(parent) { let reactions = ''; if (!parent) { parent = $(document); reactions = '.reactions > '; } parent.find(`${reactions}a.label`).popup({ position: 'bottom left', metadata: { content: 'title', title: 'none' } }); parent.find(`.select-reaction > .menu > .item, ${reactions}a.label`).on('click', function (e) { const vm = this; e.preventDefault(); if ($(this).hasClass('disabled')) return; const actionURL = $(this).hasClass('item') ? $(this).closest('.select-reaction').data('action-url') : $(this).data('action-url'); const url = `${actionURL}/${$(this).hasClass('blue') ? 'unreact' : 'react'}`; $.ajax({ type: 'POST', url, data: { _csrf: csrf, content: $(this).data('content') } }).done((resp) => { if (resp && (resp.html || resp.empty)) { const content = $(vm).closest('.content'); let react = content.find('.segment.reactions'); if (!resp.empty && react.length > 0) { react.remove(); } if (!resp.empty) { react = $(''); const attachments = content.find('.segment.bottom:first'); if (attachments.length > 0) { react.insertBefore(attachments); } else { react.appendTo(content); } react.html(resp.html); const hasEmoji = react.find('.has-emoji'); for (let i = 0; i < hasEmoji.length; i++) { emojify.run(hasEmoji.get(i)); } react.find('.dropdown').dropdown(); initReactionSelector(react); } } }); }); } function insertAtCursor(field, value) { if (field.selectionStart || field.selectionStart === 0) { const startPos = field.selectionStart; const endPos = field.selectionEnd; field.value = field.value.substring(0, startPos) + value + field.value.substring(endPos, field.value.length); field.selectionStart = startPos + value.length; field.selectionEnd = startPos + value.length; } else { field.value += value; } } function replaceAndKeepCursor(field, oldval, newval) { if (field.selectionStart || field.selectionStart === 0) { const startPos = field.selectionStart; const endPos = field.selectionEnd; field.value = field.value.replace(oldval, newval); field.selectionStart = startPos + newval.length - oldval.length; field.selectionEnd = endPos + newval.length - oldval.length; } else { field.value = field.value.replace(oldval, newval); } } function retrieveImageFromClipboardAsBlob(pasteEvent, callback) { if (!pasteEvent.clipboardData) { return; } const { items } = pasteEvent.clipboardData; if (typeof items === 'undefined') { return; } for (let i = 0; i < items.length; i++) { if (items[i].type.indexOf('image') === -1) continue; const blob = items[i].getAsFile(); if (typeof (callback) === 'function') { pasteEvent.preventDefault(); pasteEvent.stopPropagation(); callback(blob); } } } function uploadFile(file, callback) { const xhr = new XMLHttpRequest(); xhr.onload = function () { if (xhr.status === 200) { callback(xhr.responseText); } }; xhr.open('post', `${suburl}/attachments`, true); xhr.setRequestHeader('X-Csrf-Token', csrf); const formData = new FormData(); formData.append('file', file, file.name); xhr.send(formData); } function reload() { window.location.reload(); } function initImagePaste(target) { target.each(function () { const field = this; field.addEventListener('paste', (event) => { retrieveImageFromClipboardAsBlob(event, (img) => { const name = img.name.substr(0, img.name.lastIndexOf('.')); insertAtCursor(field, `![${name}]()`); uploadFile(img, (res) => { const data = JSON.parse(res); replaceAndKeepCursor(field, `![${name}]()`, `![${name}](${suburl}/attachments/${data.uuid})`); const input = $(``).val(data.uuid); $('.files').append(input); }); }); }, false); }); } function initCommentForm() { if ($('.comment.form').length === 0) { return; } initBranchSelector(); initCommentPreviewTab($('.comment.form')); initImagePaste($('.comment.form textarea')); // Listsubmit function initListSubmits(selector, outerSelector) { const $list = $(`.ui.${outerSelector}.list`); const $noSelect = $list.find('.no-select'); const $listMenu = $(`.${selector} .menu`); let hasLabelUpdateAction = $listMenu.data('action') === 'update'; const labels = {}; $(`.${selector}`).dropdown('setting', 'onHide', () => { hasLabelUpdateAction = $listMenu.data('action') === 'update'; // Update the var if (hasLabelUpdateAction) { const promises = []; Object.keys(labels).forEach((elementId) => { const label = labels[elementId]; const promise = updateIssuesMeta( label['update-url'], label.action, label['issue-id'], elementId ); promises.push(promise); }); Promise.all(promises).then(reload); } }); $listMenu.find('.item:not(.no-select)').click(function () { // we don't need the action attribute when updating assignees if (selector === 'select-assignees-modify') { // UI magic. We need to do this here, otherwise it would destroy the functionality of // adding/removing labels if ($(this).hasClass('checked')) { $(this).removeClass('checked'); $(this).find('.octicon').removeClass('octicon-check'); } else { $(this).addClass('checked'); $(this).find('.octicon').addClass('octicon-check'); } updateIssuesMeta( $listMenu.data('update-url'), '', $listMenu.data('issue-id'), $(this).data('id') ); $listMenu.data('action', 'update'); // Update to reload the page when we updated items return false; } if ($(this).hasClass('checked')) { $(this).removeClass('checked'); $(this).find('.octicon').removeClass('octicon-check'); if (hasLabelUpdateAction) { if (!($(this).data('id') in labels)) { labels[$(this).data('id')] = { 'update-url': $listMenu.data('update-url'), action: 'detach', 'issue-id': $listMenu.data('issue-id'), }; } else { delete labels[$(this).data('id')]; } } } else { $(this).addClass('checked'); $(this).find('.octicon').addClass('octicon-check'); if (hasLabelUpdateAction) { if (!($(this).data('id') in labels)) { labels[$(this).data('id')] = { 'update-url': $listMenu.data('update-url'), action: 'attach', 'issue-id': $listMenu.data('issue-id'), }; } else { delete labels[$(this).data('id')]; } } } const listIds = []; $(this).parent().find('.item').each(function () { if ($(this).hasClass('checked')) { listIds.push($(this).data('id')); $($(this).data('id-selector')).removeClass('hide'); } else { $($(this).data('id-selector')).addClass('hide'); } }); if (listIds.length === 0) { $noSelect.removeClass('hide'); } else { $noSelect.addClass('hide'); } $($(this).parent().data('id')).val(listIds.join(',')); return false; }); $listMenu.find('.no-select.item').click(function () { if (hasLabelUpdateAction || selector === 'select-assignees-modify') { updateIssuesMeta( $listMenu.data('update-url'), 'clear', $listMenu.data('issue-id'), '' ).then(reload); } $(this).parent().find('.item').each(function () { $(this).removeClass('checked'); $(this).find('.octicon').removeClass('octicon-check'); }); $list.find('.item').each(function () { $(this).addClass('hide'); }); $noSelect.removeClass('hide'); $($(this).parent().data('id')).val(''); }); } // Init labels and assignees initListSubmits('select-label', 'labels'); initListSubmits('select-assignees', 'assignees'); initListSubmits('select-assignees-modify', 'assignees'); function selectItem(select_id, input_id) { const $menu = $(`${select_id} .menu`); const $list = $(`.ui${select_id}.list`); const hasUpdateAction = $menu.data('action') === 'update'; $menu.find('.item:not(.no-select)').click(function () { $(this).parent().find('.item').each(function () { $(this).removeClass('selected active'); }); $(this).addClass('selected active'); if (hasUpdateAction) { updateIssuesMeta( $menu.data('update-url'), '', $menu.data('issue-id'), $(this).data('id') ).then(reload); } switch (input_id) { case '#milestone_id': $list.find('.selected').html(`${ htmlEncode($(this).text())}`); break; case '#assignee_id': $list.find('.selected').html(`` + `${ htmlEncode($(this).text())}`); } $(`.ui${select_id}.list .no-select`).addClass('hide'); $(input_id).val($(this).data('id')); }); $menu.find('.no-select.item').click(function () { $(this).parent().find('.item:not(.no-select)').each(function () { $(this).removeClass('selected active'); }); if (hasUpdateAction) { updateIssuesMeta( $menu.data('update-url'), '', $menu.data('issue-id'), $(this).data('id') ).then(reload); } $list.find('.selected').html(''); $list.find('.no-select').removeClass('hide'); $(input_id).val(''); }); } // Milestone and assignee selectItem('.select-milestone', '#milestone_id'); selectItem('.select-assignee', '#assignee_id'); } function initInstall() { if ($('.install').length === 0) { return; } if ($('#db_host').val() === '') { $('#db_host').val('127.0.0.1:3306'); $('#db_user').val('gitea'); $('#db_name').val('gitea'); } // Database type change detection. $('#db_type').change(function () { const sqliteDefault = 'data/gitea.db'; const tidbDefault = 'data/gitea_tidb'; const dbType = $(this).val(); if (dbType === 'SQLite3') { $('#sql_settings').hide(); $('#pgsql_settings').hide(); $('#mysql_settings').hide(); $('#sqlite_settings').show(); if (dbType === 'SQLite3' && $('#db_path').val() === tidbDefault) { $('#db_path').val(sqliteDefault); } return; } const dbDefaults = { MySQL: '127.0.0.1:3306', PostgreSQL: '127.0.0.1:5432', MSSQL: '127.0.0.1:1433' }; $('#sqlite_settings').hide(); $('#sql_settings').show(); $('#pgsql_settings').toggle(dbType === 'PostgreSQL'); $('#mysql_settings').toggle(dbType === 'MySQL'); $.each(dbDefaults, (_type, defaultHost) => { if ($('#db_host').val() === defaultHost) { $('#db_host').val(dbDefaults[dbType]); return false; } }); }); // TODO: better handling of exclusive relations. $('#offline-mode input').change(function () { if ($(this).is(':checked')) { $('#disable-gravatar').checkbox('check'); $('#federated-avatar-lookup').checkbox('uncheck'); } }); $('#disable-gravatar input').change(function () { if ($(this).is(':checked')) { $('#federated-avatar-lookup').checkbox('uncheck'); } else { $('#offline-mode').checkbox('uncheck'); } }); $('#federated-avatar-lookup input').change(function () { if ($(this).is(':checked')) { $('#disable-gravatar').checkbox('uncheck'); $('#offline-mode').checkbox('uncheck'); } }); $('#enable-openid-signin input').change(function () { if ($(this).is(':checked')) { if (!$('#disable-registration input').is(':checked')) { $('#enable-openid-signup').checkbox('check'); } } else { $('#enable-openid-signup').checkbox('uncheck'); } }); $('#disable-registration input').change(function () { if ($(this).is(':checked')) { $('#enable-captcha').checkbox('uncheck'); $('#enable-openid-signup').checkbox('uncheck'); } else { $('#enable-openid-signup').checkbox('check'); } }); $('#enable-captcha input').change(function () { if ($(this).is(':checked')) { $('#disable-registration').checkbox('uncheck'); } }); } function initRepository() { if ($('.repository').length === 0) { return; } function initFilterSearchDropdown(selector) { const $dropdown = $(selector); $dropdown.dropdown({ fullTextSearch: true, selectOnKeydown: false, onChange(_text, _value, $choice) { if ($choice.data('url')) { window.location.href = $choice.data('url'); } }, message: { noResults: $dropdown.data('no-results') } }); } // File list and commits if ($('.repository.file.list').length > 0 || ('.repository.commits').length > 0) { initFilterBranchTagDropdown('.choose.reference .dropdown'); } // Wiki if ($('.repository.wiki.view').length > 0) { initFilterSearchDropdown('.choose.page .dropdown'); } // Options if ($('.repository.settings.options').length > 0) { $('#repo_name').keyup(function () { const $prompt = $('#repo-name-change-prompt'); if ($(this).val().toString().toLowerCase() !== $(this).data('name').toString().toLowerCase()) { $prompt.show(); } else { $prompt.hide(); } }); // Enable or select internal/external wiki system and issue tracker. $('.enable-system').change(function () { if (this.checked) { $($(this).data('target')).removeClass('disabled'); if (!$(this).data('context')) $($(this).data('context')).addClass('disabled'); } else { $($(this).data('target')).addClass('disabled'); if (!$(this).data('context')) $($(this).data('context')).removeClass('disabled'); } }); $('.enable-system-radio').change(function () { if (this.value === 'false') { $($(this).data('target')).addClass('disabled'); if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).removeClass('disabled'); } else if (this.value === 'true') { $($(this).data('target')).removeClass('disabled'); if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).addClass('disabled'); } }); } // Labels if ($('.repository.labels').length > 0) { // Create label const $newLabelPanel = $('.new-label.segment'); $('.new-label.button').click(() => { $newLabelPanel.show(); }); $('.new-label.segment .cancel').click(() => { $newLabelPanel.hide(); }); $('.color-picker').each(function () { $(this).minicolors(); }); $('.precolors .color').click(function () { const color_hex = $(this).data('color-hex'); $('.color-picker').val(color_hex); $('.minicolors-swatch-color').css('background-color', color_hex); }); $('.edit-label-button').click(function () { $('#label-modal-id').val($(this).data('id')); $('.edit-label .new-label-input').val($(this).data('title')); $('.edit-label .new-label-desc-input').val($(this).data('description')); $('.edit-label .color-picker').val($(this).data('color')); $('.minicolors-swatch-color').css('background-color', $(this).data('color')); $('.edit-label.modal').modal({ onApprove() { $('.edit-label.form').submit(); } }).modal('show'); return false; }); } // Milestones if ($('.repository.new.milestone').length > 0) { const $datepicker = $('.milestone.datepicker'); $datepicker.datetimepicker({ lang: $datepicker.data('lang'), inline: true, timepicker: false, startDate: $datepicker.data('start-date'), formatDate: 'Y-m-d', onSelectDate(ct) { $('#deadline').val(ct.dateFormat('Y-m-d')); } }); $('#clear-date').click(() => { $('#deadline').val(''); return false; }); } // Issues if ($('.repository.view.issue').length > 0) { // Edit issue title const $issueTitle = $('#issue-title'); const $editInput = $('#edit-title-input input'); const editTitleToggle = function () { $issueTitle.toggle(); $('.not-in-edit').toggle(); $('#edit-title-input').toggle(); $('.in-edit').toggle(); $editInput.focus(); return false; }; $('#edit-title').click(editTitleToggle); $('#cancel-edit-title').click(editTitleToggle); $('#save-edit-title').click(editTitleToggle).click(function () { if ($editInput.val().length === 0 || $editInput.val() === $issueTitle.text()) { $editInput.val($issueTitle.text()); return false; } $.post($(this).data('update-url'), { _csrf: csrf, title: $editInput.val() }, (data) => { $editInput.val(data.title); $issueTitle.text(data.title); reload(); }); return false; }); // Edit issue or comment content $('.edit-content').click(function () { const $segment = $(this).parent().parent().parent() .next(); const $editContentZone = $segment.find('.edit-content-zone'); const $renderContent = $segment.find('.render-content'); const $rawContent = $segment.find('.raw-content'); let $textarea; // Setup new form if ($editContentZone.html().length === 0) { $editContentZone.html($('#edit-content-form').html()); $textarea = $editContentZone.find('textarea'); issuesTribute.attach($textarea.get()); emojiTribute.attach($textarea.get()); const $dropzone = $editContentZone.find('.dropzone'); $dropzone.data('saved', false); const $files = $editContentZone.find('.comment-files'); if ($dropzone.length > 0) { const filenameDict = {}; $dropzone.dropzone({ url: $dropzone.data('upload-url'), headers: { 'X-Csrf-Token': csrf }, maxFiles: $dropzone.data('max-file'), maxFilesize: $dropzone.data('max-size'), acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'), addRemoveLinks: true, dictDefaultMessage: $dropzone.data('default-message'), dictInvalidFileType: $dropzone.data('invalid-input-type'), dictFileTooBig: $dropzone.data('file-too-big'), dictRemoveFile: $dropzone.data('remove-file'), init() { this.on('success', (file, data) => { filenameDict[file.name] = { uuid: data.uuid, submitted: false }; const input = $(``).val(data.uuid); $files.append(input); }); this.on('removedfile', (file) => { if (!(file.name in filenameDict)) { return; } $(`#${filenameDict[file.name].uuid}`).remove(); if ($dropzone.data('remove-url') && $dropzone.data('csrf') && !filenameDict[file.name].submitted) { $.post($dropzone.data('remove-url'), { file: filenameDict[file.name].uuid, _csrf: $dropzone.data('csrf') }); } }); this.on('submit', () => { $.each(filenameDict, (name) => { filenameDict[name].submitted = true; }); }); this.on('reload', () => { $.getJSON($editContentZone.data('attachment-url'), (data) => { const drop = $dropzone.get(0).dropzone; drop.removeAllFiles(true); $files.empty(); $.each(data, function () { const imgSrc = `${$dropzone.data('upload-url')}/${this.uuid}`; drop.emit('addedfile', this); drop.emit('thumbnail', this, imgSrc); drop.emit('complete', this); drop.files.push(this); filenameDict[this.name] = { submitted: true, uuid: this.uuid }; $dropzone.find(`img[src='${imgSrc}']`).css('max-width', '100%'); const input = $(``).val(this.uuid); $files.append(input); }); }); }); } }); $dropzone.get(0).dropzone.emit('reload'); } // Give new write/preview data-tab name to distinguish from others const $editContentForm = $editContentZone.find('.ui.comment.form'); const $tabMenu = $editContentForm.find('.tabular.menu'); $tabMenu.attr('data-write', $editContentZone.data('write')); $tabMenu.attr('data-preview', $editContentZone.data('preview')); $tabMenu.find('.write.item').attr('data-tab', $editContentZone.data('write')); $tabMenu.find('.preview.item').attr('data-tab', $editContentZone.data('preview')); $editContentForm.find('.write.segment').attr('data-tab', $editContentZone.data('write')); $editContentForm.find('.preview.segment').attr('data-tab', $editContentZone.data('preview')); initCommentPreviewTab($editContentForm); $editContentZone.find('.cancel.button').click(() => { $renderContent.show(); $editContentZone.hide(); $dropzone.get(0).dropzone.emit('reload'); }); $editContentZone.find('.save.button').click(() => { $renderContent.show(); $editContentZone.hide(); const $attachments = $files.find('[name=files]').map(function () { return $(this).val(); }).get(); $.post($editContentZone.data('update-url'), { _csrf: csrf, content: $textarea.val(), context: $editContentZone.data('context'), files: $attachments }, (data) => { if (data.length === 0) { $renderContent.html($('#no-content').html()); } else { $renderContent.html(data.content); emojify.run($renderContent[0]); $('pre code', $renderContent[0]).each(function () { hljs.highlightBlock(this); }); } const $content = $segment.parent(); if (!$content.find('.ui.small.images').length) { if (data.attachments !== '') { $content.append( '