Files
obsidian-unicode-formatter/src/formatter.ts
T

79 lines
2.5 KiB
TypeScript

import { BOLD_MAP, ITALIC_MAP, BOLD_ITALIC_MAP, UNICODE_TO_ASCII_MAP, UNICODE_TO_STYLE } from "./unicode-maps";
export type FormatStyle = "bold" | "italic" | "bold-italic";
const STYLE_MAPS: Record<FormatStyle, Record<string, string>> = {
"bold": BOLD_MAP,
"italic": ITALIC_MAP,
"bold-italic": BOLD_ITALIC_MAP,
};
export function transformText(text: string, style: FormatStyle): string {
const map = STYLE_MAPS[style];
return [...text].map(ch => map[ch] ?? ch).join("");
}
export function cleanText(text: string): string {
return text.split("\n").map(line => {
if (line.startsWith("— ")) line = line.slice(2);
else if (line.startsWith("→ ")) line = line.slice(2);
line = line.replace(/^\(\d+\) /, "").replace(/^\d+\/ /, "");
const output: string[] = [];
let currentStyle: string | null = null;
let buf: string[] = [];
const flush = () => {
if (buf.length === 0) return;
const s = buf.join("");
if (currentStyle === "bold") output.push(`**${s}**`);
else if (currentStyle === "italic") output.push(`_${s}_`);
else if (currentStyle === "bold-italic") output.push(`**_${s}_**`);
else output.push(s);
buf = [];
};
for (const ch of line) {
const style = UNICODE_TO_STYLE.get(ch) ?? null;
const ascii = UNICODE_TO_ASCII_MAP.get(ch) ?? ch;
if (style !== currentStyle) { flush(); currentStyle = style; }
buf.push(ascii);
}
flush();
return output.join("");
}).join("\n");
}
export function bulletToEmdash(text: string): string {
return text.split("\n").map(line =>
line.startsWith("* ") ? "— " + line.slice(2) : "— " + line
).join("\n");
}
export function bulletToArrow(text: string): string {
return text.split("\n").map(line =>
line.startsWith("* ") ? "→ " + line.slice(2) : "→ " + line
).join("\n");
}
export function numberedListSlash(text: string): string {
let n = 0;
return text.split("\n").map(line => {
n++;
const content = line.startsWith("* ") ? line.slice(2) : line;
return `${n}/ ${content}`;
}).join("\n");
}
export function numberedListParens(text: string): string {
let n = 0;
return text.split("\n").map(line => {
n++;
const content = line.startsWith("* ") ? line.slice(2) : line;
return `(${n}) ${content}`;
}).join("\n");
}
export { markdownToLinkedIn } from "./linkedin";