forked from hinterland/hearth
feat: vendor gitea 1.16.2
This commit is contained in:
@@ -10,6 +10,7 @@ import {
|
||||
} from './EditorUpload.ts';
|
||||
import {handleGlobalEnterQuickSubmit} from './QuickSubmit.ts';
|
||||
import {renderPreviewPanelContent} from '../repo-editor.ts';
|
||||
import {toggleTasklistCheckbox} from '../../markup/tasklist.ts';
|
||||
import {easyMDEToolbarActions} from './EasyMDEToolbarActions.ts';
|
||||
import {initTextExpander} from './TextExpander.ts';
|
||||
import {showErrorToast} from '../../modules/toast.ts';
|
||||
@@ -17,13 +18,14 @@ import {POST} from '../../modules/fetch.ts';
|
||||
import {
|
||||
EventEditorContentChanged,
|
||||
initTextareaMarkdown,
|
||||
textareaInsertText,
|
||||
replaceTextareaSelection,
|
||||
triggerEditorContentChanged,
|
||||
} from './EditorMarkdown.ts';
|
||||
import {DropzoneCustomEventReloadFiles, initDropzone} from '../dropzone.ts';
|
||||
import {createTippy} from '../../modules/tippy.ts';
|
||||
import {fomanticQuery} from '../../modules/fomantic/base.ts';
|
||||
import type EasyMDE from 'easymde';
|
||||
import {localUserSettings} from '../../modules/user-settings.ts';
|
||||
|
||||
/**
|
||||
* validate if the given textarea is non-empty.
|
||||
@@ -81,7 +83,9 @@ export class ComboMarkdownEditor {
|
||||
textareaMarkdownToolbar: HTMLElement;
|
||||
textareaAutosize: any;
|
||||
|
||||
dropzone: HTMLElement;
|
||||
buttonMonospace: HTMLButtonElement;
|
||||
|
||||
dropzone: HTMLElement | null;
|
||||
attachedDropzoneInst: any;
|
||||
|
||||
previewMode: string;
|
||||
@@ -105,7 +109,7 @@ export class ComboMarkdownEditor {
|
||||
await this.switchToUserPreference();
|
||||
}
|
||||
|
||||
applyEditorHeights(el: HTMLElement, heights: Heights) {
|
||||
applyEditorHeights(el: HTMLElement, heights: Heights | undefined) {
|
||||
if (!heights) return;
|
||||
if (heights.minHeight) el.style.minHeight = heights.minHeight;
|
||||
if (heights.height) el.style.height = heights.height;
|
||||
@@ -114,14 +118,14 @@ export class ComboMarkdownEditor {
|
||||
|
||||
setupContainer() {
|
||||
this.supportEasyMDE = this.container.getAttribute('data-support-easy-mde') === 'true';
|
||||
this.previewMode = this.container.getAttribute('data-content-mode');
|
||||
this.previewUrl = this.container.getAttribute('data-preview-url');
|
||||
this.previewContext = this.container.getAttribute('data-preview-context');
|
||||
initTextExpander(this.container.querySelector('text-expander'));
|
||||
this.previewMode = this.container.getAttribute('data-content-mode')!;
|
||||
this.previewUrl = this.container.getAttribute('data-preview-url')!;
|
||||
this.previewContext = this.container.getAttribute('data-preview-context')!;
|
||||
initTextExpander(this.container.querySelector('text-expander')!);
|
||||
}
|
||||
|
||||
setupTextarea() {
|
||||
this.textarea = this.container.querySelector('.markdown-text-editor');
|
||||
this.textarea = this.container.querySelector('.markdown-text-editor')!;
|
||||
this.textarea._giteaComboMarkdownEditor = this;
|
||||
this.textarea.id = generateElemId(`_combo_markdown_editor_`);
|
||||
this.textarea.addEventListener('input', () => triggerEditorContentChanged(this.container));
|
||||
@@ -131,7 +135,7 @@ export class ComboMarkdownEditor {
|
||||
this.textareaAutosize = autosize(this.textarea, {viewportMarginBottom: 130});
|
||||
}
|
||||
|
||||
this.textareaMarkdownToolbar = this.container.querySelector('markdown-toolbar');
|
||||
this.textareaMarkdownToolbar = this.container.querySelector('markdown-toolbar')!;
|
||||
this.textareaMarkdownToolbar.setAttribute('for', this.textarea.id);
|
||||
for (const el of this.textareaMarkdownToolbar.querySelectorAll('.markdown-toolbar-button')) {
|
||||
// upstream bug: The role code is never executed in base MarkdownButtonElement https://github.com/github/markdown-toolbar-element/issues/70
|
||||
@@ -140,23 +144,17 @@ export class ComboMarkdownEditor {
|
||||
if (el.nodeName === 'BUTTON' && !el.getAttribute('type')) el.setAttribute('type', 'button');
|
||||
}
|
||||
|
||||
const monospaceButton = this.container.querySelector('.markdown-switch-monospace');
|
||||
const monospaceEnabled = localStorage?.getItem('markdown-editor-monospace') === 'true';
|
||||
const monospaceText = monospaceButton.getAttribute(monospaceEnabled ? 'data-disable-text' : 'data-enable-text');
|
||||
monospaceButton.setAttribute('data-tooltip-content', monospaceText);
|
||||
monospaceButton.setAttribute('aria-checked', String(monospaceEnabled));
|
||||
monospaceButton.addEventListener('click', (e) => {
|
||||
this.buttonMonospace = this.container.querySelector('.markdown-switch-monospace')!;
|
||||
this.applyMonospace();
|
||||
this.buttonMonospace.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const enabled = localStorage?.getItem('markdown-editor-monospace') !== 'true';
|
||||
localStorage.setItem('markdown-editor-monospace', String(enabled));
|
||||
this.textarea.classList.toggle('tw-font-mono', enabled);
|
||||
const text = monospaceButton.getAttribute(enabled ? 'data-disable-text' : 'data-enable-text');
|
||||
monospaceButton.setAttribute('data-tooltip-content', text);
|
||||
monospaceButton.setAttribute('aria-checked', String(enabled));
|
||||
const enabled = !localUserSettings.getBoolean('markdown-editor-monospace');
|
||||
localUserSettings.setBoolean('markdown-editor-monospace', enabled);
|
||||
applyMonospaceToAllEditors();
|
||||
});
|
||||
|
||||
if (this.supportEasyMDE) {
|
||||
const easymdeButton = this.container.querySelector('.markdown-switch-easymde');
|
||||
const easymdeButton = this.container.querySelector('.markdown-switch-easymde')!;
|
||||
easymdeButton.addEventListener('click', async (e) => {
|
||||
e.preventDefault();
|
||||
this.userPreferredEditor = 'easymde';
|
||||
@@ -173,7 +171,7 @@ export class ComboMarkdownEditor {
|
||||
async setupDropzone() {
|
||||
const dropzoneParentContainer = this.container.getAttribute('data-dropzone-parent-container');
|
||||
if (!dropzoneParentContainer) return;
|
||||
this.dropzone = this.container.closest(this.container.getAttribute('data-dropzone-parent-container'))?.querySelector('.dropzone');
|
||||
this.dropzone = this.container.closest(this.container.getAttribute('data-dropzone-parent-container')!)?.querySelector('.dropzone') ?? null;
|
||||
if (!this.dropzone) return;
|
||||
|
||||
this.attachedDropzoneInst = await initDropzone(this.dropzone);
|
||||
@@ -212,13 +210,14 @@ export class ComboMarkdownEditor {
|
||||
// Fomantic Tab requires the "data-tab" to be globally unique.
|
||||
// So here it uses our defined "data-tab-for" and "data-tab-panel" to generate the "data-tab" attribute for Fomantic.
|
||||
const tabIdSuffix = generateElemId();
|
||||
this.tabEditor = Array.from(tabs).find((tab) => tab.getAttribute('data-tab-for') === 'markdown-writer');
|
||||
this.tabPreviewer = Array.from(tabs).find((tab) => tab.getAttribute('data-tab-for') === 'markdown-previewer');
|
||||
const tabsArr = Array.from(tabs);
|
||||
this.tabEditor = tabsArr.find((tab) => tab.getAttribute('data-tab-for') === 'markdown-writer')!;
|
||||
this.tabPreviewer = tabsArr.find((tab) => tab.getAttribute('data-tab-for') === 'markdown-previewer')!;
|
||||
this.tabEditor.setAttribute('data-tab', `markdown-writer-${tabIdSuffix}`);
|
||||
this.tabPreviewer.setAttribute('data-tab', `markdown-previewer-${tabIdSuffix}`);
|
||||
|
||||
const panelEditor = this.container.querySelector('.ui.tab[data-tab-panel="markdown-writer"]');
|
||||
const panelPreviewer = this.container.querySelector('.ui.tab[data-tab-panel="markdown-previewer"]');
|
||||
const panelEditor = this.container.querySelector('.ui.tab[data-tab-panel="markdown-writer"]')!;
|
||||
const panelPreviewer = this.container.querySelector('.ui.tab[data-tab-panel="markdown-previewer"]')!;
|
||||
panelEditor.setAttribute('data-tab', `markdown-writer-${tabIdSuffix}`);
|
||||
panelPreviewer.setAttribute('data-tab', `markdown-previewer-${tabIdSuffix}`);
|
||||
|
||||
@@ -238,6 +237,20 @@ export class ComboMarkdownEditor {
|
||||
const response = await POST(this.previewUrl, {data: formData});
|
||||
const data = await response.text();
|
||||
renderPreviewPanelContent(panelPreviewer, data);
|
||||
// enable task list checkboxes in preview and sync state back to the editor
|
||||
for (const checkbox of panelPreviewer.querySelectorAll<HTMLInputElement>('.task-list-item input[type=checkbox]')) {
|
||||
checkbox.disabled = false;
|
||||
checkbox.addEventListener('input', () => {
|
||||
const position = parseInt(checkbox.getAttribute('data-source-position')!) + 1;
|
||||
const newContent = toggleTasklistCheckbox(this.value(), position, checkbox.checked);
|
||||
if (newContent === null) {
|
||||
checkbox.checked = !checkbox.checked;
|
||||
return;
|
||||
}
|
||||
this.value(newContent);
|
||||
triggerEditorContentChanged(this.container);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -254,8 +267,8 @@ export class ComboMarkdownEditor {
|
||||
}
|
||||
|
||||
initMarkdownButtonTableAdd() {
|
||||
const addTableButton = this.container.querySelector('.markdown-button-table-add');
|
||||
const addTablePanel = this.container.querySelector('.markdown-add-table-panel');
|
||||
const addTableButton = this.container.querySelector('.markdown-button-table-add')!;
|
||||
const addTablePanel = this.container.querySelector('.markdown-add-table-panel')!;
|
||||
// here the tippy can't attach to the button because the button already owns a tippy for tooltip
|
||||
const addTablePanelTippy = createTippy(addTablePanel, {
|
||||
content: addTablePanel,
|
||||
@@ -267,12 +280,12 @@ export class ComboMarkdownEditor {
|
||||
});
|
||||
addTableButton.addEventListener('click', () => addTablePanelTippy.show());
|
||||
|
||||
addTablePanel.querySelector('.ui.button.primary').addEventListener('click', () => {
|
||||
let rows = parseInt(addTablePanel.querySelector<HTMLInputElement>('[name=rows]').value);
|
||||
let cols = parseInt(addTablePanel.querySelector<HTMLInputElement>('[name=cols]').value);
|
||||
addTablePanel.querySelector('.ui.button.primary')!.addEventListener('click', () => {
|
||||
let rows = parseInt(addTablePanel.querySelector<HTMLInputElement>('.add-table-rows')!.value);
|
||||
let cols = parseInt(addTablePanel.querySelector<HTMLInputElement>('.add-table-cols')!.value);
|
||||
rows = Math.max(1, Math.min(100, rows));
|
||||
cols = Math.max(1, Math.min(100, cols));
|
||||
textareaInsertText(this.textarea, `\n${this.generateMarkdownTable(rows, cols)}\n\n`);
|
||||
replaceTextareaSelection(this.textarea, `\n${this.generateMarkdownTable(rows, cols)}\n\n`);
|
||||
addTablePanelTippy.hide();
|
||||
});
|
||||
}
|
||||
@@ -320,8 +333,10 @@ export class ComboMarkdownEditor {
|
||||
|
||||
async switchToEasyMDE() {
|
||||
if (this.easyMDE) return;
|
||||
// EasyMDE's CSS should be loaded via webpack config, otherwise our own styles can not overwrite the default styles.
|
||||
const {default: EasyMDE} = await import(/* webpackChunkName: "easymde" */'easymde');
|
||||
const [{default: EasyMDE}] = await Promise.all([
|
||||
import('easymde'),
|
||||
import('../../../css/easymde.css'),
|
||||
]);
|
||||
const easyMDEOpt: EasyMDE.Options = {
|
||||
autoDownloadFontAwesome: false,
|
||||
element: this.textarea,
|
||||
@@ -360,7 +375,7 @@ export class ComboMarkdownEditor {
|
||||
}
|
||||
},
|
||||
});
|
||||
this.applyEditorHeights(this.container.querySelector('.CodeMirror-scroll'), this.options.editorHeights);
|
||||
this.applyEditorHeights(this.container.querySelector('.CodeMirror-scroll')!, this.options.editorHeights);
|
||||
await attachTribute(this.easyMDE.codemirror.getInputField());
|
||||
if (this.dropzone) {
|
||||
initEasyMDEPaste(this.easyMDE, this.dropzone);
|
||||
@@ -368,7 +383,7 @@ export class ComboMarkdownEditor {
|
||||
hideElem(this.textareaMarkdownToolbar);
|
||||
}
|
||||
|
||||
value(v: any = undefined) {
|
||||
value(v?: any) {
|
||||
if (v === undefined) {
|
||||
if (this.easyMDE) {
|
||||
return this.easyMDE.value();
|
||||
@@ -401,15 +416,32 @@ export class ComboMarkdownEditor {
|
||||
}
|
||||
}
|
||||
|
||||
get userPreferredEditor() {
|
||||
return window.localStorage.getItem(`markdown-editor-${this.previewMode ?? 'default'}`);
|
||||
get userPreferredEditor(): string {
|
||||
return localUserSettings.getString(`markdown-editor-${this.previewMode ?? 'default'}`);
|
||||
}
|
||||
set userPreferredEditor(s) {
|
||||
window.localStorage.setItem(`markdown-editor-${this.previewMode ?? 'default'}`, s);
|
||||
|
||||
set userPreferredEditor(s: string) {
|
||||
localUserSettings.setString(`markdown-editor-${this.previewMode ?? 'default'}`, s);
|
||||
}
|
||||
|
||||
applyMonospace() {
|
||||
const enabled = localUserSettings.getBoolean('markdown-editor-monospace');
|
||||
const text = this.buttonMonospace.getAttribute(enabled ? 'data-disable-text' : 'data-enable-text')!;
|
||||
this.textarea.classList.toggle('tw-font-mono', enabled);
|
||||
this.buttonMonospace.setAttribute('data-tooltip-content', text);
|
||||
this.buttonMonospace.setAttribute('aria-checked', String(enabled));
|
||||
}
|
||||
}
|
||||
|
||||
export function getComboMarkdownEditor(el: any) {
|
||||
function applyMonospaceToAllEditors() {
|
||||
const editors = document.querySelectorAll<ComboMarkdownEditorContainer>('.combo-markdown-editor');
|
||||
for (const editorContainer of editors) {
|
||||
const editor = getComboMarkdownEditor(editorContainer);
|
||||
if (editor) editor.applyMonospace();
|
||||
}
|
||||
}
|
||||
|
||||
export function getComboMarkdownEditor(el: any): ComboMarkdownEditor | null {
|
||||
if (!el) return null;
|
||||
if (el.length) el = el[0];
|
||||
return el._giteaComboMarkdownEditor;
|
||||
|
||||
@@ -2,6 +2,7 @@ import {svg} from '../../svg.ts';
|
||||
import {html, htmlRaw} from '../../utils/html.ts';
|
||||
import {createElementFromHTML} from '../../utils/dom.ts';
|
||||
import {fomanticQuery} from '../../modules/fomantic/base.ts';
|
||||
import {hideToastsAll} from '../../modules/toast.ts';
|
||||
|
||||
const {i18n} = window.config;
|
||||
|
||||
@@ -27,6 +28,9 @@ export function createConfirmModal({header = '', content = '', confirmButtonColo
|
||||
|
||||
export function confirmModal(modal: HTMLElement | ConfirmModalOptions): Promise<boolean> {
|
||||
if (!(modal instanceof HTMLElement)) modal = createConfirmModal(modal);
|
||||
// hide existing toasts when we need to show a new modal, otherwise the toasts only interfere the UI
|
||||
// it's fine to do so because the modal is triggered by user's explicit action, so the user should already have read the toast messages
|
||||
hideToastsAll();
|
||||
return new Promise((resolve) => {
|
||||
const $modal = fomanticQuery(modal);
|
||||
$modal.modal({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {showElem, type DOMEvent} from '../../utils/dom.ts';
|
||||
import {showElem} from '../../utils/dom.ts';
|
||||
|
||||
type CropperOpts = {
|
||||
container: HTMLElement,
|
||||
@@ -7,7 +7,7 @@ type CropperOpts = {
|
||||
};
|
||||
|
||||
async function initCompCropper({container, fileInput, imageSource}: CropperOpts) {
|
||||
const {default: Cropper} = await import(/* webpackChunkName: "cropperjs" */'cropperjs');
|
||||
const {default: Cropper} = await import('cropperjs');
|
||||
let currentFileName = '';
|
||||
let currentFileLastModified = 0;
|
||||
const cropper = new Cropper(imageSource, {
|
||||
@@ -17,6 +17,7 @@ async function initCompCropper({container, fileInput, imageSource}: CropperOpts)
|
||||
crop() {
|
||||
const canvas = cropper.getCroppedCanvas();
|
||||
canvas.toBlob((blob) => {
|
||||
if (!blob) return;
|
||||
const croppedFileName = currentFileName.replace(/\.[^.]{3,4}$/, '.png');
|
||||
const croppedFile = new File([blob], croppedFileName, {type: 'image/png', lastModified: currentFileLastModified});
|
||||
const dataTransfer = new DataTransfer();
|
||||
@@ -26,9 +27,9 @@ async function initCompCropper({container, fileInput, imageSource}: CropperOpts)
|
||||
},
|
||||
});
|
||||
|
||||
fileInput.addEventListener('input', (e: DOMEvent<Event, HTMLInputElement>) => {
|
||||
const files = e.target.files;
|
||||
if (files?.length > 0) {
|
||||
fileInput.addEventListener('input', (e) => {
|
||||
const files = (e.target as HTMLInputElement).files;
|
||||
if (files?.length) {
|
||||
currentFileName = files[0].name;
|
||||
currentFileLastModified = files[0].lastModified;
|
||||
const fileURL = URL.createObjectURL(files[0]);
|
||||
@@ -42,6 +43,6 @@ async function initCompCropper({container, fileInput, imageSource}: CropperOpts)
|
||||
export async function initAvatarUploaderWithCropper(fileInput: HTMLInputElement) {
|
||||
const panel = fileInput.nextElementSibling as HTMLElement;
|
||||
if (!panel?.matches('.cropper-panel')) throw new Error('Missing cropper panel for avatar uploader');
|
||||
const imageSource = panel.querySelector<HTMLImageElement>('.cropper-source');
|
||||
const imageSource = panel.querySelector<HTMLImageElement>('.cropper-source')!;
|
||||
await initCompCropper({container: panel, fileInput, imageSource});
|
||||
}
|
||||
|
||||
@@ -24,15 +24,15 @@ test('textareaSplitLines', () => {
|
||||
});
|
||||
|
||||
test('markdownHandleIndention', () => {
|
||||
const testInput = (input: string, expected?: string) => {
|
||||
const testInput = (input: string, expected: string | null) => {
|
||||
const inputPos = input.indexOf('|');
|
||||
input = input.replace('|', '');
|
||||
input = input.replaceAll('|', '');
|
||||
const ret = markdownHandleIndention({value: input, selStart: inputPos, selEnd: inputPos});
|
||||
if (expected === null) {
|
||||
expect(ret).toEqual({handled: false});
|
||||
} else {
|
||||
const expectedPos = expected.indexOf('|');
|
||||
expected = expected.replace('|', '');
|
||||
expected = expected.replaceAll('|', '');
|
||||
expect(ret).toEqual({
|
||||
handled: true,
|
||||
valueSelection: {value: expected, selStart: expectedPos, selEnd: expectedPos},
|
||||
@@ -171,9 +171,9 @@ test('EditorMarkdown', () => {
|
||||
pos: number;
|
||||
};
|
||||
const testInput = (input: ValueWithCursor, result: ValueWithCursor) => {
|
||||
const intputValue = typeof input === 'string' ? input : input.value;
|
||||
const inputPos = typeof input === 'string' ? intputValue.length : input.pos;
|
||||
textarea.value = intputValue;
|
||||
const inputValue = typeof input === 'string' ? input : input.value;
|
||||
const inputPos = typeof input === 'string' ? inputValue.length : input.pos;
|
||||
textarea.value = inputValue;
|
||||
textarea.setSelectionRange(inputPos, inputPos);
|
||||
|
||||
const e = new KeyboardEvent('keydown', {key: 'Enter', cancelable: true});
|
||||
|
||||
@@ -4,14 +4,23 @@ export function triggerEditorContentChanged(target: HTMLElement) {
|
||||
target.dispatchEvent(new CustomEvent(EventEditorContentChanged, {bubbles: true}));
|
||||
}
|
||||
|
||||
export function textareaInsertText(textarea: HTMLTextAreaElement, value: string) {
|
||||
const startPos = textarea.selectionStart;
|
||||
const endPos = textarea.selectionEnd;
|
||||
textarea.value = textarea.value.substring(0, startPos) + value + textarea.value.substring(endPos);
|
||||
textarea.selectionStart = startPos;
|
||||
textarea.selectionEnd = startPos + value.length;
|
||||
/** replace selected text or insert text by creating a new edit history entry,
|
||||
* e.g. CTRL-Z works after this */
|
||||
export function replaceTextareaSelection(textarea: HTMLTextAreaElement, text: string) {
|
||||
const before = textarea.value.slice(0, textarea.selectionStart);
|
||||
const after = textarea.value.slice(textarea.selectionEnd);
|
||||
|
||||
textarea.focus();
|
||||
triggerEditorContentChanged(textarea);
|
||||
let success = false;
|
||||
try {
|
||||
success = document.execCommand('insertText', false, text); // eslint-disable-line @typescript-eslint/no-deprecated
|
||||
} catch {}
|
||||
|
||||
// fall back to regular replacement
|
||||
if (!success) {
|
||||
textarea.value = `${before}${text}${after}`;
|
||||
triggerEditorContentChanged(textarea);
|
||||
}
|
||||
}
|
||||
|
||||
type TextareaValueSelection = {
|
||||
@@ -45,7 +54,8 @@ function handleIndentSelection(textarea: HTMLTextAreaElement, e: KeyboardEvent)
|
||||
}
|
||||
|
||||
// re-calculating the selection range
|
||||
let newSelStart, newSelEnd;
|
||||
let newSelStart: number | null = null;
|
||||
let newSelEnd: number | null = null;
|
||||
pos = 0;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (i === selectedLines[0]) {
|
||||
@@ -134,7 +144,7 @@ export function markdownHandleIndention(tvs: TextareaValueSelection): MarkdownHa
|
||||
|
||||
// parse the indention
|
||||
let lineContent = line;
|
||||
const indention = /^\s*/.exec(lineContent)[0];
|
||||
const indention = (/^\s*/.exec(lineContent) || [''])[0];
|
||||
lineContent = lineContent.slice(indention.length);
|
||||
if (linesBuf.inlinePos <= indention.length) return unhandled; // if cursor is at the indention, do nothing, let the browser handle it
|
||||
|
||||
@@ -175,22 +185,45 @@ export function markdownHandleIndention(tvs: TextareaValueSelection): MarkdownHa
|
||||
return {handled: true, valueSelection: {value: linesBuf.lines.join('\n'), selStart: newPos, selEnd: newPos}};
|
||||
}
|
||||
|
||||
function handleNewline(textarea: HTMLTextAreaElement, e: Event) {
|
||||
if ((e as KeyboardEvent).isComposing) return;
|
||||
function handleNewline(textarea: HTMLTextAreaElement, e: KeyboardEvent) {
|
||||
if (e.isComposing) return;
|
||||
const ret = markdownHandleIndention({value: textarea.value, selStart: textarea.selectionStart, selEnd: textarea.selectionEnd});
|
||||
if (!ret.handled) return;
|
||||
if (!ret.handled || !ret.valueSelection) return; // FIXME: the "handled" seems redundant, only valueSelection is enough (null for unhandled)
|
||||
e.preventDefault();
|
||||
textarea.value = ret.valueSelection.value;
|
||||
textarea.setSelectionRange(ret.valueSelection.selStart, ret.valueSelection.selEnd);
|
||||
triggerEditorContentChanged(textarea);
|
||||
}
|
||||
|
||||
// Keys that act as dead keys will not work because the spec dictates that such keys are
|
||||
// emitted as `Dead` in e.key instead of the actual key.
|
||||
const pairs = new Map<string, string>([
|
||||
["'", "'"],
|
||||
['"', '"'],
|
||||
['`', '`'],
|
||||
['(', ')'],
|
||||
['[', ']'],
|
||||
['{', '}'],
|
||||
['<', '>'],
|
||||
]);
|
||||
|
||||
function handlePairCharacter(textarea: HTMLTextAreaElement, e: KeyboardEvent): void {
|
||||
const selStart = textarea.selectionStart;
|
||||
const selEnd = textarea.selectionEnd;
|
||||
if (selEnd === selStart) return; // do not process when no selection
|
||||
e.preventDefault();
|
||||
const inner = textarea.value.substring(selStart, selEnd);
|
||||
replaceTextareaSelection(textarea, `${e.key}${inner}${pairs.get(e.key)}`);
|
||||
textarea.setSelectionRange(selStart + 1, selEnd + 1);
|
||||
}
|
||||
|
||||
function isTextExpanderShown(textarea: HTMLElement): boolean {
|
||||
return Boolean(textarea.closest('text-expander')?.querySelector('.suggestions'));
|
||||
}
|
||||
|
||||
export function initTextareaMarkdown(textarea: HTMLTextAreaElement) {
|
||||
textarea.addEventListener('keydown', (e) => {
|
||||
if (e.isComposing) return;
|
||||
if (isTextExpanderShown(textarea)) return;
|
||||
if (e.key === 'Tab' && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
||||
// use Tab/Shift-Tab to indent/unindent the selected lines
|
||||
@@ -198,6 +231,8 @@ export function initTextareaMarkdown(textarea: HTMLTextAreaElement) {
|
||||
} else if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
||||
// use Enter to insert a new line with the same indention and prefix
|
||||
handleNewline(textarea, e);
|
||||
} else if (pairs.has(e.key)) {
|
||||
handlePairCharacter(textarea, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {imageInfo} from '../../utils/image.ts';
|
||||
import {textareaInsertText, triggerEditorContentChanged} from './EditorMarkdown.ts';
|
||||
import {replaceTextareaSelection, triggerEditorContentChanged} from './EditorMarkdown.ts';
|
||||
import {
|
||||
DropzoneCustomEventRemovedFile,
|
||||
DropzoneCustomEventUploadDone,
|
||||
@@ -43,7 +43,7 @@ class TextareaEditor {
|
||||
}
|
||||
|
||||
insertPlaceholder(value: string) {
|
||||
textareaInsertText(this.editor, value);
|
||||
replaceTextareaSelection(this.editor, value);
|
||||
}
|
||||
|
||||
replacePlaceholder(oldVal: string, newVal: string) {
|
||||
@@ -121,7 +121,10 @@ function getPastedImages(e: ClipboardEvent) {
|
||||
const images: Array<File> = [];
|
||||
for (const item of e.clipboardData?.items ?? []) {
|
||||
if (item.type?.startsWith('image/')) {
|
||||
images.push(item.getAsFile());
|
||||
const file = item.getAsFile();
|
||||
if (file) {
|
||||
images.push(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
return images;
|
||||
@@ -135,7 +138,7 @@ export function initEasyMDEPaste(easyMDE: EasyMDE, dropzoneEl: HTMLElement) {
|
||||
handleUploadFiles(editor, dropzoneEl, images, e);
|
||||
});
|
||||
easyMDE.codemirror.on('drop', (_, e) => {
|
||||
if (!e.dataTransfer.files.length) return;
|
||||
if (!e.dataTransfer?.files.length) return;
|
||||
handleUploadFiles(editor, dropzoneEl, e.dataTransfer.files, e);
|
||||
});
|
||||
dropzoneEl.dropzone.on(DropzoneCustomEventRemovedFile, ({fileUuid}) => {
|
||||
@@ -145,7 +148,7 @@ export function initEasyMDEPaste(easyMDE: EasyMDE, dropzoneEl: HTMLElement) {
|
||||
});
|
||||
}
|
||||
|
||||
export function initTextareaEvents(textarea: HTMLTextAreaElement, dropzoneEl: HTMLElement) {
|
||||
export function initTextareaEvents(textarea: HTMLTextAreaElement, dropzoneEl: HTMLElement | null) {
|
||||
subscribe(textarea); // enable paste features
|
||||
textarea.addEventListener('paste', (e: ClipboardEvent) => {
|
||||
const images = getPastedImages(e);
|
||||
@@ -154,7 +157,7 @@ export function initTextareaEvents(textarea: HTMLTextAreaElement, dropzoneEl: HT
|
||||
}
|
||||
});
|
||||
textarea.addEventListener('drop', (e: DragEvent) => {
|
||||
if (!e.dataTransfer.files.length) return;
|
||||
if (!e.dataTransfer?.files.length) return;
|
||||
if (!dropzoneEl) return;
|
||||
handleUploadFiles(new TextareaEditor(textarea), dropzoneEl, e.dataTransfer.files, e);
|
||||
});
|
||||
|
||||
@@ -14,17 +14,17 @@ export function initCompLabelEdit(pageSelector: string) {
|
||||
const elModal = pageContent.querySelector<HTMLElement>('#issue-label-edit-modal');
|
||||
if (!elModal) return;
|
||||
|
||||
const elLabelId = elModal.querySelector<HTMLInputElement>('input[name="id"]');
|
||||
const elNameInput = elModal.querySelector<HTMLInputElement>('.label-name-input');
|
||||
const elExclusiveField = elModal.querySelector('.label-exclusive-input-field');
|
||||
const elExclusiveInput = elModal.querySelector<HTMLInputElement>('.label-exclusive-input');
|
||||
const elExclusiveWarning = elModal.querySelector('.label-exclusive-warning');
|
||||
const elExclusiveOrderField = elModal.querySelector<HTMLInputElement>('.label-exclusive-order-input-field');
|
||||
const elExclusiveOrderInput = elModal.querySelector<HTMLInputElement>('.label-exclusive-order-input');
|
||||
const elIsArchivedField = elModal.querySelector('.label-is-archived-input-field');
|
||||
const elIsArchivedInput = elModal.querySelector<HTMLInputElement>('.label-is-archived-input');
|
||||
const elDescInput = elModal.querySelector<HTMLInputElement>('.label-desc-input');
|
||||
const elColorInput = elModal.querySelector<HTMLInputElement>('.color-picker-combo input');
|
||||
const elLabelId = elModal.querySelector<HTMLInputElement>('input[name="id"]')!;
|
||||
const elNameInput = elModal.querySelector<HTMLInputElement>('.label-name-input')!;
|
||||
const elExclusiveField = elModal.querySelector('.label-exclusive-input-field')!;
|
||||
const elExclusiveInput = elModal.querySelector<HTMLInputElement>('.label-exclusive-input')!;
|
||||
const elExclusiveWarning = elModal.querySelector('.label-exclusive-warning')!;
|
||||
const elExclusiveOrderField = elModal.querySelector<HTMLInputElement>('.label-exclusive-order-input-field')!;
|
||||
const elExclusiveOrderInput = elModal.querySelector<HTMLInputElement>('.label-exclusive-order-input')!;
|
||||
const elIsArchivedField = elModal.querySelector('.label-is-archived-input-field')!;
|
||||
const elIsArchivedInput = elModal.querySelector<HTMLInputElement>('.label-is-archived-input')!;
|
||||
const elDescInput = elModal.querySelector<HTMLInputElement>('.label-desc-input')!;
|
||||
const elColorInput = elModal.querySelector<HTMLInputElement>('.color-picker-combo input')!;
|
||||
|
||||
const syncModalUi = () => {
|
||||
const hasScope = nameHasScope(elNameInput.value);
|
||||
@@ -37,13 +37,13 @@ export function initCompLabelEdit(pageSelector: string) {
|
||||
if (parseInt(elExclusiveOrderInput.value) <= 0) {
|
||||
elExclusiveOrderInput.style.color = 'var(--color-placeholder-text) !important';
|
||||
} else {
|
||||
elExclusiveOrderInput.style.color = null;
|
||||
elExclusiveOrderInput.style.removeProperty('color');
|
||||
}
|
||||
};
|
||||
|
||||
const showLabelEditModal = (btn:HTMLElement) => {
|
||||
// the "btn" should contain the label's attributes by its `data-label-xxx` attributes
|
||||
const form = elModal.querySelector<HTMLFormElement>('form');
|
||||
const form = elModal.querySelector<HTMLFormElement>('form')!;
|
||||
elLabelId.value = btn.getAttribute('data-label-id') || '';
|
||||
elNameInput.value = btn.getAttribute('data-label-name') || '';
|
||||
elExclusiveOrderInput.value = btn.getAttribute('data-label-exclusive-order') || '0';
|
||||
@@ -59,7 +59,7 @@ export function initCompLabelEdit(pageSelector: string) {
|
||||
// if a label was not exclusive but has issues, then it should warn user if it will become exclusive
|
||||
const numIssues = parseInt(btn.getAttribute('data-label-num-issues') || '0');
|
||||
elModal.toggleAttribute('data-need-warn-exclusive', !elExclusiveInput.checked && numIssues > 0);
|
||||
elModal.querySelector('.header').textContent = isEdit ? elModal.getAttribute('data-text-edit-label') : elModal.getAttribute('data-text-new-label');
|
||||
elModal.querySelector('.header')!.textContent = isEdit ? elModal.getAttribute('data-text-edit-label') : elModal.getAttribute('data-text-new-label');
|
||||
|
||||
const curPageLink = elModal.getAttribute('data-current-page-link');
|
||||
form.action = isEdit ? `${curPageLink}/edit` : `${curPageLink}/new`;
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
import {POST} from '../../modules/fetch.ts';
|
||||
import type {DOMEvent} from '../../utils/dom.ts';
|
||||
import {registerGlobalEventFunc} from '../../modules/observer.ts';
|
||||
|
||||
export function initCompReactionSelector() {
|
||||
registerGlobalEventFunc('click', 'onCommentReactionButtonClick', async (target: HTMLElement, e: DOMEvent<MouseEvent>) => {
|
||||
registerGlobalEventFunc('click', 'onCommentReactionButtonClick', async (target: HTMLElement, e: Event) => {
|
||||
// there are 2 places for the "reaction" buttons, one is the top-right reaction menu, one is the bottom of the comment
|
||||
e.preventDefault();
|
||||
|
||||
if (target.classList.contains('disabled')) return;
|
||||
|
||||
const actionUrl = target.closest('[data-action-url]').getAttribute('data-action-url');
|
||||
const reactionContent = target.getAttribute('data-reaction-content');
|
||||
const actionUrl = target.closest('[data-action-url]')!.getAttribute('data-action-url');
|
||||
const reactionContent = target.getAttribute('data-reaction-content')!;
|
||||
|
||||
const commentContainer = target.closest('.comment-container');
|
||||
const commentContainer = target.closest('.comment-container')!;
|
||||
|
||||
const bottomReactions = commentContainer.querySelector('.bottom-reactions'); // may not exist if there is no reaction
|
||||
const bottomReactionBtn = bottomReactions?.querySelector(`a[data-reaction-content="${CSS.escape(reactionContent)}"]`);
|
||||
|
||||
@@ -5,10 +5,15 @@ const {appSubUrl} = window.config;
|
||||
|
||||
export function initCompSearchRepoBox(el: HTMLElement) {
|
||||
const uid = el.getAttribute('data-uid');
|
||||
const exclusive = el.getAttribute('data-exclusive');
|
||||
let url = `${appSubUrl}/repo/search?q={query}&uid=${uid}`;
|
||||
if (exclusive === 'true') {
|
||||
url += `&exclusive=true`;
|
||||
}
|
||||
fomanticQuery(el).search({
|
||||
minCharacters: 2,
|
||||
apiSettings: {
|
||||
url: `${appSubUrl}/repo/search?q={query}&uid=${uid}`,
|
||||
url,
|
||||
onResponse(response: any) {
|
||||
const items = [];
|
||||
for (const item of response.data) {
|
||||
|
||||
@@ -10,13 +10,14 @@ export function initCompSearchUserBox() {
|
||||
|
||||
const allowEmailInput = searchUserBox.getAttribute('data-allow-email') === 'true';
|
||||
const allowEmailDescription = searchUserBox.getAttribute('data-allow-email-description') ?? undefined;
|
||||
const includeOrgs = searchUserBox.getAttribute('data-include-orgs') === 'true';
|
||||
fomanticQuery(searchUserBox).search({
|
||||
minCharacters: 2,
|
||||
apiSettings: {
|
||||
url: `${appSubUrl}/user/search_candidates?q={query}`,
|
||||
url: `${appSubUrl}/user/search_candidates?q={query}&orgs=${includeOrgs}`,
|
||||
onResponse(response: any) {
|
||||
const resultItems = [];
|
||||
const searchQuery = searchUserBox.querySelector('input').value;
|
||||
const searchQuery = searchUserBox.querySelector('input')!.value;
|
||||
const searchQueryUppercase = searchQuery.toUpperCase();
|
||||
for (const item of response.data) {
|
||||
const resultItem = {
|
||||
|
||||
@@ -3,7 +3,7 @@ import {emojiString} from '../emoji.ts';
|
||||
import {svg} from '../../svg.ts';
|
||||
import {parseIssueHref, parseRepoOwnerPathInfo} from '../../utils.ts';
|
||||
import {createElementFromAttrs, createElementFromHTML} from '../../utils/dom.ts';
|
||||
import {getIssueColor, getIssueIcon} from '../issue.ts';
|
||||
import {getIssueColorClass, getIssueIcon} from '../issue.ts';
|
||||
import {debounce} from 'perfect-debounce';
|
||||
import type TextExpanderElement from '@github/text-expander-element';
|
||||
import type {TextExpanderChangeEvent, TextExpanderResult} from '@github/text-expander-element';
|
||||
@@ -25,7 +25,7 @@ async function fetchIssueSuggestions(key: string, text: string): Promise<TextExp
|
||||
for (const issue of matches) {
|
||||
const li = createElementFromAttrs(
|
||||
'li', {role: 'option', class: 'tw-flex tw-gap-2', 'data-value': `${key}${issue.number}`},
|
||||
createElementFromHTML(svg(getIssueIcon(issue), 16, ['text', getIssueColor(issue)])),
|
||||
createElementFromHTML(svg(getIssueIcon(issue), 16, [getIssueColorClass(issue)])),
|
||||
createElementFromAttrs('span', null, `#${issue.number}`),
|
||||
createElementFromAttrs('span', null, issue.title),
|
||||
);
|
||||
@@ -37,7 +37,8 @@ async function fetchIssueSuggestions(key: string, text: string): Promise<TextExp
|
||||
export function initTextExpander(expander: TextExpanderElement) {
|
||||
if (!expander) return;
|
||||
|
||||
const textarea = expander.querySelector<HTMLTextAreaElement>('textarea');
|
||||
const textarea = expander.querySelector<HTMLTextAreaElement>('textarea')!;
|
||||
const mentionsUrl = expander.closest('[data-mentions-url]')?.getAttribute('data-mentions-url');
|
||||
|
||||
// help to fix the text-expander "multiword+promise" bug: do not show the popup when there is no "#" before current line
|
||||
const shouldShowIssueSuggestions = () => {
|
||||
@@ -64,6 +65,7 @@ export function initTextExpander(expander: TextExpanderElement) {
|
||||
}, 300); // to match onInputDebounce delay
|
||||
|
||||
expander.addEventListener('text-expander-change', (e: TextExpanderChangeEvent) => {
|
||||
if (!e.detail) return;
|
||||
const {key, text, provide} = e.detail;
|
||||
if (key === ':') {
|
||||
const matches = matchEmoji(text);
|
||||
@@ -82,36 +84,39 @@ export function initTextExpander(expander: TextExpanderElement) {
|
||||
|
||||
provide({matched: true, fragment: ul});
|
||||
} else if (key === '@') {
|
||||
const matches = matchMention(text);
|
||||
if (!matches.length) return provide({matched: false});
|
||||
provide((async (): Promise<TextExpanderResult> => {
|
||||
if (!mentionsUrl) return {matched: false};
|
||||
const matches = await matchMention(mentionsUrl, text);
|
||||
if (!matches.length) return {matched: false};
|
||||
|
||||
const ul = document.createElement('ul');
|
||||
ul.classList.add('suggestions');
|
||||
for (const {value, name, fullname, avatar} of matches) {
|
||||
const li = document.createElement('li');
|
||||
li.setAttribute('role', 'option');
|
||||
li.setAttribute('data-value', `${key}${value}`);
|
||||
const ul = document.createElement('ul');
|
||||
ul.classList.add('suggestions');
|
||||
for (const {value, name, fullname, avatar} of matches) {
|
||||
const li = document.createElement('li');
|
||||
li.setAttribute('role', 'option');
|
||||
li.setAttribute('data-value', `${key}${value}`);
|
||||
|
||||
const img = document.createElement('img');
|
||||
img.src = avatar;
|
||||
li.append(img);
|
||||
const img = document.createElement('img');
|
||||
img.src = avatar;
|
||||
li.append(img);
|
||||
|
||||
const nameSpan = document.createElement('span');
|
||||
nameSpan.classList.add('name');
|
||||
nameSpan.textContent = name;
|
||||
li.append(nameSpan);
|
||||
const nameSpan = document.createElement('span');
|
||||
nameSpan.classList.add('name');
|
||||
nameSpan.textContent = name;
|
||||
li.append(nameSpan);
|
||||
|
||||
if (fullname && fullname.toLowerCase() !== name) {
|
||||
const fullnameSpan = document.createElement('span');
|
||||
fullnameSpan.classList.add('fullname');
|
||||
fullnameSpan.textContent = fullname;
|
||||
li.append(fullnameSpan);
|
||||
if (fullname && fullname.toLowerCase() !== name) {
|
||||
const fullnameSpan = document.createElement('span');
|
||||
fullnameSpan.classList.add('fullname');
|
||||
fullnameSpan.textContent = fullname;
|
||||
li.append(fullnameSpan);
|
||||
}
|
||||
|
||||
ul.append(li);
|
||||
}
|
||||
|
||||
ul.append(li);
|
||||
}
|
||||
|
||||
provide({matched: true, fragment: ul});
|
||||
return {matched: true, fragment: ul};
|
||||
})());
|
||||
} else if (key === '#') {
|
||||
provide(debouncedIssueSuggestions(key, text));
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ export function initCompWebHookEditor() {
|
||||
if (httpMethodInput) {
|
||||
const updateContentType = function () {
|
||||
const visible = httpMethodInput.value === 'POST';
|
||||
toggleElem(document.querySelector('#content_type').closest('.field'), visible);
|
||||
toggleElem(document.querySelector('#content_type')!.closest('.field')!, visible);
|
||||
};
|
||||
updateContentType();
|
||||
httpMethodInput.addEventListener('change', updateContentType);
|
||||
@@ -36,9 +36,12 @@ export function initCompWebHookEditor() {
|
||||
// Test delivery
|
||||
document.querySelector<HTMLButtonElement>('#test-delivery')?.addEventListener('click', async function () {
|
||||
this.classList.add('is-loading', 'disabled');
|
||||
await POST(this.getAttribute('data-link'));
|
||||
await POST(this.getAttribute('data-link')!);
|
||||
setTimeout(() => {
|
||||
window.location.href = this.getAttribute('data-redirect');
|
||||
const redirectUrl = this.getAttribute('data-redirect');
|
||||
if (redirectUrl) {
|
||||
window.location.href = redirectUrl;
|
||||
}
|
||||
}, 5000);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user