# Documentation

> Documentation for the research article template and its collaborative editor: quickstart, Hugging Face plan requirements, writing, components, interactive figures, theming and publishing.

Source: https://tfrere-research-article-template-site.hf.space/docs

Everything you need to write and publish a web-native research article - with the collaborative editor or the code-first template. The full, always-current reference lives inside the [demo article](https://tfrere-research-article-template.hf.space/), which is itself written with the template.

## Overview

Two products share one rendering engine, so they produce the same articles:

-   **The editor** - a real-time collaborative editor running on a Hugging Face Space. Host your own copy (duplicating the Space needs HF PRO or a Team organization), sign in with your HF account, write with your co-authors, publish in one click.
-   **The template** - an Astro + MDX repository, free to clone. Write chapters in MDX, craft D3 embeds by hand, version everything with git, deploy as a Docker Space or as static files.

Both give you KaTeX math, BibTeX citations, footnotes, interactive D3.js figures, automatic dark mode, brand-color theming, PDF export and an LLM-readable twin of the article at `/llms.txt`.

## Editor or template?

|  | Editor | Template |
| --- | --- | --- |
| Setup | Duplicate a Space | `git clone` |
| Hugging Face plan | PRO (solo) or Team org (co-authors) | Free with a static Space |
| Writing | Rich-text, live collaboration | MDX files in your editor |
| Figures | AI embed studio or paste HTML | Hand-written D3 embeds |
| Versioning | Autosaved to an HF dataset | git, PRs, CI |
| Publishing | One click | `git push space main` |
| Best for | Teams, fast iteration | Full control, custom code |

You can start in the editor and graduate to the template later - the article format is the same.

## Editor - quickstart

To try it first, open the [live demo](https://tfrere-research-article-editor-demo.static.hf.space/): the editor running in your browser, with no account and nothing saved. Simulated co-authors (Alice, Bob and Alice's agent) write alongside you; AI and publishing are disabled, and *Download .mdx* keeps a copy of your draft.

The public [editor Space](https://huggingface.co/spaces/tfrere/research-article-template-editor) is read-only for visitors: only the Space owner, or members of the owning organization with a write role, can edit. To write, host your own copy:

1.  Open the [editor Space](https://huggingface.co/spaces/tfrere/research-article-template-editor), use the *"..." menu, Duplicate this Space* and pick your organization as the owner. Or from a terminal (huggingface\_hub 1.6+, after `hf auth login`):
    
    ```bash
    hf repos duplicate tfrere/research-article-template-editor your-org/paper-editor --type space
    ```
    
2.  Sign in with Hugging Face OAuth - no API key to configure.
3.  Share your Space URL with co-authors: members of the organization with write access can join the document and edit live. Org roles are free on any plan.

Since July 21, 2026, duplicating a Docker Space needs a paid Hugging Face plan ([Duplicating a Space](https://huggingface.co/docs/hub/spaces-overview#duplicating-a-space)): a **Team or Enterprise organization** to write with co-authors, or a **PRO account** for a personal copy, where only you can edit. Without a paid plan you can still write with the template and host the published article for free on a static Space (see [Deploy & sync](https://tfrere-research-article-template-site.hf.space/docs#template-deploy)).

Documents autosave continuously and persist to a Hugging Face dataset in your namespace, so your writing survives Space restarts and rebuilds.

## Editor - writing together

Collaboration is powered by Y.js CRDTs: every author sees live cursors and per-user colors, and concurrent edits merge without conflicts. On top of that:

-   **Comments** - anchor a thread on any selection, resolve inline.
-   **AI assistant** - ask for rewrites or content edits in a chat; it runs on your own HF Inference Providers quota.
-   **Blocks** - math, code, tables, images, HTML embeds, footnotes and citations, reorderable by drag and drop.

## Editor - AI embed studio

Describe a figure in plain language - or paste a CSV - and the studio generates a self-contained D3 embed, live in your article. Iterate in a chat loop until it looks right.

-   Works from a prompt, a dataset, or both.
-   The output is plain HTML + D3 you own and can edit by hand.
-   Generated embeds follow the template's conventions (theme variables, `ColorPalettes`), so they retint with your brand color and dark mode automatically.

*[Video: Demo of the AI embed studio: an author generates an animated article banner and an interactive accuracy chart from short text prompts]*

## Editor - publishing

One click produces, in 15-25 seconds, while others keep editing:

-   a static HTML page ready to share,
-   a print-ready PDF with full typography,
-   a social thumbnail captured automatically,
-   a Markdown twin at `/llms.txt`, advertised in `robots.txt`.

## Template - installation

Clone the [template repository](https://github.com/tfrere/research-article-template) (free, requires Node.js 20+ and Git LFS for the images):

```bash
git clone https://github.com/tfrere/research-article-template.git my-paper
cd my-paper
git lfs install && git lfs pull
cd app
npm install
npm run dev   # dev server on port 4321
```

Then edit `app/src/content/article.mdx` (title, authors, template variant) and the chapters it imports.

## Template - variants

Choose the layout in the `article.mdx` frontmatter:

```yaml
template: "article"  # grid: TOC rail, body, margin column for sidenotes
template: "paper"    # lighter: one centered column, link pills
```

`article` opens with a centered hero (title, subtitle, banner) and meta columns: authors, affiliations, published date and reading time, then a Resources column with the PDF and Cite buttons and your `links`. In `paper`, the same `links` become pill buttons under the author line. Long titles are auto-balanced; force a break with `\n`:

```yaml
title: "Why Open-Source LLMs\nAre Reshaping the AI Landscape"
```

Banner, table of contents and links are frontmatter fields too:

```yaml
banner: "banner-groove.html"   # any file in embeds/, or false to hide it
tocExpanded: false               # only the section being read expands in the TOC
links:                           # shown in the Resources column of the hero
  - label: "Code"
    url: "https://github.com/..."
  - label: "Checkpoints"
    url: "https://huggingface.co/..."
```

`banner` defaults to `banner.html`; `tocExpanded` defaults to `true` (every h3 visible). Every field is listed in the [article-frontmatter skill](https://github.com/tfrere/research-article-template/blob/main/.ai/skills/article-frontmatter/SKILL.md).

## Template - layout & grid

The `article` page is one CSS grid with named lines (`screen`, `page`, `toc`, `outset`, `body`, `margin`). From 1280px, sidenotes sit in the margin column; between 1101 and 1279px the TOC rail is compact and sidenotes go inline; at 1100px and below the page is a single column and the TOC becomes a top bar with a drawer.

-   **Tokens** - every width, gutter and sticky offset is a `--layout-*` variable in [`app/src/styles/_grid.css`](https://github.com/tfrere/research-article-template/blob/main/app/src/styles/_grid.css). Change the layout there, not in components.
-   **Placement** - content goes to `body`; `Wide` spans `body-start / margin-end`; `FullWidth` spans `screen`; a `Sidenote` placed right after a block sits in `margin`.
-   **Heading anchors** - h2 to h4 get a link icon on hover or focus; clicking it copies the section URL, and links with a hash land on that heading.
-   **Debug grid** - add `?grid` to any URL, or press `G` in `npm run dev` (`Shift+G` toggles the baseline). It draws the live tracks, so it always shows the current tokens.

```css
:root {
  --layout-body: 664px;        /* body column */
  --layout-prose: 620px;       /* max line length of text */
  --layout-gap: 32px;          /* gutter between rail, body and margin */
  --layout-side-min: 260px;    /* TOC rail and margin column at 1280px */
  --layout-side-max: 360px;    /* ...growing up to this on wide screens */
}
```

## Template - deploy & sync

**Free: a static Space.** Build locally and upload the output to a Space created with the *Static* SDK at [huggingface.co/new-space](https://huggingface.co/new-space):

```bash
cd app
npm run build
hf upload <you>/<your-space> dist . --repo-type space
```

**Docker Space.** Push the repository to a Space created with the *Docker* SDK: it builds on Hugging Face with the included `Dockerfile`.

```bash
# create a Docker Space at huggingface.co/new-space, then:
git remote add space git@hf.co:spaces/<you>/<your-space>
git push space main
```

A `[slugified-title].pdf` and a `thumb.jpg` are generated at build time. Serving `dist/` from any static host works too. Keep the `research-article-template` tag in the Space `README.md`: it lists your article in the [community gallery](https://huggingface.co/spaces/tfrere/research-article-gallery). To pull the latest template improvements without touching your content:

```bash
npm run sync:template -- --dry-run   # preview
npm run sync:template                # update (preserves src/content/)
```

## Article structure

Your article lives in `app/src/content/`. The entry point is `article.mdx`: frontmatter (title, authors, affiliations, DOI, template variant...) plus imported chapters:

```mdx
# app/src/content/article.mdx
---
title: "My paper"
authors:
  - name: "Ada Lovelace"
    url: "https://huggingface.co/ada"
    affiliations: [1]
affiliations:
  - name: "Analytical Engines Lab"
published: "Aug 8, 2026"
template: "article"
---

import Introduction from "./chapters/introduction.mdx";

<Introduction />
```

Chapters are plain `.mdx` files in `src/content/chapters/`; the table of contents is generated from your headings.

## Markdown & math

-   **Math** - KaTeX: `$e^{i\pi} + 1 = 0$` inline, `$$...$$` for display equations.
-   **Citations** - BibTeX entries in `bibliography.bib`, cited with `[@vaswani2017attention]` or grouped `[@a; @b]`. Pick the style (APA, IEEE, Vancouver...) in the frontmatter.
-   **Footnotes** - `[^note]` with definitions anywhere in the file; they support math and citations.
-   **Mermaid** - fenced ` ```mermaid ` blocks render as diagrams.
-   **Code, tables, audio** - syntax-highlighted code blocks, GFM tables, audio players from local files.

Below, an actual rendered snippet - KaTeX equation, citation and footnote - exactly as it comes out of the engine. The [markdown chapter](https://tfrere-research-article-template.hf.space/#markdown) of the demo shows every feature live.

*[Interactive figure: Markdown sample with a KaTeX equation, citation and footnote, rendered live]*

## Components

Import what you need at the top of any chapter:

```mdx
import Note from "../../components/Note.astro";
import HtmlEmbed from "../../components/HtmlEmbed.astro";
```

| Component | What it does |
| --- | --- |
| `Image` | zoomable, downloadable figures with captions |
| `Note` / `Sidenote` | callouts and margin notes |
| `Quote` | attributed quotations |
| `Accordion` | collapsible sections (code examples, proofs) |
| `Glossary` | hoverable term definitions |
| `Stack` | multi-column layouts |
| `Wide` / `FullWidth` | break out of the text column |
| `HtmlEmbed` | self-contained interactive figures (below) |

A few of them, rendered right here (the accordion really opens):

**Note** Callouts like this one carry context or caveats without interrupting the argument.

> “Attention is all you need.”
> 
> Vaswani et al., 2017

Accordion - expand for the full proof

Collapsible sections keep long code samples and derivations out of the reading flow. This one is a real element, not a screenshot.

The [components chapter](https://tfrere-research-article-template.hf.space/#components) demonstrates each one live.

## Interactive figures

Figures are self-contained `.html` files in `app/src/content/embeds/`: one root `<div>` whose class matches the file name, a `<style>` scoped to that class, and a `<script>` calling `Embed.mount`. The shared runtime (`app/public/scripts/embed-runtime.js`) loads D3, reads the `data` and `config` props, re-renders on resize and theme changes, shows errors and signals readiness. The same contract runs in the editor, so an embed moves between the two unchanged.

```html
<div class="d3-my-chart"></div>
<style>
  .d3-my-chart { position: relative; color: var(--text-color); font-size: 12px; }
  .d3-my-chart svg { display: block; width: 100%; overflow: visible; }
  .d3-my-chart .axis text { fill: var(--tick-color); }
</style>
<script>
  Embed.mount('d3-my-chart', async (ctx) => {
    // Setup, runs once: data, scales, persistent DOM.
    const rows = await ctx.data();
    const svg = d3.select(ctx.root).append('svg');
    ctx.describe(`Line chart of ${ctx.config.metric || 'loss'} over training.`);

    // Render, runs on first paint and on width, theme or palette change.
    return ({ width, isDark }) => {
      const h = Math.max(240, Math.min(420, Math.round(width * 0.5)));
      svg.attr('viewBox', `0 0 ${width} ${h}`).attr('height', h);
      const [color] = ctx.colors('categorical', 1);
      // scales, axes, data joins with selection.join()
    };
  });
</script>
```

Drop it into a chapter:

```mdx
<HtmlEmbed
  src="d3-my-chart.html"
  title="Validation loss during pre-training"
  desc="Lower is better."
  data="my-data.csv"
  config={{ metric: "loss" }}
/>
```

-   `setup(ctx)` runs once (data, scales, persistent DOM) and returns a render function, called with `{ width, height, theme, isDark }` on first paint and on every width, theme or palette change. Keep it idempotent with data joins.
-   Data files (CSV, JSON...) go in `app/src/content/assets/data/`, are served under `/data/` and passed with `data`; `ctx.data()` fetches and parses them (CSV typed with `d3.autoType`). `config` arrives as `ctx.config`.
-   Colors come from CSS variables (`--text-color`, `--axis-color`, `--grid-color`...) and `ctx.colors(kind, n)`, read inside render, so the figure follows dark mode and the brand color. Never hardcode them.
-   Call `ctx.describe()` with the takeaway: it sets the accessible label of the chart.
-   Start from `.ai/skills/create-html-embed/template.html`; the full API is in [runtime.md](https://github.com/tfrere/research-article-template/blob/main/.ai/skills/create-html-embed/runtime.md).

Check it before publishing: the checker renders the embed in headless Chrome inside the real article styles (light, dark, several widths) and reports runtime errors, failed requests, leaked globals, unreadable text, overlapping labels, overflow and a missing description.

```bash
cd app
npm run check:embed -- d3-my-chart.html --data my-data.csv
npm run check:embed -- --all   # every embed in the repo
```

Below, the demo article's reusable line chart, running live with a `config` (try the zoom and the smoothing toggle):

*[Interactive figure: Generic line chart embed from the demo article, running live]*

The gallery on the [home page](https://tfrere-research-article-template-site.hf.space/#studio) runs three more embeds from the demo article.

## Colors & dark mode

One variable drives the whole article: `--primary-color` (an OKLCH color). Categorical, sequential and diverging palettes are derived from it at runtime:

```js
const cat = window.ColorPalettes.getColors("categorical", 8);
const seq = window.ColorPalettes.getColors("sequential", 8);
const div = window.ColorPalettes.getColors("diverging", 7);

// change the brand color, notify listeners
document.documentElement.style.setProperty("--primary-color", "#6D4AFF");
window.ColorPalettes.refresh();
```

Inside an embed, use `ctx.colors(kind, n)` in the render function: the runtime re-renders on `palettes:updated` and on theme flips, so the figure retints live. Dark mode flips automatically with the reader's system preference (`data-theme` on the root element); text, axes and surfaces use CSS variables so everything follows.

Drag the hue: the figure below re-derives its palette in real time.

*[Interactive figure: Parameter comparison embed retinting live with the hue slider]*

## Import LaTeX / Notion

The template ships importers to bootstrap an article from existing sources:

-   **LaTeX** - converts sections, math, citations and figures to MDX chapters.
-   **Notion** - pulls a shared page through a Notion integration token, locally or directly on the Space.

Setup details live in the [import chapter](https://tfrere-research-article-template.hf.space/#import-from-latex) of the demo.

## Help & links

-   [Demo article](https://tfrere-research-article-template.hf.space/) - the full reference, written with the template itself.
-   [Editor Space](https://huggingface.co/spaces/tfrere/research-article-template-editor) - look around (read-only for visitors) or duplicate it with HF PRO or a Team organization.
-   [Editor MCP server](https://huggingface.co/spaces/tfrere/research-article-template-editor/blob/main/docs/MCP.md) - connect Claude Code, Cursor or Codex to a live article.
-   [For AI agents](https://tfrere-research-article-template-site.hf.space/docs/agents) - copy-pasteable steps for coding agents (also as [Markdown](https://tfrere-research-article-template-site.hf.space/docs/agents.md)).
-   [GitHub repository](https://github.com/tfrere/research-article-template) - source, issues and discussions.
-   [Report an issue](https://github.com/tfrere/research-article-template/issues) - bugs and feature requests welcome.
-   [Community gallery](https://tfrere-research-article-template-site.hf.space/#showcase) - real articles published with the engine.
-   [llms.txt](https://tfrere-research-article-template-site.hf.space/llms.txt) and [llms-full.txt](https://tfrere-research-article-template-site.hf.space/llms-full.txt) - this site for LLMs: an index and the full docs as Markdown.
