npm package: @sciflow/editor-start
Description: Documentation: [docs.sciflow.org](https://docs.sciflow.org)
Latest version: 0.0.3

# @sciflow/editor-start

Documentation: [docs.sciflow.org](https://docs.sciflow.org)

Lit-based wrapper around the SciFlow ProseMirror schema. It loads all the packages required to get started with a basic editor.

## Building

- `npx nx build @sciflow/editor-start` &mdash; compile TypeScript output and declaration files.
- `npx nx bundle @sciflow/editor-start` &mdash; run the TypeScript build and emit an ES module bundle under `dist/bundle/` for the demo and browser usage.

## Running unit tests

- `npx nx test @sciflow/editor-start`

## Usage

```html
<sciflow-editor id="demo-editor"></sciflow-editor>
<sciflow-formatbar id="demo-toolbar"></sciflow-formatbar>

<script type="module">
  import '@sciflow/editor-start';

  const editor = document.querySelector('sciflow-editor');
  const toolbar = document.querySelector('sciflow-formatbar');

  if (editor && toolbar) {
    const bindToolbar = () => {
      toolbar.editor = editor;
    };

    editor.addEventListener('editor-ready', bindToolbar, { once: true });
    bindToolbar();
  }
</script>
```

Companion elements for sidebars—`<sciflow-selection-editor>` and `<sciflow-reference-list>`—are also registered by the bundle. See `demo/` for wiring examples.

`editor-change` events include `{ doc, operations, files, references }`, where `files` mirrors uploaded assets (full URLs plus optional previews) maintained by the figure feature.

## Developer docs

- Selection editor internals (selection interaction, property editing, JSON schema): `docs/selection-editor.md`

### Custom shadow-root styles

Inject CSS directly into the editor's shadow root to override the built-in ProseMirror styles without touching global stylesheets. Styles can be set before or after initialization:

```js
const editor = document.querySelector('sciflow-editor');

// Option 1: Set via property (works before or after initialization)
editor.shadowStyles = [
  '.ProseMirror { line-height: 1.6; }',
  '.ProseMirror h1 { font-family: "Merriweather", serif; }',
];

// Option 2: Use the imperative method (recommended for dynamic updates)
editor.setShadowStyles(`
  .ProseMirror p { max-width: 72ch; }
  .ProseMirror a { color: rebeccapurple; }
`);
```

**Dynamic style injection** (e.g., for ProseMirror decorations added via plugins):

```js
// Initialize editor first
editor.doc = { doc: myDocument, files: [], references: [] };

// Later: add styles for decorations dynamically
editor.setShadowStyles([`
  .my-annotation {
    background: rgba(255, 200, 0, 0.3);
    border-bottom: 2px solid orange;
  }
  .my-highlight {
    background: yellow;
  }
`]);

// Or append to existing styles (normalize first: shadowStyles can be string or string[])
const current = editor.shadowStyles;
const currentStyles = Array.isArray(current) ? current : current ? [current] : [];
editor.setShadowStyles([...currentStyles, `.my-new-decoration { background: pink; }`]);
```

Use `setShadowStyles()` when you need styles applied immediately (e.g., after adding a plugin). Property assignment applies asynchronously via Lit's lifecycle.

### Global theme

Apply a single theme across all SciFlow components:

```js
import { setSciFlowThemeStyles } from '@sciflow/editor-start';

setSciFlowThemeStyles(`
  :host {
    --sciflow-accent: #2563eb;
    --sciflow-surface: #ffffff;
  }
`);
```

### Reference list

`<sciflow-reference-list>` renders a draggable, highlightable list of references (CSL-style objects). It does not auto-bind to the editor; push data into it from your own listeners:

```js
const refList = document.querySelector('sciflow-reference-list');

// When your editor change event fires:
refList.references = snapshot.references; // array of reference objects
refList.highlight(['ref-1', 'ref-2']); // optional highlighted ids
```

Properties and behaviours:
- `references`: array of objects with fields like `id`, `rawReference`/`raw_reference`, `author`, `title`, `issued`, etc.
- `highlightedIds`: string array; can also call `highlight(ids)` to update them.
- `id` and `rawReference` are required. `rawReference` can be any formatted bibliography string (including hand-written).
- `mimeType` should be set for anything besides CSL JSON; default is `application/vnd.citationstyles.csl+json`. Use `application/vnd.openalex+json` for OpenAlex or your own type for custom payloads.
- Dragging an item sets `application/json`, `application/x-sciflow-reference`, and `text/plain` payloads for integrations.

### Citation query helpers

Re-exported from `@sciflow/editor-core` for convenience:

```ts
import { getCitedReferenceIds, validateDocumentResources } from '@sciflow/editor-start';
```

- **`getCitedReferenceIds(doc, from?, to?)`** — extract cited reference IDs from the document (or a range within it). Useful for highlighting references that match the current selection.
- **`validateDocumentResources(doc, files, references)`** — validate that all figure sources and citation references in the document JSON exist in the snapshot. Returns `MissingResource[]`.

See the [`@sciflow/editor-core` README](../core/README.md) for details.

### Translation extraction

Extract all built-in translation keys and their English defaults to create a template for a new language:

```bash
npx @sciflow/editor-start extract-translations > en.json        # JSON
npx @sciflow/editor-start extract-translations --csv > en.csv   # CSV
```

Translate the values in the output file, then register at runtime:

```js
import { registerTranslations, setLocale } from '@sciflow/editor-start';
import fr from './fr.json' with { type: 'json' };

registerTranslations('fr', fr);
setLocale('fr');
```

See the [Localization guide](https://docs.sciflow.org/user-guide/customization/localization/) for details.

### Math (equations)

When the **math** feature is enabled (it is included in the default feature list), users can insert and edit TeX equations. Equations are rendered as SVG in the editor using MathJax 4.

- **Loading MathJax:** The host page must load the MathJax 4 `tex-svg` component before equations will render, e.g.  
  `<script defer src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-svg.js"></script>`  
  If MathJax is not loaded, math nodes show a short message and the raw TeX; the document still saves and loads correctly.
- **Editing:** Select a math node in the editor; the selection sidebar shows a **math** panel with TeX source, inline/display style, optional label, live preview, and **Apply** / **Escape** (cancel). Use **Ctrl+Enter** (or **Cmd+Enter**) to apply changes and **Escape** to cancel.
- **Errors and warnings:** Invalid TeX shows an error message in the node view and in the sidebar preview. MathJax errors and warnings are always shown when they occur so users can fix equations.

The format bar shows an **Insert equation** button when the math feature is active.

### Format bar coverage (v1)

The format bar exposes the most common authoring commands. Some schema-level marks and node types are intentionally **not** surfaced in v1:

| Type | Schema name | Reason |
|------|-------------|--------|
| Mark | `code` (inline code) | Planned for v2. Users can paste code or apply it programmatically. |
| Node | `code_block` | Planned for v2. No insert button yet. |
| Node | `horizontal_rule` | Planned for v2. No insert button yet. |
| Node | `image` (inline) | Inline images are in the schema but only figure-level images have UI. |
| Mark | `bdi` | Bidirectional isolate — niche; may be exposed when RTL support is prioritised. |
| Mark | `tags` | Semantic classification mark managed by the host application, not end users. |

### Footnotes

The **footnote** feature is also included in the default feature list.

- The format bar shows an **Insert footnote** button when the feature is active.
- Running `insertFootnote` with a text selection moves the selected text into the new footnote body.

## Demo

- `npx nx run @sciflow/editor-start:demo` &mdash; runs `vite build --watch` to keep the ES module bundle up to date **and** serves the demo via `vite dev`. The demo always loads `dist/bundle/sciflow-editor.js`, so the behaviour matches what you ship to consumers.
- `npx nx bundle @sciflow/editor-start` &mdash; single build of the browser bundle (useful when packaging the demo for sharing).
- `./build-demo-zip.sh` &mdash; convenience script that runs the bundle build and produces `sciflow-editor-demo.zip` containing `demo/` and `dist/bundle/`.

When you need to hand the demo to someone without repository access:

1. Run `npx nx bundle @sciflow/editor-start` to refresh `dist/bundle/`.
2. Zip `packages/editor/start/demo/` together with `packages/editor/start/dist/bundle/`.
3. They can unpack the archive and open `demo/index.html` (or serve the folder with any static server) to explore the integration.

## Production deployment notes (Lit)

When serving the demo or a host app in production, apply the same deployment hardening recommended by Lit:

- Enable text compression at the server/CDN layer (gzip or brotli).
- Use cache-busting/fingerprinted URLs where feasible in the host application.
- Keep JavaScript minification enabled (the Vite production build already does this).
- The bundle is built with Vite (esbuild minification).