src / pageXml.ts
/** Builders for OneNote page-update XML (ported from xml_utils.py). */
import { ONE_NS } from "./constants";
import { ContentFormat, contentToOeXml, escapeAttr, escapeText, oneT } from "./htmlToOneNote";
export function buildTitleXml(title: string): string {
return `<one:Title><one:OE>${oneT(escapeText(title))}</one:OE></one:Title>`;
}
export async function buildOutlineXml(
content: string,
opts: { contentFormat?: ContentFormat; objectId?: string | null; x?: number | null; y?: number | null; mdTimeout?: number } = {},
): Promise<string> {
const objectAttr = opts.objectId ? ` objectID="${escapeAttr(opts.objectId)}"` : "";
let position = "";
if (opts.x !== undefined && opts.x !== null || opts.y !== undefined && opts.y !== null) {
const px = opts.x === undefined || opts.x === null ? 36.0 : Number(opts.x);
const py = opts.y === undefined || opts.y === null ? 86.0 : Number(opts.y);
position = `<one:Position x="${px.toFixed(2)}" y="${py.toFixed(2)}" z="0"/>`;
}
const oe = await contentToOeXml(content, opts.contentFormat ?? "plain", opts.mdTimeout ?? 30);
return `<one:Outline${objectAttr}>${position}<one:OEChildren>${oe}</one:OEChildren></one:Outline>`;
}
export async function buildPageUpdateXml(
pageId: string,
opts: { title?: string | null; content?: string | null; contentFormat?: ContentFormat; x?: number | null; y?: number | null; mdTimeout?: number } = {},
): Promise<string> {
const parts = [`<one:Page xmlns:one="${ONE_NS}" ID="${escapeAttr(pageId)}">`];
if (opts.title !== undefined && opts.title !== null) parts.push(buildTitleXml(opts.title));
if (opts.content !== undefined && opts.content !== null && opts.content !== "") {
parts.push(
await buildOutlineXml(opts.content, {
contentFormat: opts.contentFormat,
x: opts.x,
y: opts.y,
mdTimeout: opts.mdTimeout,
}),
);
}
parts.push("</one:Page>");
return parts.join("");
}
export function buildImagePageUpdateXml(
pageId: string,
opts: { imageBase64: string; imageFormat: string; x?: number; y?: number; width?: number | null; height?: number | null },
): string {
const x = opts.x ?? 36.0;
const y = opts.y ?? 120.0;
let size = "";
if (opts.width !== undefined && opts.width !== null && opts.height !== undefined && opts.height !== null) {
size = `<one:Size width="${Number(opts.width).toFixed(2)}" height="${Number(opts.height).toFixed(2)}"/>`;
}
return (
`<one:Page xmlns:one="${ONE_NS}" ID="${escapeAttr(pageId)}">` +
"<one:Outline>" +
`<one:Position x="${Number(x).toFixed(2)}" y="${Number(y).toFixed(2)}" z="0"/>` +
"<one:OEChildren><one:OE>" +
`<one:Image format="${escapeAttr(opts.imageFormat.toLowerCase())}">` +
`${size}<one:Data>${opts.imageBase64}</one:Data>` +
"</one:Image>" +
"</one:OE></one:OEChildren>" +
"</one:Outline>" +
"</one:Page>"
);
}