Actually make the plugin

This commit is contained in:
Jack
2023-03-29 00:50:42 +01:00
parent d64d089e1a
commit 32c9f88374
23 changed files with 4151 additions and 259 deletions

2
.cargo/config Normal file
View File

@ -0,0 +1,2 @@
[build]
rustflags = ["--cfg=web_sys_unstable_apis"]

5
.gitignore vendored
View File

@ -20,3 +20,8 @@ data.json
# Exclude macOS Finder (System Explorer) View States
.DS_Store
# Added by cargo
/target

1305
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

39
Cargo.toml Normal file
View File

@ -0,0 +1,39 @@
[package]
name = "obsidian-typst"
version = "0.1.0"
authors = ["fenjalien"]
edition = "2021"
description = "Renders `typst` code blocks to images with Typst."
readme = "README.md"
[lib]
crate-type = ["cdylib"]
[dependencies]
# Everything to do with Typst
typst = { git = "https://github.com/typst/typst.git" }
typst-library = { git = "https://github.com/typst/typst.git" }
comemo = { git = "https://github.com/typst/comemo" }
once_cell = "1.17.1"
siphasher = "0.3.10"
elsa = "1.8.0"
# Everything to do with wasm
wasm-bindgen = { version = "^0.2" }
js-sys = "^0.3"
wasm-bindgen-futures = "^0.4"
serde = { version = "^1.0", features = ["derive"] }
serde-wasm-bindgen = "^0.5"
web-sys = { version = "^0.3", features = ["console", "Window", "FontData", "Blob", "ImageData"] }
[patch.crates-io]
web-sys = { git = "https://github.com/fenjalien/wasm-bindgen.git" }
js-sys = { git = "https://github.com/fenjalien/wasm-bindgen.git" }
wasm-bindgen-futures = { git = "https://github.com/fenjalien/wasm-bindgen.git" }
wasm-bindgen = { git = "https://github.com/fenjalien/wasm-bindgen.git" }
[profile.release]
debug = true

114
README.md
View File

@ -1,96 +1,38 @@
# Obsidian Sample Plugin
# Obsidian Typst
This is a sample plugin for Obsidian (https://obsidian.md).
Renders `typst` code blocks into images using [Typst](https://github.com/typst/typst) through the power of WASM!
This project uses Typescript to provide type checking and documentation.
The repo depends on the latest plugin API (obsidian.d.ts) in Typescript Definition format, which contains TSDoc comments describing what it does.
## Example
**Note:** The Obsidian API is still in early alpha and is subject to change at any time!
```
```typst
#set page(width: 10cm, height: auto)
#set heading(numbering: "1.")
#set text(white)
This sample plugin demonstrates some of the basic functionality the plugin API can do.
- Changes the default font color to red using `styles.css`.
- Adds a ribbon icon, which shows a Notice when clicked.
- Adds a command "Open Sample Modal" which opens a Modal.
- Adds a plugin setting tab to the settings page.
- Registers a global click event and output 'click' to the console.
- Registers a global interval which logs 'setInterval' to the console.
= Fibonacci sequence
The Fibonacci sequence is defined through the
_recurrence relation_ $F_n = F_(n-1) + F_(n-2)$.
It can also be expressed in closed form:
## First time developing plugins?
$ F_n = floor(1 / sqrt(5) phi.alt^n), quad
phi.alt = (1 + sqrt(5)) / 2 $
Quick starting guide for new plugin devs:
#let count = 10
#let nums = range(1, count + 1)
#let fib(n) = (
if n <= 2 { 1 }
else { fib(n - 1) + fib(n - 2) }
)
- Check if [someone already developed a plugin for what you want](https://obsidian.md/plugins)! There might be an existing plugin similar enough that you can partner up with.
- Make a copy of this repo as a template with the "Use this template" button (login to GitHub if you don't see it).
- Clone your repo to a local development folder. For convenience, you can place this folder in your `.obsidian/plugins/your-plugin-name` folder.
- Install NodeJS, then run `npm i` in the command line under your repo folder.
- Run `npm run dev` to compile your plugin from `main.ts` to `main.js`.
- Make changes to `main.ts` (or create new `.ts` files). Those changes should be automatically compiled into `main.js`.
- Reload Obsidian to load the new version of your plugin.
- Enable plugin in settings window.
- For updates to the Obsidian API run `npm update` in the command line under your repo folder.
The first #count numbers of the sequence are:
## Releasing new releases
- Update your `manifest.json` with your new version number, such as `1.0.1`, and the minimum Obsidian version required for your latest release.
- Update your `versions.json` file with `"new-plugin-version": "minimum-obsidian-version"` so older versions of Obsidian can download an older version of your plugin that's compatible.
- Create new GitHub release using your new version number as the "Tag version". Use the exact version number, don't include a prefix `v`. See here for an example: https://github.com/obsidianmd/obsidian-sample-plugin/releases
- Upload the files `manifest.json`, `main.js`, `styles.css` as binary attachments. Note: The manifest.json file must be in two places, first the root path of your repository and also in the release.
- Publish the release.
> You can simplify the version bump process by running `npm version patch`, `npm version minor` or `npm version major` after updating `minAppVersion` manually in `manifest.json`.
> The command will bump version in `manifest.json` and `package.json`, and add the entry for the new version to `versions.json`
## Adding your plugin to the community plugin list
- Check https://github.com/obsidianmd/obsidian-releases/blob/master/plugin-review.md
- Publish an initial version.
- Make sure you have a `README.md` file in the root of your repo.
- Make a pull request at https://github.com/obsidianmd/obsidian-releases to add your plugin.
## How to use
- Clone this repo.
- `npm i` or `yarn` to install dependencies
- `npm run dev` to start compilation in watch mode.
## Manually installing the plugin
- Copy over `main.js`, `styles.css`, `manifest.json` to your vault `VaultFolder/.obsidian/plugins/your-plugin-id/`.
## Improve code quality with eslint (optional)
- [ESLint](https://eslint.org/) is a tool that analyzes your code to quickly find problems. You can run ESLint against your plugin to find common bugs and ways to improve your code.
- To use eslint with this project, make sure to install eslint from terminal:
- `npm install -g eslint`
- To use eslint to analyze this project use this command:
- `eslint main.ts`
- eslint will then create a report with suggestions for code improvement by file and line number.
- If your source code is in a folder, such as `src`, you can use eslint with this command to analyze all files in that folder:
- `eslint .\src\`
## Funding URL
You can include funding URLs where people who use your plugin can financially support it.
The simple way is to set the `fundingUrl` field to your link in your `manifest.json` file:
```json
{
"fundingUrl": "https://buymeacoffee.com"
}
#align(center, table(
columns: count,
..nums.map(n => $F_#n$),
..nums.map(n => str(fib(n))),
))
```
```
If you have multiple URLs, you can also do:
```json
{
"fundingUrl": {
"Buy Me a Coffee": "https://buymeacoffee.com",
"GitHub Sponsor": "https://github.com/sponsors",
"Patreon": "https://www.patreon.com/"
}
}
```
## API Documentation
See https://github.com/obsidianmd/obsidian-api
<img src="assets/example.png">

BIN
assets/example.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -3,46 +3,79 @@ import process from "process";
import builtins from "builtin-modules";
const banner =
`/*
`/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
`;
const prod = (process.argv[2] === "production");
import * as fs from 'fs';
import * as path from 'path';
let wasmPlugin = {
name: 'wasm',
setup(build) {
// let path = require('path')
// let fs = require('fs')
// Resolve ".wasm" files to a path with a namespace
build.onResolve({ filter: /\.wasm$/ }, args => {
if (args.resolveDir === '') {
return // Ignore unresolvable paths
}
return {
path: path.isAbsolute(args.path) ? args.path : path.join(args.resolveDir, args.path),
namespace: 'wasm-binary',
}
})
// Virtual modules in the "wasm-binary" namespace contain the
// actual bytes of the WebAssembly file. This uses esbuild's
// built-in "binary" loader instead of manually embedding the
// binary data inside JavaScript code ourselves.
build.onLoad({ filter: /.*/, namespace: 'wasm-binary' }, async (args) => ({
contents: await fs.promises.readFile(args.path),
loader: 'binary',
}))
},
}
const context = await esbuild.context({
banner: {
js: banner,
},
entryPoints: ["main.ts"],
bundle: true,
external: [
"obsidian",
"electron",
"@codemirror/autocomplete",
"@codemirror/collab",
"@codemirror/commands",
"@codemirror/language",
"@codemirror/lint",
"@codemirror/search",
"@codemirror/state",
"@codemirror/view",
"@lezer/common",
"@lezer/highlight",
"@lezer/lr",
...builtins],
format: "cjs",
target: "es2018",
logLevel: "info",
sourcemap: prod ? false : "inline",
treeShaking: true,
outfile: "main.js",
});
banner: {
js: banner,
},
entryPoints: ["main.ts"],
bundle: true,
external: [
"obsidian",
"electron",
"@codemirror/autocomplete",
"@codemirror/collab",
"@codemirror/commands",
"@codemirror/language",
"@codemirror/lint",
"@codemirror/search",
"@codemirror/state",
"@codemirror/view",
"@lezer/common",
"@lezer/highlight",
"@lezer/lr",
...builtins],
format: "cjs",
target: "es2018",
logLevel: "info",
sourcemap: prod ? false : "inline",
treeShaking: true,
outfile: "main.js",
plugins: [
wasmPlugin
]
})
if (prod) {
await context.rebuild();
process.exit(0);
await context.rebuild();
process.exit(0);
} else {
await context.watch();
await context.watch();
}

244
main.ts
View File

@ -1,137 +1,145 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
import { App, HexString, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
// Remember to rename these classes and interfaces!
interface MyPluginSettings {
mySetting: string;
// @ts-ignore
import typst_wasm_bin from './pkg/obsidian_typst_bg.wasm'
import typstInit, * as typst from './pkg/obsidian_typst'
// temp.track()
interface TypstPluginSettings {
noFill: boolean,
fill: HexString,
pixel_per_pt: number,
}
const DEFAULT_SETTINGS: MyPluginSettings = {
mySetting: 'default'
const DEFAULT_SETTINGS: TypstPluginSettings = {
noFill: false,
fill: "#ffffff",
pixel_per_pt: 1
}
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
export default class TypstPlugin extends Plugin {
settings: TypstPluginSettings;
compiler: typst.SystemWorld;
async onload() {
await this.loadSettings();
async onload() {
await typstInit(typst_wasm_bin)
this.loadSettings()
let notice = new Notice("Loading fonts for Typst...")
this.compiler = await new typst.SystemWorld(this.app.vault.getRoot().path);
notice.hide();
notice = new Notice("Finished loading fonts for Typst", 5000);
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (evt: MouseEvent) => {
// Called when the user clicks the icon.
new Notice('This is a notice!');
});
// Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class');
this.addSettingTab(new TypstSettingTab(this.app, this));
this.registerMarkdownCodeBlockProcessor("typst", (source, el, ctx) => {
try {
const image = this.compiler.compile(source, this.settings.pixel_per_pt, `${this.settings.fill}${this.settings.noFill ? "00" : "ff"}`);
let canvas = el.createEl("canvas", {
cls: "obsidian-typst",
attr: {
width: image.width,
height: image.height,
}
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
const statusBarItemEl = this.addStatusBarItem();
statusBarItemEl.setText('Status Bar Text');
});
let ctx = canvas.getContext("2d");
ctx?.putImageData(image, 0, 0);
} catch (error) {
console.error(error);
}
})
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: 'open-sample-modal-simple',
name: 'Open sample modal (simple)',
callback: () => {
new SampleModal(this.app).open();
}
});
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: 'sample-editor-command',
name: 'Sample editor command',
editorCallback: (editor: Editor, view: MarkdownView) => {
console.log(editor.getSelection());
editor.replaceSelection('Sample Editor Command');
}
});
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-sample-modal-complex',
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView) {
// If checking is true, we're simply "checking" if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
new SampleModal(this.app).open();
}
/// Renders typst using the cli
// this.registerMarkdownCodeBlockProcessor("typst", (source, el, ctx) => {
// temp.mkdir("obsidian-typst", (err, folder) => {
// if (err) {
// el.innerHTML = err;
// console.log(err);
// } else {
// fs.writeFileSync(path.join(folder, "main.typ"), source)
// exec(
// `typst main.typ --image ${this.settings.noFill ? "--no-fill" : "--fill=" + this.settings.fill} --pixel-per-pt=${this.settings.pixel_per_pt}`,
// { cwd: folder }, (err, stdout, stderr) => {
// if (err || stdout || stderr) {
// // console.log(err, stdout, stderr);
// el.innerHTML = [String(err), stdout, stderr.replace(/\u001b[^m]*?m/g, "")].join("\n")
// } else {
// el.createEl("img", {
// cls: "obsidian-typst",
// attr: {
// src: `data:image/png;base64,${fs.readFileSync(path.join(folder, "main-1.png")).toString("base64")}`
// }
// })
// }
// })
// }
// // temp.cleanup()
// })
// });
console.log("loaded Typst");
}
// This command will only show up in Command Palette when the check function returns true
return true;
}
}
});
onunload() {
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this));
}
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', (evt: MouseEvent) => {
console.log('click', evt);
});
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class SampleModal extends Modal {
constructor(app: App) {
super(app);
}
class TypstSettingTab extends PluginSettingTab {
plugin: TypstPlugin;
onOpen() {
const {contentEl} = this;
contentEl.setText('Woah!');
}
constructor(app: App, plugin: TypstPlugin) {
super(app, plugin);
this.plugin = plugin;
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
containerEl.createEl('h2', {text: 'Settings for my awesome plugin.'});
new Setting(containerEl)
.setName('Setting #1')
.setDesc('It\'s a secret')
.addText(text => text
.setPlaceholder('Enter your secret')
.setValue(this.plugin.settings.mySetting)
.onChange(async (value) => {
console.log('Secret: ' + value);
this.plugin.settings.mySetting = value;
await this.plugin.saveSettings();
}));
}
display(): void {
const { containerEl } = this;
containerEl.empty();
let fill_color = new Setting(containerEl)
.setName("Fill Color")
.setDisabled(this.plugin.settings.noFill)
.addColorPicker((picker) => {
picker.setValue(this.plugin.settings.fill)
.onChange(
async (value) => {
this.plugin.settings.fill = value;
await this.plugin.saveSettings();
}
)
})
new Setting(containerEl)
.setName("No Fill (Transparent)")
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.noFill)
.onChange(
async (value) => {
this.plugin.settings.noFill = value;
await this.plugin.saveSettings();
fill_color.setDisabled(value)
}
)
});
new Setting(containerEl)
.setName("Pixel Per Point")
.addSlider((slider) =>
slider.setValue(this.plugin.settings.pixel_per_pt)
.setLimits(1, 5, 1)
.onChange(
async (value) => {
this.plugin.settings.pixel_per_pt = value;
await this.plugin.saveSettings();
}
))
}
}

View File

@ -1,11 +1,10 @@
{
"id": "obsidian-sample-plugin",
"name": "Sample Plugin",
"version": "1.0.0",
"minAppVersion": "0.15.0",
"description": "This is a sample plugin for Obsidian. This plugin demonstrates some of the capabilities of the Obsidian API.",
"author": "Obsidian",
"authorUrl": "https://obsidian.md",
"fundingUrl": "https://obsidian.md/pricing",
"isDesktopOnly": false
"id": "obsidian-typst",
"name": "Obsidian Typst",
"version": "0.1.0",
"minAppVersion": "1.0.0",
"description": "Renders `typst` code blocks to images with Typst.",
"author": "fenjalien",
"authorUrl": "https://github.com/fenjalien",
"isDesktopOnly": true
}

2272
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +1,32 @@
{
"name": "obsidian-sample-plugin",
"version": "1.0.0",
"description": "This is a sample plugin for Obsidian (https://obsidian.md)",
"name": "obsidian-typst-plugin",
"version": "0.1.0",
"description": "Renders `typst` code blocks to images with Typst.",
"main": "main.js",
"scripts": {
"dev": "node esbuild.config.mjs",
"wasm": "wasm-pack build --target web",
"dev": "wasm-pack build --target web --dev && node esbuild.config.mjs",
"wasm-build": "wasm-pack build --target web && tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"version": "node version-bump.mjs && git add manifest.json versions.json"
},
"keywords": [],
"author": "",
"license": "MIT",
"author": "fenjalien",
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^16.11.6",
"@types/temp": "^0.9.1",
"@typescript-eslint/eslint-plugin": "5.29.0",
"@typescript-eslint/parser": "5.29.0",
"builtin-modules": "3.3.0",
"esbuild": "0.17.3",
"esbuild-plugin-wasm": "^1.0.0",
"obsidian": "latest",
"tslib": "2.4.0",
"typescript": "4.7.4"
},
"dependencies": {
"obsidian-typst": "file:pkg",
"temp": "^0.9.4"
}
}
}

283
src/lib.rs Normal file
View File

@ -0,0 +1,283 @@
use comemo::Prehashed;
use elsa::FrozenVec;
use js_sys::Uint8Array;
use once_cell::unsync::OnceCell;
use siphasher::sip128::{Hasher128, SipHasher};
use std::{
cell::{RefCell, RefMut},
collections::HashMap,
hash::Hash,
path::{Path, PathBuf},
str::FromStr,
};
use typst::{
diag::{FileError, FileResult},
eval::Library,
font::{Font, FontBook, FontInfo},
geom::{Color, RgbaColor},
syntax::{Source, SourceId},
util::{Buffer, PathExt},
World,
};
use wasm_bindgen::{prelude::*, Clamped};
use wasm_bindgen_futures::JsFuture;
use web_sys::{console, Blob, FontData, ImageData};
#[wasm_bindgen]
extern "C" {
fn alert(s: &str);
}
#[wasm_bindgen(module = "fs")]
extern "C" {
#[wasm_bindgen(catch)]
fn readFileSync(path: &str) -> Result<JsValue, JsValue>;
}
#[wasm_bindgen(module = "utils")]
extern "C" {
async fn get_fonts() -> JsValue;
async fn get_local_fonts() -> JsValue;
}
/// A world that provides access to the operating system.
#[wasm_bindgen]
pub struct SystemWorld {
root: PathBuf,
library: Prehashed<Library>,
book: Prehashed<FontBook>,
fonts: Vec<FontSlot>,
hashes: RefCell<HashMap<PathBuf, FileResult<PathHash>>>,
paths: RefCell<HashMap<PathHash, PathSlot>>,
sources: FrozenVec<Box<Source>>,
main: SourceId,
}
#[wasm_bindgen]
impl SystemWorld {
#[wasm_bindgen(constructor)]
pub async fn new(root: String) -> Result<SystemWorld, JsValue> {
let mut searcher = FontSearcher::new();
searcher.search_system().await?;
Ok(Self {
root: PathBuf::from(root),
library: Prehashed::new(typst_library::build()),
book: Prehashed::new(searcher.book),
fonts: searcher.fonts,
hashes: RefCell::default(),
paths: RefCell::default(),
sources: FrozenVec::new(),
main: SourceId::detached(),
})
}
pub fn compile(
&mut self,
source: String,
pixel_per_pt: f32,
fill: String,
) -> Result<ImageData, JsValue> {
self.main = self.insert("<user input>".as_ref(), source);
match typst::compile(self) {
Ok(document) => {
let render = typst::export::render(
&document.pages[0],
pixel_per_pt,
Color::Rgba(RgbaColor::from_str(&fill)?),
);
Ok(ImageData::new_with_u8_clamped_array_and_sh(
Clamped(render.data()),
render.width(),
render.height(),
)?)
}
Err(errors) => Err(format!("{:?}", *errors).into()),
}
}
}
impl World for SystemWorld {
fn root(&self) -> &Path {
&self.root
}
fn library(&self) -> &Prehashed<Library> {
&self.library
}
fn main(&self) -> &Source {
self.source(self.main)
}
fn resolve(&self, path: &Path) -> FileResult<SourceId> {
self.slot(path)?
.source
.get_or_init(|| {
let buf = read(path)?;
let text = String::from_utf8(buf)?;
Ok(self.insert(path, text))
})
.clone()
}
fn source(&self, id: SourceId) -> &Source {
&self.sources[id.into_u16() as usize]
}
fn book(&self) -> &Prehashed<FontBook> {
&self.book
}
fn font(&self, id: usize) -> Option<Font> {
let slot = &self.fonts[id];
slot.font
.get_or_init(|| Font::new(slot.buffer.clone(), slot.index))
.clone()
}
fn file(&self, path: &Path) -> FileResult<Buffer> {
self.slot(path)?
.buffer
.get_or_init(|| read(path).map(Buffer::from))
.clone()
}
}
impl SystemWorld {
fn slot(&self, path: &Path) -> FileResult<RefMut<PathSlot>> {
let mut hashes = self.hashes.borrow_mut();
let hash = match hashes.get(path).cloned() {
Some(hash) => hash,
None => {
let hash = PathHash::new(path);
if let Ok(canon) = path.canonicalize() {
hashes.insert(canon.normalize(), hash.clone());
}
hashes.insert(path.into(), hash.clone());
hash
}
}?;
Ok(std::cell::RefMut::map(self.paths.borrow_mut(), |paths| {
paths.entry(hash).or_default()
}))
}
fn insert(&self, path: &Path, text: String) -> SourceId {
let id = SourceId::from_u16(self.sources.len() as u16);
let source = Source::new(id, path, text);
self.sources.push(Box::new(source));
id
}
}
fn read(path: &Path) -> FileResult<Vec<u8>> {
let f = |e: JsValue| {
console::log_1(&e);
FileError::Other
};
Ok(Uint8Array::new(&readFileSync(path.to_str().unwrap()).map_err(f)?).to_vec())
}
/// Holds details about the location of a font and lazily the font itself.
struct FontSlot {
buffer: Buffer,
index: u32,
font: OnceCell<Option<Font>>,
}
/// A hash that is the same for all paths pointing to the same entity.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
struct PathHash(u128);
impl PathHash {
fn new(path: &Path) -> FileResult<Self> {
let handle = Buffer::from(read(path)?);
let mut state = SipHasher::new();
handle.hash(&mut state);
Ok(Self(state.finish128().as_u128()))
}
}
/// Holds canonical data for all paths pointing to the same entity.
#[derive(Default)]
struct PathSlot {
source: OnceCell<FileResult<SourceId>>,
buffer: OnceCell<FileResult<Buffer>>,
}
struct FontSearcher {
book: FontBook,
fonts: Vec<FontSlot>,
}
impl FontSearcher {
fn new() -> Self {
Self {
book: FontBook::new(),
fonts: vec![],
}
}
fn add_embedded(&mut self) {
let mut add = |bytes: &'static [u8]| {
let buffer = Buffer::from_static(bytes);
for (i, font) in Font::iter(buffer.clone()).enumerate() {
self.book.push(font.info().clone());
self.fonts.push(FontSlot {
buffer: buffer.clone(),
index: i as u32,
font: OnceCell::from(Some(font)),
});
}
};
// Embed default fonts.
add(include_bytes!("../assets/fonts/LinLibertine_R.ttf"));
add(include_bytes!("../assets/fonts/LinLibertine_RB.ttf"));
add(include_bytes!("../assets/fonts/LinLibertine_RBI.ttf"));
add(include_bytes!("../assets/fonts/LinLibertine_RI.ttf"));
add(include_bytes!("../assets/fonts/NewCMMath-Book.otf"));
add(include_bytes!("../assets/fonts/NewCMMath-Regular.otf"));
add(include_bytes!("../assets/fonts/DejaVuSansMono.ttf"));
add(include_bytes!("../assets/fonts/DejaVuSansMono-Bold.ttf"));
add(include_bytes!("../assets/fonts/DejaVuSansMono-Oblique.ttf"));
add(include_bytes!(
"../assets/fonts/DejaVuSansMono-BoldOblique.ttf"
));
}
async fn search_system(&mut self) -> Result<(), JsValue> {
self.add_embedded();
if let Some(window) = web_sys::window() {
for fontdata in JsFuture::from(window.query_local_fonts()?)
.await?
.dyn_into::<js_sys::Array>()?
.to_vec()
{
let buffer = Buffer::from(
js_sys::Uint8Array::new(
&JsFuture::from(
JsFuture::from(fontdata.dyn_into::<FontData>()?.blob())
.await?
.dyn_into::<Blob>()?
.array_buffer(),
)
.await?,
)
.to_vec(),
);
for (i, info) in FontInfo::iter(buffer.as_slice()).enumerate() {
self.book.push(info);
self.fonts.push(FontSlot {
buffer: buffer.clone(),
index: i as u32,
font: OnceCell::new(),
})
}
}
}
Ok(())
}
}

View File

@ -1,8 +1,4 @@
/*
This CSS file will be included with your plugin, and
available in the app when your plugin is enabled.
If your plugin does not need CSS, delete this file.
*/
.obsidian-typst {
display: block;
margin: auto;
}