Metadata-Version: 2.4
Name: dj-spellbook
Version: 0.1.0
Summary: Render spellbook syntax on Django templates and create custom Spellblocks. Turn complex HTML into simple Markdown anyone can edit.
License-Expression: AGPL-3.0-only
Project-URL: Repository, https://git.stormdevelopments.ca/official-public/dj-spellbook
Keywords: django,markdown,spellbook,spellblocks
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Text Processing :: Markup :: Markdown
Classifier: Typing :: Typed
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: django>=5.2
Requires-Dist: spellbook-engine<0.2,>=0.1.1
Requires-Dist: markdown-it-py>=4.0
Provides-Extra: dev
Requires-Dist: ruff==0.17.6; extra == "dev"
Requires-Dist: mypy<3.0,>=1.13; extra == "dev"
Dynamic: license-file

<img src="https://git.stormdevelopments.ca/official-public/dj-spellbook/raw/branch/main/icon.svg" alt="" width="96" align="right">

# dj-spellbook

[![CI](https://git.stormdevelopments.ca/official-public/dj-spellbook/actions/workflows/test.yml/badge.svg)](https://git.stormdevelopments.ca/official-public/dj-spellbook/actions)
[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](https://git.stormdevelopments.ca/official-public/dj-spellbook/src/branch/main/LICENSE)
![64 tests](https://img.shields.io/badge/tests-64-blue.svg)
![7 source files](https://img.shields.io/badge/source_files-7-blue.svg)
![3 dependencies](https://img.shields.io/badge/dependencies-3-blue.svg)

Renders markdown that contains SpellBlocks into HTML, inside a Django project.
A SpellBlock is a named block an author writes in the markdown. A Django
template renders it. The markdown around it renders as CommonMark,
with one change: a new line inside a paragraph is a line break.

```markdown
## Before you deploy

{~ alert type="warning" ~}
Take a backup **first**.
{~~}
```

```python
from dj_spellbook import spellbook_render

html = spellbook_render(document)
```

```html
<h2>Before you deploy</h2>
<aside class="spell-callout spell-callout--warning">
<div class="spell-callout-body">
<p>Take a backup <strong>first</strong>.</p>
</div>
</aside>
```

`html` is a `SafeString`, so a template prints it with `{{ html }}` and no
`|safe`.

## Install

```text
pip install dj-spellbook
```

Python 3.12 or newer, Django 5.2 or newer. It depends on Django,
[spellbook-engine](https://git.stormdevelopments.ca/official-public/spellbook-engine),
which decides where each block starts and ends, and markdown-it-py. The
engine's wheel is built for Linux x86-64. Anywhere else pip builds it from
source and needs a Rust toolchain.

Add `"dj_spellbook"` to `INSTALLED_APPS`. That gives you the three built-in
blocks and their stylesheet, and finds the blocks your own apps define.

## The syntax

A block with a body opens with its name and closes alone on a line. A block
with no body closes itself. Arguments are `key="value"` pairs and bare flags.
`.name` adds a class and `#name` sets the id.

```markdown
{~ card title="Pricing" footer="Billed monthly in CAD" .wide #pricing ~}
One block, one price.
{~~}

{~ accordion title="Why a block?" open ~}
So the words and the markup stay apart.
{~~}

{~ alert type="info" /~}
```

A block with a body cannot sit inside another block. A block that closes
itself can. The full grammar is the engine's
[SPEC.md](https://git.stormdevelopments.ca/official-public/spellbook-engine/src/branch/main/SPEC.md).

## Writing a SpellBlock

A SpellBlock is a class and a template. Put the class in a `spellblocks.py` in
any installed app. It is found at startup, with no setting and no URL config. A
`spellblocks.py` that fails to import stops startup with its error.

```python
from dj_spellbook import BasicSpellBlock, SpellBlockRegistry


@SpellBlockRegistry.register()
class StepsBlock(BasicSpellBlock):
    name = "steps"
    arguments = ("here",)
    template = "myapp/steps.html"

    def vet(self):
        if not self.kwargs.get("here", "1").isdigit():
            raise ValueError("`here` is a step number")

    def get_context(self):
        here = self.kwargs.get("here", "")
        items = [line[2:] for line in self.content.splitlines() if line.startswith("- ")]
        steps = [{"n": f"{n:02d}", "text": text, "here": here == str(n)} for n, text in enumerate(items, 1)]
        return {"steps": steps}
```

`myapp/templates/myapp/steps.html`:

```django
<ol class="steps">{% for s in steps %}<li class="step{% if s.here %} step--here{% endif %}"><span class="step-n">{{ s.n }}</span>{{ s.text }}</li>{% endfor %}</ol>
```

```markdown
{~ steps here="3" ~}
- Tested locally
- Tested on staging
- The alpha
- Customer nodes
{~~}
```

```html
<ol class="steps"><li class="step"><span class="step-n">01</span>Tested locally</li><li class="step"><span class="step-n">02</span>Tested on staging</li><li class="step step--here"><span class="step-n">03</span>The alpha</li><li class="step"><span class="step-n">04</span>Customer nodes</li></ol>
```

What a block has to work with:

- `name` is what the author types. Two blocks cannot share one.
- `arguments` lists the arguments the block accepts, and it refuses any other.
  A block that lists none accepts anything. `.class` and `#id` are always
  accepted.
- `self.content` is the body exactly as written, blocks inside it unrendered,
  or `None` for a block that closes itself.
- `self.kwargs` holds every argument as a string: a pair under its key, a flag
  under its own name (`open` gives `"open"`), the classes joined by spaces
  under `class`, and the id under `id`.
- `process_content()` returns the body rendered to HTML, blocks inside it
  included.
- `get_context()` returns what the template gets. By default that is
  `content`, the rendered body, plus every key of `self.kwargs`.
- `vet()` refuses a bad value by raising `ValueError`. It runs before any
  template does. By default it accepts everything.

## The built-ins

| Block | Arguments | Renders |
|-------|-----------|---------|
| `alert` | `type`: `info` (the default), `warning`, `success` or `danger` | `<aside>` |
| `card` | `title`, `footer`, each printed only when given | `<article>` |
| `accordion` | `title`, and the flag `open` to start it open | `<details>` |

Their class names are stable, so your own CSS can hang off them:

- `spell-callout`, `spell-callout--info`, `spell-callout--warning`,
  `spell-callout--success`, `spell-callout--danger`, `spell-callout-body`
- `spell-card`, `spell-card-head`, `spell-card-body`, `spell-card-foot`
- `spell-accordion`, `spell-accordion-summary`, `spell-accordion-body`

An author's `.class` names are added after the built-in class, and `#id`
becomes the element's `id`.

## The stylesheet

One small file styles the three built-ins and nothing else.

```django
{% load static %}
<link rel="stylesheet" href="{% static 'dj_spellbook/spellbook.css' %}">
```

It reads these variables: `--spell-radius`, `--spell-gap`, `--spell-border`,
`--spell-surface`, `--spell-info`, `--spell-warning`, `--spell-success`,
`--spell-danger`. Set them, or override the rules, in your own CSS loaded after
it. Or leave the file out: a block you write yourself carries your own classes
and your own CSS, and needs nothing from this one.

## Refusals and the check

A wrong document is refused, never partly rendered. `spellbook_render` raises
`SpellbookRefusal`, a `ValueError` with `line`, `column` and `reason`. It is
raised for what the engine's syntax refuses, a block name nothing registered,
an argument a block does not list, and a value a block's `vet()` refuses. Only
a syntax refusal names a column.

`spellbook_check` returns every refusal a document would get, and renders
nothing. Run it where a document is saved or imported. A document that passes
the check is never refused at render.

```markdown
{~ steps here="three" ~}
- Plan
{~~}

{~ nosuch /~}
```

```python
from dj_spellbook import spellbook_check

for refusal in spellbook_check(document):
    print(refusal)
```

```text
line 1: `steps`: `here` is a step number
line 5: no SpellBlock is named `nosuch`
```

## Trust

Raw HTML in a document passes through unchanged. A document is trusted: it is
written by your own people. Never render a stranger's markdown with this.
Values an author passes to a block reach its template as ordinary context, and
Django escapes them as it escapes any other.

## Next

The generator: a folder of markdown files becomes pages, with views and URLs.
It is not built yet. Today dj-spellbook takes one document and returns HTML.

## Licence

AGPL-3.0. Maintained by [Storm Developments](https://stormdevelopments.ca).
