Skip to content

Commit

Permalink
Merge remote-tracking branch 'giteaofficial/main'
Browse files Browse the repository at this point in the history
* giteaofficial/main:
  Fix avatar radius problem on the new issue page (go-gitea#31506)
  Make toast support preventDuplicates (go-gitea#31501)
  Improve attachment upload methods (go-gitea#30513)
  • Loading branch information
zjjhot committed Jun 28, 2024
2 parents b71ae6f + d655ff1 commit b9bbd74
Show file tree
Hide file tree
Showing 18 changed files with 258 additions and 139 deletions.
11 changes: 0 additions & 11 deletions templates/devtest/gitea-ui.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -182,15 +182,6 @@
</div>
</div>

<div>
<h1>Toast</h1>
<div>
<button class="ui button" id="info-toast">Show Info Toast</button>
<button class="ui button" id="warning-toast">Show Warning Toast</button>
<button class="ui button" id="error-toast">Show Error Toast</button>
</div>
</div>

<div>
<h1>ComboMarkdownEditor</h1>
<div>ps: no JS code attached, so just a layout</div>
Expand All @@ -201,7 +192,5 @@
<div>
<button class="{{if true}}tw-bg-red{{end}} tw-p-5 tw-border tw-rounded hover:tw-bg-blue active:tw-bg-yellow">Button</button>
</div>

<script src="{{AssetUrlPrefix}}/js/devtest.js?v={{AssetVersion}}"></script>
</div>
{{template "base/footer" .}}
15 changes: 15 additions & 0 deletions templates/devtest/toast.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{{template "base/head" .}}

<div>
<h1>Toast</h1>
<div>
<button class="ui button toast-test-button" data-toast-level="info" data-toast-message="test info">Show Info Toast</button>
<button class="ui button toast-test-button" data-toast-level="warning" data-toast-message="test warning">Show Warning Toast</button>
<button class="ui button toast-test-button" data-toast-level="error" data-toast-message="test error">Show Error Toast</button>
<button class="ui button toast-test-button" data-toast-level="error" data-toast-message="very looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong message">Show Error Toast (long)</button>
</div>
</div>

<script src="{{AssetUrlPrefix}}/js/devtest.js?v={{AssetVersion}}"></script>

{{template "base/footer" .}}
10 changes: 6 additions & 4 deletions web_src/css/modules/animations.css
Original file line number Diff line number Diff line change
Expand Up @@ -92,20 +92,22 @@ code.language-math.is-loading::after {
}
}

@keyframes pulse {
/* 1p5 means 1-point-5. it can't use "pulse" here, otherwise the animation is not right (maybe due to some conflicts */
@keyframes pulse-1p5 {
0% {
transform: scale(1);
}
50% {
transform: scale(1.8);
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}

.pulse {
animation: pulse 2s linear;
/* pulse animation for scale(1.5) in 200ms */
.pulse-1p5-200 {
animation: pulse-1p5 200ms linear;
}

.ui.modal,
Expand Down
26 changes: 20 additions & 6 deletions web_src/css/modules/toast.css
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,31 @@
overflow-wrap: anywhere;
}

.toast-close,
.toast-icon {
color: currentcolor;
.toast-close {
border-radius: var(--border-radius);
background: transparent;
border: none;
display: flex;
width: 30px;
height: 30px;
justify-content: center;
}

.toast-icon {
display: inline-flex;
width: 30px;
height: 30px;
align-items: center;
justify-content: center;
}

.toast-duplicate-number::before {
content: "(";
}
.toast-duplicate-number {
display: inline-block;
margin-right: 5px;
user-select: none;
}
.toast-duplicate-number::after {
content: ")";
}

.toast-close:hover {
Expand Down
2 changes: 1 addition & 1 deletion web_src/css/repo.css
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,7 @@ td .commit-summary {
min-width: 100px;
}

#new-issue .avatar {
#new-issue .comment .avatar {
width: 3em;
}

Expand Down
10 changes: 5 additions & 5 deletions web_src/js/features/comp/ComboMarkdownEditor.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ import '@github/text-expander-element';
import $ from 'jquery';
import {attachTribute} from '../tribute.js';
import {hideElem, showElem, autosize, isElemVisible} from '../../utils/dom.js';
import {initEasyMDEPaste, initTextareaPaste} from './Paste.js';
import {initEasyMDEPaste, initTextareaUpload} from './EditorUpload.js';
import {handleGlobalEnterQuickSubmit} from './QuickSubmit.js';
import {renderPreviewPanelContent} from '../repo-editor.js';
import {easyMDEToolbarActions} from './EasyMDEToolbarActions.js';
import {initTextExpander} from './TextExpander.js';
import {showErrorToast} from '../../modules/toast.js';
import {POST} from '../../modules/fetch.js';
import {initTextareaMarkdown} from './EditorMarkdown.js';
import {initDropzone} from '../dropzone.js';
import {DropzoneCustomEventReloadFiles, initDropzone} from '../dropzone.js';

let elementIdCounter = 0;

Expand Down Expand Up @@ -111,7 +111,7 @@ class ComboMarkdownEditor {

initTextareaMarkdown(this.textarea);
if (this.dropzone) {
initTextareaPaste(this.textarea, this.dropzone);
initTextareaUpload(this.textarea, this.dropzone);
}
}

Expand All @@ -130,13 +130,13 @@ class ComboMarkdownEditor {

dropzoneReloadFiles() {
if (!this.dropzone) return;
this.attachedDropzoneInst.emit('reload');
this.attachedDropzoneInst.emit(DropzoneCustomEventReloadFiles);
}

dropzoneSubmitReload() {
if (!this.dropzone) return;
this.attachedDropzoneInst.emit('submit');
this.attachedDropzoneInst.emit('reload');
this.attachedDropzoneInst.emit(DropzoneCustomEventReloadFiles);
}

setupTab() {
Expand Down
4 changes: 3 additions & 1 deletion web_src/js/features/comp/EditorMarkdown.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {triggerEditorContentChanged} from './Paste.js';
export function triggerEditorContentChanged(target) {
target.dispatchEvent(new CustomEvent('ce-editor-content-changed', {bubbles: true}));
}

function handleIndentSelection(textarea, e) {
const selStart = textarea.selectionStart;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,29 @@
import {htmlEscape} from 'escape-goat';
import {POST} from '../../modules/fetch.js';
import {imageInfo} from '../../utils/image.js';
import {getPastedContent, replaceTextareaSelection} from '../../utils/dom.js';
import {replaceTextareaSelection} from '../../utils/dom.js';
import {isUrl} from '../../utils/url.js';

async function uploadFile(file, uploadUrl) {
const formData = new FormData();
formData.append('file', file, file.name);

const res = await POST(uploadUrl, {data: formData});
return await res.json();
}

export function triggerEditorContentChanged(target) {
target.dispatchEvent(new CustomEvent('ce-editor-content-changed', {bubbles: true}));
import {triggerEditorContentChanged} from './EditorMarkdown.js';
import {
DropzoneCustomEventRemovedFile,
DropzoneCustomEventUploadDone,
generateMarkdownLinkForAttachment,
} from '../dropzone.js';

let uploadIdCounter = 0;

function uploadFile(dropzoneEl, file) {
return new Promise((resolve) => {
const curUploadId = uploadIdCounter++;
file._giteaUploadId = curUploadId;
const dropzoneInst = dropzoneEl.dropzone;
const onUploadDone = ({file}) => {
if (file._giteaUploadId === curUploadId) {
dropzoneInst.off(DropzoneCustomEventUploadDone, onUploadDone);
resolve();
}
};
dropzoneInst.on(DropzoneCustomEventUploadDone, onUploadDone);
dropzoneInst.handleFiles([file]);
});
}

class TextareaEditor {
Expand Down Expand Up @@ -82,48 +92,25 @@ class CodeMirrorEditor {
}
}

async function handleClipboardImages(editor, dropzone, images, e) {
const uploadUrl = dropzone.getAttribute('data-upload-url');
const filesContainer = dropzone.querySelector('.files');

if (!dropzone || !uploadUrl || !filesContainer || !images.length) return;

async function handleUploadFiles(editor, dropzoneEl, files, e) {
e.preventDefault();
e.stopPropagation();

for (const img of images) {
const name = img.name.slice(0, img.name.lastIndexOf('.'));
for (const file of files) {
const name = file.name.slice(0, file.name.lastIndexOf('.'));
const {width, dppx} = await imageInfo(file);
const placeholder = `[${name}](uploading ...)`;

const placeholder = `![${name}](uploading ...)`;
editor.insertPlaceholder(placeholder);

const {uuid} = await uploadFile(img, uploadUrl);
const {width, dppx} = await imageInfo(img);

let text;
if (width > 0 && dppx > 1) {
// Scale down images from HiDPI monitors. This uses the <img> tag because it's the only
// method to change image size in Markdown that is supported by all implementations.
// Make the image link relative to the repo path, then the final URL is "/sub-path/owner/repo/attachments/{uuid}"
const url = `attachments/${uuid}`;
text = `<img width="${Math.round(width / dppx)}" alt="${htmlEscape(name)}" src="${htmlEscape(url)}">`;
} else {
// Markdown always renders the image with a relative path, so the final URL is "/sub-path/owner/repo/attachments/{uuid}"
// TODO: it should also use relative path for consistency, because absolute is ambiguous for "/sub-path/attachments" or "/attachments"
const url = `/attachments/${uuid}`;
text = `![${name}](${url})`;
}
editor.replacePlaceholder(placeholder, text);

const input = document.createElement('input');
input.setAttribute('name', 'files');
input.setAttribute('type', 'hidden');
input.setAttribute('id', uuid);
input.value = uuid;
filesContainer.append(input);
await uploadFile(dropzoneEl, file); // the "file" will get its "uuid" during the upload
editor.replacePlaceholder(placeholder, generateMarkdownLinkForAttachment(file, {width, dppx}));
}
}

export function removeAttachmentLinksFromMarkdown(text, fileUuid) {
text = text.replace(new RegExp(`!?\\[([^\\]]+)\\]\\(/?attachments/${fileUuid}\\)`, 'g'), '');
text = text.replace(new RegExp(`<img[^>]+src="/?attachments/${fileUuid}"[^>]*>`, 'g'), '');
return text;
}

function handleClipboardText(textarea, e, {text, isShiftDown}) {
// pasting with "shift" means "paste as original content" in most applications
if (isShiftDown) return; // let the browser handle it
Expand All @@ -139,16 +126,37 @@ function handleClipboardText(textarea, e, {text, isShiftDown}) {
// else, let the browser handle it
}

export function initEasyMDEPaste(easyMDE, dropzone) {
// extract text and images from "paste" event
function getPastedContent(e) {
const images = [];
for (const item of e.clipboardData?.items ?? []) {
if (item.type?.startsWith('image/')) {
images.push(item.getAsFile());
}
}
const text = e.clipboardData?.getData?.('text') ?? '';
return {text, images};
}

export function initEasyMDEPaste(easyMDE, dropzoneEl) {
const editor = new CodeMirrorEditor(easyMDE.codemirror);
easyMDE.codemirror.on('paste', (_, e) => {
const {images} = getPastedContent(e);
if (images.length) {
handleClipboardImages(new CodeMirrorEditor(easyMDE.codemirror), dropzone, images, e);
}
if (!images.length) return;
handleUploadFiles(editor, dropzoneEl, images, e);
});
easyMDE.codemirror.on('drop', (_, e) => {
if (!e.dataTransfer.files.length) return;
handleUploadFiles(editor, dropzoneEl, e.dataTransfer.files, e);
});
dropzoneEl.dropzone.on(DropzoneCustomEventRemovedFile, ({fileUuid}) => {
const oldText = easyMDE.codemirror.getValue();
const newText = removeAttachmentLinksFromMarkdown(oldText, fileUuid);
if (oldText !== newText) easyMDE.codemirror.setValue(newText);
});
}

export function initTextareaPaste(textarea, dropzone) {
export function initTextareaUpload(textarea, dropzoneEl) {
let isShiftDown = false;
textarea.addEventListener('keydown', (e) => {
if (e.shiftKey) isShiftDown = true;
Expand All @@ -159,9 +167,17 @@ export function initTextareaPaste(textarea, dropzone) {
textarea.addEventListener('paste', (e) => {
const {images, text} = getPastedContent(e);
if (images.length) {
handleClipboardImages(new TextareaEditor(textarea), dropzone, images, e);
handleUploadFiles(new TextareaEditor(textarea), dropzoneEl, images, e);
} else if (text) {
handleClipboardText(textarea, e, {text, isShiftDown});
}
});
textarea.addEventListener('drop', (e) => {
if (!e.dataTransfer.files.length) return;
handleUploadFiles(new TextareaEditor(textarea), dropzoneEl, e.dataTransfer.files, e);
});
dropzoneEl.dropzone.on(DropzoneCustomEventRemovedFile, ({fileUuid}) => {
const newText = removeAttachmentLinksFromMarkdown(textarea.value, fileUuid);
if (textarea.value !== newText) textarea.value = newText;
});
}
14 changes: 14 additions & 0 deletions web_src/js/features/comp/EditorUpload.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {removeAttachmentLinksFromMarkdown} from './EditorUpload.js';

test('removeAttachmentLinksFromMarkdown', () => {
expect(removeAttachmentLinksFromMarkdown('a foo b', 'foo')).toBe('a foo b');
expect(removeAttachmentLinksFromMarkdown('a [x](attachments/foo) b', 'foo')).toBe('a b');
expect(removeAttachmentLinksFromMarkdown('a ![x](attachments/foo) b', 'foo')).toBe('a b');
expect(removeAttachmentLinksFromMarkdown('a [x](/attachments/foo) b', 'foo')).toBe('a b');
expect(removeAttachmentLinksFromMarkdown('a ![x](/attachments/foo) b', 'foo')).toBe('a b');

expect(removeAttachmentLinksFromMarkdown('a <img src="attachments/foo"> b', 'foo')).toBe('a b');
expect(removeAttachmentLinksFromMarkdown('a <img width="100" src="attachments/foo"> b', 'foo')).toBe('a b');
expect(removeAttachmentLinksFromMarkdown('a <img src="/attachments/foo"> b', 'foo')).toBe('a b');
expect(removeAttachmentLinksFromMarkdown('a <img src="/attachments/foo" width="100"/> b', 'foo')).toBe('a b');
});
Loading

0 comments on commit b9bbd74

Please sign in to comment.