Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions scripts/documents.conflicts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const { createDocumentSession } = await import('../src/lib/sessions/documentSess
const { createWindowExit } = await import('../src/lib/sessions/windowExit.js');
const { createExternalChange } = await import('../src/lib/sessions/externalChange.svelte.js');
const { HOME_TAB_PATH } = await import('../src/lib/utils/homeTab.js');
const { stampImageGeneration } = await import('../src/lib/utils/markdown.js');

// An unanswered external-change conflict is a question only the user can
// answer. The viewer's saves that nobody asked for — leaving the editor or
Expand Down Expand Up @@ -276,6 +277,21 @@ describe('external change conflicts', () => {
assert.deepEqual(viewer.toasts, ['toast.reloadedFromDisk']);
});

// #1066: both reverts refetch the document's images, not only its text.
test('both reload commands make the preview fetch local images again', async () => {
const image = '<img src="a.png">';
const viewer = makeViewer();
const tab = conflicted(viewer);

const before = stampImageGeneration(image);
await viewer.conflicts.resolveExternalChangeByReloading(tab.id);
const afterConflictReload = stampImageGeneration(image);
assert.notEqual(afterConflictReload, before, 'Reload on the conflict bar kept the cached images');

await viewer.conflicts.reloadFromDisk();
assert.notEqual(stampImageGeneration(image), afterConflictReload, 'Reload from disk kept the cached images');
});

// --- the watcher's `file-changed` event ---

/** a.md in the background, b.md on screen, both saved and clean. */
Expand Down
49 changes: 49 additions & 0 deletions scripts/preview.imageReload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import { processMarkdownHtml, refetchLocalImages, stampImageGeneration } from '../src/lib/utils/markdown.ts';
import { useShimDom } from './preview.domShim.ts';
import { parseHtml } from './renderProtocolDom.ts';

// #1066: Reload must fetch an image edited on disk again, not reuse the old copy.
describe('reload refetches local images', () => {
useShimDom({ window: { __TAURI_INTERNALS__: { convertFileSrc: (path: string) => `asset://localhost/${path}` } } });

const FILE_PATH = '/documents/notes.md';
const RENDERED = '<p data-sourcepos="1:1-1:4">text</p>\0<p data-sourcepos="3:1-3:12"><img src="a.png" alt="" /></p>';
const srcOf = (html: string) => parseHtml(processMarkdownHtml(html, FILE_PATH, new Set())).body.querySelector('img')?.getAttribute('src');

test('before any reload the markup and the URL are untouched', () => {
assert.equal(stampImageGeneration(RENDERED), RENDERED);
assert.equal(srcOf(RENDERED), 'asset://localhost//documents/a.png');
});

test('each reload changes only the blocks holding an image, and their URL', () => {
refetchLocalImages();
const first = stampImageGeneration(RENDERED).split('\0');
assert.equal(first[0], RENDERED.split('\0')[0], 'a block without an image would be re-inserted for nothing');
assert.notEqual(first[1], RENDERED.split('\0')[1], 'the image block would be kept, so its <img> never reloads');
assert.equal(srcOf(first.join('\0')), 'asset://localhost//documents/a.png?v=1');

refetchLocalImages();
assert.equal(srcOf(stampImageGeneration(RENDERED)), 'asset://localhost//documents/a.png?v=2');
});

test('the stamp does not survive into the preview, and only real img tags get it', () => {
const html = processMarkdownHtml(stampImageGeneration(RENDERED), FILE_PATH, new Set());
assert.doesNotMatch(html, /data-image-generation/);
assert.match(stampImageGeneration('<IMG src="b.png">'), /data-image-generation/);
assert.equal(stampImageGeneration('<imgx src="b.png">'), '<imgx src="b.png">');
});

// The stamp is text, so it also lands on `<img` written inside raw HTML's
// attribute values. Unquoted, it cannot close the attribute it lands in.
test('an <img> written inside an attribute value leaves the attribute whole', () => {
const body = parseHtml(stampImageGeneration('<p><span title="a <img> b">x</span></p>')).body;
assert.equal(body.querySelector('span')?.textContent, 'x');
assert.match(body.querySelector('span')?.getAttribute('title') ?? '', /^a <img .*> b$/);
});

test('a remote image keeps the URL its author wrote', () => {
assert.equal(srcOf(stampImageGeneration('<p><img src="https://example.com/a.png" /></p>')), 'https://example.com/a.png');
});
});
3 changes: 2 additions & 1 deletion src/lib/MarkdownViewer.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { type FoldLayoutObservation } from './utils/foldLayout.js';
import { followFoldLayout, previewPaneShown } from './utils/foldLayoutEffect.svelte.js';
import { followPreviewPatch } from './utils/previewPatchEffect.svelte.js';
import { patchHost } from './utils/previewPatch.js';
import { stampImageGeneration } from './utils/markdown.js';
import { refreshesPreviewCache } from './utils/previewRefresh.js';
import {
revealFold,
Expand Down Expand Up @@ -908,7 +909,7 @@ import { followActiveFile } from './sessions/fileWatch.svelte.js';
// moved the tab to the new file and cleared its folds by then.
async function renderMarkdownPreview(raw: string) {
const body = getMarkdownBodyWithoutFrontMatter(raw);
return await commands.renderMarkdown(body, true);
return stampImageGeneration(await commands.renderMarkdown(body, true));
}

async function renderTabPreviewFromRaw(tab: Tab) {
Expand Down
3 changes: 3 additions & 0 deletions src/lib/sessions/externalChange.svelte.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { LanguageCode, TranslationKey } from '../utils/i18n.js';
import type { LoadMarkdownOptions } from './documentSession.svelte.js';
import { refetchLocalImages } from '../utils/markdown.js';

type ConflictTab = { id: string; path: string; originalContent: string; rawContent: string; isDirty: boolean };

Expand Down Expand Up @@ -147,6 +148,7 @@ export function createExternalChange(options: ExternalChangeOptions) {
if (!tab?.path || tab.id !== tabId) return;
comparison = null;
clearExternalChangeConflict(tab.id);
refetchLocalImages();
await loadMarkdown(tab.path, {
preserveEditState: true,
skipTabManagement: true,
Expand All @@ -165,6 +167,7 @@ export function createExternalChange(options: ExternalChangeOptions) {
if (!activeId || !tab?.path) return;
if (!(await options.canCloseTab(activeId))) return;

refetchLocalImages();
await loadMarkdown(tab.path, {
preserveEditState: true,
skipTabManagement: true,
Expand Down
23 changes: 22 additions & 1 deletion src/lib/utils/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,25 @@ export function processMarkdownHtml(
/** `+` or `-`, on a foldable callout: what the document opens it as. */
const CALLOUT_FOLD_ATTR = "data-callout-fold";

/**
* Reload re-reads the document, not its images (#1066). An image edited on
* disk keeps its URL, so the webview shows the copy it already decoded, and a
* block whose markup did not change is not even re-inserted. Each explicit
* reload starts a new generation: the preview stamps it onto every `<img>`,
* which changes exactly the blocks holding one, and their local URLs carry it
* as a query the asset protocol ignores (it reads only the path).
*/
let imageGeneration = 0;
const GENERATION_ATTR = "data-image-generation";

export function refetchLocalImages(): void {
imageGeneration++;
}

export function stampImageGeneration(html: string): string {
return imageGeneration ? html.replace(/<img(?=[\s/>])/gi, `<img ${GENERATION_ATTR}=${imageGeneration}`) : html;
}

/**
* Everything `processMarkdownHtml` does that only looks inside one top-level
* block. Fold keys and the heading wrappers need the whole document and are
Expand All @@ -707,6 +726,8 @@ export function processBlockMarkup(root: Element, filePath: string): void {
const doc = root.ownerDocument;
for (const img of root.querySelectorAll("img")) {
const src = img.getAttribute("src");
const generation = img.getAttribute(GENERATION_ATTR);
img.removeAttribute(GENERATION_ATTR);
let finalSrc = src;
if (src && !src.startsWith("http") && !src.startsWith("data:")) {
try {
Expand All @@ -719,7 +740,7 @@ export function processBlockMarkup(root: Element, filePath: string): void {
finalSrc = null;
img.removeAttribute("src");
} else {
finalSrc = convertFileSrc(resolved);
finalSrc = convertFileSrc(resolved) + (generation ? `?v=${generation}` : "");
img.setAttribute("src", finalSrc);
}
} catch (e) {
Expand Down
Loading