de-duplicated getFontDataURL, svgToBase64, and cropCanvas

This commit is contained in:
zsviczian committed 2026-08-08 21:45:19 +02:00
1 parent ff2c8536ce
commit 00a1bed763
3 files changed
+46 -87

No files matched your search

+5 -1
View File
@@ -20,7 +20,7 @@ validated, and what remains uncertain.
| --- | --- | --- |
| Assessment and baseline design | Complete | Initial architecture, risks, sequencing, and validation matrix documented |
| Retire legacy AI settings and fallbacks | Complete | Removed the retired migration, schema/default fields, GPT reset, and AI runtime fallbacks without filtering unknown persisted keys; manual testing found no issues |
| Audit and consolidate duplicate logic | In progress | Consolidated `updateFrontmatterInString()`, `arrayToMap()`, `wrapTextAtCharLength()`, `getLinkParts()`/`LinkParts`, and `getBinaryFileFromDataURL()`; continue one independently testable helper family at a time |
| Audit and consolidate duplicate logic | In progress | Consolidated `updateFrontmatterInString()`, `arrayToMap()`, `wrapTextAtCharLength()`, `getLinkParts()`/`LinkParts`, `getBinaryFileFromDataURL()`, `svgToBase64()`, `getFontDataURL()`, and `cropCanvas()`; continue one independently testable helper family at a time |
| All later phases | Planned | Begin only after the preceding checkpoint is validated |
### Action log
@@ -39,6 +39,10 @@ validated, and what remains uncertain.
| 2026-08-08 | Consolidated `getLinkParts()` and `LinkParts` | Moved the duplicated parser and type to documented `linkUtils.ts`, preserving both existing value and type import paths through re-exports | Repository search confirms one function and one type definition; targeted ESLint and `npm run build` passed; the existing 34 circular dependency warnings are unchanged; bundle size decreased by 395 bytes to 5,096,593 bytes |
| 2026-08-08 | Consolidated `getBinaryFileFromDataURL()` | Moved the duplicated URL-fetch/base64 decoding helper into `fileUtils.ts`, its existing dependency owner, and preserved both old import paths through re-exports. Replaced the loosely typed first `matchAll()` result with equivalent typed `match()` capture handling | Repository search confirms one implementation; targeted ESLint, `npm run build`, `npm run lib`, and `git diff --check` passed; the existing 34 circular dependency warnings are unchanged; bundle size decreased by 405 bytes to 5,096,188 bytes |
| 2026-08-08 | Closed the text, link, and binary helper validation checkpoint | Manual testing found no regressions in wrapping, link parsing, or binary image handling | User confirmed the recommended checks completed successfully |
| 2026-08-08 | Consolidated `svgToBase64()` | Kept `embeddedAssetUtils.ts` as the canonical owner, added TSDoc for XML entity and UTF-8 handling, and preserved the `utils.ts` import surface through a re-export. Added explicit regex callback parameter types without changing encoding behavior | Repository search confirms one implementation; `npm run build` passed with the unchanged 34 circular dependency warnings; bundle size decreased by 206 bytes to 5,095,988 bytes; targeted ESLint has no diagnostics on the consolidated helper and retains two unrelated backlog errors in `embeddedAssetUtils.ts`; `git diff --check` passed |
| 2026-08-08 | Consolidated `getFontDataURL()` | Kept `embeddedAssetUtils.ts` as the canonical owner, added TSDoc for vault resolution, extension mapping, and empty-result behavior, and preserved the `utils.ts` export used by plugin startup | Repository search confirms one implementation; `npm run build` passed with the unchanged 34 circular dependency warnings; bundle size decreased by 609 bytes to 5,095,379 bytes; targeted ESLint has no diagnostics on the consolidated helper and retains the same two unrelated backlog errors in `embeddedAssetUtils.ts`; `git diff --check` passed |
| 2026-08-08 | Closed the font helper validation checkpoint | Manual testing found no regressions in vault font loading | User confirmed `getFontDataURL()` works |
| 2026-08-08 | Consolidated `cropCanvas()` | Kept `embeddedAssetUtils.ts` as the canonical owner, added TSDoc for source rectangles, output scaling, and intentionally unchanged browser canvas behavior, and preserved the `utils.ts` export | Repository search confirms one implementation; `npm run build` passed with the unchanged 34 circular dependency warnings; bundle size remains 5,095,379 bytes because Rollup already removed the unused duplicate; targeted ESLint has no diagnostics on the consolidated helper and retains the same two unrelated backlog errors in `embeddedAssetUtils.ts`; `git diff --check` passed |
## Executive recommendation
+37 -1
View File
@@ -6,6 +6,19 @@ import { getDataURL } from "./coreUtils";
export { getEmbeddedFilenameParts } from "./embeddedFilenameParts";
/**
* Loads a vault font and creates its data URL and `@font-face` definition.
*
* @param app - Obsidian application used to resolve and read the font file.
* @param fontFileName - Vault link path or font filename to resolve.
* @param sourcePath - Vault path from which the font link is resolved.
* @param name - Optional font-family name overriding the file basename.
* @returns The font definition, resolved family name, and encoded data URL.
* Empty strings are returned when the font cannot be resolved.
* @remarks
* MIME types and CSS format names intentionally preserve the established
* extension mapping used by plugin startup and embedded SVG font loading.
*/
export async function getFontDataURL(
app: App,
fontFileName: string,
@@ -50,11 +63,22 @@ export async function getFontDataURL(
return { fontDef, fontName, dataURL };
}
/**
* Encodes SVG markup as a base64 data URL.
*
* @param svg - Serialized SVG markup.
* @returns A base64-encoded `data:image/svg+xml` URL.
* @remarks
* Literal ` ` entities are converted to spaces before encoding because
* they are not valid predefined XML entities. URI encoding is converted to a
* byte string before `btoa()` so non-Latin text remains UTF-8 safe.
*/
export function svgToBase64(svg: string): string {
const cleanSvg = svg.replaceAll(" ", " ");
const encodedData = encodeURIComponent(cleanSvg).replace(
/%([0-9A-F]{2})/g,
(_match, p1) => String.fromCharCode(parseInt(p1, 16)),
(_match: string, hexByte: string) =>
String.fromCharCode(parseInt(hexByte, 16)),
);
return `data:image/svg+xml;base64,${btoa(encodedData)}`;
}
@@ -168,6 +192,18 @@ export function getExportPadding(
return plugin.settings.exportPaddingSVG;
}
/**
* Copies a rectangular canvas region into a new canvas, optionally scaling it.
* Based on: https://stackoverflow.com/a/54555834
*
* @param srcCanvas - Source canvas to crop.
* @param crop - Source rectangle in canvas coordinates.
* @param output - Destination dimensions; defaults to the crop dimensions.
* @returns A newly created canvas containing the cropped image.
* @remarks
* This preserves the existing `drawImage()` behavior without clamping the
* source rectangle or changing browser interpolation and transparency rules.
*/
export function cropCanvas(
srcCanvas: HTMLCanvasElement,
crop: { left: number; top: number; width: number; height: number },
+4 -85
View File
@@ -6,7 +6,7 @@ import {
BinaryFiles,
NormalizedZoomValue,
} from "@zsviczian/excalidraw/types/excalidraw/types";
import { errorlog, getDataURL } from "./coreUtils";
import { errorlog } from "./coreUtils";
import {
exportToSvg,
exportToBlob,
@@ -57,8 +57,11 @@ export { arrayToMap };
export { errorlog, getDataURL } from "./coreUtils";
export { addAppendUpdateCustomData } from "./elementCustomDataUtils";
export { getBinaryFileFromDataURL } from "./fileUtils";
export { cropCanvas } from "./embeddedAssetUtils";
export { getFontDataURL } from "./embeddedAssetUtils";
export { getLinkParts } from "./linkUtils";
export type { LinkParts } from "./linkUtils";
export { svgToBase64 } from "./embeddedAssetUtils";
export { wrapTextAtCharLength } from "./textUtils";
export {
getEmbeddedFilenameParts,
@@ -213,50 +216,6 @@ export function rotatedDimensions(
return [bb.minX, bb.minY, bb.maxX - bb.minX, bb.maxY - bb.minY];
}
export async function getFontDataURL(
app: App,
fontFileName: string,
sourcePath: string,
name?: string,
): Promise<{ fontDef: string; fontName: string; dataURL: string }> {
let fontDef: string = "";
let fontName = "";
let dataURL = "";
const f = app.metadataCache.getFirstLinkpathDest(fontFileName, sourcePath);
if (f) {
const ab = await app.vault.readBinary(f);
let mimeType = "";
let format = "";
switch (f.extension) {
case "woff":
mimeType = "application/font-woff";
format = "woff";
break;
case "woff2":
mimeType = "font/woff2";
format = "woff2";
break;
case "ttf":
mimeType = "font/ttf";
format = "truetype";
break;
case "otf":
mimeType = "font/otf";
format = "opentype";
break;
default:
mimeType = "application/octet-stream"; // Fallback if file type is unexpected
}
fontName = name ?? f.basename;
dataURL = await getDataURL(ab, mimeType);
const split = dataURL.split(";base64,", 2);
dataURL = `${split[0]};charset=utf-8;base64,${split[1]}`;
fontDef = ` @font-face {font-family: "${fontName}";src: url("${dataURL}") format("${format}")}`;
}
return { fontDef, fontName, dataURL };
}
export function base64StringToBlob(
base64String: string,
mimeType: string,
@@ -265,18 +224,6 @@ export function base64StringToBlob(
return new Blob([buffer], { type: mimeType });
}
export function svgToBase64(svg: string): string {
const cleanSvg = svg.replaceAll("&nbsp;", " ");
// Convert the string to UTF-8 and handle non-Latin1 characters
const encodedData = encodeURIComponent(cleanSvg).replace(
/%([0-9A-F]{2})/g,
(match, p1) => String.fromCharCode(parseInt(p1, 16)),
);
return `data:image/svg+xml;base64,${btoa(encodedData)}`;
}
/**
* Exports an Excalidraw scene to SVG.
*
@@ -1160,34 +1107,6 @@ export async function getFontMetrics(
}
}
// Thanks https://stackoverflow.com/a/54555834
export function cropCanvas(
srcCanvas: HTMLCanvasElement,
crop: { left: number; top: number; width: number; height: number },
output: { width: number; height: number } = {
width: crop.width,
height: crop.height,
},
) {
const dstCanvas = createEl("canvas");
dstCanvas.width = output.width;
dstCanvas.height = output.height;
dstCanvas
.getContext("2d")
.drawImage(
srcCanvas,
crop.left,
crop.top,
crop.width,
crop.height,
0,
0,
output.width,
output.height,
);
return dstCanvas;
}
// Promise.try, adapted from https://github.com/sindresorhus/p-try
export async function promiseTry<TValue, TArgs extends unknown[]>(
fn: (...args: TArgs) => PromiseLike<TValue> | TValue,