mirror of
https://github.com/go-gitea/gitea.git
synced 2026-09-27 07:07:22 +02:00
Merge branch 'main' into feature/workflow-graph
Signed-off-by: Semenets V. Pavel <p.semenets@gmail.com>
This commit is contained in:
@@ -6,7 +6,7 @@ import {html} from './utils/html.ts';
|
||||
|
||||
// This sets up the URL prefix used in webpack's chunk loading.
|
||||
// This file must be imported before any lazy-loading is being attempted.
|
||||
__webpack_public_path__ = `${window.config?.assetUrlPrefix ?? '/assets'}/`;
|
||||
window.__webpack_public_path__ = `${window.config?.assetUrlPrefix ?? '/assets'}/`;
|
||||
|
||||
function shouldIgnoreError(err: Error) {
|
||||
const ignorePatterns = [
|
||||
@@ -41,7 +41,7 @@ export function showGlobalErrorMessage(msg: string, msgType: Intent = 'error') {
|
||||
|
||||
function processWindowErrorEvent({error, reason, message, type, filename, lineno, colno}: ErrorEvent & PromiseRejectionEvent) {
|
||||
const err = error ?? reason;
|
||||
const assetBaseUrl = String(new URL(__webpack_public_path__, window.location.origin));
|
||||
const assetBaseUrl = String(new URL(window.__webpack_public_path__, window.location.origin));
|
||||
const {runModeIsProd} = window.config ?? {};
|
||||
|
||||
// `error` and `reason` are not guaranteed to be errors. If the value is falsy, it is likely a
|
||||
|
||||
@@ -4,6 +4,7 @@ import {toggleElem} from '../utils/dom.ts';
|
||||
import {diffTreeStore} from '../modules/diff-file.ts';
|
||||
import {setFileFolding} from '../features/file-fold.ts';
|
||||
import {onMounted, onUnmounted} from 'vue';
|
||||
import {localUserSettings} from '../modules/user-settings.ts';
|
||||
|
||||
const LOCAL_STORAGE_KEY = 'diff_file_tree_visible';
|
||||
|
||||
@@ -11,7 +12,7 @@ const store = diffTreeStore();
|
||||
|
||||
onMounted(() => {
|
||||
// Default to true if unset
|
||||
store.fileTreeIsVisible = localStorage.getItem(LOCAL_STORAGE_KEY) !== 'false';
|
||||
store.fileTreeIsVisible = localUserSettings.getBoolean(LOCAL_STORAGE_KEY, true);
|
||||
document.querySelector('.diff-toggle-file-tree-button')!.addEventListener('click', toggleVisibility);
|
||||
|
||||
hashChangeListener();
|
||||
@@ -43,7 +44,7 @@ function toggleVisibility() {
|
||||
|
||||
function updateVisibility(visible: boolean) {
|
||||
store.fileTreeIsVisible = visible;
|
||||
localStorage.setItem(LOCAL_STORAGE_KEY, store.fileTreeIsVisible.toString());
|
||||
localUserSettings.setBoolean(LOCAL_STORAGE_KEY, store.fileTreeIsVisible);
|
||||
updateState(store.fileTreeIsVisible);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import {POST, DELETE} from '../modules/fetch.ts';
|
||||
import type {IntervalId} from '../types.ts';
|
||||
import {toggleFullScreen} from '../utils.ts';
|
||||
import WorkflowGraph from './WorkflowGraph.vue'
|
||||
import {localUserSettings} from '../modules/user-settings.ts';
|
||||
|
||||
// see "models/actions/status.go", if it needs to be used somewhere else, move it to a shared file like "types/actions.ts"
|
||||
type RunStatus = 'unknown' | 'waiting' | 'running' | 'success' | 'failure' | 'cancelled' | 'skipped' | 'blocked';
|
||||
@@ -74,15 +75,6 @@ type LocaleStorageOptions = {
|
||||
expandRunning: boolean;
|
||||
};
|
||||
|
||||
function getLocaleStorageOptions(): LocaleStorageOptions {
|
||||
try {
|
||||
const optsJson = localStorage.getItem('actions-view-options');
|
||||
if (optsJson) return JSON.parse(optsJson);
|
||||
} catch {}
|
||||
// if no options in localStorage, or failed to parse, return default options
|
||||
return {autoScroll: true, expandRunning: false};
|
||||
}
|
||||
|
||||
export default defineComponent({
|
||||
name: 'RepoActionView',
|
||||
components: {
|
||||
@@ -110,7 +102,8 @@ export default defineComponent({
|
||||
},
|
||||
|
||||
data() {
|
||||
const {autoScroll, expandRunning} = getLocaleStorageOptions();
|
||||
const defaultViewOptions: LocaleStorageOptions = {autoScroll: true, expandRunning: false};
|
||||
const {autoScroll, expandRunning} = localUserSettings.getJsonObject('actions-view-options', defaultViewOptions);
|
||||
return {
|
||||
// internal state
|
||||
loadingAbortController: null as AbortController | null,
|
||||
@@ -229,7 +222,7 @@ export default defineComponent({
|
||||
methods: {
|
||||
saveLocaleStorageOptions() {
|
||||
const opts: LocaleStorageOptions = {autoScroll: this.optionAlwaysAutoScroll, expandRunning: this.optionAlwaysExpandRunning};
|
||||
localStorage.setItem('actions-view-options', JSON.stringify(opts));
|
||||
localUserSettings.setJsonObject('actions-view-options', opts);
|
||||
},
|
||||
|
||||
// get the job step logs container ('.job-step-logs')
|
||||
|
||||
@@ -20,6 +20,9 @@ export function createViewFileTreeStore(props: {repoLink: string, treePath: stri
|
||||
selectedItem: props.treePath,
|
||||
|
||||
async loadChildren(treePath: string, subPath: string = '') {
|
||||
// there is no git ref if no commits were made yet (an empty repo)
|
||||
if (!props.currentRefNameSubURL) return null;
|
||||
|
||||
const response = await GET(`${props.repoLink}/tree-view/${props.currentRefNameSubURL}/${pathEscapeSegments(treePath)}?sub_path=${encodeURIComponent(subPath)}`);
|
||||
const json = await response.json();
|
||||
const poolSvgs = [];
|
||||
|
||||
@@ -2,6 +2,7 @@ import {checkAppUrl} from '../common-page.ts';
|
||||
import {hideElem, queryElems, showElem, toggleElem} from '../../utils/dom.ts';
|
||||
import {POST} from '../../modules/fetch.ts';
|
||||
import {fomanticQuery} from '../../modules/fomantic/base.ts';
|
||||
import {urlQueryEscape} from '../../utils.ts';
|
||||
|
||||
const {appSubUrl} = window.config;
|
||||
|
||||
@@ -122,7 +123,7 @@ function initAdminAuthentication() {
|
||||
document.querySelector<HTMLInputElement>(`#oauth2_${custom}`)!.value = document.querySelector<HTMLInputElement>(`#${provider}_${custom}`)!.value;
|
||||
}
|
||||
const customInput = document.querySelector(`#${provider}_${custom}`);
|
||||
if (customInput && customInput.getAttribute('data-available') === 'true') {
|
||||
if (customInput?.getAttribute('data-available') === 'true') {
|
||||
for (const input of document.querySelectorAll(`.oauth2_${custom} input`)) {
|
||||
input.setAttribute('required', 'required');
|
||||
}
|
||||
@@ -230,7 +231,7 @@ function initAdminAuthentication() {
|
||||
const elAuthName = document.querySelector<HTMLInputElement>('#auth_name')!;
|
||||
const onAuthNameChange = function () {
|
||||
// appSubUrl is either empty or is a path that starts with `/` and doesn't have a trailing slash.
|
||||
document.querySelector('#oauth2-callback-url')!.textContent = `${window.location.origin}${appSubUrl}/user/oauth2/${encodeURIComponent(elAuthName.value)}/callback`;
|
||||
document.querySelector('#oauth2-callback-url')!.textContent = `${window.location.origin}${appSubUrl}/user/oauth2/${urlQueryEscape(elAuthName.value)}/callback`;
|
||||
};
|
||||
elAuthName.addEventListener('input', onAuthNameChange);
|
||||
onAuthNameChange();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {getCurrentLocale} from '../utils.ts';
|
||||
import {fomanticQuery} from '../modules/fomantic/base.ts';
|
||||
import {localUserSettings} from '../modules/user-settings.ts';
|
||||
|
||||
const {pageData} = window.config;
|
||||
|
||||
@@ -38,7 +39,7 @@ export async function initCitationFileCopyContent() {
|
||||
if ((!citationCopyApa && !citationCopyBibtex) || !inputContent) return;
|
||||
|
||||
const updateUi = () => {
|
||||
const isBibtex = (localStorage.getItem('citation-copy-format') || defaultCitationFormat) === 'bibtex';
|
||||
const isBibtex = localUserSettings.getString('citation-copy-format', defaultCitationFormat) === 'bibtex';
|
||||
const copyContent = (isBibtex ? citationCopyBibtex : citationCopyApa).getAttribute('data-text')!;
|
||||
inputContent.value = copyContent;
|
||||
citationCopyBibtex.classList.toggle('primary', isBibtex);
|
||||
@@ -55,12 +56,12 @@ export async function initCitationFileCopyContent() {
|
||||
updateUi();
|
||||
|
||||
citationCopyApa.addEventListener('click', () => {
|
||||
localStorage.setItem('citation-copy-format', 'apa');
|
||||
localUserSettings.setString('citation-copy-format', 'apa');
|
||||
updateUi();
|
||||
});
|
||||
|
||||
citationCopyBibtex.addEventListener('click', () => {
|
||||
localStorage.setItem('citation-copy-format', 'bibtex');
|
||||
localUserSettings.setString('citation-copy-format', 'bibtex');
|
||||
updateUi();
|
||||
});
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ test('parseIssueListQuickGotoLink', () => {
|
||||
expect(parseIssueListQuickGotoLink('/link', 'abc')).toEqual('');
|
||||
expect(parseIssueListQuickGotoLink('/link', '123')).toEqual('/link/issues/123');
|
||||
expect(parseIssueListQuickGotoLink('/link', '#123')).toEqual('/link/issues/123');
|
||||
expect(parseIssueListQuickGotoLink('/link', 'owner/repo#123')).toEqual('');
|
||||
expect(parseIssueListQuickGotoLink('/link', 'owner/repo#123')).toEqual('/owner/repo/issues/123');
|
||||
|
||||
expect(parseIssueListQuickGotoLink('', '')).toEqual('');
|
||||
expect(parseIssueListQuickGotoLink('', 'abc')).toEqual('');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {isElemVisible, onInputDebounce, submitEventSubmitter, toggleElem} from '../utils/dom.ts';
|
||||
import {onInputDebounce, toggleElem} from '../utils/dom.ts';
|
||||
import {GET} from '../modules/fetch.ts';
|
||||
|
||||
const {appSubUrl} = window.config;
|
||||
@@ -17,37 +17,25 @@ export function parseIssueListQuickGotoLink(repoLink: string, searchText: string
|
||||
} else if (reIssueSharpIndex.test(searchText)) {
|
||||
targetUrl = `${repoLink}/issues/${searchText.substring(1)}`;
|
||||
}
|
||||
} else {
|
||||
// try to parse it for a global search (eg: "owner/repo#123")
|
||||
const [_, owner, repo, index] = reIssueOwnerRepoIndex.exec(searchText) || [];
|
||||
if (owner) {
|
||||
targetUrl = `${appSubUrl}/${owner}/${repo}/issues/${index}`;
|
||||
}
|
||||
}
|
||||
// try to parse it for a global search (eg: "owner/repo#123")
|
||||
const [_, owner, repo, index] = reIssueOwnerRepoIndex.exec(searchText) || [];
|
||||
if (owner) {
|
||||
targetUrl = `${appSubUrl}/${owner}/${repo}/issues/${index}`;
|
||||
}
|
||||
return targetUrl;
|
||||
}
|
||||
|
||||
export function initCommonIssueListQuickGoto() {
|
||||
const goto = document.querySelector<HTMLElement>('#issue-list-quick-goto');
|
||||
if (!goto) return;
|
||||
const elGotoButton = document.querySelector<HTMLElement>('#issue-list-quick-goto');
|
||||
if (!elGotoButton) return;
|
||||
|
||||
const form = goto.closest('form')!;
|
||||
const form = elGotoButton.closest('form')!;
|
||||
const input = form.querySelector<HTMLInputElement>('input[name=q]')!;
|
||||
const repoLink = goto.getAttribute('data-repo-link')!;
|
||||
const repoLink = elGotoButton.getAttribute('data-repo-link') || '';
|
||||
|
||||
form.addEventListener('submit', (e) => {
|
||||
// if there is no goto button, or the form is submitted by non-quick-goto elements, submit the form directly
|
||||
let doQuickGoto = isElemVisible(goto);
|
||||
const submitter = submitEventSubmitter(e);
|
||||
if (submitter !== form && submitter !== input && submitter !== goto) doQuickGoto = false;
|
||||
if (!doQuickGoto) return;
|
||||
|
||||
// if there is a goto button, use its link
|
||||
e.preventDefault();
|
||||
const link = goto.getAttribute('data-issue-goto-link');
|
||||
if (link) {
|
||||
window.location.href = link;
|
||||
}
|
||||
elGotoButton.addEventListener('click', () => {
|
||||
window.location.href = elGotoButton.getAttribute('data-issue-goto-link')!;
|
||||
});
|
||||
|
||||
const onInput = async () => {
|
||||
@@ -61,8 +49,8 @@ export function initCommonIssueListQuickGoto() {
|
||||
// if the input value has changed, then ignore the result
|
||||
if (input.value !== searchText) return;
|
||||
|
||||
toggleElem(goto, Boolean(targetUrl));
|
||||
goto.setAttribute('data-issue-goto-link', targetUrl);
|
||||
toggleElem(elGotoButton, Boolean(targetUrl));
|
||||
elGotoButton.setAttribute('data-issue-goto-link', targetUrl);
|
||||
};
|
||||
|
||||
input.addEventListener('input', onInputDebounce(onInput));
|
||||
|
||||
@@ -24,6 +24,7 @@ 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,6 +82,8 @@ export class ComboMarkdownEditor {
|
||||
textareaMarkdownToolbar: HTMLElement;
|
||||
textareaAutosize: any;
|
||||
|
||||
buttonMonospace: HTMLButtonElement;
|
||||
|
||||
dropzone: HTMLElement | null;
|
||||
attachedDropzoneInst: any;
|
||||
|
||||
@@ -140,19 +143,13 @@ 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) {
|
||||
@@ -369,7 +366,7 @@ export class ComboMarkdownEditor {
|
||||
hideElem(this.textareaMarkdownToolbar);
|
||||
}
|
||||
|
||||
value(v: any = undefined) {
|
||||
value(v?: any) {
|
||||
if (v === undefined) {
|
||||
if (this.easyMDE) {
|
||||
return this.easyMDE.value();
|
||||
@@ -403,10 +400,27 @@ export class ComboMarkdownEditor {
|
||||
}
|
||||
|
||||
get userPreferredEditor(): string {
|
||||
return window.localStorage.getItem(`markdown-editor-${this.previewMode ?? 'default'}`) || '';
|
||||
return localUserSettings.getString(`markdown-editor-${this.previewMode ?? 'default'}`);
|
||||
}
|
||||
|
||||
set userPreferredEditor(s: string) {
|
||||
window.localStorage.setItem(`markdown-editor-${this.previewMode ?? 'default'}`, s);
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
function applyMonospaceToAllEditors() {
|
||||
const editors = document.querySelectorAll<ComboMarkdownEditorContainer>('.combo-markdown-editor');
|
||||
for (const editorContainer of editors) {
|
||||
const editor = getComboMarkdownEditor(editorContainer);
|
||||
if (editor) editor.applyMonospace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -186,6 +186,7 @@ export function markdownHandleIndention(tvs: TextareaValueSelection): MarkdownHa
|
||||
}
|
||||
|
||||
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 || !ret.valueSelection) return; // FIXME: the "handled" seems redundant, only valueSelection is enough (null for unhandled)
|
||||
e.preventDefault();
|
||||
|
||||
@@ -33,7 +33,7 @@ export function initNotificationCount() {
|
||||
|
||||
if (notificationSettings.EventSourceUpdateTime > 0 && window.EventSource && window.SharedWorker) {
|
||||
// Try to connect to the event source via the shared worker first
|
||||
const worker = new SharedWorker(`${__webpack_public_path__}js/eventsource.sharedworker.js?v=${assetVersionEncoded}`, 'notification-worker');
|
||||
const worker = new SharedWorker(`${window.__webpack_public_path__}js/eventsource.sharedworker.js?v=${assetVersionEncoded}`, 'notification-worker');
|
||||
worker.addEventListener('error', (event) => {
|
||||
console.error('worker error', event);
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import RepoActivityTopAuthors from '../components/RepoActivityTopAuthors.vue';
|
||||
import {createApp} from 'vue';
|
||||
import {toOriginUrl} from '../utils/url.ts';
|
||||
import {createTippy} from '../modules/tippy.ts';
|
||||
import {localUserSettings} from '../modules/user-settings.ts';
|
||||
|
||||
async function onDownloadArchive(e: Event) {
|
||||
e.preventDefault();
|
||||
@@ -57,7 +58,7 @@ function initCloneSchemeUrlSelection(parent: Element) {
|
||||
const tabSsh = parent.querySelector('.repo-clone-ssh');
|
||||
const tabTea = parent.querySelector('.repo-clone-tea');
|
||||
const updateClonePanelUi = function() {
|
||||
let scheme = localStorage.getItem('repo-clone-protocol')!;
|
||||
let scheme = localUserSettings.getString('repo-clone-protocol');
|
||||
if (!['https', 'ssh', 'tea'].includes(scheme)) {
|
||||
scheme = 'https';
|
||||
}
|
||||
@@ -114,15 +115,15 @@ function initCloneSchemeUrlSelection(parent: Element) {
|
||||
updateClonePanelUi();
|
||||
// tabSsh or tabHttps might not both exist, eg: guest view, or one is disabled by the server
|
||||
tabHttps?.addEventListener('click', () => {
|
||||
localStorage.setItem('repo-clone-protocol', 'https');
|
||||
localUserSettings.setString('repo-clone-protocol', 'https');
|
||||
updateClonePanelUi();
|
||||
});
|
||||
tabSsh?.addEventListener('click', () => {
|
||||
localStorage.setItem('repo-clone-protocol', 'ssh');
|
||||
localUserSettings.setString('repo-clone-protocol', 'ssh');
|
||||
updateClonePanelUi();
|
||||
});
|
||||
tabTea?.addEventListener('click', () => {
|
||||
localStorage.setItem('repo-clone-protocol', 'tea');
|
||||
localUserSettings.setString('repo-clone-protocol', 'tea');
|
||||
updateClonePanelUi();
|
||||
});
|
||||
elCloneUrlInput.addEventListener('focus', () => {
|
||||
|
||||
@@ -47,7 +47,7 @@ export function initStopwatch() {
|
||||
// if the browser supports EventSource and SharedWorker, use it instead of the periodic poller
|
||||
if (notificationSettings.EventSourceUpdateTime > 0 && window.EventSource && window.SharedWorker) {
|
||||
// Try to connect to the event source via the shared worker first
|
||||
const worker = new SharedWorker(`${__webpack_public_path__}js/eventsource.sharedworker.js?v=${assetVersionEncoded}`, 'notification-worker');
|
||||
const worker = new SharedWorker(`${window.__webpack_public_path__}js/eventsource.sharedworker.js?v=${assetVersionEncoded}`, 'notification-worker');
|
||||
worker.addEventListener('error', (event) => {
|
||||
console.error('worker error', event);
|
||||
});
|
||||
|
||||
@@ -29,7 +29,7 @@ export async function attachTribute(element: HTMLElement) {
|
||||
return html`<div class="tribute-item">${htmlRaw(emojiHTML(item.original))}<span>${item.original}</span></div>`;
|
||||
},
|
||||
}, { // mentions
|
||||
values: window.config.mentionValues ?? [],
|
||||
values: window.config.mentionValues,
|
||||
requireLeadingSpace: true,
|
||||
menuItemTemplate: (item: TributeItem) => {
|
||||
const fullNameHtml = item.original.fullname && item.original.fullname !== '' ? html`<span class="fullname">${item.original.fullname}</span>` : '';
|
||||
|
||||
Vendored
+21
-4
@@ -18,8 +18,6 @@ declare module '*.vue' {
|
||||
export function initRepositoryActionView(): void;
|
||||
}
|
||||
|
||||
declare let __webpack_public_path__: string;
|
||||
|
||||
declare module 'htmx.org/dist/htmx.esm.js' {
|
||||
const value = await import('htmx.org');
|
||||
export default value;
|
||||
@@ -51,8 +49,26 @@ interface Element {
|
||||
}
|
||||
|
||||
interface Window {
|
||||
__webpack_public_path__: string;
|
||||
config: import('./web_src/js/types.ts').Config;
|
||||
config: {
|
||||
appUrl: string,
|
||||
appSubUrl: string,
|
||||
assetVersionEncoded: string,
|
||||
assetUrlPrefix: string,
|
||||
runModeIsProd: boolean,
|
||||
customEmojis: Record<string, string>,
|
||||
pageData: Record<string, any>,
|
||||
notificationSettings: Record<string, any>,
|
||||
enableTimeTracking: boolean,
|
||||
mentionValues: Array<{
|
||||
key: string,
|
||||
value: string,
|
||||
name: string,
|
||||
fullname: string,
|
||||
avatar: string,
|
||||
}>,
|
||||
mermaidMaxSourceCharacters: number,
|
||||
i18n: Record<string, string>,
|
||||
},
|
||||
$: typeof import('@types/jquery'),
|
||||
jQuery: typeof import('@types/jquery'),
|
||||
htmx: typeof import('htmx.org').default,
|
||||
@@ -61,6 +77,7 @@ interface Window {
|
||||
push: (e: ErrorEvent & PromiseRejectionEvent) => void | number,
|
||||
},
|
||||
codeEditors: any[], // export editor for customization
|
||||
localUserSettings: typeof import('./modules/user-settings.ts').localUserSettings,
|
||||
|
||||
// various captcha plugins
|
||||
grecaptcha: any,
|
||||
|
||||
@@ -6,6 +6,7 @@ import './bootstrap.ts';
|
||||
import './globals.ts';
|
||||
|
||||
import './webcomponents/index.ts';
|
||||
import './modules/user-settings.ts'; // templates also need to use localUserSettings in inline scripts
|
||||
import {onDomReady} from './utils/dom.ts';
|
||||
|
||||
// TODO: There is a bug in htmx, it incorrectly checks "readyState === 'complete'" when the DOM tree is ready and won't trigger DOMContentLoaded
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
import {svg} from '../svg.ts';
|
||||
|
||||
// Rendered content from users have IDs prefixed with `user-content-` to avoid conflicts with other IDs on the page.
|
||||
// - security concern: elements with IDs can affect frontend logic, for example: sending requests.
|
||||
// To make end users have better experience, the prefixes are stripped from the href attributes of links.
|
||||
// The same as GitHub: backend generates anchor `id="user-content-faq"` but the link shown to users is `href="#faq"`.
|
||||
//
|
||||
// At the moment, the anchor processing works like this:
|
||||
// - backend adds `user-content-` prefix for elements like `<h1 id>` and `<a href>`
|
||||
// - js adds the `user-content-` prefix to user-generated `<a name>` targets
|
||||
// - js intercepts the hash navigation on page load and whenever a link is clicked
|
||||
// to add the prefix so the correct prefixed `id`/`name` element is focused
|
||||
//
|
||||
// TODO: ideally, backend should be able to generate elements with necessary anchors,
|
||||
// backend doesn't need to add the prefix to `href`, then frontend doesn't need to spend
|
||||
// time on adding new elements or removing the prefixes.
|
||||
|
||||
const addPrefix = (str: string): string => `user-content-${str}`;
|
||||
const removePrefix = (str: string): string => str.replace(/^user-content-/, '');
|
||||
const hasPrefix = (str: string): boolean => str.startsWith('user-content-');
|
||||
|
||||
@@ -11,7 +11,7 @@ export function initMarkupRefIssue(el: HTMLElement) {
|
||||
});
|
||||
}
|
||||
|
||||
export function showMarkupRefIssuePopup(e: MouseEvent | FocusEvent) {
|
||||
function showMarkupRefIssuePopup(e: MouseEvent | FocusEvent) {
|
||||
const refIssue = e.currentTarget as HTMLElement;
|
||||
if (getAttachedTippyInstance(refIssue)) return;
|
||||
if (refIssue.classList.contains('ref-external-issue')) return;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {generateElemId, queryElemChildren} from '../utils/dom.ts';
|
||||
import {isDarkTheme} from '../utils.ts';
|
||||
|
||||
export async function loadRenderIframeContent(iframe: HTMLIFrameElement) {
|
||||
async function loadRenderIframeContent(iframe: HTMLIFrameElement) {
|
||||
const iframeSrcUrl = iframe.getAttribute('data-src')!;
|
||||
if (!iframe.id) iframe.id = generateElemId('gitea-iframe-');
|
||||
|
||||
@@ -9,7 +9,9 @@ export async function loadRenderIframeContent(iframe: HTMLIFrameElement) {
|
||||
if (!e.data?.giteaIframeCmd || e.data?.giteaIframeId !== iframe.id) return;
|
||||
const cmd = e.data.giteaIframeCmd;
|
||||
if (cmd === 'resize') {
|
||||
iframe.style.height = `${e.data.iframeHeight}px`;
|
||||
// TODO: sometimes the reported iframeHeight is not the size we need, need to figure why. Example: openapi swagger.
|
||||
// As a workaround, add some pixels here.
|
||||
iframe.style.height = `${e.data.iframeHeight + 2}px`;
|
||||
} else if (cmd === 'open-link') {
|
||||
if (e.data.anchorTarget === '_blank') {
|
||||
window.open(e.data.openLink, '_blank');
|
||||
|
||||
@@ -22,7 +22,7 @@ export function request(url: string, {method = 'GET', data, headers = {}, ...oth
|
||||
headersMerged.set(name, value);
|
||||
}
|
||||
|
||||
return fetch(url, {
|
||||
return fetch(url, { // eslint-disable-line no-restricted-globals
|
||||
method,
|
||||
headers: headersMerged,
|
||||
...other,
|
||||
|
||||
@@ -65,7 +65,7 @@ function updateSelectionLabel(label: HTMLElement) {
|
||||
const deleteIcon = label.querySelector('.delete.icon');
|
||||
if (deleteIcon) {
|
||||
deleteIcon.setAttribute('aria-hidden', 'false');
|
||||
deleteIcon.setAttribute('aria-label', window.config.i18n.remove_label_str.replace('%s', label.getAttribute('data-value')));
|
||||
deleteIcon.setAttribute('aria-label', window.config.i18n.remove_label_str.replace('%s', label.getAttribute('data-value')!));
|
||||
deleteIcon.setAttribute('role', 'button');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/* eslint-disable no-restricted-globals */
|
||||
// Some people deploy Gitea under a subpath, so it needs prefix to avoid local storage key conflicts.
|
||||
// And these keys are for user settings only, it also needs a specific prefix,
|
||||
// in case in the future there are other uses of local storage, and/or we need to clear some keys when the quota is exceeded.
|
||||
const itemKeyPrefix = 'gitea:setting:';
|
||||
|
||||
function handleLocalStorageError(e: any) {
|
||||
// in the future, maybe we need to handle quota exceeded errors differently
|
||||
console.error('Error using local storage for user settings', e);
|
||||
}
|
||||
|
||||
function getLocalStorageUserSetting(settingKey: string): string | null {
|
||||
const legacyKey = settingKey;
|
||||
const itemKey = `${itemKeyPrefix}${settingKey}`;
|
||||
try {
|
||||
const legacyValue = localStorage?.getItem(legacyKey) ?? null;
|
||||
const value = localStorage?.getItem(itemKey) ?? null; // avoid undefined
|
||||
if (value !== null && legacyValue !== null) {
|
||||
// if both values exist, remove the legacy one
|
||||
localStorage?.removeItem(legacyKey);
|
||||
} else if (value === null && legacyValue !== null) {
|
||||
// migrate legacy value to new key
|
||||
localStorage?.removeItem(legacyKey);
|
||||
localStorage?.setItem(itemKey, legacyValue);
|
||||
return legacyValue;
|
||||
}
|
||||
return value;
|
||||
} catch (e) {
|
||||
handleLocalStorageError(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function setLocalStorageUserSetting(settingKey: string, value: string) {
|
||||
const legacyKey = settingKey;
|
||||
const itemKey = `${itemKeyPrefix}${settingKey}`;
|
||||
try {
|
||||
localStorage?.removeItem(legacyKey);
|
||||
localStorage?.setItem(itemKey, value);
|
||||
} catch (e) {
|
||||
handleLocalStorageError(e);
|
||||
}
|
||||
}
|
||||
|
||||
export const localUserSettings = {
|
||||
getString: (key: string, def: string = ''): string => {
|
||||
return getLocalStorageUserSetting(key) ?? def;
|
||||
},
|
||||
setString: (key: string, value: string) => {
|
||||
setLocalStorageUserSetting(key, value);
|
||||
},
|
||||
getBoolean: (key: string, def: boolean = false): boolean => {
|
||||
return localUserSettings.getString(key, String(def)) === 'true';
|
||||
},
|
||||
setBoolean: (key: string, value: boolean) => {
|
||||
localUserSettings.setString(key, String(value));
|
||||
},
|
||||
getJsonObject: <T extends Record<string, any>>(key: string, def: T): T => {
|
||||
const value = getLocalStorageUserSetting(key);
|
||||
try {
|
||||
const decoded = value !== null ? JSON.parse(value) : def;
|
||||
return decoded ?? def;
|
||||
} catch (e) {
|
||||
console.error(`Unable to parse JSON value for local user settings ${key}=${value}`, e);
|
||||
}
|
||||
return def;
|
||||
},
|
||||
setJsonObject: <T extends Record<string, any>>(key: string, value: T) => {
|
||||
localUserSettings.setString(key, JSON.stringify(value));
|
||||
},
|
||||
};
|
||||
|
||||
window.localUserSettings = localUserSettings;
|
||||
@@ -21,6 +21,9 @@ function mainExternalRenderIframe() {
|
||||
};
|
||||
|
||||
const updateIframeHeight = () => postIframeMsg('resize', {iframeHeight: document.documentElement.scrollHeight});
|
||||
const resizeObserver = new ResizeObserver(() => updateIframeHeight());
|
||||
resizeObserver.observe(window.document.documentElement);
|
||||
|
||||
updateIframeHeight();
|
||||
window.addEventListener('DOMContentLoaded', updateIframeHeight);
|
||||
// the easiest way to handle dynamic content changes and easy to debug, can be fine-tuned in the future
|
||||
|
||||
@@ -1,18 +1,31 @@
|
||||
import SwaggerUI from 'swagger-ui-dist/swagger-ui-es-bundle.js';
|
||||
import 'swagger-ui-dist/swagger-ui.css';
|
||||
import {load as loadYaml} from 'js-yaml';
|
||||
import {GET} from '../modules/fetch.ts';
|
||||
|
||||
window.addEventListener('load', async () => {
|
||||
const url = document.querySelector('#swagger-ui')!.getAttribute('data-source')!;
|
||||
const res = await fetch(url);
|
||||
const spec = await res.json();
|
||||
const elSwaggerUi = document.querySelector('#swagger-ui')!;
|
||||
const url = elSwaggerUi.getAttribute('data-source')!;
|
||||
let spec: any;
|
||||
if (url) {
|
||||
const res = await GET(url);
|
||||
spec = await res.json();
|
||||
} else {
|
||||
const elSpecContent = elSwaggerUi.querySelector<HTMLTextAreaElement>('.swagger-spec-content')!;
|
||||
const filename = elSpecContent.getAttribute('data-spec-filename');
|
||||
const isJson = filename?.toLowerCase().endsWith('.json');
|
||||
spec = isJson ? JSON.parse(elSpecContent.value) : loadYaml(elSpecContent.value);
|
||||
}
|
||||
|
||||
// Make the page's protocol be at the top of the schemes list
|
||||
const proto = window.location.protocol.slice(0, -1);
|
||||
spec.schemes.sort((a: string, b: string) => {
|
||||
if (a === proto) return -1;
|
||||
if (b === proto) return 1;
|
||||
return 0;
|
||||
});
|
||||
if (spec?.schemes) {
|
||||
spec.schemes.sort((a: string, b: string) => {
|
||||
if (a === proto) return -1;
|
||||
if (b === proto) return 1;
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
SwaggerUI({
|
||||
spec,
|
||||
|
||||
@@ -1,26 +1,3 @@
|
||||
export type MentionValue = {
|
||||
key: string,
|
||||
value: string,
|
||||
name: string,
|
||||
fullname: string,
|
||||
avatar: string,
|
||||
};
|
||||
|
||||
export type Config = {
|
||||
appUrl: string,
|
||||
appSubUrl: string,
|
||||
assetVersionEncoded: string,
|
||||
assetUrlPrefix: string,
|
||||
runModeIsProd: boolean,
|
||||
customEmojis: Record<string, string>,
|
||||
pageData: Record<string, any>,
|
||||
notificationSettings: Record<string, any>,
|
||||
enableTimeTracking: boolean,
|
||||
mentionValues?: MentionValue[],
|
||||
mermaidMaxSourceCharacters: number,
|
||||
i18n: Record<string, string>,
|
||||
};
|
||||
|
||||
export type IntervalId = ReturnType<typeof setInterval>;
|
||||
|
||||
export type Intent = 'error' | 'warning' | 'info';
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
dirname, basename, extname, isObject, stripTags, parseIssueHref,
|
||||
parseUrl, translateMonth, translateDay, blobToDataURI,
|
||||
toAbsoluteUrl, encodeURLEncodedBase64, decodeURLEncodedBase64, isImageFile, isVideoFile, parseRepoOwnerPathInfo,
|
||||
urlQueryEscape,
|
||||
} from './utils.ts';
|
||||
|
||||
test('dirname', () => {
|
||||
@@ -33,6 +34,12 @@ test('stripTags', () => {
|
||||
expect(stripTags('<a>test</a>')).toEqual('test');
|
||||
});
|
||||
|
||||
test('urlQueryEscape', () => {
|
||||
const input = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
|
||||
const expected = '%21%22%23%24%25%26%27%28%29%2A%2B%2C-.%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E_%60%7B%7C%7D~';
|
||||
expect(urlQueryEscape(input)).toEqual(expected);
|
||||
});
|
||||
|
||||
test('parseIssueHref', () => {
|
||||
expect(parseIssueHref('/owner/repo/issues/1')).toEqual({ownerName: 'owner', repoName: 'repo', pathType: 'issues', indexString: '1'});
|
||||
expect(parseIssueHref('/owner/repo/pulls/1?query')).toEqual({ownerName: 'owner', repoName: 'repo', pathType: 'pulls', indexString: '1'});
|
||||
|
||||
@@ -43,6 +43,15 @@ export function stripTags(text: string): string {
|
||||
return text;
|
||||
}
|
||||
|
||||
export function urlQueryEscape(s: string) {
|
||||
// See "TestQueryEscape" in backend
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent#encoding_for_rfc3986
|
||||
return encodeURIComponent(s).replace(
|
||||
/[!'()*]/g,
|
||||
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function parseIssueHref(href: string): IssuePathInfo {
|
||||
// FIXME: it should use pathname and trim the appSubUrl ahead
|
||||
const path = (href || '').replace(/[#?].*$/, '');
|
||||
|
||||
@@ -44,11 +44,11 @@ test('queryElemChildren', () => {
|
||||
});
|
||||
|
||||
test('toggleElem', () => {
|
||||
const el = createElementFromHTML('<p><div>a</div><div class="tw-hidden">b</div></p>');
|
||||
const el = createElementFromHTML('<div><div>a</div><div class="tw-hidden">b</div></div>');
|
||||
toggleElem(el.children);
|
||||
expect(el.outerHTML).toEqual('<p><div class="tw-hidden">a</div><div class="">b</div></p>');
|
||||
expect(el.outerHTML).toEqual('<div><div class="tw-hidden">a</div><div class="">b</div></div>');
|
||||
toggleElem(el.children, false);
|
||||
expect(el.outerHTML).toEqual('<p><div class="tw-hidden">a</div><div class="tw-hidden">b</div></p>');
|
||||
expect(el.outerHTML).toEqual('<div><div class="tw-hidden">a</div><div class="tw-hidden">b</div></div>');
|
||||
toggleElem(el.children, true);
|
||||
expect(el.outerHTML).toEqual('<p><div class="">a</div><div class="">b</div></p>');
|
||||
expect(el.outerHTML).toEqual('<div><div class="">a</div><div class="">b</div></div>');
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ const pngPhys = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91
|
||||
const pngEmpty = 'data:image/png;base64,';
|
||||
|
||||
async function dataUriToBlob(datauri: string) {
|
||||
return await (await globalThis.fetch(datauri)).blob();
|
||||
return await (await globalThis.fetch(datauri)).blob(); // eslint-disable-line no-restricted-properties
|
||||
}
|
||||
|
||||
test('pngChunks', async () => {
|
||||
|
||||
@@ -35,7 +35,7 @@ export function matchMention(queryText: string): MentionSuggestion[] {
|
||||
|
||||
// results is a map of weights, lower is better
|
||||
const results = new Map<MentionSuggestion, number>();
|
||||
for (const obj of window.config.mentionValues ?? []) {
|
||||
for (const obj of window.config.mentionValues) {
|
||||
const index = obj.key.toLowerCase().indexOf(query);
|
||||
if (index === -1) continue;
|
||||
const existing = results.get(obj);
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
// even if backend is in testing mode, frontend could be complied in production mode
|
||||
// so this function only checks if the frontend is in unit testing mode (usually from *.test.ts files)
|
||||
export function isInFrontendUnitTest() {
|
||||
return process.env.TEST === 'true';
|
||||
return import.meta.env.TEST === 'true';
|
||||
}
|
||||
|
||||
@@ -18,9 +18,9 @@ test('toAbsoluteLocaleDate', () => {
|
||||
expect(toAbsoluteLocaleDate('10000-01-01', '', {})).toEqual('Invalid Date');
|
||||
|
||||
// test different timezone
|
||||
const oldTZ = process.env.TZ;
|
||||
process.env.TZ = 'America/New_York';
|
||||
const oldTZ = import.meta.env.TZ;
|
||||
import.meta.env.TZ = 'America/New_York';
|
||||
expect(new Date('2024-03-15').toLocaleString('en-US')).toEqual('3/14/2024, 8:00:00 PM');
|
||||
expect(toAbsoluteLocaleDate('2024-03-15', 'en-US')).toEqual('3/15/2024, 12:00:00 AM');
|
||||
process.env.TZ = oldTZ;
|
||||
import.meta.env.TZ = oldTZ;
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user