init
This commit is contained in:
commit
1c75afe0fd
244 files changed
+27710
No files matched your search
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@ohmycv/case-police",
|
||||
"version": "0.1.1",
|
||||
"description": "Use `case-police` in the browser environment.",
|
||||
"homepage": "https://github.com/Renovamen/oh-my-cv/tree/main/packages/case-police",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Renovamen/oh-my-cv"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Renovamen/oh-my-cv.git",
|
||||
"directory": "packages/case-police"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Renovamen <renovamenzxh@gmail.com>",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.js",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build-fast:pkg": "tsup src/index.ts --format cjs,esm",
|
||||
"build:pkg": "pnpm run build-fast:pkg --dts"
|
||||
},
|
||||
"dependencies": {
|
||||
"case-police": "^0.6.1"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { replaceCore, loadPresets, DISABLE_KEY, type Preset } from "./utils";
|
||||
|
||||
/**
|
||||
* Works like `case-police`'s CLI, but in the browser environment.
|
||||
*
|
||||
* @param code The code to correct.
|
||||
* @param options Options for case-police.
|
||||
* - `ignore` A list of words to ignore.
|
||||
* - `dict` Custom dictionary JSON, will be merged with original dict
|
||||
* - `presets` Filter the default presets (softwares, products, general, brands, abbreviates)
|
||||
*
|
||||
* @returns
|
||||
* - `{ code, changed }` The corrected code and a list of changed words, if any changes are made
|
||||
* - `undefined` if the code contains `@case-police-disable` or no changes are made
|
||||
*
|
||||
* @see {@link CasePoliceReturn}
|
||||
*/
|
||||
export const replace = (
|
||||
code: string,
|
||||
options: {
|
||||
ignore?: string[];
|
||||
dict?: Record<string, string>;
|
||||
presets?: Preset[];
|
||||
} = {}
|
||||
) => {
|
||||
if (code.includes(DISABLE_KEY)) return;
|
||||
|
||||
const ignore = (options.ignore || []).map((i) => i.trim().toLowerCase());
|
||||
const dict = {
|
||||
...loadPresets(options.presets),
|
||||
...options.dict
|
||||
};
|
||||
|
||||
return replaceCore(code, dict, ignore);
|
||||
};
|
||||
|
||||
export default replace;
|
||||
|
||||
export type { Preset, CasePoliceReturn, ChangedCase } from "./utils";
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* @fileoverview This file is modified from https://github.com/antfu/case-police/blob/main/packages/case-police/src/utils.ts.
|
||||
*
|
||||
* The original file relies on Node.js APIs, which are removed in this file, so that
|
||||
* this package can be used in the browser environment.
|
||||
*/
|
||||
|
||||
import abbreviates from "case-police/dict/abbreviates.json" assert { type: "json" };
|
||||
import brands from "case-police/dict/brands.json" assert { type: "json" };
|
||||
import general from "case-police/dict/general.json" assert { type: "json" };
|
||||
import products from "case-police/dict/products.json" assert { type: "json" };
|
||||
import softwares from "case-police/dict/softwares.json" assert { type: "json" };
|
||||
|
||||
export type Preset = "softwares" | "products" | "general" | "brands" | "abbreviates";
|
||||
|
||||
export type ChangedCase = {
|
||||
from: string;
|
||||
to: string;
|
||||
index: number;
|
||||
};
|
||||
|
||||
export type CasePoliceReturn = {
|
||||
code: string;
|
||||
changed: ChangedCase[];
|
||||
};
|
||||
|
||||
export const DISABLE_KEY = "@case-police-disable";
|
||||
export const IGNORE_REGEX = /@case-police-ignore\s+([^\s]+)/g;
|
||||
|
||||
export const UTF8_RANGE = "[\u0080-\uFFFF]";
|
||||
|
||||
export const AVALIABLE_PRESETS: Record<Preset, Record<string, string>> = {
|
||||
softwares,
|
||||
products,
|
||||
general,
|
||||
brands,
|
||||
abbreviates
|
||||
};
|
||||
|
||||
export function buildRegex(dictionary: Record<string, string>): RegExp {
|
||||
const keys = Object.keys(dictionary);
|
||||
const regex = new RegExp(`\\b(${keys.join("|").replace(/\+/g, "\\+")})\\b`, "gi");
|
||||
return regex;
|
||||
}
|
||||
|
||||
export function replaceCore(
|
||||
code: string,
|
||||
dict: Record<string, string>,
|
||||
ignore: string[] = [],
|
||||
output?: (code: string, index: number, from: string, to: string) => void,
|
||||
regex?: RegExp
|
||||
): CasePoliceReturn | undefined {
|
||||
regex = regex || buildRegex(dict);
|
||||
|
||||
Array.from(code.matchAll(IGNORE_REGEX)).forEach((match) => {
|
||||
const [, key] = match;
|
||||
ignore.push(
|
||||
...key
|
||||
.split(",")
|
||||
.map((k) => k.trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
);
|
||||
});
|
||||
|
||||
const changed = [] as ChangedCase[];
|
||||
|
||||
code = code.replace(regex, (_, from: string, index: number) => {
|
||||
if (containsUTF8(code, from, index)) return _;
|
||||
|
||||
if (!from.match(/[A-Z]/) || !from.match(/[a-z]/)) return _;
|
||||
|
||||
const lower = from.toLowerCase();
|
||||
if (ignore.includes(lower)) return _;
|
||||
|
||||
const to = dict[lower];
|
||||
if (!to || to === from) return _;
|
||||
|
||||
changed.push({ from, to, index });
|
||||
output?.(code, index, from, to);
|
||||
|
||||
return to;
|
||||
});
|
||||
|
||||
if (changed.length) return { code, changed };
|
||||
}
|
||||
|
||||
function containsUTF8(code: string, key: string, index: number) {
|
||||
const utf8Regex = new RegExp(`${UTF8_RANGE}`);
|
||||
const head = code.charAt(index - 1);
|
||||
const tail = code.charAt(index + key.length);
|
||||
return utf8Regex.test(head) || utf8Regex.test(tail);
|
||||
}
|
||||
|
||||
export function loadPresets(presets?: Preset[]): Record<string, string> {
|
||||
presets = presets ?? (Object.keys(AVALIABLE_PRESETS) as Preset[]);
|
||||
|
||||
return presets.reduce(
|
||||
(dictionary, preset) => ({
|
||||
...dictionary,
|
||||
...AVALIABLE_PRESETS[preset]
|
||||
}),
|
||||
{}
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["./src"]
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "@ohmycv/dynamic-css",
|
||||
"version": "0.1.1",
|
||||
"description": "Dynamically injects global CSS.",
|
||||
"homepage": "https://github.com/Renovamen/oh-my-cv/tree/main/packages/dynamic-css",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Renovamen/oh-my-cv"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Renovamen/oh-my-cv.git",
|
||||
"directory": "packages/dynamic-css"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Renovamen <renovamenzxh@gmail.com>",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.js",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build-fast:pkg": "tsup src/index.ts --format cjs,esm",
|
||||
"build:pkg": "pnpm run build-fast:pkg --dts"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
const sheetsMap = new Map<string, HTMLStyleElement>();
|
||||
|
||||
/**
|
||||
* Dynamically injects CSS into the document. Borrowed from Vite:
|
||||
* https://github.com/vitejs/vite/blob/main/packages/vite/src/client/client.ts
|
||||
*
|
||||
* This used to be implemented using constructable stylesheets, but that was abandoned
|
||||
* due to low performance, see https://github.com/vitejs/vite/pull/11818.
|
||||
*
|
||||
* @param id To make sure the CSS won't override each other.
|
||||
* @param content A string of CSS to inject.
|
||||
*/
|
||||
export const injectCss = (id: string, content: string) => {
|
||||
let style = sheetsMap.get(id);
|
||||
|
||||
if (!style) {
|
||||
style = document.createElement("style");
|
||||
|
||||
style.setAttribute("type", "text/css");
|
||||
style.setAttribute("data-dynamic-css-id", id);
|
||||
style.textContent = content;
|
||||
|
||||
document.head.appendChild(style);
|
||||
} else {
|
||||
style.textContent = content;
|
||||
}
|
||||
|
||||
sheetsMap.set(id, style);
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove the CSS from the document.
|
||||
*
|
||||
* @param id The ID of the CSS to remove.
|
||||
*/
|
||||
export const removeCss = (id: string) => {
|
||||
const style = sheetsMap.get(id);
|
||||
|
||||
if (style) {
|
||||
document.head.removeChild(style);
|
||||
sheetsMap.delete(id);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["./src"]
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"name": "@ohmycv/front-matter",
|
||||
"version": "0.1.1",
|
||||
"description": "A better `js-yaml`, for extracting and parsing YAML front matter from strings.",
|
||||
"keywords": [
|
||||
"yaml",
|
||||
"front matter",
|
||||
"meta data"
|
||||
],
|
||||
"homepage": "https://github.com/Renovamen/oh-my-cv/tree/main/packages/front-matter",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Renovamen/oh-my-cv"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Renovamen/oh-my-cv.git",
|
||||
"directory": "packages/front-matter"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Renovamen <renovamenzxh@gmail.com>",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.js",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build-fast:pkg": "tsup src/index.ts --format cjs,esm",
|
||||
"build:pkg": "pnpm run build-fast:pkg --dts"
|
||||
},
|
||||
"dependencies": {
|
||||
"js-yaml": "^4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^20.14.10"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// Adapted from and improved upon https://github.com/jxson/front-matter
|
||||
|
||||
import * as yamlParser from "js-yaml";
|
||||
|
||||
const OPTIONAL_BYTE_ORDER_MARK = "\\ufeff?";
|
||||
const PLATFORM = typeof process !== "undefined" ? process.platform : "";
|
||||
const PATTERN =
|
||||
"^(" +
|
||||
OPTIONAL_BYTE_ORDER_MARK +
|
||||
"(= yaml =|---)" +
|
||||
"$([\\s\\S]*?)" +
|
||||
"^(?:\\2|\\.\\.\\.)\\s*" +
|
||||
"$" +
|
||||
(PLATFORM === "win32" ? "\\r?" : "") +
|
||||
"(?:\\n)?)";
|
||||
|
||||
export interface FrontMatterResults<T> {
|
||||
/**
|
||||
* Body content (without front matter).
|
||||
*/
|
||||
readonly body: string;
|
||||
|
||||
/**
|
||||
* Line number where the body begins.
|
||||
*/
|
||||
readonly bodyBegin: number;
|
||||
|
||||
/**
|
||||
* Parsed front matter object.
|
||||
*/
|
||||
readonly frontMatter: T;
|
||||
|
||||
/**
|
||||
* Front matter string.
|
||||
*/
|
||||
readonly frontMatterString?: string;
|
||||
}
|
||||
|
||||
export interface FrontMatterOptions {
|
||||
/**
|
||||
* Behavior when an error occurs while parsing the front matter YAML.
|
||||
* - "last": Returns the last successfully parsed front matter.
|
||||
* - "empty": Returns an empty front matter object.
|
||||
* - "error": Throws an error.
|
||||
* @default "error"
|
||||
*/
|
||||
errorBehavior?: "last" | "empty" | "error";
|
||||
}
|
||||
|
||||
export class FrontMatterParser<T = { [key: string]: any }> {
|
||||
private options: FrontMatterOptions;
|
||||
private _lastFrontMatter: T = {} as T;
|
||||
|
||||
constructor(options: FrontMatterOptions = {}) {
|
||||
this.options = options;
|
||||
this.options.errorBehavior = options.errorBehavior || "error";
|
||||
}
|
||||
|
||||
private _emptyResults = (body: string) => ({
|
||||
frontMatter: {} as T,
|
||||
body,
|
||||
bodyBegin: 1
|
||||
});
|
||||
|
||||
/**
|
||||
* Get the line number where the body begins.
|
||||
*/
|
||||
private _bodyBegin(match: RegExpExecArray, content: string) {
|
||||
const offset = match.index + match[0].length;
|
||||
const lines = content.slice(0, offset).split("\n");
|
||||
return lines.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split the content into front matter and body.
|
||||
*
|
||||
* @param content Markdown content, including front matter and body.
|
||||
* @returns
|
||||
* - `false` if the content does not contain front matter
|
||||
* - `{ frontMatterString, body, bodyBegin }` if contains
|
||||
* @see {@link FrontMatterResults}
|
||||
*/
|
||||
public split(content: string) {
|
||||
const regex = new RegExp(PATTERN, "m");
|
||||
const match = regex.exec(content);
|
||||
|
||||
if (!match) return false;
|
||||
|
||||
const frontMatterString = match[match.length - 1].trim();
|
||||
const body = content.slice(match[0].length);
|
||||
const bodyBegin = this._bodyBegin(match, content);
|
||||
|
||||
return {
|
||||
frontMatterString,
|
||||
body,
|
||||
bodyBegin
|
||||
};
|
||||
}
|
||||
|
||||
private _parse(content: string): FrontMatterResults<T> {
|
||||
const split = this.split(content);
|
||||
|
||||
if (!split) return this._emptyResults(content);
|
||||
|
||||
try {
|
||||
const frontMatter = (yamlParser.load(split.frontMatterString) || {}) as T;
|
||||
this._lastFrontMatter = frontMatter;
|
||||
|
||||
return { ...split, frontMatter };
|
||||
} catch (e) {
|
||||
const frontMatter =
|
||||
this.options.errorBehavior === "error"
|
||||
? (() => {
|
||||
throw e;
|
||||
})()
|
||||
: this.options.errorBehavior === "last"
|
||||
? this._lastFrontMatter
|
||||
: ({} as T);
|
||||
|
||||
return { ...split, frontMatter };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract and parse front matter from a markdown document. A front matter should look like:
|
||||
*
|
||||
* ```
|
||||
* ---
|
||||
* key: value
|
||||
* ---
|
||||
* ```
|
||||
*
|
||||
* @param content Markdown content, including front matter and body.
|
||||
* @returns `{ body, bodyBegin, frontMatter, frontMatterString }`
|
||||
* @see {@link FrontMatterResults}
|
||||
*/
|
||||
public parse(content: string): FrontMatterResults<T> {
|
||||
const lines = content.split(/(\r?\n)/);
|
||||
|
||||
if (lines[0] && /= yaml =|---/.test(lines[0])) {
|
||||
return this._parse(content);
|
||||
} else {
|
||||
return this._emptyResults(content);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { FrontMatterParser } from "./front-matter";
|
||||
|
||||
export default FrontMatterParser;
|
||||
export * from "./front-matter";
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["./src"]
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "@ohmycv/google-fonts-loader",
|
||||
"version": "0.1.1",
|
||||
"description": "Load Goolge Fonts with ease.",
|
||||
"keywords": [
|
||||
"google fonts",
|
||||
"fonts"
|
||||
],
|
||||
"homepage": "https://github.com/Renovamen/oh-my-cv/tree/main/packages/gfonts-loader",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Renovamen/oh-my-cv"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Renovamen/oh-my-cv.git",
|
||||
"directory": "packages/gfonts-loader"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Renovamen <renovamenzxh@gmail.com>",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.js",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build-fast:pkg": "tsup src/index.ts --format cjs,esm",
|
||||
"build:pkg": "pnpm run build-fast:pkg --dts"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { fetchFontList, loadFontStylesheet } from "./utils";
|
||||
import type { Font, FontMap, Options } from "./types";
|
||||
|
||||
export class GoogleFontsLoader {
|
||||
private readonly apiKey: string;
|
||||
private readonly options: Options;
|
||||
private activeFontFamily: string; // Name of currently applied font
|
||||
private onChange: (font: Font) => void;
|
||||
private fontMap: FontMap = new Map<string, Font>(); // Map from font families to font objects
|
||||
|
||||
constructor(
|
||||
apiKey: string,
|
||||
{
|
||||
families = [],
|
||||
categories = [],
|
||||
subsets = ["latin"],
|
||||
variants = ["regular"],
|
||||
filter = () => true,
|
||||
limit = -1,
|
||||
sort = "alphabet"
|
||||
}: Options = {},
|
||||
|
||||
onChange: (font: Font) => void = (): void => {}
|
||||
) {
|
||||
this.apiKey = apiKey;
|
||||
this.options = {
|
||||
families,
|
||||
categories,
|
||||
subsets,
|
||||
variants,
|
||||
filter,
|
||||
limit,
|
||||
sort
|
||||
};
|
||||
this.onChange = onChange;
|
||||
this.activeFontFamily = "";
|
||||
}
|
||||
|
||||
public async init(): Promise<FontMap> {
|
||||
// Load all fonts
|
||||
const fonts = await fetchFontList(this.apiKey);
|
||||
|
||||
// Function to check if a font satisfies the filter criteria
|
||||
const isFontIncluded = (font: Font) =>
|
||||
// Only keep fonts whose names are included in the provided array
|
||||
(this.options.families!.length === 0 ||
|
||||
this.options.families!.includes(font.family)) &&
|
||||
// Only keep fonts in categories from the provided array
|
||||
(this.options.categories!.length === 0 ||
|
||||
this.options.categories!.includes(font.category)) &&
|
||||
// Only keep fonts which are available in all specified subsets
|
||||
this.options.subsets!.every((subset) => font.subsets.includes(subset)) &&
|
||||
// Only keep fonts which contain all specified variants
|
||||
this.options.variants!.every((variant) => font.variants.includes(variant)) &&
|
||||
// Only keep fonts for which the `filter` function evaluates to `true`
|
||||
this.options.filter!(font) === true;
|
||||
|
||||
// Save desired fonts in the font map
|
||||
for (const font of fonts) {
|
||||
// Exit once specified limit of number of fonts is reached
|
||||
if (this.options.limit! >= 0 && this.fontMap.size >= this.options.limit!) break;
|
||||
// Only keep fonts that satisfy the filter criteria
|
||||
if (isFontIncluded(font)) this.fontMap.set(font.family, font);
|
||||
}
|
||||
|
||||
// Sort the font map if required
|
||||
if (this.options.sort === "alphabet") {
|
||||
this.fontMap = new Map(
|
||||
[...this.fontMap.entries()].sort(([family1], [family2]) =>
|
||||
family1.localeCompare(family2)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return this.fontMap;
|
||||
}
|
||||
|
||||
public getFontMap(): FontMap {
|
||||
return this.fontMap;
|
||||
}
|
||||
|
||||
public getActiveFont(): Font {
|
||||
const activeFont = this.fontMap.get(this.activeFontFamily);
|
||||
if (!activeFont) {
|
||||
throw Error(
|
||||
`Cannot get active font: "${this.activeFontFamily}" is not in the font list`
|
||||
);
|
||||
} else {
|
||||
return activeFont;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the specified font as the active font and download it
|
||||
*/
|
||||
public async setActiveFont(fontFamily: string) {
|
||||
const activeFont = this.fontMap.get(fontFamily);
|
||||
|
||||
if (!activeFont) {
|
||||
// Font is not in fontList: Keep current activeFont and log error
|
||||
throw Error(`Cannot update active font: "${fontFamily}" is not in the font list`);
|
||||
}
|
||||
|
||||
this.activeFontFamily = fontFamily;
|
||||
|
||||
await loadFontStylesheet(activeFont, this.options.subsets!, this.options.variants!);
|
||||
|
||||
this.onChange(activeFont);
|
||||
}
|
||||
|
||||
public setOnChange(onChange: (font: Font) => void) {
|
||||
this.onChange = onChange;
|
||||
}
|
||||
}
|
||||
|
||||
export * from "./types";
|
||||
export default GoogleFontsLoader;
|
||||
@@ -0,0 +1,76 @@
|
||||
export type Category = "sans-serif" | "serif" | "display" | "handwriting" | "monospace";
|
||||
|
||||
export type Subset =
|
||||
| "arabic"
|
||||
| "bengali"
|
||||
| "chinese-simplified"
|
||||
| "chinese-traditional"
|
||||
| "cyrillic"
|
||||
| "cyrillic-ext"
|
||||
| "devanagari"
|
||||
| "greek"
|
||||
| "greek-ext"
|
||||
| "gujarati"
|
||||
| "gurmukhi"
|
||||
| "hebrew"
|
||||
| "japanese"
|
||||
| "kannada"
|
||||
| "khmer"
|
||||
| "korean"
|
||||
| "latin"
|
||||
| "latin-ext"
|
||||
| "malayalam"
|
||||
| "myanmar"
|
||||
| "oriya"
|
||||
| "sinhala"
|
||||
| "tamil"
|
||||
| "telugu"
|
||||
| "thai"
|
||||
| "vietnamese";
|
||||
|
||||
export type Variant =
|
||||
| "100"
|
||||
| "100italic"
|
||||
| "200"
|
||||
| "200italic"
|
||||
| "300"
|
||||
| "300italic"
|
||||
| "regular"
|
||||
| "italic"
|
||||
| "500"
|
||||
| "500italic"
|
||||
| "600"
|
||||
| "600italic"
|
||||
| "700"
|
||||
| "700italic"
|
||||
| "800"
|
||||
| "800italic"
|
||||
| "900"
|
||||
| "900italic";
|
||||
|
||||
export type Font = {
|
||||
family: string;
|
||||
id: string;
|
||||
category: Category;
|
||||
subsets: Subset[];
|
||||
variants: Variant[];
|
||||
|
||||
kind?: string; // Usually "webfonts#webfont"
|
||||
version?: string; // Version number
|
||||
lastModified?: string; // Date of last modification (yyyy-MM-dd)
|
||||
files?: Record<Variant, string>; // Font file for each variant
|
||||
};
|
||||
|
||||
export type FontMap = Map<string, Font>;
|
||||
|
||||
export type SortOption = "alphabet" | "popularity";
|
||||
|
||||
export type Options = {
|
||||
families?: string[];
|
||||
categories?: Category[];
|
||||
subsets?: Subset[];
|
||||
variants?: Variant[];
|
||||
filter?: (font: Font) => boolean;
|
||||
limit?: number;
|
||||
sort?: SortOption;
|
||||
};
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { Font, Variant, Subset } from "../types";
|
||||
import { hasStylesheet, createStylesheet } from "./stylesheets";
|
||||
|
||||
const GOOGLE_FONTS_API = "https://www.googleapis.com/webfonts/v1/webfonts";
|
||||
const GOOGLE_FONTS_CSS = "https://fonts.googleapis.com/css";
|
||||
|
||||
const get = (url: string): Promise<string> =>
|
||||
new Promise((resolve, reject): void => {
|
||||
const request = new XMLHttpRequest();
|
||||
|
||||
request.overrideMimeType("application/json");
|
||||
request.open("GET", url, true);
|
||||
|
||||
request.onreadystatechange = () => {
|
||||
if (request.readyState === 4) {
|
||||
if (request.status !== 200) {
|
||||
reject(new Error(`Response has status code ${request.status}`));
|
||||
} else {
|
||||
resolve(request.responseText);
|
||||
}
|
||||
}
|
||||
};
|
||||
request.send();
|
||||
});
|
||||
|
||||
const getFontStylesheet = async (
|
||||
fonts: Font[],
|
||||
subsets: Subset[],
|
||||
variants: Variant[]
|
||||
): Promise<string> => {
|
||||
const url = new URL(GOOGLE_FONTS_CSS);
|
||||
|
||||
const variantsStr = variants.join(",");
|
||||
const familiesStr = fonts.map((font): string => `${font.family}:${variantsStr}`);
|
||||
|
||||
url.searchParams.append("family", familiesStr.join("|"));
|
||||
url.searchParams.append("subset", subsets.join(","));
|
||||
// Tell browser to render fallback font immediately and swap in the new font once it's loaded
|
||||
url.searchParams.append("font-display", "swap");
|
||||
|
||||
return get(url.href);
|
||||
};
|
||||
|
||||
const getFontId = (fontFamily: string) => fontFamily.replace(/\s+/g, "-").toLowerCase();
|
||||
|
||||
export const fetchFontList = async (apiKey: string): Promise<Font[]> => {
|
||||
// Request a list of all available Google Fonts, sorted by popularity
|
||||
const url = new URL(GOOGLE_FONTS_API);
|
||||
|
||||
url.searchParams.append("sort", "popularity");
|
||||
url.searchParams.append("key", apiKey);
|
||||
|
||||
const response = await get(url.href);
|
||||
const fonts: Font[] = JSON.parse(response).items;
|
||||
|
||||
// Generate an ID for each font
|
||||
return fonts.map((font) => ({
|
||||
...font,
|
||||
id: getFontId(font.family)
|
||||
}));
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a stylesheet for the given font to the document head
|
||||
*/
|
||||
export const loadFontStylesheet = async (
|
||||
font: Font,
|
||||
subsets: Subset[],
|
||||
variants: Variant[]
|
||||
) => {
|
||||
// Load font stylesheet if it hasn't been loaded yet
|
||||
if (!hasStylesheet(font.id)) {
|
||||
const fontStyle = await getFontStylesheet([font], subsets, variants);
|
||||
createStylesheet(font.id, fontStyle);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./fonts";
|
||||
@@ -0,0 +1,13 @@
|
||||
const _stylesheetId = (fontId: string) => `font-${fontId}`;
|
||||
|
||||
export const hasStylesheet = (fontId: string) =>
|
||||
document.getElementById(_stylesheetId(fontId)) !== null;
|
||||
|
||||
export const createStylesheet = (fontId: string, styles: string) => {
|
||||
const stylesheet = document.createElement("style");
|
||||
|
||||
stylesheet.id = _stylesheetId(fontId);
|
||||
stylesheet.textContent = styles;
|
||||
|
||||
document.head.appendChild(stylesheet);
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["./src"]
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "@ohmycv/markdown-it-cross-ref",
|
||||
"version": "0.1.1",
|
||||
"description": "Enable cross-references in markdown-it.",
|
||||
"keywords": [
|
||||
"markdown",
|
||||
"markdown-it-plugin",
|
||||
"markdown-it"
|
||||
],
|
||||
"homepage": "https://github.com/Renovamen/oh-my-cv/tree/main/packages/markdown-it-cross-ref",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Renovamen/oh-my-cv"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Renovamen/oh-my-cv.git",
|
||||
"directory": "packages/markdown-it-cross-ref"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Renovamen <renovamenzxh@gmail.com>",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.js",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build-fast:pkg": "tsup src/index.ts --format cjs,esm",
|
||||
"build:pkg": "pnpm run build-fast:pkg --dts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/markdown-it": "^14.1.1",
|
||||
"markdown-it": "^14.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
// Based on https://github.com/markdown-it/markdown-it-footnote
|
||||
|
||||
import type {
|
||||
Token,
|
||||
PluginSimple,
|
||||
ParserBlock,
|
||||
ParserInline,
|
||||
Core,
|
||||
Renderer,
|
||||
StateBlock,
|
||||
StateInline
|
||||
} from "markdown-it";
|
||||
|
||||
const _anchorId = (tokens: Token[], idx: number) =>
|
||||
Number(tokens[idx].meta.id + 1).toString();
|
||||
|
||||
const _anchorLabel = (tokens: Token[], idx: number) => tokens[idx].meta.label;
|
||||
|
||||
const _isOpen = (state: StateBlock | StateInline, start: number) => {
|
||||
return (
|
||||
state.src.charCodeAt(start) === 0x5b /* [ */ &&
|
||||
state.src.charCodeAt(start + 1) === 0x7e /* ~ */
|
||||
);
|
||||
};
|
||||
|
||||
const _isClose = (state: StateBlock | StateInline, pos: number) => {
|
||||
return state.src.charCodeAt(pos) === 0x5d /* ] */;
|
||||
};
|
||||
|
||||
const _extractLabel = (state: StateBlock | StateInline, start: number, end: number) => {
|
||||
return state.src.slice(start, end);
|
||||
};
|
||||
|
||||
const render =
|
||||
(type: "defOpen" | "ref"): Renderer.RenderRule =>
|
||||
(tokens, idx) => {
|
||||
const id = `cross-ref-${_anchorId(tokens, idx)}`;
|
||||
const label = _anchorLabel(tokens, idx);
|
||||
|
||||
return type === "ref"
|
||||
? `<sup data-scope="cross-ref" data-part="reference"><a data-scope="cross-ref" data-part="link" href="#${id}" id="${id}">${label}</a></sup>`
|
||||
: `<ul data-scope="cross-ref" data-part="definitions"><li id="${id}" data-scope="cross-ref" data-part="definition" data-label="${label}">`;
|
||||
};
|
||||
|
||||
const _processDefToken = (
|
||||
state: StateBlock,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
pos: number,
|
||||
label: string
|
||||
) => {
|
||||
state.env.crossRef ??= {};
|
||||
state.env.crossRef.labelToId ??= {};
|
||||
state.env.crossRef.labelToId[label] = -1;
|
||||
|
||||
// Create and push the opening token
|
||||
const openToken = new state.Token("renderDefOpen", "", 1);
|
||||
openToken.meta = { label };
|
||||
openToken.level = state.level++;
|
||||
state.tokens.push(openToken);
|
||||
|
||||
// Save the current state
|
||||
const bMarks = state.bMarks[startLine];
|
||||
const tShift = state.tShift[startLine];
|
||||
const sCount = state.sCount[startLine];
|
||||
|
||||
// Calculate the initial offset
|
||||
const posAfterColon = pos;
|
||||
const initial = sCount + pos - (bMarks + tShift);
|
||||
let offset = initial;
|
||||
|
||||
// Adjust position and offset for spaces
|
||||
while (pos < state.eMarks[startLine]) {
|
||||
const ch = state.src.charCodeAt(pos);
|
||||
|
||||
if (state.md.utils.isSpace(ch)) {
|
||||
offset += ch === 0x09 ? 4 - (offset % 4) : 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
||||
pos++;
|
||||
}
|
||||
|
||||
// Update state shifts and block indent
|
||||
state.tShift[startLine] = pos - posAfterColon;
|
||||
state.sCount[startLine] = offset - initial;
|
||||
state.bMarks[startLine] = posAfterColon;
|
||||
state.blkIndent += 4;
|
||||
|
||||
if (state.sCount[startLine] < state.blkIndent)
|
||||
state.sCount[startLine] += state.blkIndent;
|
||||
|
||||
// Tokenize the block
|
||||
state.md.block.tokenize(state, startLine, endLine);
|
||||
|
||||
// Restore the previous state
|
||||
state.blkIndent -= 4;
|
||||
state.tShift[startLine] = tShift;
|
||||
state.sCount[startLine] = sCount;
|
||||
state.bMarks[startLine] = bMarks;
|
||||
|
||||
// Create and push the closing token
|
||||
const closeToken = new state.Token("renderDefClose", "", -1);
|
||||
closeToken.level = --state.level;
|
||||
state.tokens.push(closeToken);
|
||||
};
|
||||
|
||||
const processDef: ParserBlock.RuleBlock = (state, startLine, endLine, silent) => {
|
||||
const start = state.bMarks[startLine] + state.tShift[startLine];
|
||||
const max = state.eMarks[startLine];
|
||||
|
||||
// Should be at least 5 chars ("[~x]:") and start with "[~"
|
||||
if (start + 4 > max || !_isOpen(state, start)) return false;
|
||||
|
||||
// Find closing square bracket "]"
|
||||
let pos = start + 2;
|
||||
while (pos < max && !_isClose(state, pos)) pos++;
|
||||
|
||||
// Empty label is not allowed
|
||||
if (pos === start + 2) return false;
|
||||
// No "]" found or no ":" after "]"
|
||||
if (pos + 1 >= max || state.src.charCodeAt(pos + 1) !== 0x3a /* : */) return false;
|
||||
|
||||
if (silent) return true;
|
||||
|
||||
// Extract content between "[~" and "]"
|
||||
const label = _extractLabel(state, start + 2, pos);
|
||||
|
||||
// Process the blocks belonging to the definition
|
||||
_processDefToken(state, startLine, endLine, pos + 2, label);
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const processRef: ParserInline.RuleInline = (state, silent) => {
|
||||
if (!state.env.crossRef?.labelToId) return false;
|
||||
|
||||
// Should be at least 4 chars ("[~x]") and start with "[~"
|
||||
if (state.pos + 3 > state.posMax || !_isOpen(state, state.pos)) return false;
|
||||
|
||||
// Find closing square bracket "]"
|
||||
let pos = state.pos + 2;
|
||||
while (pos < state.posMax && !_isClose(state, pos)) pos++;
|
||||
|
||||
// Empty label or no "]" found
|
||||
if (pos === state.pos + 2 || pos >= state.posMax) return false;
|
||||
|
||||
// Extract content between "[~" and "]"
|
||||
const label = _extractLabel(state, state.pos + 2, pos);
|
||||
|
||||
// No corresponding definition found
|
||||
if (state.env.crossRef.labelToId[label] === undefined) return false;
|
||||
|
||||
if (!silent) {
|
||||
state.env.crossRef.list ??= [];
|
||||
|
||||
const id =
|
||||
state.env.crossRef.labelToId[label] === -1
|
||||
? state.env.crossRef.list.push(label) - 1
|
||||
: state.env.crossRef.labelToId[label];
|
||||
|
||||
state.env.crossRef.labelToId[label] = id;
|
||||
|
||||
const token = state.push("renderRef", "", 0);
|
||||
token.meta = { id, label };
|
||||
}
|
||||
|
||||
state.pos = pos + 1;
|
||||
return true;
|
||||
};
|
||||
|
||||
const postProcessDef: Core.RuleCore = (state) => {
|
||||
// We don't know the ID of the definition when we first encounter it,
|
||||
// so we need to go back and update it after we've processed all the references
|
||||
for (const token of state.tokens) {
|
||||
if (token.type === "renderDefOpen") {
|
||||
token.meta = {
|
||||
...token.meta,
|
||||
id: state.env.crossRef?.labelToId?.[token.meta.label] ?? -1
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A markdown-it plugin for cross-references.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```markdown
|
||||
* [~Reference name]: This is a reference.
|
||||
*
|
||||
* It can span multiple lines.
|
||||
*
|
||||
* This is a reference to [~Reference name].
|
||||
* ```
|
||||
*/
|
||||
export const MarkdownItCrossRef: PluginSimple = (md) => {
|
||||
md.renderer.rules.renderRef = render("ref");
|
||||
md.renderer.rules.renderDefOpen = render("defOpen");
|
||||
md.renderer.rules.renderDefClose = () => "</li>\n</ul>\n";
|
||||
|
||||
md.block.ruler.before("reference", "processDef", processDef, {
|
||||
alt: ["paragraph", "reference"]
|
||||
});
|
||||
md.inline.ruler.after("image", "processRef", processRef);
|
||||
md.core.ruler.after("inline", "postProcessDef", postProcessDef);
|
||||
};
|
||||
|
||||
export default MarkdownItCrossRef;
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["./src"]
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "@ohmycv/markdown-it-katex",
|
||||
"version": "0.1.1",
|
||||
"description": "Fast math support for markdown-it with KaTeX",
|
||||
"keywords": [
|
||||
"markdown",
|
||||
"KaTeX",
|
||||
"math",
|
||||
"LaTeX",
|
||||
"markdown-it-plugin",
|
||||
"markdown-it"
|
||||
],
|
||||
"homepage": "https://github.com/Renovamen/oh-my-cv/tree/main/packages/markdown-it-katex",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Renovamen/oh-my-cv"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Renovamen/oh-my-cv.git",
|
||||
"directory": "packages/markdown-it-katex"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Renovamen <renovamenzxh@gmail.com>",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.js",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build-fast:pkg": "tsup src/index.ts --format cjs,esm",
|
||||
"build:pkg": "pnpm run build-fast:pkg --dts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@renovamen/utils": "workspace:*",
|
||||
"katex": "^0.16.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/katex": "^0.16.7",
|
||||
"@types/markdown-it": "^14.1.1",
|
||||
"markdown-it": "^14.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import Katex, { type KatexOptions } from "katex";
|
||||
import type {
|
||||
PluginWithOptions,
|
||||
StateInline,
|
||||
ParserBlock,
|
||||
ParserInline
|
||||
} from "markdown-it";
|
||||
import { htmlEscape } from "@renovamen/utils";
|
||||
|
||||
const isValidDelim = (
|
||||
state: StateInline,
|
||||
pos: number
|
||||
): { canOpen: boolean; canClose: boolean } => {
|
||||
const prevChar = pos > 0 ? state.src.charCodeAt(pos - 1) : -1;
|
||||
const nextChar = pos + 1 <= state.posMax ? state.src.charCodeAt(pos + 1) : -1;
|
||||
|
||||
// 0x20: " ", 0x09: \t
|
||||
const isWhitespace = (char: number) => char === 0x20 || char === 0x09;
|
||||
// 0x30: "0", 0x39: "9"
|
||||
const isDigit = (char: number) => char >= 0x30 && char <= 0x39;
|
||||
|
||||
const canOpen = !isWhitespace(nextChar);
|
||||
const canClose = !isWhitespace(prevChar) && !isDigit(nextChar);
|
||||
|
||||
return { canOpen, canClose };
|
||||
};
|
||||
|
||||
const mathInline: ParserInline.RuleInline = (state, silent) => {
|
||||
if (state.src[state.pos] !== "$") return false;
|
||||
|
||||
const res = isValidDelim(state, state.pos);
|
||||
if (!res.canOpen) {
|
||||
if (!silent) state.pending += "$";
|
||||
state.pos += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* First check for and bypass all properly escaped delimieters
|
||||
* This loop will assume that the first leading backtick can not
|
||||
* be the first character in state.src, which is known since
|
||||
* we have found an opening delimieter already.
|
||||
*/
|
||||
const start = state.pos + 1;
|
||||
let match = start;
|
||||
|
||||
while ((match = state.src.indexOf("$", match)) !== -1) {
|
||||
// Found potential $, look for escapes, pos will point to
|
||||
// first non escape when complete
|
||||
let pos = match - 1;
|
||||
while (state.src[pos] === "\\") pos -= 1;
|
||||
|
||||
// Even number of escapes, potential closing delimiter found
|
||||
if ((match - pos) % 2 === 1) break;
|
||||
|
||||
match += 1;
|
||||
}
|
||||
|
||||
// No closing delimter found. Consume $ and continue.
|
||||
if (match === -1) {
|
||||
if (!silent) state.pending += "$";
|
||||
state.pos = start;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check if we have empty content, ie: $$. Do not parse.
|
||||
if (match - start === 0) {
|
||||
if (!silent) state.pending += "$$";
|
||||
state.pos = start + 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for valid closing delimiter
|
||||
const closeDelim = isValidDelim(state, match);
|
||||
if (!closeDelim.canClose) {
|
||||
if (!silent) state.pending += "$";
|
||||
state.pos = start;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!silent) {
|
||||
const token = state.push("mathInline", "math", 0);
|
||||
token.markup = "$";
|
||||
token.content = state.src.slice(start, match);
|
||||
}
|
||||
|
||||
state.pos = match + 1;
|
||||
return true;
|
||||
};
|
||||
|
||||
const mathBlock: ParserBlock.RuleBlock = (state, start, end, silent) => {
|
||||
let pos = state.bMarks[start] + state.tShift[start];
|
||||
const max = state.eMarks[start];
|
||||
|
||||
if (pos + 2 > max || state.src.slice(pos, pos + 2) !== "$$") return false;
|
||||
|
||||
pos += 2;
|
||||
let firstLine = state.src.slice(pos, max);
|
||||
|
||||
if (silent) return true;
|
||||
|
||||
let found = firstLine.trim().endsWith("$$");
|
||||
// Single line expression
|
||||
if (found) firstLine = firstLine.trim().slice(0, -2);
|
||||
|
||||
let next = start;
|
||||
let lastLine = "";
|
||||
|
||||
while (!found) {
|
||||
next += 1;
|
||||
|
||||
if (next >= end) break;
|
||||
|
||||
pos = state.bMarks[next] + state.tShift[next];
|
||||
const lineMax = state.eMarks[next];
|
||||
|
||||
// Non-empty line with negative indent should stop the list
|
||||
if (pos < lineMax && state.tShift[next] < state.blkIndent) break;
|
||||
|
||||
const trimmedLine = state.src.slice(pos, lineMax).trim();
|
||||
if (trimmedLine.endsWith("$$")) {
|
||||
lastLine = trimmedLine.slice(0, -2);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
|
||||
state.line = next + 1;
|
||||
|
||||
const token = state.push("mathBlock", "math", 0);
|
||||
|
||||
token.block = true;
|
||||
token.content =
|
||||
(firstLine.trim() ? `${firstLine}\n` : "") +
|
||||
state.getLines(start + 1, next, state.tShift[start], true) +
|
||||
(lastLine.trim() ? lastLine : "");
|
||||
token.map = [start, state.line];
|
||||
token.markup = "$$";
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* A markdown-it plugin for rendering KaTeX math expressions, improved from
|
||||
* https://github.com/waylonflinn/markdown-it-katex.
|
||||
*
|
||||
* This one is typed and has clearer code.
|
||||
*/
|
||||
export const MarkdownItKatex: PluginWithOptions<KatexOptions> = (
|
||||
md,
|
||||
options = { throwOnError: false }
|
||||
) => {
|
||||
const renderKatex = (
|
||||
tex: string,
|
||||
options: KatexOptions,
|
||||
displayMode: boolean // Whether to render as block math
|
||||
): string => {
|
||||
options.displayMode = displayMode;
|
||||
|
||||
try {
|
||||
return displayMode
|
||||
? `<p>${Katex.renderToString(tex, options)}</p>\n`
|
||||
: Katex.renderToString(tex, options);
|
||||
} catch (error) {
|
||||
if (options.throwOnError) console.warn(error);
|
||||
|
||||
const errorMsg = htmlEscape((error as Error).toString());
|
||||
const escapedTex = htmlEscape(tex);
|
||||
|
||||
return displayMode
|
||||
? `<p class='katex-error' title='${errorMsg}'>${escapedTex}</p>\n`
|
||||
: `<span title='${errorMsg}'>${escapedTex}</span>`;
|
||||
}
|
||||
};
|
||||
|
||||
md.inline.ruler.after("escape", "mathInline", mathInline);
|
||||
md.block.ruler.after("blockquote", "mathBlock", mathBlock, {
|
||||
alt: ["paragraph", "reference", "blockquote", "list"]
|
||||
});
|
||||
|
||||
md.renderer.rules.mathInline = (tokens, idx): string =>
|
||||
renderKatex(tokens[idx].content, options, false);
|
||||
md.renderer.rules.mathBlock = (tokens, idx): string =>
|
||||
renderKatex(tokens[idx].content, options, true);
|
||||
};
|
||||
|
||||
export default MarkdownItKatex;
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["./src"]
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "@ohmycv/markdown-it-latex-cmds",
|
||||
"version": "0.1.1",
|
||||
"description": "Enable using LaTeX like commands in markdown-it",
|
||||
"keywords": [
|
||||
"markdown",
|
||||
"markdown-it-plugin",
|
||||
"markdown-it"
|
||||
],
|
||||
"homepage": "https://github.com/Renovamen/oh-my-cv/tree/main/packages/markdown-it-latex-cmds",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Renovamen/oh-my-cv"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Renovamen/oh-my-cv.git",
|
||||
"directory": "packages/markdown-it-latex-cmds"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Renovamen <renovamenzxh@gmail.com>",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.js",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build-fast:pkg": "tsup src/index.ts --format cjs,esm",
|
||||
"build:pkg": "pnpm run build-fast:pkg --dts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/markdown-it": "^14.1.1",
|
||||
"markdown-it": "^14.1.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import type { PluginSimple, Renderer, ParserBlock, StateBlock } from "markdown-it";
|
||||
|
||||
// same as UNESCAPE_MD_RE plus a space
|
||||
const UNESCAPE_RE = /\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;
|
||||
|
||||
const renderNewPage: Renderer.RenderRule = () => `<div class="md-it-newpage"></div>`;
|
||||
|
||||
const renderLineBreak: Renderer.RenderRule = (tokens, idx) =>
|
||||
`<div class="md-it-line-break" style="margin-top:${tokens[idx].meta.h};"></div>`;
|
||||
|
||||
const checkPattern = (
|
||||
state: StateBlock,
|
||||
start: number,
|
||||
pattern: string,
|
||||
options: {
|
||||
minLength?: number;
|
||||
silent?: boolean;
|
||||
} = {}
|
||||
) => {
|
||||
const { minLength = pattern.length, silent = false } = options;
|
||||
|
||||
const pos = state.bMarks[start] + state.tShift[start];
|
||||
const max = state.eMarks[start];
|
||||
|
||||
// Don't run any pairs in validation mode
|
||||
if (silent) return false;
|
||||
|
||||
// Should contain at least minLength characters
|
||||
if (pos + minLength > max) return false;
|
||||
// Should be the same as pattern
|
||||
if (state.src.slice(pos, pos + pattern.length) !== pattern) return false;
|
||||
|
||||
return {
|
||||
pos,
|
||||
max
|
||||
};
|
||||
};
|
||||
|
||||
const newPage: ParserBlock.RuleBlock = (state, start, end, silent) => {
|
||||
if (!checkPattern(state, start, "\\newpage", { silent })) return false;
|
||||
|
||||
// Skip "\newpage"
|
||||
state.line = start + 1;
|
||||
|
||||
// Add newpage div token
|
||||
const token = state.push("renderNewPage", "", 0);
|
||||
token.block = true;
|
||||
token.map = [start, state.line];
|
||||
token.markup = "\\newpage";
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const lineBreak: ParserBlock.RuleBlock = (state, start, end, silent) => {
|
||||
// Try to find "\\["
|
||||
const res = checkPattern(state, start, "\\\\[", {
|
||||
minLength: 5, // Should be at least "\\[x]"
|
||||
silent
|
||||
});
|
||||
if (!res) return false;
|
||||
|
||||
const { pos, max } = res;
|
||||
|
||||
// Try to find "]"
|
||||
let lastPos = pos + 4;
|
||||
while (lastPos < max && state.src[lastPos] !== "]") lastPos++;
|
||||
|
||||
// Did't find "]"
|
||||
if (lastPos >= max) return false;
|
||||
|
||||
// Parse line break height, e.g. "\\[10px]"
|
||||
const height = state.src.slice(pos + 3, lastPos);
|
||||
// Don't allow unescaped spaces/newlines inside
|
||||
if (height.match(/(^|[^\\])(\\\\)*\s/)) return false;
|
||||
|
||||
// Skip "\\[x]"
|
||||
state.line = start + 1;
|
||||
|
||||
// Add line break div token
|
||||
const token = state.push("renderLineBreak", "", 0);
|
||||
token.meta = { h: height.replace(UNESCAPE_RE, "$1") };
|
||||
token.block = true;
|
||||
token.map = [start, state.line];
|
||||
token.markup = "\\[]";
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* A plugin for markdown-it that adds LaTeX commands. This plugin adds the following commands:
|
||||
* - `\newpage`: Adds a new page.
|
||||
* - `\\[10px]`: Adds a line break with a height of 10px.
|
||||
*/
|
||||
export const MarkdownItLatexCmds: PluginSimple = (md) => {
|
||||
md.renderer.rules.renderNewPage = renderNewPage;
|
||||
md.renderer.rules.renderLineBreak = renderLineBreak;
|
||||
|
||||
md.block.ruler.after("blockquote", "newPage", newPage);
|
||||
md.block.ruler.after("newPage", "lineBreak", lineBreak);
|
||||
};
|
||||
|
||||
export default MarkdownItLatexCmds;
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["./src"]
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "@renovamen/utils",
|
||||
"version": "0.1.1",
|
||||
"description": "Useful utils, zero dependencies.",
|
||||
"homepage": "https://github.com/Renovamen/oh-my-cv/tree/main/packages/utils",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Renovamen/oh-my-cv"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Renovamen/oh-my-cv.git",
|
||||
"directory": "packages/utils"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Renovamen <renovamenzxh@gmail.com>",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.js",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build-fast:pkg": "tsup src/index.ts --format cjs,esm",
|
||||
"build:pkg": "pnpm run build-fast:pkg --dts"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { isObject } from "./is";
|
||||
|
||||
// Copied from https://github.com/meteorlxy/vscode-slugify
|
||||
export const slugify = (str: string) =>
|
||||
encodeURI(
|
||||
str
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, "-") // Replace whitespace with -
|
||||
.replace(
|
||||
/[\]\[\!\'\#\$\%\&\(\)\*\+\,\.\/\:\;\<\=\>\?\@\\\^\_\{\|\}\~\`。,、;:?!…—·ˉ¨‘’“”々~‖∶"'`|〃〔〕〈〉《》「」『』.〖〗【】()[]{}]/g,
|
||||
""
|
||||
) // Remove known punctuators
|
||||
.replace(/^\-+/, "") // Remove leading -
|
||||
.replace(/\-+$/, "") // Remove trailing -
|
||||
);
|
||||
|
||||
export const htmlEscape = (str: string) => {
|
||||
const escapeMap: Record<string, string> = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
"'": "'",
|
||||
'"': """
|
||||
};
|
||||
|
||||
return str.replace(/[&<>'"]/g, (char) => escapeMap[char]);
|
||||
};
|
||||
|
||||
export const copy = <T>(obj: T): T => {
|
||||
if (isObject(obj)) return JSON.parse(JSON.stringify(obj));
|
||||
throw new Error("Input must be a non-null object.");
|
||||
};
|
||||
|
||||
export const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
export const now = () => Date.now();
|
||||
|
||||
export const arrayify = <T>(value: T | T[]): T[] =>
|
||||
Array.isArray(value) ? value : [value];
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import type { Callback } from "./types";
|
||||
|
||||
export const fetchFile = async (url: string): Promise<string> => {
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Request error: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
return await res.text();
|
||||
} catch (error) {
|
||||
return Promise.reject(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Open file dialog with ease. This hook differs from vueuse's useFileDialog in that it
|
||||
* doesn't require Vue.
|
||||
*
|
||||
* @param accept File types to accept
|
||||
* @returns
|
||||
*/
|
||||
export const useFileDialog = (accept?: string) => {
|
||||
let callback: Callback<File> | null = null;
|
||||
|
||||
let input: HTMLInputElement | undefined;
|
||||
|
||||
if (document) {
|
||||
input = document.createElement("input");
|
||||
|
||||
input.type = "file";
|
||||
input.style.display = "none";
|
||||
if (accept) input.accept = accept;
|
||||
|
||||
input.onchange = (event: Event) => {
|
||||
const target = event.target as HTMLInputElement;
|
||||
const file = target.files?.[0];
|
||||
|
||||
if (file && callback) callback(file);
|
||||
};
|
||||
}
|
||||
|
||||
const open = () => {
|
||||
if (!input) return;
|
||||
|
||||
document.body.appendChild(input);
|
||||
input.click();
|
||||
document.body.removeChild(input);
|
||||
};
|
||||
|
||||
const onChange = (cb: Callback<File>) => {
|
||||
callback = cb;
|
||||
};
|
||||
|
||||
return {
|
||||
open,
|
||||
onChange
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Read file content as text.
|
||||
*
|
||||
* @param file File object
|
||||
* @returns Promise containing file content as string
|
||||
*/
|
||||
export const readFile = (file: File): Promise<string> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = () => resolve(reader.result as string);
|
||||
reader.onerror = () => reject(new Error("Failed to read file"));
|
||||
|
||||
reader.readAsText(file);
|
||||
});
|
||||
};
|
||||
|
||||
export const downloadFile = (filename: string, content: string) => {
|
||||
const element = document.createElement("a");
|
||||
|
||||
element.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
|
||||
element.download = filename;
|
||||
element.style.display = "none";
|
||||
|
||||
document.body.appendChild(element);
|
||||
element.click();
|
||||
document.body.removeChild(element);
|
||||
};
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
export * from "./file";
|
||||
export * from "./common";
|
||||
export * from "./types";
|
||||
export * from "./is";
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
export const isClient = typeof window !== "undefined" && typeof document !== "undefined";
|
||||
|
||||
export const isMac =
|
||||
isClient && typeof navigator !== "undefined" && /Macintosh/.test(navigator.userAgent);
|
||||
|
||||
export const isExternal = (path: string) => {
|
||||
const outboundRE = /^(https?:|mailto:|tel:)/;
|
||||
return outboundRE.test(path);
|
||||
};
|
||||
|
||||
export const isObject = (v: any) => toString.call(v) === "[object Object]";
|
||||
|
||||
export const isInteger = (v: any, { allowString = false } = {}): boolean => {
|
||||
return typeof v === "number"
|
||||
? Number.isInteger(v)
|
||||
: allowString && typeof v === "string" && Number.isInteger(Number(v));
|
||||
};
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
export type Optional<T, K extends keyof T> = Omit<T, K> & Partial<T>;
|
||||
|
||||
export type PartialWithRequired<T, K extends keyof T> = Pick<T, K> & Partial<T>;
|
||||
|
||||
// https://stackoverflow.com/questions/55541275/typescript-check-for-the-any-type
|
||||
// https://github.com/vueuse/vueuse/blob/main/packages/shared/utils/types.ts
|
||||
export type IfAny<T, Y, N> = 0 extends 1 & T ? Y : N;
|
||||
export type IsAny<T> = IfAny<T, true, false>;
|
||||
|
||||
export type Callback<T> =
|
||||
IsAny<T> extends true
|
||||
? (param: any) => void
|
||||
: [T] extends [void]
|
||||
? () => void
|
||||
: (param: T) => void;
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["./src"]
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "@ohmycv/vue-shortcuts",
|
||||
"version": "0.1.1",
|
||||
"description": "Use keyboard shortcuts in Vue.",
|
||||
"homepage": "https://github.com/Renovamen/oh-my-cv/tree/main/packages/vue-shortcuts",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Renovamen/oh-my-cv"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Renovamen/oh-my-cv.git",
|
||||
"directory": "packages/vue-shortcuts"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Renovamen <renovamenzxh@gmail.com>",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.js",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build-fast:pkg": "tsup src/index.ts --format cjs,esm",
|
||||
"build:pkg": "pnpm run build-fast:pkg --dts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@renovamen/utils": "workspace:*",
|
||||
"@vueuse/core": "^10.11.0",
|
||||
"vue": "^3.4.31"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { watch } from "vue";
|
||||
import { useMagicKeys } from "@vueuse/core";
|
||||
import { isMac } from "@renovamen/utils";
|
||||
|
||||
/**
|
||||
* Handle keyboard shortcuts, dealing ctrl/meta key for Windows/Mac automatically.
|
||||
*
|
||||
* @param keys Keyboard shortcuts, split by `+`, e.g. `ctrl+shift+e`.
|
||||
* @param cb Callback function to be called when the shortcuts are triggered.
|
||||
*/
|
||||
export const useShortcuts = (keys: string, cb: () => void) => {
|
||||
const adjustedKeys = keys.replace("ctrl", isMac ? "meta" : "ctrl").split("+");
|
||||
|
||||
const magic = useMagicKeys({
|
||||
passive: false,
|
||||
onEventFired: (e) => {
|
||||
if (e.type !== "keydown") return;
|
||||
|
||||
const isKeyActive = (key: string) => {
|
||||
switch (key) {
|
||||
case "ctrl":
|
||||
return e.ctrlKey;
|
||||
case "meta":
|
||||
return e.metaKey;
|
||||
case "shift":
|
||||
return e.shiftKey;
|
||||
default:
|
||||
return e.key === key;
|
||||
}
|
||||
};
|
||||
|
||||
if (adjustedKeys.every(isKeyActive)) e.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
const shortcuts = magic[adjustedKeys.join("+")];
|
||||
const { current } = magic;
|
||||
|
||||
watch(shortcuts, (v) => {
|
||||
if (v && current.size === adjustedKeys.length) cb();
|
||||
});
|
||||
};
|
||||
|
||||
export default useShortcuts;
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["./src"]
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "@ohmycv/vue-smart-pages",
|
||||
"version": "0.1.1",
|
||||
"description": "Automatically break your content into multiple pages, just like what Word does.",
|
||||
"homepage": "https://github.com/Renovamen/oh-my-cv/tree/main/packages/vue-smart-pages",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Renovamen/oh-my-cv"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Renovamen/oh-my-cv.git",
|
||||
"directory": "packages/vue-smart-pages"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Renovamen <renovamenzxh@gmail.com>",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.js",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build-fast:pkg": "tsup src/index.ts --format cjs,esm",
|
||||
"build:pkg": "pnpm run build-fast:pkg --dts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vueuse/core": "^10.11.0",
|
||||
"vue": "^3.4.31"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { PageSize, PageMargins } from "./types";
|
||||
|
||||
const NEW_PAGE_CLASS = "md-it-newpage";
|
||||
|
||||
const _elementHeight = (element: Element) => {
|
||||
const style = window.getComputedStyle(element);
|
||||
|
||||
const marginTop = parseInt(style.marginTop) || 0;
|
||||
const marginBottom = parseInt(style.marginBottom) || 0;
|
||||
|
||||
return element.clientHeight + marginTop + marginBottom;
|
||||
};
|
||||
|
||||
const _createPage = (size: PageSize, margins: Required<PageMargins>) => {
|
||||
const page = document.createElement("div");
|
||||
|
||||
page.dataset.scope = "vue-smart-pages";
|
||||
page.dataset.part = "page";
|
||||
|
||||
page.style.height = `${size.height}px`;
|
||||
setWidthAndMargins(page, size, margins);
|
||||
|
||||
return page;
|
||||
};
|
||||
|
||||
export const setWidthAndMargins = (
|
||||
element: HTMLElement,
|
||||
size: PageSize,
|
||||
margins: Required<PageMargins>
|
||||
) => {
|
||||
element.style.width = `${size.width}mm`;
|
||||
element.style.padding = `${margins.top}px ${margins.right}px ${margins.bottom}px ${margins.left}px`;
|
||||
};
|
||||
|
||||
export const breakPage = (
|
||||
target: HTMLElement,
|
||||
size: PageSize,
|
||||
margins: Required<PageMargins>
|
||||
) => {
|
||||
const maxHeight = size.height - margins.top - margins.bottom;
|
||||
const pages = document.createElement("div");
|
||||
|
||||
let accHeight = 0;
|
||||
let page = _createPage(size, margins);
|
||||
|
||||
Array.from(target.children).forEach((child) => {
|
||||
const childHeight = _elementHeight(child);
|
||||
|
||||
if (accHeight + childHeight > maxHeight || child.className === NEW_PAGE_CLASS) {
|
||||
pages.appendChild(page);
|
||||
|
||||
accHeight = 0;
|
||||
page = _createPage(size, margins);
|
||||
}
|
||||
|
||||
page.appendChild(child);
|
||||
accHeight += childHeight;
|
||||
});
|
||||
|
||||
pages.appendChild(page);
|
||||
target.innerHTML = pages.innerHTML;
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
import { useSmartPages } from "./useSmartPages";
|
||||
|
||||
export * from "./useSmartPages";
|
||||
export type * from "./types";
|
||||
|
||||
export default useSmartPages;
|
||||
@@ -0,0 +1,11 @@
|
||||
export type PageSize = {
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
export type PageMargins = Partial<{
|
||||
top: number;
|
||||
bottom: number;
|
||||
left: number;
|
||||
right: number;
|
||||
}>;
|
||||
@@ -0,0 +1,89 @@
|
||||
import { onMounted } from "vue";
|
||||
import {
|
||||
unrefElement,
|
||||
toValue,
|
||||
watchThrottled,
|
||||
type WatchThrottledOptions,
|
||||
type MaybeComputedElementRef
|
||||
} from "@vueuse/core";
|
||||
import type { MaybeRef } from "@vueuse/shared";
|
||||
import { breakPage, setWidthAndMargins } from "./dom";
|
||||
import type { PageSize, PageMargins } from "./types";
|
||||
|
||||
/**
|
||||
* Break the content into pages based on the given size and margins.
|
||||
*
|
||||
* @param target HTML element
|
||||
* @param html Content that will be rendered as innerHTML of the target element
|
||||
* @param size Size and margins of each page
|
||||
* @param options
|
||||
*
|
||||
* @returns A render function to manually trigger the page breaking
|
||||
*
|
||||
* @example
|
||||
* ```vue
|
||||
* <template>
|
||||
* <div ref="target" />
|
||||
* </template>
|
||||
*
|
||||
* <script setup>
|
||||
* import { ref } from "vue";
|
||||
* import { useSmartPages } from "vue-smart-pages";
|
||||
*
|
||||
* const target = ref();
|
||||
*
|
||||
* const { render } = useSmartPages(target, "<p>Content</p>", { width: 210, height: 297 }, { top: 10, bottom: 10, left: 10, right: 10 });
|
||||
* </script>
|
||||
* ```
|
||||
*/
|
||||
export const useSmartPages = (
|
||||
target: MaybeComputedElementRef,
|
||||
html: MaybeRef<string>,
|
||||
size: MaybeRef<PageSize>,
|
||||
margins: MaybeRef<PageMargins> = {},
|
||||
options: {
|
||||
beforeRender?: () => void | Promise<void>;
|
||||
afterRender?: () => void | Promise<void>;
|
||||
watchThrottledOptions?: WatchThrottledOptions<Readonly<boolean>>;
|
||||
} = {}
|
||||
) => {
|
||||
const render = async () => {
|
||||
const element = unrefElement(target) as HTMLElement | undefined | null;
|
||||
if (!element) return;
|
||||
|
||||
const { width, height } = toValue(size);
|
||||
const { top = 0, bottom = 0, left = 0, right = 0 } = toValue(margins);
|
||||
|
||||
const _size = { width, height };
|
||||
const _margins = { top, bottom, left, right };
|
||||
|
||||
// To calculate the correct child heights for breaking the page, we first apply the content,
|
||||
// size, and margins to a clone of the element, instead of the original element.
|
||||
// This is to avoid flickering when the original element is modified.
|
||||
const copy = element.cloneNode(true) as HTMLElement;
|
||||
|
||||
copy.innerHTML = toValue(html);
|
||||
setWidthAndMargins(copy, _size, _margins);
|
||||
|
||||
// Attach it to the body temporarily to get the correct computed styles
|
||||
document.body.appendChild(copy);
|
||||
|
||||
if (options.beforeRender) await options.beforeRender();
|
||||
|
||||
// Break the page based on the given size and margins
|
||||
breakPage(copy, _size, _margins);
|
||||
|
||||
// Replace the original element with the modified copy
|
||||
element.innerHTML = copy.innerHTML;
|
||||
|
||||
// Remove the copy from the body
|
||||
document.body.removeChild(copy);
|
||||
|
||||
if (options.afterRender) await options.afterRender();
|
||||
};
|
||||
|
||||
onMounted(render);
|
||||
watchThrottled([size, margins, html], render, options.watchThrottledOptions);
|
||||
|
||||
return { render };
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["./src"]
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "@ohmycv/vue-zoom",
|
||||
"version": "0.1.1",
|
||||
"description": "Vue 3 component for zooming content.",
|
||||
"homepage": "https://github.com/Renovamen/oh-my-cv/tree/main/packages/vue-zoom",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Renovamen/oh-my-cv"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Renovamen/oh-my-cv.git",
|
||||
"directory": "packages/vue-zoom"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Renovamen <renovamenzxh@gmail.com>",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.js",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build-fast:pkg": "tsup src/index.ts --format cjs,esm",
|
||||
"build:pkg": "pnpm run build-fast:pkg --dts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vueuse/core": "^10.11.0",
|
||||
"vue": "^3.4.31"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
import { defineComponent, ref, computed, h } from "vue";
|
||||
import { useElementSize } from "@vueuse/core";
|
||||
import type { VNode } from "vue";
|
||||
|
||||
export default defineComponent({
|
||||
name: "Zoom",
|
||||
|
||||
props: {
|
||||
scale: {
|
||||
type: Number,
|
||||
required: true
|
||||
}
|
||||
},
|
||||
|
||||
setup(props, { slots }) {
|
||||
const container = ref<HTMLElement>();
|
||||
const zoom = ref<HTMLElement>();
|
||||
|
||||
const sizeC = useElementSize(container);
|
||||
const sizeZ = useElementSize(zoom);
|
||||
|
||||
const left = computed(() =>
|
||||
Math.max(0, (sizeC.width.value - props.scale * sizeZ.width.value) / 2)
|
||||
);
|
||||
|
||||
return (): VNode =>
|
||||
h(
|
||||
"div",
|
||||
{
|
||||
class: "vue-zoom-container",
|
||||
ref: container,
|
||||
style: {
|
||||
height: "100%"
|
||||
}
|
||||
},
|
||||
[
|
||||
h(
|
||||
"div",
|
||||
{
|
||||
class: "vue-zoom",
|
||||
ref: zoom,
|
||||
style: {
|
||||
width: "fit-content",
|
||||
transformOrigin: "top left",
|
||||
transform: `scale(${props.scale})`,
|
||||
marginLeft: `${left.value}px`
|
||||
}
|
||||
},
|
||||
[slots.default!()]
|
||||
)
|
||||
]
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["./src"]
|
||||
}
|
||||
Reference in new issue
Block a user