fix: discard stale markdown preview and diff responses (#40289)

Preview and diff tabs render whichever response arrives last, so a slow
earlier request can overwrite the result of a newer click. Introduce
ExclusiveFetch class to handle duplicate requests.

Fixes: https://github.com/go-gitea/gitea/issues/40223

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
Toniandwxiaoguang authored and GitHub committed 2026-11-10 14:22:53 +00:00
1 parent 25c5b6ab37
commit 518e08c2c7
4 files changed
+119 -27

No files matched your search

+17 -11
View File
@@ -12,7 +12,7 @@ import {renderPreviewPanelContent} from '../repo-editor.ts';
import {toggleTasklistCheckbox} from '../../markup/tasklist.ts';
import {easyMDEToolbarActions, type EasyMdeToolbarAction} from './EasyMDEToolbarActions.ts';
import {showErrorToast} from '../../modules/toast.ts';
import {POST} from '../../modules/fetch.ts';
import {ExclusiveFetch} from '../../modules/fetch.ts';
import {
EventEditorContentChanged,
initTextareaMarkdown,
@@ -92,6 +92,8 @@ export class ComboMarkdownEditor {
previewUrl!: string;
previewContext!: string;
previewFetch: ExclusiveFetch = new ExclusiveFetch();
constructor(container: ComboMarkdownEditorContainer, options:ComboMarkdownEditorOptions = {}) {
if (container._giteaComboMarkdownEditor) throw new Error('ComboMarkdownEditor already initialized');
container._giteaComboMarkdownEditor = this;
@@ -241,16 +243,7 @@ export class ComboMarkdownEditor {
});
});
this.tabPreviewer.addEventListener('click', async () => {
// use capture to get the event before Fomantic Tab switches the tab, so that we can set the minHeight of the previewer panel to avoid flickering.
panelPreviewer.style.minHeight = `${panelEditor?.clientHeight}px`;
this.updateEditorContainerTabPage('previewer');
const formData = new FormData();
formData.append('mode', this.previewMode);
formData.append('context', this.previewContext);
formData.append('text', this.value());
const response = await POST(this.previewUrl, {data: formData});
const data = await response.text();
const renderPreview = (data: string) => {
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]')) {
@@ -266,6 +259,19 @@ export class ComboMarkdownEditor {
triggerEditorContentChanged(this.container);
});
}
};
this.tabPreviewer.addEventListener('click', async () => {
// use capture to get the event before Fomantic Tab switches the tab, so that we can set the minHeight of the previewer panel to avoid flickering.
panelPreviewer.style.minHeight = `${panelEditor?.clientHeight}px`;
this.updateEditorContainerTabPage('previewer');
const formData = new FormData();
formData.append('mode', this.previewMode);
formData.append('context', this.previewContext);
formData.append('text', this.value());
const resp = this.previewFetch.request(this.previewUrl, {method: 'POST', data: formData});
resp.onResponseError((resp) => showErrorToast(`Failed to render preview: ${resp.status} ${resp.statusText}`));
await resp.fetchText(renderPreview);
}, {capture: true});
}
+10 -14
View File
@@ -2,7 +2,7 @@ import {html, htmlRaw} from '../utils/html.ts';
import {createCodeEditor} from '../modules/codeeditor/main.ts';
import {trimTrailingWhitespaceFromView} from '../modules/codeeditor/utils.ts';
import {hideElem, queryElems, showElem, createElementFromHTML, onInputDebounce} from '../utils/dom.ts';
import {POST} from '../modules/fetch.ts';
import {ExclusiveFetch} from '../modules/fetch.ts';
import {initDropzone} from './dropzone.ts';
import {confirmModal} from './comp/ConfirmModal.ts';
import {applyAreYouSure, ignoreAreYouSure} from '../modules/are-you-sure.ts';
@@ -25,6 +25,9 @@ function initEditPreviewTab(elForm: HTMLFormElement) {
const elPreviewTab = elTabMenu.querySelector('a[data-tab="preview"]')!;
const elPreviewPanel = elForm.querySelector('.tab[data-tab="preview"]')!;
const previewFetch = new ExclusiveFetch(), diffFetch = new ExclusiveFetch();
elPreviewTab.addEventListener('click', async () => {
// "preview context" is the request path directory of the file, the rendered links will be resolved based on this path
// TODO: MARKUP-RENDER-CONTEXT: due to various hacky patches, this logic is unnecessarily complicated, see the backend
@@ -34,13 +37,9 @@ function initEditPreviewTab(elForm: HTMLFormElement) {
formData.append('context', previewContext);
formData.append('text', elTextarea.value);
formData.append('file_path', elTreePath.value);
const resp = await POST(`${repoLink}/markup`, {data: formData});
if (!resp.ok) {
showErrorToast(`Failed to render preview: ${resp.status} ${resp.statusText}`);
return;
}
const data = await resp.text();
renderPreviewPanelContent(elPreviewPanel, data);
const resp = previewFetch.request(`${repoLink}/markup`, {method: 'POST', data: formData});
resp.onResponseError((resp) => showErrorToast(`Failed to render preview: ${resp.status} ${resp.statusText}`));
await resp.fetchText((data) => renderPreviewPanelContent(elPreviewPanel, data));
});
const elDiffTab = elTabMenu.querySelector('a[data-tab="diff"]');
@@ -50,12 +49,9 @@ function initEditPreviewTab(elForm: HTMLFormElement) {
elDiffTab.addEventListener('click', async () => {
const diffUrl = `${repoLink}/_preview/${pathEscapeSegments(branchName)}/${pathEscapeSegments(elTreePath.value)}`;
// don't use FormData, because FormData sends "\r\n" line endings, backend assumes "\n" line endings
const resp = await POST(diffUrl, {data: new URLSearchParams({content: elTextarea.value})});
if (!resp.ok) {
showErrorToast(`Failed to render diff: ${resp.status} ${resp.statusText}`);
return;
}
elDiffPanel.innerHTML = await resp.text();
const resp = diffFetch.request(diffUrl, {method: 'POST', data: new URLSearchParams({content: elTextarea.value})});
resp.onResponseError((resp) => showErrorToast(`Failed to render diff: ${resp.status} ${resp.statusText}`));
await resp.fetchText((data) => elDiffPanel.innerHTML = data);
});
}
}
+26 -2
View File
@@ -1,6 +1,6 @@
import {GET, POST, PATCH, PUT, DELETE} from './fetch.ts';
import {GET, POST, PATCH, PUT, DELETE, ExclusiveFetch} from './fetch.ts';
// tests here are only to satisfy the linter for unused functions
// This test satisfies the linter for unused functions.
test('exports', () => {
expect(GET).toBeTruthy();
expect(POST).toBeTruthy();
@@ -8,3 +8,27 @@ test('exports', () => {
expect(PUT).toBeTruthy();
expect(DELETE).toBeTruthy();
});
test('ExclusiveFetch discards a superseded response while reading its body', async () => {
const bodyStarted = Promise.withResolvers<void>();
const oldBody = Promise.withResolvers<string>();
const oldResponse = new Response();
vi.spyOn(oldResponse, 'text').mockImplementation(() => {
bodyStarted.resolve();
return oldBody.promise;
});
const fetchMock = vi.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(oldResponse)
.mockResolvedValueOnce(new Response('new'));
onTestFinished(() => { fetchMock.mockRestore() });
const exclusiveFetch = new ExclusiveFetch();
const render = vi.fn();
const oldRequest = exclusiveFetch.request('/old').fetchText(render);
await bodyStarted.promise;
await exclusiveFetch.request('/new').fetchText(render);
oldBody.resolve('old');
await oldRequest;
expect(render.mock.calls).toEqual([['new']]);
});
+66
View File
@@ -31,3 +31,69 @@ export const POST = (url: string, opts?: RequestOpts) => request(url, {method: '
export const PATCH = (url: string, opts?: RequestOpts) => request(url, {method: 'PATCH', ...opts});
export const PUT = (url: string, opts?: RequestOpts) => request(url, {method: 'PUT', ...opts});
export const DELETE = (url: string, opts?: RequestOpts) => request(url, {method: 'DELETE', ...opts});
class ExclusiveResponse {
private readonly promiseResp: Promise<Response>;
private readonly exclusiveFetch: ExclusiveFetch;
private readonly abortController: AbortController;
private onResponseErrorFn: ((resp: Response) => void) | null = null;
constructor(exclusiveFetch: ExclusiveFetch, abortController: AbortController, promiseResp: Promise<Response>) {
this.exclusiveFetch = exclusiveFetch;
this.abortController = abortController;
this.promiseResp = promiseResp;
}
private isAborted() {
return this.abortController.signal.aborted || this.exclusiveFetch.currentController !== this.abortController;
}
// fetchGeneric is designed for future usages like "resp.json()", "resp.blob()", etc, they share the same "exclusive" logic
private async fetchGeneric<T>(readResp: (resp: Response) => Promise<T>, userFn: (ret: T) => void): Promise<boolean> {
try {
const resp = await this.promiseResp;
if (this.isAborted()) return false;
if (!resp.ok) {
this.onResponseErrorFn?.(resp);
return false;
}
const ret = await readResp(resp);
if (this.isAborted()) return false;
userFn(ret);
return true;
} catch (err) {
if (this.isAborted()) return false;
throw err;
}
}
// onResponseError allows the user to set a callback function that will be called when the response is not ok (e.g., 4xx or 5xx status codes).
// The callback is only called when the request is not-ok and not aborted (the request is the last one).
onResponseError(fn: (resp: Response) => void) {
this.onResponseErrorFn = fn;
}
// fetchText reads the response as text and passes it to the provided callback function.
// The callback is only called when the request is successful and not aborted (the request is the last one).
async fetchText(fn: (text: string) => void): Promise<boolean> {
return this.fetchGeneric((resp) => resp.text(), fn);
}
}
// ExclusiveFetch is used for fetching data where only the latest request is relevant.
// If a new request is made before the previous one completes, the previous request will be aborted and discarded.
// This class is composed with "fetch(request)" and "AbortController" to provide a convenient way to handle exclusive requests:
// * Use AbortController to abort previous requests when a new one is made.
// * Handle network exceptions (caused by abort)
// * Ignore outdated/stale responses
// * Handle network error codes
export class ExclusiveFetch {
public currentController: AbortController | null = null;
request(url: string, {method = 'GET', data, headers = {}, ...other}: RequestOpts = {}): ExclusiveResponse {
if (this.currentController) this.currentController.abort();
const controller = new AbortController();
this.currentController = controller;
return new ExclusiveResponse(this, controller, request(url, {method, data, headers, ...other, signal: controller.signal}));
}
}