Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(import): honor the shrink-images option for Notion and OneNote
Elian Doran7300fd6f81f7
diff --git a/apps/client/src/services/onenote_import.ts b/apps/client/src/services/onenote_import.tsindex 9960ae8f7a..a3b14f08fc 100644--- a/apps/client/src/services/onenote_import.ts+++ b/apps/client/src/services/onenote_import.ts@@ -40,7 +40,7 @@ function getNotebooks() {// Kicks off the import and returns as soon as the server has accepted it. The import itself runs in the// background on the server; progress, completion (navigation to the imported note) and any error all// arrive over the WebSocket via the shared "importNotes" toast handlers in import.ts.-function runImport(payload: { parentNoteId: string; sections: OneNoteSectionSelection[]; taskId: string; debug?: boolean }) {+function runImport(payload: { parentNoteId: string; sections: OneNoteSectionSelection[]; taskId: string; debug?: boolean; shrinkImages?: boolean }) {return server.post<void>("onenote-import/import", payload);}diff --git a/apps/client/src/widgets/dialogs/import/onenote.tsx b/apps/client/src/widgets/dialogs/import/onenote.tsxindex 4e0c792d0c..2daafd1f2d 100644--- a/apps/client/src/widgets/dialogs/import/onenote.tsx+++ b/apps/client/src/widgets/dialogs/import/onenote.tsx@@ -7,6 +7,7 @@ import { isElectron, randomString } from "../../../services/utils.js";import Button from "../../react/Button.js";import { Card, CardSection } from "../../react/Card.js";import FormCheckbox from "../../react/FormCheckbox.js";+import { useTriliumOptionBool } from "../../react/hooks.js";import LoadingSpinner from "../../react/LoadingSpinner.js";import NoItems from "../../react/NoItems.js";import OptionsRow, { OptionsRowWithToggle } from "../../type_widgets/options/components/OptionsRow.js";@@ -21,6 +22,8 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPaconst [notebooks, setNotebooks] = useState<OneNoteNotebook[]>([]);const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());const [debug, setDebug] = useState(false);+ const [compressImages] = useTriliumOptionBool("compressImages");+ const [shrinkImages, setShrinkImages] = useState(compressImages);const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);const stopPolling = useCallback(() => {@@ -134,11 +137,11 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa// the only errors caught here are upfront ones like a lost connection or an invalid selection.closeDialog();try {- await onenoteImport.runImport({ parentNoteId, sections, taskId: randomString(10), debug });+ await onenoteImport.runImport({ parentNoteId, sections, taskId: randomString(10), debug, shrinkImages: compressImages && shrinkImages });} catch (e) {toast.showError(e instanceof Error ? e.message : String(e));}- }, [notebooks, selectedIds, parentNoteId, debug, closeDialog]);+ }, [notebooks, selectedIds, parentNoteId, debug, compressImages, shrinkImages, closeDialog]);// Keep the latest import handler in a ref so the footer effect below depends only on the values the// footer actually shows (all primitives), never on doImport's identity. Depending on doImport — which@@ -206,6 +209,14 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa))}</div></OptionsRow>+ <OptionsRowWithToggle+ name="onenote-shrink-images"+ label={t("import.shrinkImages")}+ description={t("import.shrinkImagesProviderTooltip")}+ currentValue={compressImages && shrinkImages}+ onChange={setShrinkImages}+ disabled={!compressImages}+ /><OptionsRowWithTogglename="onenote-debug"label={t("onenote_import.attach_source")}diff --git a/apps/server/src/routes/api/onenote_import.ts b/apps/server/src/routes/api/onenote_import.tsindex b3da99924c..32b7e6a286 100644--- a/apps/server/src/routes/api/onenote_import.ts+++ b/apps/server/src/routes/api/onenote_import.ts@@ -87,7 +87,7 @@ async function runImport(req: Request) {return [401, "Not connected to OneNote."];}- const { parentNoteId, sections, taskId, debug } = req.body as { parentNoteId: string; sections: OneNoteSectionSelection[]; taskId: string; debug?: boolean };+ const { parentNoteId, sections, taskId, debug, shrinkImages } = req.body as { parentNoteId: string; sections: OneNoteSectionSelection[]; taskId: string; debug?: boolean; shrinkImages?: boolean };if (!parentNoteId || !taskId) {throw new ValidationError("parentNoteId and taskId are required.");}@@ -100,7 +100,7 @@ async function runImport(req: Request) {// we return immediately and let the import report progress, completion and any error over the// WebSocket (taskType "importNotes"). importSelection catches and reports its own failures, so the// detached promise never rejects.- void importer.importSelection({ accessToken, parentNoteId, sections, taskId, debug: !!debug });+ void importer.importSelection({ accessToken, parentNoteId, sections, taskId, debug: !!debug, shrinkImages: !!shrinkImages });return {};}diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.tsindex a3fa580d16..2eb1e6395c 100644--- a/apps/server/src/services/import/onenote/importer.ts+++ b/apps/server/src/services/import/onenote/importer.ts@@ -65,8 +65,8 @@ interface FetchedSection {* reported over the WebSocket via the "importNotes" TaskContext, so this never throws to the caller:* any error is caught and surfaced as a task error toast instead.*/-export async function importSelection({ accessToken, parentNoteId, sections, taskId, debug = false }: { accessToken: string; parentNoteId: string; sections: OneNoteSectionSelection[]; taskId: string; debug?: boolean }): Promise<void> {- const taskContext = TaskContext.getInstance(taskId, "importNotes", { safeImport: true });+export async function importSelection({ accessToken, parentNoteId, sections, taskId, debug = false, shrinkImages = false }: { accessToken: string; parentNoteId: string; sections: OneNoteSectionSelection[]; taskId: string; debug?: boolean; shrinkImages?: boolean }): Promise<void> {+ const taskContext = TaskContext.getInstance(taskId, "importNotes", { safeImport: true, shrinkImages });try {// Phase 1: pull everything over the network first, so note creation can run in a single@@ -104,7 +104,7 @@ export async function importSelection({ accessToken, parentNoteId, sections, tas}// Phase 2: create the note tree.- const rootNoteId = sql.transactional(() => createNotes(parentNoteId, fetched, debug));+ const rootNoteId = sql.transactional(() => createNotes(parentNoteId, fetched, debug, shrinkImages));taskContext.taskSucceeded({ parentNoteId, importedNoteId: rootNoteId });} catch (e: unknown) {@@ -113,7 +113,7 @@ export async function importSelection({ accessToken, parentNoteId, sections, tas}}-function createNotes(parentNoteId: string, sections: FetchedSection[], debug: boolean): string {+function createNotes(parentNoteId: string, sections: FetchedSection[], debug: boolean, shrinkImages: boolean): string {const parentNote = becca.getNoteOrThrow(parentNoteId);const isProtected = parentNote.isProtected && protectedSession.isProtectedSessionAvailable();@@ -180,10 +180,10 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo// second pass below, once every page has a note to point at.let content = page.html;if (page.resources.length > 0) {- content = rewritePageResources(pageNote, content, page.resources);+ content = rewritePageResources(pageNote, content, page.resources, shrinkImages);}if (page.inkSvg) {- content += renderInkFigure(pageNote, page.inkSvg);+ content += renderInkFigure(pageNote, page.inkSvg, shrinkImages);}createdPages.push({ note: pageNote, original: page.html, content, page });@@ -273,8 +273,8 @@ function toUtcDbDate(isoDateTime: string | undefined): string | undefined {* Saves a page's rendered ink SVG as an image attachment on the note and returns the `<figure>` markup* that embeds it inline. Returns an empty string if the attachment could not be created.*/-function renderInkFigure(note: BNote, svg: string): string {- const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, binary_utils.encodeUtf8(svg), "OneNote ink.svg", false);+function renderInkFigure(note: BNote, svg: string, shrinkImages: boolean): string {+ const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, binary_utils.encodeUtf8(svg), "OneNote ink.svg", shrinkImages);if (!attachmentId) {return "";}@@ -364,7 +364,7 @@ export async function mapWithConcurrency<T, R>(items: T[], limit: number, worker* images become attachment-backed `<img src="api/attachments/…">`, file attachments become Trilium* reference links. References whose download failed are left as-is.*/-function rewritePageResources(note: BNote, html: string, resources: DownloadedResource[]): string {+function rewritePageResources(note: BNote, html: string, resources: DownloadedResource[], shrinkImages: boolean): string {const byUrl = new Map(resources.map((resource) => [resource.url, resource]));const root = parse(html);@@ -374,7 +374,7 @@ function rewritePageResources(note: BNote, html: string, resources: DownloadedRecontinue;}const originalName = resource.title.includes(".") ? resource.title : `${resource.title}.${extensionForMime(resource.mime)}`;- const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, resource.content, originalName, false);+ const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, resource.content, originalName, shrinkImages);if (attachmentId) {img.setAttribute("src", `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`);}diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.tsindex dcb761d0be..a4e3af0f93 100644--- a/packages/trilium-core/src/services/import/notion/importer.ts+++ b/packages/trilium-core/src/services/import/notion/importer.ts@@ -189,6 +189,7 @@ function parsePage(path: string, html: string): ParsedPage | null {function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<string, Uint8Array>, taskContext: TaskContext<"importNotes">, csvColumnsByFolder: Map<string, string[]>): BNote {/* v8 ignore next -- the protected branch needs a protected import root with an active protected session, which the in-memory test DB has no way to set up */const isProtected = importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable();+ const shrinkImages = !!taskContext.data?.shrinkImages;const rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: t("notion_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;rootNote.addLabel("iconClass", "bx bx-import");@@ -229,7 +230,7 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<// Attachments hang off the note, so this must run after creation; it returns the content with the// <img> srcs and file links pointing at the saved attachments.- const withImages = rewriteImages(note, body, page.path, resources);+ const withImages = rewriteImages(note, body, page.path, resources, shrinkImages);created.push({ note, content: rewriteAttachments(note, withImages, page.path, resources), page });taskContext.increaseProgressCount();}@@ -262,7 +263,7 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<* point at it. References that don't resolve to a bundled file (e.g. external image URLs) are left as-is.* Returns the (possibly unchanged) content.*/-function rewriteImages(note: BNote, content: string, pagePath: string, resources: Map<string, Uint8Array>): string {+function rewriteImages(note: BNote, content: string, pagePath: string, resources: Map<string, Uint8Array>, shrinkImages: boolean): string {const root = parse(content);let changed = false;@@ -276,7 +277,7 @@ function rewriteImages(note: BNote, content: string, pagePath: string, resourcesif (!bytes) {continue;}- const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, bytes, baseName(resourcePath), false);+ const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, bytes, baseName(resourcePath), shrinkImages);/* v8 ignore next -- saveImageToAttachment always returns the id of the attachment it just created, so this guard is never false in practice */if (attachmentId) {img.setAttribute("src", `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`);