Browser editor package (npm)
ReShiki’s drawing editor in the browser, compiled to WebAssembly. It runs the same Rust code as the desktop app, without a server.
To convert structures between formats and draw them without the editor, use
@ameyanagi/reshiki-headless. Up to ReShiki 0.15.0
that library was this package’s main entry (import … from "@ameyanagi/reshiki"); see
Moving from 0.15.
Install
Section titled “Install”bun add @ameyanagi/reshikinpm install @ameyanagi/reshikipnpm add @ameyanagi/reshikiEach ReShiki release publishes the package with the app’s version, so
@ameyanagi/[email protected] is the editor of ReShiki 0.16.0. Prereleases are
under the next tag (bun add @ameyanagi/reshiki@next). The package carries
the license texts and third-party notices in dist/licenses.
scripts/build_wasm.sh # from the repository rootscripts/build_wasm.sh --test # and run the testsThe script needs Rust (the toolchain in rust-toolchain.toml and its
wasm32-unknown-unknown target), uv and bun. It installs the matching
wasm-bindgen CLI and a pinned binaryen wasm-opt under target/tools. It
writes the editor to dist/editor, its worker for naming to
dist/worker, and the license texts and third-party notices to
dist/licenses. The same run builds
@ameyanagi/reshiki-headless in packages/headless.
Editor
Section titled “Editor”The editor is the desktop app’s window, drawn into a page element with WebGPU, or WebGL2 where the browser has no WebGPU. It fills the element, so give the element a size of at least 1040 × 680 CSS pixels, the desktop window minimum. At narrower widths, the tool palette and 300 px inspector leave little or no room to draw. The bare imports below work with a bundler or the import map in the plain HTML recipe.
import { mount } from "@ameyanagi/reshiki/editor";
const editor = await mount(document.getElementById("editor"), { data: "CN1C=NC2=C1C(=O)N(C(=O)N2C)C", format: "smiles", onChange: () => console.log("edited"),});await editor.load(molfile, "mol"); // replaces the drawing in frontconst mol = await editor.save("mol"); // rsk, mol, smiles, inchi, cdxml, cdx, rxn, rsmiconst svg = await editor.exportImage("svg"); // svg (text), png or pdf (bytes)const stop = editor.onChange(() => {}); // returns a function that stops iteditor.destroy();Leaving the page while any tab has unsaved changes (reload, closing the browser tab, following a link) asks first with the browser’s “Leave site?” prompt. Closing an unsaved tab inside the editor asks Save, Don’t Save or Cancel. The page can follow the same state:
const editor = await mount(element, { title: true, // document.title follows the drawing: "Untitled • — ReShiki" onDirtyChange: (dirty) => console.log(dirty ? "unsaved" : "saved"), onTitleChange: (title) => console.log(title),});editor.isDirty(); // whether any tab has unsaved changesconst stopDirty = editor.onDirtyChange((dirty) => {}); // returns a function that stops itconst stopTitle = editor.onTitleChange((title) => {});The title is Name — ReShiki, with a • after the name while the tab in
front has unsaved changes, as on the desktop. Without title: true the page
keeps its own title, and onTitleChange hands it the editor’s.
load takes the same formats as convert in
@ameyanagi/reshiki-headless and rejects with
the app’s message when it cannot read the data; so does mount for its
data, before the editor starts. Mount on an element in the page’s body: the
editor cannot start inside a shadow root. save and exportImage return what
that convert would for the drawing in front.
Some inputs import with a change or an assumption. For these, load resolves
to { warnings } with the app’s messages, and the editor’s status bar shows
them after the drawing opens, as the desktop does. The status bar also shows
the warnings for mount’s data.
const { warnings } = await editor.load("C~C", "smiles");// ["Bond C1–C2 has any order (~); bond order assumed single"]A page runs one editor: the editor and the page share one thread and one
WebAssembly instance, and a second mount, or one after destroy, rejects.
For several editors, or to keep the page’s styles away from the editor, put
each in an iframe:
import { embed } from "@ameyanagi/reshiki/embed";
const editor = embed(document.getElementById("left"));await editor.ready;await editor.load("CCO", "smiles");embed returns the same methods as mount, sent to src/frame.html with
postMessage. Serve that page with the package’s src and dist folders, or
pass its URL as frameUrl. The frame answers only the page that embeds it. It
learns that page’s origin from the browser: location.ancestorOrigins, or the
referrer in Firefox, so a page on another origin must not hide its referrer
from the frame.
The custom element wraps mount:
<script type="module"> import "@ameyanagi/reshiki/element";</script><reshiki-editor src="caffeine.mol" format="mol" style="height: 680px"></reshiki-editor>It fires ready and change, and error when the editor cannot start, for
example when src answers 404, and has load, save and exportImage.
await element.ready resolves to the mounted editor once it runs, or rejects
if it could not start. This promise also works when the ready event has
already fired.
Changing the src or format attribute once the editor runs loads the drawing
at src in place of the one in front. Loading does not ask about unsaved
changes, so once the file is fetched the element fires a cancelable
beforeload event whose detail is { src, format, dirty }; dirty is
isDirty() at that moment. Call preventDefault() to keep the current
drawing:
element.addEventListener("beforeload", (event) => { if (event.detail.dirty && !confirm("Discard unsaved changes?")) event.preventDefault();});element.setAttribute("src", "aspirin.mol");A src that cannot be loaded fires error and keeps the current drawing.
Removing src keeps it too. Of several changes in a row, only the last loads.
If the editor could not start, for example because the first src answered
404, a changed src starts it.
Plain HTML page
Section titled “Plain HTML page”This example uses the installed npm package without a bundler. Start in an empty folder with Bun and Python 3 installed:
bun init -ybun add @ameyanagi/reshiki @ameyanagi/reshiki-headlessbun -e 'import { convert } from "@ameyanagi/reshiki-headless"; await Bun.write("caffeine.mol", await convert("CN1C=NC2=C1C(=O)N(C(=O)N2C)C", "smiles", "mol"))'Save the following as index.html in that folder:
<!doctype html><html lang="en"> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>My ReShiki page</title> <script type="importmap"> { "imports": { "@ameyanagi/reshiki/editor": "./node_modules/@ameyanagi/reshiki/src/editor.js", "@ameyanagi/reshiki/element": "./node_modules/@ameyanagi/reshiki/src/element.js", "@ameyanagi/reshiki/embed": "./node_modules/@ameyanagi/reshiki/src/embed.js" } } </script> <reshiki-editor src="caffeine.mol" format="mol" style="height: 680px"></reshiki-editor> <script type="module"> import "@ameyanagi/reshiki/element"; const element = document.querySelector("reshiki-editor"); await element.ready; console.log("Ready:", await element.save("smiles")); </script></html>Serve this folder, including node_modules, over HTTP:
python3 -m http.server 8080 --bind 127.0.0.1Open http://127.0.0.1:8080/ in Safari or Chrome. The page shows caffeine
(C8H10N4O2), and the browser console prints Ready: followed by its SMILES.
Import → Name can preview ethanol locally. Python 3’s server serves .wasm
as application/wasm; a production server must do the same.
Keep the package’s src/ and dist/ folders beside each other when copying
them to a public directory: src/editor.js and src/worker.js load
../dist/…. Adjust the three import-map URLs to that directory together.
The page and package must share an origin for the naming worker; see
Naming. Open the HTTP URL, rather than index.html as a local file.
The repository’s examples/serve.ts is a development tool and is not part
of the installed package.
The editor can only draw with fonts loaded into it as bytes: it bundles Liberation Sans, which has Arial’s letter widths and answers to Arial, so drawings lay out as on the desktop. Text that font lacks falls back to the fonts below.
- Chinese, Japanese and Korean text. The first time a caption, a tab’s file name or the status line has such characters that no loaded font draws, the editor loads a fallback once for that language. If the page already has Local Font Access permission (Chrome and Edge), it uses the computer’s own font, such as Hiragino Sans, Apple SD Gothic Neo or PingFang SC, without a prompt. Otherwise it downloads a Noto Sans Regular subset (SIL Open Font License 1.1) from jsDelivr: JP (4.5 MB) for kana and kanji, KR (4.6 MB) for Hangul, and SC (8.3 MB) for Bopomofo and for ideographs the Japanese font lacks. Pages without such text download nothing. The fonts are not bundled in this package.
- The page’s own fonts.
fontstakes TrueType or OpenType files (or collections) as URLs or bytes. They load before the editor starts, and text whose font lacks a glyph falls back to them. URLs on another origin need CORS.
await mount(element, { fonts: ["/fonts/MyLabels.ttf"], cjkFont: "/fonts/NotoSansCJK-Regular.otc", // one self-hosted fallback for every language, or false for none onError: (error) => console.warn(error.message), // a font that could not load});embed() takes the same options, with fonts as URLs on the page’s own origin
or the frame’s; it reports a font from anywhere else, or one whose URL
redirects, through onError and does not load it. mount follows a font’s
redirects unless fontRedirect is "error". The custom element
takes fonts (URLs separated by spaces) and cjk-font (a URL, or false)
attributes and fires error for a font that could not load. Fonts added this
way also reach save and exportImage figures.
Each font added with fonts, addFont or the Japanese fallback is kept in
browser storage (below) and added again on a later visit once a caption needs
it, so the fallback is downloaded once per site rather than once per visit. The editor cannot list
or read the computer’s installed fonts by itself: browsers only offer them
through Local Font Access, behind a permission prompt.
Storage
Section titled “Storage”The editor keeps what the desktop app keeps in its data folder in the
browser’s IndexedDB for the page’s site (database reshiki): appearance
settings, My templates and favorites, saved themes, your abbreviations,
added fonts and recovery drafts. They load before the editor starts, and a change in one tab
reaches the site’s other tabs while they run. A tab keeps a change only if the
stored file is still the one it read, so tabs never save over each other; a
save that another tab beat, or one the browser refuses because storage is
full, is undone and the status bar says why. Messages name this storage
“Browser storage”. Where the browser offers no storage, as in some private
windows, the editor starts with defaults and saving a setting, template, theme
or abbreviation says that browser storage is unavailable. Clearing the site’s
data removes it all.
As in the desktop app, each drawing with unsaved changes has a recovery draft, written within about a second of each change. If the page is reloaded, closed or crashes, the next page of the site offers the drafts in the status bar: the number of drafts, the newest drawing’s title and its age, with Restore…, Discard… and Dismiss. Restore… lists the drafts by title, date and atom count and restores the checked ones or all of them as tabs. Discard… asks before deleting the offered drafts permanently, since the browser has no Trash. Dismiss hides the offer until the page is loaded again and keeps the drafts. Drafts of the site’s other open tabs are not offered (this needs Web Locks, which current browsers have). The page cannot write while it unloads, so a change made in the last second before a reload can be lost.
Content Security Policy
Section titled “Content Security Policy”On a page with a Content-Security-Policy, the editor needs:
script-src 'wasm-unsafe-eval'(with the source the package is served from), or the WebAssembly does not start and the page stays blank;connect-src https://cdn.jsdelivr.netfor the Chinese, Japanese and Korean fallback font, unlesscjkFontnames a font on the page’s own site or isfalse, plus the sitesfontsandsrcload from;worker-src blob:on browsers withoutscheduler.postTask, where the event loop’s timer runs in a small worker made from ablob:URL.
The optional, user-confirmed PubChem name lookup also needs
connect-src https://pubchem.ncbi.nlm.nih.gov. Omitting it blocks online lookup
without affecting local name parsing. The editor never sends a chemical name
to PubChem until the user confirms that individual lookup.
style-src can stay strict: mount and <reshiki-editor> style the editor
through the CSSOM, which style-src does not restrict. src/frame.html, the
page embed() loads, has an inline <style>, so serve it with
style-src 'unsafe-inline' or a page of your own.
Naming
Section titled “Naming”Name ↔ structure conversion (Import → Name, Name molecule) runs the
desktop’s OPSIN Rust port and naming rules in a module Web Worker,
src/worker.js, which loads its own WebAssembly
(dist/worker/reshiki_web_worker_bg.wasm, about 2.3 MB gzipped) the first time
a name is converted, never at startup. As on the desktop, a request stops after
15 seconds and the worker’s heap is limited to 96 MiB (its memory to
128 MiB), so a runaway name cannot block or crash the editor; the next
request starts a new worker.
Browsers start workers only from the page’s own origin, so serve the package
from the page’s site to use naming. A Content-Security-Policy whose
script-src allows that site needs nothing more. If it sets worker-src (or
child-src), that must allow the site too, for example
worker-src 'self' blob:.
scripts/build_wasm.sh # from the repository rootcd packages/editor && bun examples/serve.tsThen open http://localhost:8080/, which is the editor alone, filling the
window. http://localhost:8080/examples/api.html calls the JavaScript API from
the page’s own buttons, and http://localhost:8080/examples/iframe.html shows
two editors in iframes. PORT picks another port.
The same editor-only page runs at https://reshiki.com/demo/, packaged by
scripts/package_web_demo.sh with a dismissible note that it is a browser
preview, not the full app. The list below is what it leaves out; point people
to the desktop app whenever they can use
it.
What the browser editor leaves out
Section titled “What the browser editor leaves out”- Naming and NMR prediction work: naming runs in its own worker (see Naming). 3D models and 3D optimization work, but pause the page while they compute. The assistant and printing need the desktop app and are hidden, Check for updates does not apply (the page updates the editor), and Office and LibreOffice integration are not available.
- Open and Save use the browser: Open, Insert from file and the drawing style, theme, template and picture choosers use the browser’s file chooser, and files dropped on the editor open or insert as in the desktop app. Save and Export download a file under the drawing’s name.
- Copying and pasting drawings goes through
navigator.clipboard, which asks for permission to read, and carries PNG, HTML, SVG (Chrome and Edge) and text, not PDF, CDX or ChemDraw’s own formats. Text fields copy, cut and paste plain text; their paste uses the browser’s paste event and needs no permission. - Input methods (Japanese, Chinese and Korean) type into text fields and captions through a hidden textarea that the editor adds to the element. Typing atom labels straight onto the drawing, without a text field, takes keys only, not composed text.
- Only Liberation Sans and a small subset of DejaVu Sans for the interface’s
key and arrow symbols are bundled, so drawing symbols they lack, such as ℃,
⇌ and superscript ⁺ and ⁻, need a font from
fonts. Chinese, Japanese and Korean text loads a fallback (see Fonts). - Shortcuts follow the desktop app, with ⌘ as Command on a Mac, except three that browsers keep for their own tabs: New is Alt+N, Close tab Alt+W and next/previous tab Alt+] / Alt+[ (⌃N, ⌃W, ⌃] / ⌃[ on a Mac).
- Work other than naming runs on the page’s thread, so a long cleanup, import, NMR prediction or 3D model pauses the page.
- Without WebGPU, lines are drawn without antialiasing: WebGL2 loses most canvases with it.
cd packages/editorbun testPull request CI runs these tests, after Clippy for wasm32, in the Browser build (wasm32) job of the Checks workflow; see Development.