/* globals wipPrefixes */ /* exported timeAddManual, toggleStopwatch, cancelStopwatch */ /* exported toggleDeadlineForm, setDeadline, updateDeadline, deleteDependencyModal, cancelCodeComment, onOAuthLoginClick */ import './publicpath.js'; import './polyfills.js'; import Vue from 'vue'; import 'jquery.are-you-sure'; import './vendor/semanticdropdown.js'; import {svg} from './utils.js'; import initContextPopups from './features/contextpopup.js'; import initGitGraph from './features/gitgraph.js'; import initClipboard from './features/clipboard.js'; import initUserHeatmap from './features/userheatmap.js'; import initDateTimePicker from './features/datetimepicker.js'; import initServiceWorker from './features/serviceworker.js'; import {initTribute, issuesTribute, emojiTribute} from './features/tribute.js'; import createDropzone from './features/dropzone.js'; import highlight from './features/highlight.js'; import ActivityTopAuthors from './components/ActivityTopAuthors.vue'; import {initNotificationsTable, initNotificationCount} from './features/notification.js'; import {createCodeEditor} from './features/codeeditor.js'; const {AppSubUrl, StaticUrlPrefix, csrf} = window.config; function htmlEncode(text) { return jQuery('
').text(text).html(); } let previewFileModes; const commentMDEditors = {}; // Silence fomantic's error logging when tabs are used without a target content element $.fn.tab.settings.silent = true; function initCommentPreviewTab($form) { const $tabMenu = $form.find('.tabular.menu'); $tabMenu.find('.item').tab(); $tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`).on('click', function () { const $this = $(this); $.post($this.data('url'), { _csrf: csrf, mode: 'comment', context: $this.data('context'), text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val() }, (data) => { const $previewPanel = $form.find(`.tab[data-tab="${$tabMenu.data('preview')}"]`); $previewPanel.html(data); $('pre code', $previewPanel[0]).each(function () { highlight(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.on('click', function () { const $this = $(this); let context = `${$this.data('context')}/`; const mode = $this.data('markdown-mode') || 'comment'; const treePathEl = $form.find('input#tree_path'); if (treePathEl.length > 0) { context += treePathEl.val(); } context = context.substring(0, context.lastIndexOf('/')); $.post($this.data('url'), { _csrf: csrf, mode, context, text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val() }, (data) => { const $previewPanel = $form.find(`.tab[data-tab="${$tabMenu.data('preview')}"]`); $previewPanel.html(data); $('pre code', $previewPanel[0]).each(function () { highlight(this); }); }); }); } } function initEditDiffTab($form) { const $tabMenu = $form.find('.tabular.menu'); $tabMenu.find('.item').tab(); $tabMenu.find(`.item[data-tab="${$tabMenu.data('diff')}"]`).on('click', function () { const $this = $(this); $.post($this.data('url'), { _csrf: csrf, context: $this.data('context'), content: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val() }, (data) => { const $diffPreviewPanel = $form.find(`.tab[data-tab="${$tabMenu.data('diff')}"]`); $diffPreviewPanel.html(data); }); }); } 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 () { $($(this).data('id-selector')).val($(this).data('id')); $selectBranch.find('.ui .branch-name').text($(this).data('name')); }); $selectBranch.find('.reference.column').on('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 initLabelEdit() { // Create label const $newLabelPanel = $('.new-label.segment'); $('.new-label.button').on('click', () => { $newLabelPanel.show(); }); $('.new-label.segment .cancel').on('click', () => { $newLabelPanel.hide(); }); $('.color-picker').each(function () { $(this).minicolors(); }); $('.precolors .color').on('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').on('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').trigger('submit'); } }).modal('show'); return false; }); } function updateIssuesMeta(url, action, issueIds, elementId, isAdd) { return new Promise(((resolve) => { $.ajax({ type: 'POST', url, data: { _csrf: csrf, action, issue_ids: issueIds, id: elementId, is_add: isAdd }, 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: `${AppSubUrl}/${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 || resp.html === '') && 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); 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.includes('image')) 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.addEventListener('load', () => { if (xhr.status === 200) { callback(xhr.responseText); } }); xhr.open('post', `${AppSubUrl}/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}](${AppSubUrl}/attachments/${data.uuid})`); const input = $(``).val(data.uuid); $('.files').append(input); }); }); }, false); }); } function initSimpleMDEImagePaste(simplemde, files) { simplemde.codemirror.on('paste', (_, event) => { retrieveImageFromClipboardAsBlob(event, (img) => { const name = img.name.substr(0, img.name.lastIndexOf('.')); uploadFile(img, (res) => { const data = JSON.parse(res); const pos = simplemde.codemirror.getCursor(); simplemde.codemirror.replaceRange(`![${name}](${AppSubUrl}/attachments/${data.uuid})`, pos); const input = $(``).val(data.uuid); files.append(input); }); }); }); } let autoSimpleMDE; function initCommentForm() { if ($('.comment.form').length === 0) { return; } autoSimpleMDE = setCommentSimpleMDE($('.comment.form textarea:not(.review-textarea)')); 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, label['is-checked'] ); promises.push(promise); }); Promise.all(promises).then(reload); } }); $listMenu.find('.item:not(.no-select)').on('click', function () { // we don't need the action attribute when updating assignees if (selector === 'select-assignees-modify' || selector === 'select-reviewers-modify') { // UI magic. We need to do this here, otherwise it would destroy the functionality of // adding/removing labels if ($(this).data('can-change') === 'block') { return false; } if ($(this).hasClass('checked')) { $(this).removeClass('checked'); $(this).find('.octicon-check').addClass('invisible'); $(this).data('is-checked', 'remove'); } else { $(this).addClass('checked'); $(this).find('.octicon-check').removeClass('invisible'); $(this).data('is-checked', 'add'); } updateIssuesMeta( $listMenu.data('update-url'), '', $listMenu.data('issue-id'), $(this).data('id'), $(this).data('is-checked') ); $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-check').addClass('invisible'); 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-check').removeClass('invisible'); 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').on('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').addClass('invisible'); $(this).data('is-checked', 'remove'); }); $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'); initListSubmits('select-reviewers-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)').on('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'), $(this).data('is-checked') ).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').on('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'), $(this).data('is-checked') ).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').on('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').on('change', function () { if ($(this).is(':checked')) { $('#disable-gravatar').checkbox('check'); $('#federated-avatar-lookup').checkbox('uncheck'); } }); $('#disable-gravatar input').on('change', function () { if ($(this).is(':checked')) { $('#federated-avatar-lookup').checkbox('uncheck'); } else { $('#offline-mode').checkbox('uncheck'); } }); $('#federated-avatar-lookup input').on('change', function () { if ($(this).is(':checked')) { $('#disable-gravatar').checkbox('uncheck'); $('#offline-mode').checkbox('uncheck'); } }); $('#enable-openid-signin input').on('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').on('change', function () { if ($(this).is(':checked')) { $('#enable-captcha').checkbox('uncheck'); $('#enable-openid-signup').checkbox('uncheck'); } else { $('#enable-openid-signup').checkbox('check'); } }); $('#enable-captcha input').on('change', function () { if ($(this).is(':checked')) { $('#disable-registration').checkbox('uncheck'); } }); } function initIssueComments() { if ($('.repository.view.issue .timeline').length === 0) return; $('.re-request-review').on('click', function (event) { const url = $(this).data('update-url'); const issueId = $(this).data('issue-id'); const id = $(this).data('id'); const isChecked = $(this).data('is-checked'); event.preventDefault(); updateIssuesMeta( url, '', issueId, id, isChecked ).then(reload); }); $(document).on('click', (event) => { const urlTarget = $(':target'); if (urlTarget.length === 0) return; const urlTargetId = urlTarget.attr('id'); if (!urlTargetId) return; if (!/^(issue|pull)(comment)?-\d+$/.test(urlTargetId)) return; const $target = $(event.target); if ($target.closest(`#${urlTargetId}`).length === 0) { const scrollPosition = $(window).scrollTop(); window.location.hash = ''; $(window).scrollTop(scrollPosition); window.history.pushState(null, null, ' '); } }); } async 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) { // Enable or select internal/external wiki system and issue tracker. $('.enable-system').on('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').on('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) { initLabelEdit(); } // Milestones if ($('.repository.new.milestone').length > 0) { const $datepicker = $('.milestone.datepicker'); await initDateTimePicker($datepicker.data('lang')); $datepicker.datetimepicker({ inline: true, timepicker: false, startDate: $datepicker.data('start-date'), onSelectDate(date) { $('#deadline').val(date.toISOString().substring(0, 10)); }, }); $('#clear-date').on('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(); $('#pull-desc').toggle(); $('#pull-desc-edit').toggle(); $('.in-edit').toggle(); $editInput.focus(); return false; }; const changeBranchSelect = function () { const selectionTextField = $('#pull-target-branch'); const baseName = selectionTextField.data('basename'); const branchNameNew = $(this).data('branch'); const branchNameOld = selectionTextField.data('branch'); // Replace branch name to keep translation from HTML template selectionTextField.html(selectionTextField.html().replace( `${baseName}:${branchNameOld}`, `${baseName}:${branchNameNew}` )); selectionTextField.data('branch', branchNameNew); // update branch name in setting }; $('#branch-select > .item').on('click', changeBranchSelect); $('#edit-title').on('click', editTitleToggle); $('#cancel-edit-title').on('click', editTitleToggle); $('#save-edit-title').on('click', editTitleToggle).on('click', function () { const pullrequest_targetbranch_change = function (update_url) { const targetBranch = $('#pull-target-branch').data('branch'); const $branchTarget = $('#branch_target'); if (targetBranch === $branchTarget.text()) { return false; } $.post(update_url, { _csrf: csrf, target_branch: targetBranch }).done((data) => { $branchTarget.text(data.base_branch); }).always(() => { reload(); }); }; const pullrequest_target_update_url = $(this).data('target-update-url'); if ($editInput.val().length === 0 || $editInput.val() === $issueTitle.text()) { $editInput.val($issueTitle.text()); pullrequest_targetbranch_change(pullrequest_target_update_url); } else { $.post($(this).data('update-url'), { _csrf: csrf, title: $editInput.val() }, (data) => { $editInput.val(data.title); $issueTitle.text(data.title); pullrequest_targetbranch_change(pullrequest_target_update_url); reload(); }); } return false; }); // Issue Comments initIssueComments(); // Issue/PR Context Menus $('.context-dropdown').dropdown({ action: 'hide' }); // Quote reply $('.quote-reply').on('click', function (event) { $(this).closest('.dropdown').find('.menu').toggle('visible'); const target = $(this).data('target'); const quote = $(`#comment-${target}`).text().replace(/\n/g, '\n> '); const content = `> ${quote}\n\n`; let $content; if ($(this).hasClass('quote-reply-diff')) { const $parent = $(this).closest('.comment-code-cloud'); $parent.find('button.comment-form-reply').trigger('click'); $content = $parent.find('[name="content"]'); if ($content.val() !== '') { $content.val(`${$content.val()}\n\n${content}`); } else { $content.val(`${content}`); } $content.focus(); } else if (autoSimpleMDE !== null) { if (autoSimpleMDE.value() !== '') { autoSimpleMDE.value(`${autoSimpleMDE.value()}\n\n${content}`); } else { autoSimpleMDE.value(`${content}`); } } event.preventDefault(); }); // Edit issue or comment content $('.edit-content').on('click', async function (event) { $(this).closest('.dropdown').find('.menu').toggle('visible'); const $segment = $(this).closest('.header').next(); const $editContentZone = $segment.find('.edit-content-zone'); const $renderContent = $segment.find('.render-content'); const $rawContent = $segment.find('.raw-content'); let $textarea; let $simplemde; // 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()); let dz; const $dropzone = $editContentZone.find('.dropzone'); const $files = $editContentZone.find('.comment-files'); if ($dropzone.length > 0) { $dropzone.data('saved', false); const filenameDict = {}; dz = await createDropzone($dropzone[0], { 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) => { dz.removeAllFiles(true); $files.empty(); $.each(data, function () { const imgSrc = `${$dropzone.data('upload-url')}/${this.uuid}`; dz.emit('addedfile', this); dz.emit('thumbnail', this, imgSrc); dz.emit('complete', this); dz.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); }); }); }); } }); dz.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').attr('data-tab', $editContentZone.data('write')); $editContentForm.find('.preview').attr('data-tab', $editContentZone.data('preview')); $simplemde = setCommentSimpleMDE($textarea); commentMDEditors[$editContentZone.data('write')] = $simplemde; initCommentPreviewTab($editContentForm); initSimpleMDEImagePaste($simplemde, $files); $editContentZone.find('.cancel.button').on('click', () => { $renderContent.show(); $editContentZone.hide(); dz.emit('reload'); }); $editContentZone.find('.save.button').on('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); $('pre code', $renderContent[0]).each(function () { highlight(this); }); } const $content = $segment.parent(); if (!$content.find('.ui.small.images').length) { if (data.attachments !== '') { $content.append( '