From 788f69efd3d275a935b5061736850e61da2d87e0 Mon Sep 17 00:00:00 2001 From: Gitea OpenCode Agent Date: Thu, 15 Oct 2026 19:07:09 +0000 Subject: [PATCH] Fix issue #79: Implement documentation --- AGENTS.md | 34 +- frontend/app/app.vue | 63 +-- frontend/app/components/views/AppShell.vue | 67 +++ frontend/app/components/views/DocsView.vue | 404 ++++++++++++++++++ .../app/components/windows/MainMenuWindow.vue | 19 + .../01-what-is-dragonroll.md | 45 ++ .../02-your-first-campaign.md | 67 +++ .../01-notes-and-markdown.md | 89 ++++ .../02-characters-and-items.md | 47 ++ .../docs/02-using-dragonroll/03-maps.md | 51 +++ .../01-connecting-a-service.md | 51 +++ .../docs/03-integrations/02-discord.md | 62 +++ .../docs/03-integrations/03-foundry.md | 114 +++++ .../docs/03-integrations/04-obsidian.md | 77 ++++ frontend/app/pages/[...all].vue | 9 + frontend/app/pages/docs/[slug].vue | 8 + frontend/app/pages/docs/index.vue | 7 + frontend/app/pages/index.vue | 7 + frontend/app/services/Docs.js | 114 +++++ frontend/app/services/DocsMarkdown.js | 90 ++++ frontend/i18n/locales/ca/docs.json | 15 + frontend/i18n/locales/ca/main-menu.json | 1 + frontend/i18n/locales/en/docs.json | 15 + frontend/i18n/locales/en/main-menu.json | 1 + frontend/i18n/locales/es/docs.json | 15 + frontend/i18n/locales/es/main-menu.json | 1 + tests/docs.test.js | 328 ++++++++++++++ 27 files changed, 1731 insertions(+), 70 deletions(-) create mode 100644 frontend/app/components/views/AppShell.vue create mode 100644 frontend/app/components/views/DocsView.vue create mode 100644 frontend/app/content/docs/01-getting-started/01-what-is-dragonroll.md create mode 100644 frontend/app/content/docs/01-getting-started/02-your-first-campaign.md create mode 100644 frontend/app/content/docs/02-using-dragonroll/01-notes-and-markdown.md create mode 100644 frontend/app/content/docs/02-using-dragonroll/02-characters-and-items.md create mode 100644 frontend/app/content/docs/02-using-dragonroll/03-maps.md create mode 100644 frontend/app/content/docs/03-integrations/01-connecting-a-service.md create mode 100644 frontend/app/content/docs/03-integrations/02-discord.md create mode 100644 frontend/app/content/docs/03-integrations/03-foundry.md create mode 100644 frontend/app/content/docs/03-integrations/04-obsidian.md create mode 100644 frontend/app/pages/[...all].vue create mode 100644 frontend/app/pages/docs/[slug].vue create mode 100644 frontend/app/pages/docs/index.vue create mode 100644 frontend/app/pages/index.vue create mode 100644 frontend/app/services/Docs.js create mode 100644 frontend/app/services/DocsMarkdown.js create mode 100644 frontend/i18n/locales/ca/docs.json create mode 100644 frontend/i18n/locales/en/docs.json create mode 100644 frontend/i18n/locales/es/docs.json create mode 100644 tests/docs.test.js diff --git a/AGENTS.md b/AGENTS.md index 5b381fae..aef9adb2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,11 +10,11 @@ Free/open-source helper for tabletop RPG campaigns (campaigns, markdown notes, f items, maps, dice widgets, sounds). - `backend/` — Node + **Express 5** + **Mongoose 9** (MongoDB) REST API, JWT auth, CommonJS, entry `src/index.js`. -- `frontend/` — **Nuxt 4 / Vue 3** (` - - diff --git a/frontend/app/components/views/AppShell.vue b/frontend/app/components/views/AppShell.vue new file mode 100644 index 00000000..3fab1115 --- /dev/null +++ b/frontend/app/components/views/AppShell.vue @@ -0,0 +1,67 @@ + + + + + diff --git a/frontend/app/components/views/DocsView.vue b/frontend/app/components/views/DocsView.vue new file mode 100644 index 00000000..5d34cf1d --- /dev/null +++ b/frontend/app/components/views/DocsView.vue @@ -0,0 +1,404 @@ + + + + + diff --git a/frontend/app/components/windows/MainMenuWindow.vue b/frontend/app/components/windows/MainMenuWindow.vue index c338de07..c413f2db 100644 --- a/frontend/app/components/windows/MainMenuWindow.vue +++ b/frontend/app/components/windows/MainMenuWindow.vue @@ -76,6 +76,7 @@ onMounted(() => {
+ {{ $t("main-menu.documentation") }}
@@ -145,6 +146,24 @@ h2, h3 { flex-direction: column; } +/* L'enllaç a la documentació és un `` i els botons estan estilats per element, així + que li toca portar el mateix look. */ +.docs-link { + display: block; + padding: 14px; + border-radius: 6px; + border: solid 1px var(--color-border); + background-color: var(--color-button-background); + color: var(--color-text); + text-align: center; + text-decoration: none; + transition: 300ms background-color; +} + +.docs-link:hover { + background-color: var(--color-button-hover); +} + p { user-select: none; } diff --git a/frontend/app/content/docs/01-getting-started/01-what-is-dragonroll.md b/frontend/app/content/docs/01-getting-started/01-what-is-dragonroll.md new file mode 100644 index 00000000..5907ca30 --- /dev/null +++ b/frontend/app/content/docs/01-getting-started/01-what-is-dragonroll.md @@ -0,0 +1,45 @@ +# What is Dragonroll? + +Dragonroll is a free and open-source helper for tabletop RPG campaigns. It keeps the things a group +carries around a table in one place — the campaign's notes, its characters, its items, its maps — and +lets the tools you already play with read and change them: Discord, Foundry VTT and Obsidian. + +It is not a full virtual tabletop. There is no game loop, no combat tracker and no rule engine: +Dragonroll is the shared memory of a campaign, and the place its characters and items are written +down. + +## What you get + +- **Campaigns.** Every note, character, item and map belongs to one campaign, and each campaign has + its own colour, description and integrations. [Start one](/docs/your-first-campaign). +- **Notes in markdown.** The campaign's text lives in markdown notes, filed into folders that nest as + deep as you need. Notes can hold a [dice widget](/docs/notes-and-markdown) that rolls when you + look at it. +- **Characters and items.** Actors (characters, NPCs and creatures) have a sheet with ability scores, + combat stats, proficiencies, traits, spells and an inventory. Items have a category, a rarity and an + icon. See [characters and items](/docs/characters-and-items). +- **Maps.** Upload a map image with a grid, then pin notes onto the places they belong and stand your + characters on the grid as [tokens](/docs/maps). +- **Integrations.** Consult the campaign from [Discord](/docs/discord), keep a Foundry VTT world and + a campaign [in step](/docs/foundry), and write campaign notes in [Obsidian](/docs/obsidian). + +## How it is put together + +Three pieces work together, and you only ever see the first of them: + +| Piece | What it does | +| --- | --- | +| The web app | What you open: campaigns, notes, characters, items, maps, and the documentation you are reading | +| The API | Stores everything the app shows and answers the integrations' requests | +| The integrations | The Discord bot, the Foundry VTT module and the Obsidian plugin | + +You sign in to the app with one account, and everything you create belongs to you. Integrations never +hold a Dragonroll login: they ask you to authorize them for one campaign, which +[you can take back](/docs/connecting-a-service) at any time. + +## Where to go next + +- New here? [Create your first campaign](/docs/your-first-campaign). +- Writing the campaign down? [Notes and markdown](/docs/notes-and-markdown). +- Playing on a screen? [Maps, pins and tokens](/docs/maps). +- Connecting the tools you use? [Connecting a service](/docs/connecting-a-service). diff --git a/frontend/app/content/docs/01-getting-started/02-your-first-campaign.md b/frontend/app/content/docs/01-getting-started/02-your-first-campaign.md new file mode 100644 index 00000000..57f46c13 --- /dev/null +++ b/frontend/app/content/docs/01-getting-started/02-your-first-campaign.md @@ -0,0 +1,67 @@ +# Your first campaign + +## Signing in + +The very first time you open a Dragonroll server there is no account yet, so the app asks you to +create one: that first account becomes the server's **administrator**, which is the account that can +later create or remove the other accounts. Everyone else is invited to register by whoever runs the +server. + +Sign in with your username or your email and your password. Sessions last 48 hours, after which the +app asks you again. Under your name in the main menu you can change your profile — your name, your +email and the avatar that shows up beside your characters. + +## The main menu + +The main menu is where you pick up where you left off: + +- your campaigns, ready to open, +- **Create campaign** to add one, +- **Settings**, with your own appearance and language, and an *Administration* tab for + administrators to manage the other accounts, +- **Log out**. + +## Creating a campaign + +**Create campaign** asks for three things: a name, a short description and an accent colour. The +colour follows the campaign wherever it shows up, so a group that runs two campaigns can tell them +apart at a glance. Nothing else about a campaign is fixed: you can change the name, description and +colour later in its settings. + +## The campaign workspace + +Opening a campaign replaces the menu with its workspace. + +| Part | What it holds | +| --- | --- | +| Top bar | The campaign's name, the search, **Settings** and **Exit** | +| Sidebar | The campaign's contents, in four sections: **Notes**, **Actors & Characters**, **Items** and **Maps** | +| Note column | The notes you have open, side by side, or the map you have anchored | +| Status bar | What the app is doing: saving, syncing, and errors when something fails | + +The sidebar is the heart of it. Each of its sections lists the entries of that kind, and each entry +can stand in a folder: folders nest, so a campaign can be organised however the group thinks of it. +The sidebar itself collapses to give the notes room when you are showing a screen at the table. + +## Finding things + +The search in the top bar looks through the notes, characters, items and maps of the campaign you are +in, and opens whatever you pick from the results. **Cmd+K** (or **Ctrl+K**) puts the cursor in it. + +## Campaign settings + +**Settings** in the top bar has two tabs: + +- **Basic** — the campaign's name and colour. +- **Integrations** — which external services are connected to this campaign and how to + [connect one](/docs/connecting-a-service), plus the address of the Foundry VTT instance when the + campaign reads icons from a linked world. + +**Exit** leaves the campaign and returns to the main menu. Nothing is lost: the notes you had open and +the campaign you were in are remembered for the next time you open the app. + +## Next + +- Write the campaign down in [notes and markdown](/docs/notes-and-markdown). +- Write its characters and items on [sheets](/docs/characters-and-items). +- Put it on a [map](/docs/maps). diff --git a/frontend/app/content/docs/02-using-dragonroll/01-notes-and-markdown.md b/frontend/app/content/docs/02-using-dragonroll/01-notes-and-markdown.md new file mode 100644 index 00000000..388600a3 --- /dev/null +++ b/frontend/app/content/docs/02-using-dragonroll/01-notes-and-markdown.md @@ -0,0 +1,89 @@ +# Notes and markdown + +Notes are where a campaign is written down: sessions, NPCs, the lore of a city, the ritual the party +found in a dungeon. They are plain markdown, so anything you already know from README files and +Obsidian works as it is. + +## Opening and editing a note + +Clicking a note in the sidebar opens it in the note column, where you can have several open side by +side. A note opens in **display mode**, showing its formatted markdown. Press **Cmd+E** (**Ctrl+E**) +to edit its source, and **Cmd+S** (**Ctrl+S**) to save it; a dot in the note's title bar reminds you +that there is something to save. The cross in the title bar closes the note — it does not delete it. + +## Folders + +The sidebar's sections hold notes in folders, and folders hold folders, so a campaign can be nested as +deep as it needs. Right-clicking gives the commands: + +| Right-click on… | You get | +| --- | --- | +| a note | Open, Rename, a colour, the folder to move it to, Delete | +| a folder | New note in it, Rename, a colour, Delete folder | + +Dragging a note onto a folder moves it there, and dropping it at the bottom of the list takes it back +to the root. Colouring a note or a folder tints its row in the sidebar, which is a quick way to mark +what matters. + +Deleting a folder does not delete your notes: the notes it held move up to its parent folder, its +sub-folders move up with them, and only the empty folders go away. + +## Markdown + +Headings, **bold**, *italic*, lists, quotes, tables, code and links all work: + +```markdown +## The Wreck of the Salt Gull + +- [ ] Burn the manifest +- [x] Ask the harbourmaster + +| Cargo | Worth | +| --- | --- | +| Salted fish | 20 gp | +``` + +Clicking a heading **folds** the section under it — handy when you are reading a long note on a +projector and only want the part you are talking about. Sub-headings fold with their parent. + +## Rolling dice in a note + +A note can hold a dice widget: a button that rolls and shows the result right there, so the book of a +spell does not need a second app next to it. + +Write `@roll` and the expression in square brackets to drop it in the middle of a sentence: + +```markdown +The goblin attacks with @roll[1d20+4]. +``` + +Or in a block of its own, between `@roll` and `@end`, when the roll is worth showing on its own line: + +```markdown +@roll +8d6 +@end +``` + +Either way the widget shows the expression as a button: press it and the dice land, with every die and +the total spelled out. Press it again to roll again. Only the expression itself goes between `@roll` +and `@end` — write the note about the roll next to the widget, not inside it. + +The expression understands: + +| Written | Meaning | +| --- | --- | +| `d20`, `1d20` | one die; the number in front is how many, so `4d6` | +| `d20adv`, `d20dis` | roll twice and keep the higher / the lower | +| `4d6kh1`, `4d6kl1` | keep the highest / lowest one of four (any number after `kh` / `kl`) | +| `+`, `-`, `*`, `/` | arithmetic; `2d6+3`, `1d8/2` | +| `( )` | grouping, as in `(1d8+4)*2` | +| `-3` | a negative number | + +Division rounds down, the way damage does. Spaces between the parts of an expression do not matter, but +a modifier belongs right after the dice: write `4d6kh1`, not `4d6 kh 1`. + +## Next + +- Put the people and things of your notes on [sheets](/docs/characters-and-items). +- Pin a note onto a spot on a [map](/docs/maps). diff --git a/frontend/app/content/docs/02-using-dragonroll/02-characters-and-items.md b/frontend/app/content/docs/02-using-dragonroll/02-characters-and-items.md new file mode 100644 index 00000000..beb906fb --- /dev/null +++ b/frontend/app/content/docs/02-using-dragonroll/02-characters-and-items.md @@ -0,0 +1,47 @@ +# Characters and items + +The **Actors & Characters** and **Items** sections of the sidebar hold the people and things of a +campaign as entries of their own, with a sheet each. They can be written by hand, and they are also +what a linked [Foundry VTT](/docs/foundry) world keeps itself in step with. + +## Actors + +An actor is anyone the campaign can point at: a **Character**, an **NPC** or a **Creature**. Creating +one asks for the few fields that identify it — type, species, class, level, background, and a challenge +rating for the monsters — and the rest is filled in on its sheet. + +Opening an actor opens its **character sheet**, in tabs: + +| Tab | What it holds | +| --- | --- | +| Ability Scores | Strength, Dexterity, Constitution, Intelligence, Wisdom, Charisma, and the proficiency bonus | +| Inventory | What it carries: item, quantity and weight each, with the total carried weight added up | +| Traits | Features, traits and other details, as text | +| Spells | The spells it knows, one per line | + +Combat lives above the tabs: armor class, speed, initiative, current and maximum hit points, and hit +dice. The photo at the top of the sheet is what shows up next to the character everywhere else — +including in [Discord](/docs/discord), where players can read the sheet of the character they hold. + +**Edit** turns the sheet into fields you can change; **Save sheet** writes them back. Characters are +filed in folders like notes are, so a campaign can keep its party, its villains and its bestiary +apart. + +## Items + +An item is anything the campaign names: a weapon, a potion, a piece of treasure. Its sheet holds a +name, a description, a **category** (weapon, armor, shield, adventuring gear, magic item, consumable, +tool, treasure, other), a **rarity** from common to artifact, a weight in pounds, and its properties +("finesse, versatile"). + +The rarity colours the item's row in the sidebar — common white, uncommon green, rare blue, very rare +purple, legendary orange — so what is worth something stands out while you scroll. + +Every item can have an icon. Upload an image, or pick one out of the icon library your linked Foundry +world ships with, browsing its folders one at a time. + +## Characters on the table + +Drag an actor out of the sidebar and drop it on a map and it stands there as a +[token](/docs/maps), sized to the map's grid. Drag a note instead and it is filed into whatever folder +you drop it on. diff --git a/frontend/app/content/docs/02-using-dragonroll/03-maps.md b/frontend/app/content/docs/02-using-dragonroll/03-maps.md new file mode 100644 index 00000000..0ad244c3 --- /dev/null +++ b/frontend/app/content/docs/02-using-dragonroll/03-maps.md @@ -0,0 +1,51 @@ +# Maps, pins and tokens + +A map is a picture of a place — a dungeon floor, a town, a combat encounter — with a grid laid over +it. On top of the picture you can pin the notes that belong to a spot and stand the campaign's +characters on its cells. + +## Creating a map + +**Maps → New map** asks for an image and the grid that goes with it: + +| Setting | What it is | +| --- | --- | +| Map image | A photo or scan of the map. Uploading a new one replaces it, and leaving it empty keeps the current image | +| Grid size (px) | How wide one grid cell is in the image, in image pixels | +| Offset X / Offset Y | Where the grid starts in the image, so the grid can be lined up with the drawing | +| Scale | How much distance one cell stands for, like 5 feet | + +The grid size, offsets and scale are what let the app turn a point on the screen into a cell of the +map, so a token stands where it should and pins stay put when you zoom. + +## Looking at a map + +Clicking a map in the sidebar anchors it in the place the open notes occupy, and **Open in window** +puts it in a window of its own, which you can drag next to the notes. Once a map is on screen: + +- scroll to zoom towards the cursor, or use the zoom buttons and **Fit to window**, +- drag to pan, +- **Show grid** turns the grid overlay on and off. The grid is drawn over the image, so its lines stay + crisp whatever the zoom. + +## Pinning notes + +Right-click anywhere on a map and pick **Pin a note here**, then choose the note: a marker appears on +that spot, and clicking the marker opens the note. A pinned note can be read straight off the map +without hunting for it in the sidebar, which is what makes a town map usable at the table. + +**Remove pin** takes the marker off; the note itself is untouched. Deleting a note that is pinned drops +its pins. + +## Tokens + +Drag an actor from the sidebar onto a map and it stands there as a token: it snaps to the centre of the +cell you dropped it on and is sized by that cell, so a huge creature can be given more than one cell by +sizing it up on the map's settings. + +Once a token is on the map you can drag it to another cell, step it across the grid one cell at a time +with the **arrow keys**, and take it off with **Delete**. Clicking a token opens the sheet of the actor +it stands for. + +Tokens belong to the map, not to the actor: the same character can stand on several maps, and taking a +token off does not remove the character from the campaign. diff --git a/frontend/app/content/docs/03-integrations/01-connecting-a-service.md b/frontend/app/content/docs/03-integrations/01-connecting-a-service.md new file mode 100644 index 00000000..892f5f29 --- /dev/null +++ b/frontend/app/content/docs/03-integrations/01-connecting-a-service.md @@ -0,0 +1,51 @@ +# Connecting a service + +Dragonroll talks to three services: [Discord](/docs/discord), [Foundry VTT](/docs/foundry) and +[Obsidian](/docs/obsidian). They all connect the same way, and none of them is given your Dragonroll +password. + +## How a connection works + +A service asks Dragonroll for a **sign-up link** and shows it to you. You open that link in your +browser, sign in if you are not signed in already, and pick which of your campaigns the service may +use. Only then does the service get its own credential, which lets it read and change that one +campaign and nothing else. + +| You see | What it means | +| --- | --- | +| A link in Discord, in the Foundry module or in the Obsidian plugin | The service is waiting for you to pick a campaign | +| A campaign picker in your browser | Sign in and choose the campaign, and the service is connected | +| "Connected" in the service | It picked up its credential and can start working | + +The link is short-lived — it expires after ten minutes — and can only be used once. If you close it +without choosing, ask the service for a new one. If a service loses the credential it was given, it +asks for a new link too: nothing is kept that would let it back in. + +## What a connection allows + +What a service may do is decided by the campaign you pick, so check the name before you confirm. The +screen tells you which service is asking, and what it wants: + +- a **Discord server** reads the campaign's characters, so whoever is in that server can read them, +- a **Foundry world** keeps its actors and items in step with the campaign, which means it writes into + it, and Dragonroll writes into it, +- **Obsidian** reads the campaign's notes and pushes the ones you tell it to. + +A campaign holds one link per service: linking a second Foundry world, or a second Discord server, +replaces the one it had. Authorizing a service with a different Dragonroll account replaces who the +service answers to. + +## Seeing and undoing a connection + +Open the campaign and look at **Settings → Integrations**. It lists the three services and, for each +one, whether it is connected, what is connected to it, and which Dragonroll account authorized it. + +**Unlink** ends it. The service loses access the next time it asks — nothing it already wrote into the +campaign is deleted, and nothing about your campaign changes. To use the service again, start a new +link from its own side. + +## Next + +- [Discord](/docs/discord) — read characters and campaigns from a server. +- [Foundry VTT](/docs/foundry) — keep a world and a campaign in step. +- [Obsidian](/docs/obsidian) — write campaign notes in your vault. diff --git a/frontend/app/content/docs/03-integrations/02-discord.md b/frontend/app/content/docs/03-integrations/02-discord.md new file mode 100644 index 00000000..17f5b473 --- /dev/null +++ b/frontend/app/content/docs/03-integrations/02-discord.md @@ -0,0 +1,62 @@ +# Discord + +The Dragonroll Discord bot lets a server read the characters of a campaign without anyone leaving +Discord: the roster, a character's sheet with its portrait, and who plays whom. It is a read-only bot — +it never changes your campaign. + +## Connecting a server + +1. Invite the bot to the server with the `bot` and `applications.commands` scopes. +2. A Discord **administrator** runs `/dragonroll connect`. The bot answers with a *Sign in to + Dragonroll* button. +3. Whoever opens it signs in to the Dragonroll account that owns the campaign and picks that campaign. + The server is now linked to it, and the bot says so. +4. From then on anybody in the server can look the campaign's characters up. + +The authorization link lasts ten minutes and works once. A campaign is linked to one Discord server at +a time, and a server to one campaign; authorizing the server with a different Dragonroll account takes +over the connection. + +## Commands + +| Command | Who | What it does | +| --- | --- | --- | +| `/characters [type]` | everybody | Lists the characters of the campaign this server is linked to. `type` narrows the list to **Characters**, **NPCs** or **Creatures**. Every character a player has claimed shows up next to that player. | +| `/character name [public]` | everybody | Shows one actor's sheet: its portrait, description, race, class and level, background, armor class and speed, ability scores, proficiencies, traits, spells and inventory. Start typing a name and Discord offers the campaign's roster. Set `public` to `true` to show the sheet to the whole channel instead of only to you. | +| `/dragonroll connect` | administrators | Asks Dragonroll for the sign-up link that connects this server, and confirms here once somebody has authorized it. | +| `/dragonroll link campaign:` | administrators | Moves this server to another campaign of the connected Dragonroll account. Type part of a name to filter the choices. | +| `/dragonroll unlink` | administrators | Removes this server's campaign link. The campaign is untouched; the commands simply have nothing to read until one is linked again. | +| `/dragonroll status` | everybody | Shows which campaign this server reads, and which character your Discord account holds on it. | +| `/dragonroll refresh` | everybody | Asks Dragonroll again where the connection stands, and shows what it answered. | +| `/dragonroll assign character:` | everybody | Links a character of the campaign to your Discord account, so the bot knows it is yours and `/characters` says so. You can take a character nobody holds; a character somebody else holds can only be moved by an administrator. | +| `/dragonroll unassign [character]` | everybody | Drops a character link. Without the option you give up your own character; naming somebody else's takes it off them, which only an administrator can do. | + +Replies are private: only you see them, so a player can look up their character in a busy channel. The +one exception is `/character` with `public:true`, which posts the sheet where everyone can read it — for +the villain the party is talking to, or the magic item they just found. + +## Characters and their players + +`/dragonroll assign` is how a player says *this one is mine*: + +- each account holds one character, so claiming a second one frees the first, +- a free character can be taken by anybody, +- a character somebody holds can only be taken or freed by a server administrator, +- the pairing shows up in `/characters` and in `/dragonroll status`, which is what lets the table see + who is playing whom. + +Assigning a character does not hide anything: the bot is read-only and every member of the server can +already read the campaign's characters with `/character`. + +## When something goes wrong + +| The bot says | What is going on | +| --- | --- | +| "Connect a Dragonroll account first with /dragonroll connect." | Nobody has authorized this server yet, or the authorization expired before anyone opened it. | +| "Only Discord server administrators can connect Dragonroll or change this campaign link." | The command changes the server's connection, so it needs the Discord Administrator permission. | +| "The bot API secret is missing or does not match the backend." | Whoever runs the bot has to set the same `DRAGONROLL_DISCORD_BOT_SECRET` in the bot and in the Dragonroll backend. | +| "This server does not have a linked campaign." | The link was removed; an administrator has to pick a campaign with `/dragonroll link`. | + +Character portraits are read from Dragonroll's public upload folder, so the bot needs to be able to +reach the server Dragonroll runs on. Whoever hosts the bot finds its setup in `discord-bot/README.md` +in the source repository. diff --git a/frontend/app/content/docs/03-integrations/03-foundry.md b/frontend/app/content/docs/03-integrations/03-foundry.md new file mode 100644 index 00000000..b515bd81 --- /dev/null +++ b/frontend/app/content/docs/03-integrations/03-foundry.md @@ -0,0 +1,114 @@ +# Foundry VTT + +The Foundry integration keeps a Dragonroll campaign and a Foundry world in step: the world's +characters and item directory arrive in the campaign, and what you change in Dragonroll goes back to +the world. + +There are two separate parts, and you only need the first of them: + +| Part | What it is | +| --- | --- | +| The **Dragonroll Foundry API** module | Installed in the world. Links it to a campaign and keeps its actors and items synced. Runs in the game client. | +| The optional **snapshot bridge** | A small process on the Foundry host that publishes a read-only snapshot of the world for Dragonroll to browse. Only for reading world data over the API. | + +Character and item sync works without the bridge. + +## Installing the module + +Foundry VTT v12 to v14. Copy the `dragonroll-foundry` folder into +`{Foundry user data}/Data/modules/dragonroll-foundry/`, restart Foundry, and enable **Dragonroll +Foundry API** in the world's module settings. + +The module's own settings hold two things you set: the **Dragonroll Endpoint** — the address of your +Dragonroll server, `https://dragonroll.aranroig.com` by default — and **Dragonroll Auto-sync**, which +is on. + +## Linking a world + +Open the world with a GM account. The module asks Dragonroll for a sign-up link and prints it in a +notification: open it, sign in, and pick the campaign this world belongs to. **Dragonroll Pairing +Status** in the module settings always says where things stand — waiting for a link, connected to a +named campaign, or why a link could not be used. + +Worth knowing: + +- The link expires after ten minutes and works once. If it goes unused, reload the world to get a new + one. +- A world links to one campaign, and a campaign to one Foundry world: linking a second world replaces + the first. +- The link, the sync token it hands back and the pairing status are all **client** settings: the + browser that completed the link is the one that syncs. Another browser on the same world reads as not + paired until it links too. +- **Dragonroll Pairing Status** is written by the module. It is not a field to fill in. +- The campaign shows the linked world's title and system under **Settings → Integrations**, where + **Unlink** ends the pairing. + +## What syncs + +| In Foundry | In the campaign | +| --- | --- | +| Character, NPC and creature actors | Actors with the same sheet: abilities, combat stats, proficiencies, traits, spells, carried gear, portrait | +| The world's **item directory** (the items tab) | The campaign's item list, with category, rarity, quantity, weight, properties and description | +| The folders grouping that item directory | Item folders with the same names and nesting | +| A folder's colour | The campaign's folder colour — and the other way round, what you colour in Dragonroll lands on the world's folder | + +The item list is the world's item directory and nothing else. The gear a character carries is that +character's inventory: it travels with the character and stays on its sheet, so a sword a fighter owns +does not turn up in the campaign's item list. Spells, classes, subclasses, backgrounds, feats and +species are not gear and are not imported. + +An actor or item keeps the Dragonroll id it was given in a `dragonroll-foundry.actorId` / +`dragonroll-foundry.itemId` flag, and that is what makes the two sides recognise each other. A world +item that carries no flag is matched by name, so a hand-written item in Dragonroll is adopted instead of +doubled, and renaming it in either place does not resurrect a duplicate. + +Changes flow both ways as they happen, and Dragonroll's own edits are applied back in Foundry within a +few seconds. A **full** snapshot — the one taken when the world links, or forced from the actor +directory — is the only thing that prunes: it is the only moment either side can see the whole list and +notice what is gone. Live edits never delete anything. + +## Auto-sync, and sending one actor on purpose + +**Dragonroll Auto-sync** is what keeps the two in step: actors and world items you create, change or +delete are sent to the campaign, and both sides reconcile every few seconds. Turning it off stops all +of it — nothing is sent, and Dragonroll stops rewriting your Foundry documents, so the campaign keeps +whatever it already holds. Turn it back on and both sides reconcile again, including the edits queued +while it was off. + +To send one character across right now, or to cross over while autosync is off, right-click the actor +(or several) in the Foundry actor directory and pick **Dragonroll: Force Sync**. Those actors, with the +gear inside them, are pushed immediately. It only upserts: it never prunes the campaign's other actors. +Actors Dragonroll does not import — anything that is not a character, NPC or creature — are refused with +a notification saying so. + +## Foundry's icons in Dragonroll + +With a world linked, Dragonroll's item icon browser can page through the icon library that world ships +with, one folder at a time. If it says the world has no address, set it under **Settings → Integrations +→ Foundry VTT URL** in the campaign. + +## The optional snapshot bridge + +The bridge is a small Node.js (18 or newer) process that runs beside Foundry. A GM client publishes the +world's actor and item snapshot to it, and Dragonroll reads that snapshot back through its own API, so +a server can ask what a world holds without touching the game. It is read-only, it keeps nothing across +restarts, and character sync does not depend on it. + +It needs its own tokens — separate ones for publishing and for reading — and an origin allow-list for +the Foundry client: + +| Variable | What it is | +| --- | --- | +| `DRAGONROLL_FOUNDRY_PUSH_TOKEN` | The token the Foundry client publishes with; the backend's `FOUNDRY_API_PUSH_TOKEN` must match it | +| `DRAGONROLL_FOUNDRY_READ_TOKEN` | The token reads with; the backend's `FOUNDRY_API_TOKEN` must match it | +| `DRAGONROLL_FOUNDRY_ALLOWED_ORIGINS` | The browser origins allowed to publish, comma separated | +| `DRAGONROLL_FOUNDRY_HOST` / `DRAGONROLL_FOUNDRY_PORT` | Where the bridge listens; `0.0.0.0:8787` by default | +| `DRAGONROLL_FOUNDRY_DATA_PATH` | The Foundry Data directory, which lets the bridge list the core `icons/` library | + +The backend points at it with `FOUNDRY_API_URL` (and `FOUNDRY_API_CLIENT_URL` when the Foundry clients +reach it under a different address than the backend does). Once it is set up, Dragonroll answers +`GET /api/foundry/world`, `/actors`, `/characters`, `/items`, one of each by id, an actor's embedded +items, and `/icons` — all for a signed-in Dragonroll user, and all read-only. + +`dragonroll-foundry/README.md` in the source repository documents the bridge, its routes and its +heartbeat in full. diff --git a/frontend/app/content/docs/03-integrations/04-obsidian.md b/frontend/app/content/docs/03-integrations/04-obsidian.md new file mode 100644 index 00000000..cc798d72 --- /dev/null +++ b/frontend/app/content/docs/03-integrations/04-obsidian.md @@ -0,0 +1,77 @@ +# Obsidian + +The **Dragonroll Sync** plugin moves campaign notes between a Dragonroll campaign and an Obsidian +vault: import the campaign so you can read and write it with your own notes, and push the note you are +working on back to the campaign. + +It is an explicit, you-ask-for-it workflow. Nothing happens in the background, and the plugin never +deletes a note. + +## Installing + +Copy `main.js` and `manifest.json` into your vault: + +```text +/.obsidian/plugins/dragonroll-sync/ +``` + +Then enable **Dragonroll Sync** under Settings → Community plugins. It is plain JavaScript, so there is +nothing to build, and it runs on desktop and mobile alike. + +## Connecting + +Under **Settings → Community plugins → Dragonroll Sync**: + +1. Set the **Dragonroll API URL** — `https://dragonroll.aranroig.com/api` by default, or your own + server, such as `http://localhost:5000/api`. +2. **Sign in** with your Dragonroll username or email and your password. The password is used once to + sign in and is not saved; what the plugin keeps is the session token, in this vault, and it expires + after 48 hours like any other Dragonroll session. +3. Pick the **campaign**. Every import and push works against that campaign. + +## Commands + +Both are in Obsidian's command palette: + +| Command | What it does | +| --- | --- | +| **Import or refresh campaign notes** | Brings every note of the campaign into `Dragonroll//`, folders and nesting included, and updates the ones already there. Imported notes keep their place in the campaign's folder tree. | +| **Push active note to Dragonroll** | Sends the note you are in to the campaign: a new root note if it is not linked yet, or an update of the note it is linked to. | + +## How a note knows where it belongs + +An imported note carries three properties in its frontmatter: + +```yaml +--- +dragonrollId: 665f1c… +dragonrollCampaign: 665f0a… +dragonrollTitle: The Salt Gull +--- +``` + +They are what ties the file to its note in the campaign: they survive renames, and they are stripped +from the markdown the plugin sends back, so they never show up in Dragonroll. Pushing a brand new local +note adds them too, which is how the next push updates the same note instead of creating a copy. + +Renaming the note's title in Dragonroll renames the imported file on the next import; renaming the file +in Obsidian renames the note in Dragonroll on the next push. + +## Your edits are not overwritten + +The plugin remembers how a note looked the last time it was imported or pushed, and uses that as the +baseline: + +| Since the last sync | What the import does | +| --- | --- | +| Only the campaign's copy changed | The local file is updated | +| Only your local file changed | Your file is kept as it is, and reported for you to look at | +| Both changed | Your file is kept as it is, and reported for you to look at | +| Neither changed | Nothing is touched | + +So a note you were rewriting in Obsidian is never quietly replaced: the plugin leaves it alone and tells +you it is waiting. Pushing is the deliberate direction — it writes the active note's current title and +content into Dragonroll. + +A note that is linked to a different campaign cannot be pushed while another campaign is selected: +switch the campaign in the plugin settings first. diff --git a/frontend/app/pages/[...all].vue b/frontend/app/pages/[...all].vue new file mode 100644 index 00000000..2b787b3e --- /dev/null +++ b/frontend/app/pages/[...all].vue @@ -0,0 +1,9 @@ + + + diff --git a/frontend/app/pages/docs/[slug].vue b/frontend/app/pages/docs/[slug].vue new file mode 100644 index 00000000..18942586 --- /dev/null +++ b/frontend/app/pages/docs/[slug].vue @@ -0,0 +1,8 @@ + + + diff --git a/frontend/app/pages/docs/index.vue b/frontend/app/pages/docs/index.vue new file mode 100644 index 00000000..5943b0b7 --- /dev/null +++ b/frontend/app/pages/docs/index.vue @@ -0,0 +1,7 @@ + + + diff --git a/frontend/app/pages/index.vue b/frontend/app/pages/index.vue new file mode 100644 index 00000000..9f8577b2 --- /dev/null +++ b/frontend/app/pages/index.vue @@ -0,0 +1,7 @@ + + + diff --git a/frontend/app/services/Docs.js b/frontend/app/services/Docs.js new file mode 100644 index 00000000..1d9f553c --- /dev/null +++ b/frontend/app/services/Docs.js @@ -0,0 +1,114 @@ +import { Marked } from "marked"; +import { CreateHeadingSlugger, HeadingsFromMarkdown, TitleFromMarkdown } from "./DocsMarkdown"; + +/* +The documentation served at /docs is markdown files under app/content/docs, so writing a page means +adding a file. The layout of a page's path says everything the sidebar needs: + + app/content/docs//-.md + +The folder is the sidebar group and its own number orders the groups, the number in front of the file +orders the pages inside its group, and the rest of the file name is the page's slug (`02-discord.md` +is `/docs/discord`). A page's title is its first heading, and the first page of the first group is +served at `/docs` itself. + +A group's label is looked up under `docs.groups.` in the locale files of +`i18n/locales/en/docs.json` and its siblings, so a new group needs that label in every locale. +*/ +const markdownFiles = import.meta.glob("../content/docs/*/*.md", { query: "?raw", eager: true, import: "default" }); + +const Numbered = /^(\d+)-/; +const WithoutNumber = (name) => name.replace(Numbered, ""); +// A name without a number in front sorts after every numbered one in its folder. +const OrderOf = (name) => { + const numbered = Numbered.exec(name); + return numbered ? Number(numbered[1]) : Number.MAX_SAFE_INTEGER; +}; + +const pages = Object.entries(markdownFiles) + .map(([file, source]) => { + const [folder, filename] = file.split("/").slice(-2); + const markdown = String(source ?? ""); + + return { + group: WithoutNumber(folder), + groupOrder: OrderOf(folder), + slug: WithoutNumber(filename).replace(/\.md$/, ""), + order: OrderOf(filename), + title: TitleFromMarkdown(markdown), + headings: HeadingsFromMarkdown(markdown), + markdown, + }; + }) + .sort((left, right) => + left.groupOrder - right.groupOrder || left.order - right.order || left.slug.localeCompare(right.slug) + ); + +// `/docs` is the first page of the documentation, the rest hang under it by their slug. +function GetDocsHref(slug) { + return pages.length && slug === pages[0].slug ? "/docs" : `/docs/${slug}`; +} + +function GetDocsFirstSlug() { + return pages.length ? pages[0].slug : ""; +} + +// The sidebar: one entry per group folder, in reading order, holding its pages. +function GetDocsNav() { + const nav = []; + + for (const page of pages) { + let group = nav.find((entry) => entry.key === page.group); + if (!group) { + group = { key: page.group, pages: [] }; + nav.push(group); + } + group.pages.push({ slug: page.slug, title: page.title, href: GetDocsHref(page.slug) }); + } + + return nav; +} + +const marked = new Marked(); + +// Every heading gets the anchor the sidebar and the "on this page" list link to. The slugger is +// replaced at the start of a parse so each page numbers its repeated headings on its own: marked +// parses one document at a time and does it synchronously, so no other parse can cut in. +let slugHeadings = CreateHeadingSlugger(); + +marked.use({ + renderer: { + heading({ tokens, depth }) { + const content = this.parser.parseInline(tokens); + return `${content}`; + }, + }, +}); + +function RenderDocsMarkdown(markdown) { + slugHeadings = CreateHeadingSlugger(); + return String(marked.parse(markdown || "")); +} + +// What the /docs page shows: a rendered page with the headings it holds and whichever pages come +// before and after it, or null when nothing is published under that slug. +function GetDocsPage(slug) { + const index = pages.findIndex((page) => page.slug === slug); + if (index === -1) return null; + + const page = pages[index]; + const neighbours = (page) => (page ? { slug: page.slug, title: page.title, href: GetDocsHref(page.slug) } : null); + + return { + slug: page.slug, + group: page.group, + title: page.title, + // The page's own h1 is in the body already; the list is for its sections. + headings: page.headings.filter((heading) => heading.depth > 1 && heading.depth <= 3), + html: RenderDocsMarkdown(page.markdown), + previous: neighbours(pages[index - 1]), + next: neighbours(pages[index + 1]), + }; +} + +export { GetDocsFirstSlug, GetDocsHref, GetDocsNav, GetDocsPage, RenderDocsMarkdown }; diff --git a/frontend/app/services/DocsMarkdown.js b/frontend/app/services/DocsMarkdown.js new file mode 100644 index 00000000..4bb97ffa --- /dev/null +++ b/frontend/app/services/DocsMarkdown.js @@ -0,0 +1,90 @@ +/* +String helpers for the documentation under /docs: the words a heading shows, the anchor it gets, and +the headings the sidebar lists. They import nothing at all, not even marked, because the repository +root installs no dependencies and `tests/docs.test.js` loads this file straight from source. +*/ + +// What marked escapes, back to the character it stands for: an anchor has to be the same whether it +// was written as `'` or arrived as `'`. +const Entities = { + amp: "&", + lt: "<", + gt: ">", + quot: '"', + apos: "'", + nbsp: " ", + "#39": "'", + "#x27": "'", +}; + +function DecodeEntities(value) { + return value.replace(/&(#?[a-z0-9]+);/gi, (entity, body) => (Entities[body.toLowerCase()] ?? "")); +} + +// A heading's anchor is built from its markdown source when the sidebar is built, and from the HTML +// marked has rendered when the page is. This drops everything the two forms disagree on — the tags +// marked adds, the entities it escapes, and the characters markdown uses for emphasis and links — so +// both keep the same words and land on the same anchor. +function HeadingText(value) { + return DecodeEntities( + String(value ?? "") + .replace(/<[^>]*>/g, "") // , , … around the heading's words + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") // a link keeps the label it shows, not its target + .replace(/[*_`~]/g, "") // emphasis + ).trim(); +} + +// Lower case letters, numbers and dashes: what a url fragment and a query selector both accept. +function Slugify(value) { + return HeadingText(value) + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); +} + +// Two headings with the same words cannot share an anchor: the second becomes `words-1`, the third +// `words-2`. The sidebar and the renderer both walk a page's headings in document order, so the +// numbers they hand out are the same. +function CreateHeadingSlugger() { + const seen = new Map(); + + return (value) => { + const base = Slugify(value) || "section"; + const times = seen.get(base) || 0; + seen.set(base, times + 1); + return times === 0 ? base : `${base}-${times}`; + }; +} + +// The headings of a markdown document, in order, each with the anchor its renderer will give it: +// `{ depth: 2, text: "Link a world", slug: "link-a-world" }`. Lines inside a fenced code block are +// skipped — a `# comment` there is shell, not a heading. +function HeadingsFromMarkdown(source) { + const slug = CreateHeadingSlugger(); + const headings = []; + let inFence = false; + + for (const line of String(source ?? "").split(/\r?\n/)) { + if (/^ {0,3}(```|~~~)/.test(line)) { + inFence = !inFence; + continue; + } + if (inFence) continue; + + const heading = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line); + if (!heading) continue; + + const text = HeadingText(heading[2]); + headings.push({ depth: heading[1].length, text, slug: slug(text) }); + } + + return headings; +} + +// A documentation page's title is its first heading. +function TitleFromMarkdown(source) { + const [first] = HeadingsFromMarkdown(source); + return first ? first.text : ""; +} + +export { CreateHeadingSlugger, HeadingsFromMarkdown, HeadingText, Slugify, TitleFromMarkdown }; diff --git a/frontend/i18n/locales/ca/docs.json b/frontend/i18n/locales/ca/docs.json new file mode 100644 index 00000000..37372dfc --- /dev/null +++ b/frontend/i18n/locales/ca/docs.json @@ -0,0 +1,15 @@ +{ + "title": "Documentació", + "contents": "Contingut", + "on-this-page": "En aquesta pàgina", + "open-app": "Obrir Dragonroll", + "previous": "Anterior", + "next": "Següent", + "not-found": "No hi ha cap pàgina de la documentació que es digui «{page}».", + "back-to-docs": "Tornar a la documentació", + "groups": { + "getting-started": "Primers passos", + "using-dragonroll": "Fer servir Dragonroll", + "integrations": "Integracions" + } +} diff --git a/frontend/i18n/locales/ca/main-menu.json b/frontend/i18n/locales/ca/main-menu.json index 47355006..f8eac65b 100644 --- a/frontend/i18n/locales/ca/main-menu.json +++ b/frontend/i18n/locales/ca/main-menu.json @@ -2,6 +2,7 @@ "main-menu": "Menú principal", "edit-profile": "Editar perfil", "create-campaign": "Crear campanya", + "documentation": "Documentació", "log-out": "Tanca la sessió", "settings": "Configuració", "exit": "Sortir" diff --git a/frontend/i18n/locales/en/docs.json b/frontend/i18n/locales/en/docs.json new file mode 100644 index 00000000..f3663a55 --- /dev/null +++ b/frontend/i18n/locales/en/docs.json @@ -0,0 +1,15 @@ +{ + "title": "Documentation", + "contents": "Contents", + "on-this-page": "On this page", + "open-app": "Open Dragonroll", + "previous": "Previous", + "next": "Next", + "not-found": "There is no documentation page called “{page}”.", + "back-to-docs": "Back to the documentation", + "groups": { + "getting-started": "Getting started", + "using-dragonroll": "Using Dragonroll", + "integrations": "Integrations" + } +} diff --git a/frontend/i18n/locales/en/main-menu.json b/frontend/i18n/locales/en/main-menu.json index b1f8c866..63798bdd 100644 --- a/frontend/i18n/locales/en/main-menu.json +++ b/frontend/i18n/locales/en/main-menu.json @@ -2,6 +2,7 @@ "main-menu": "Main menu", "edit-profile": "Edit profile", "create-campaign": "Create Campaign", + "documentation": "Documentation", "log-out": "Log out", "settings": "Settings", "exit": "Exit" diff --git a/frontend/i18n/locales/es/docs.json b/frontend/i18n/locales/es/docs.json new file mode 100644 index 00000000..87bf3f23 --- /dev/null +++ b/frontend/i18n/locales/es/docs.json @@ -0,0 +1,15 @@ +{ + "title": "Documentación", + "contents": "Contenido", + "on-this-page": "En esta página", + "open-app": "Abrir Dragonroll", + "previous": "Anterior", + "next": "Siguiente", + "not-found": "No hay ninguna página de la documentación que se llame «{page}».", + "back-to-docs": "Volver a la documentación", + "groups": { + "getting-started": "Primeros pasos", + "using-dragonroll": "Usar Dragonroll", + "integrations": "Integraciones" + } +} diff --git a/frontend/i18n/locales/es/main-menu.json b/frontend/i18n/locales/es/main-menu.json index 3881bc27..80716fe5 100644 --- a/frontend/i18n/locales/es/main-menu.json +++ b/frontend/i18n/locales/es/main-menu.json @@ -2,6 +2,7 @@ "main-menu": "Menú principal", "edit-profile": "Editar perfil", "create-campaign": "Crear campanya", + "documentation": "Documentación", "log-out": "Cerrar sesión", "settings": "Configuración", "exit": "Salir" diff --git a/tests/docs.test.js b/tests/docs.test.js new file mode 100644 index 00000000..409792df --- /dev/null +++ b/tests/docs.test.js @@ -0,0 +1,328 @@ +// Tests for the documentation under /docs (Syndria98/dragonroll#79): the markdown pages are the +// documentation, so what has to stay right is (1) the pages are well formed — a title, a slug, a +// numbered group, translations for the group's label, and no link pointing at a page that does not +// exist, (2) the page about an integration really documents what that integration offers, which is +// checked against the sources that define it: the slash commands of discord-bot/src/commands.js and +// the commands the Obsidian plugin registers, and (3) the routes: /docs and /docs/ render the +// documentation and every other address still opens the window app. +// +// `frontend/app/services/DocsMarkdown.js` is the pure part of the docs (headings, slugs, titles) and +// is loaded straight from source, the way the other tests load the frontend services; it imports +// nothing, so the repository root's no-dependencies rule holds. `Docs.js` itself is not loaded: it +// reads the markdown through `import.meta.glob`, which only Vite can answer. +// +// Run with `npm test` from the repository root, or `node --test tests/`. + +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const vm = require("node:vm"); + +function readRepoFile(...parts) { + return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8"); +} + +function loadDocsMarkdown() { + const source = readRepoFile("frontend", "app", "services", "DocsMarkdown.js"); + return vm.compileFunction(source.replace("export {", "return {") , [], { + parsingContext: vm.createContext({}), + })(); +} + +const docs = loadDocsMarkdown(); + +// The documentation pages, as the folder layout defines them. +const docsRoot = path.join(__dirname, "..", "frontend", "app", "content", "docs"); +const docPages = fs.readdirSync(docsRoot, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .sort((left, right) => left.name.localeCompare(right.name)) + .flatMap((group) => fs.readdirSync(path.join(docsRoot, group.name)) + .filter((file) => file.endsWith(".md")) + .sort() + .map((file) => ({ + group: group.name.replace(/^\d+-/, ""), + slug: file.replace(/^\d+-/, "").replace(/\.md$/, ""), + markdown: fs.readFileSync(path.join(docsRoot, group.name, file), "utf8"), + })) + ); + +const slugs = new Set(docPages.map((page) => page.slug)); +const groups = [...new Set(docPages.map((page) => page.group))]; + +const pageAbout = (slug) => docPages.find((page) => page.slug === slug); + +// --- The heading helpers the sidebar and the anchors are built from --- + +test("a heading's slug comes out of its words, whatever form they arrive in", () => { + assert.equal(docs.Slugify("Link a world"), "link-a-world"); + assert.equal(docs.Slugify(" Auto-sync, and one actor "), "auto-sync-and-one-actor"); + assert.equal(docs.Slugify("Dragonroll: Force Sync!"), "dragonroll-force-sync"); +}); + +test("the anchor built from a heading's markdown is the one built from its HTML", () => { + // The sidebar slugs the markdown source and the renderer slugs what marked produced, so the two + // have to land on the same anchor for a sidebar link to land on its section. + const pairs = [ + ["**Link** a `world`", "Link a world"], + ["Commands & characters", "Commands & characters"], + ["[Foundry](/docs/foundry) worlds", 'Foundry worlds'], + ["It's here", "It's here"], + ]; + + for (const [markdown, html] of pairs) { + assert.equal(docs.Slugify(markdown), docs.Slugify(html), `slug of ${markdown}`); + } +}); + +test("repeated headings get distinct anchors, in the order they are written", () => { + const slug = docs.CreateHeadingSlugger(); + assert.equal(slug("Setup"), "setup"); + assert.equal(slug("setup"), "setup-1"); + assert.equal(slug("Setup"), "setup-2"); +}); + +test("the headings of a page are listed in order, with their anchors", () => { + const headings = docs.HeadingsFromMarkdown([ + "# Connecting a service", + "", + "## How a connection works", + "text", + "### What it allows", + "```sh", + "# not a heading", + "```", + "## Next", + ].join("\n")); + + // The service is loaded from another realm, so the values are copied out before being compared. + assert.deepEqual( + JSON.parse(JSON.stringify(headings.map(({ depth, text, slug }) => ({ depth, text, slug })))), + [ + { depth: 1, text: "Connecting a service", slug: "connecting-a-service" }, + { depth: 2, text: "How a connection works", slug: "how-a-connection-works" }, + { depth: 3, text: "What it allows", slug: "what-it-allows" }, + { depth: 2, text: "Next", slug: "next" }, + ] + ); +}); + +test("a page takes its title from its first heading", () => { + assert.equal(docs.TitleFromMarkdown("# Your first campaign\n\n## Signing in"), "Your first campaign"); + assert.equal(docs.TitleFromMarkdown("no heading here"), ""); +}); + +// --- The pages themselves --- + +test("the documentation has pages, in numbered groups", () => { + assert.ok(docPages.length >= 5, `expected several documentation pages, found ${docPages.length}`); + + for (const page of docPages) { + const folder = `${page.group}`; + assert.ok(folder.length > 0, `${page.slug} sits in an oddly named folder`); + assert.match(page.slug, /^[a-z0-9]+(-[a-z0-9]+)*$/, `${page.slug} is not a url-friendly slug`); + } +}); + +test("every page has a title, and no two pages share a slug", () => { + const seen = new Set(); + + for (const page of docPages) { + const title = docs.TitleFromMarkdown(page.markdown); + assert.ok(title, `${page.slug} has no heading to title it`); + assert.ok(!seen.has(page.slug), `${page.slug} is published twice`); + seen.add(page.slug); + } + assert.equal(seen.size, docPages.length); +}); + +test("every page has sections, which is what the sidebar lists beside it", () => { + for (const page of docPages) { + const sections = docs.HeadingsFromMarkdown(page.markdown).filter((heading) => heading.depth > 1); + assert.ok(sections.length, `${page.slug} has no section headings to list`); + } +}); + +test("every group has a sidebar label in every locale", () => { + const labels = ["en", "es", "ca"].map((locale) => + JSON.parse(readRepoFile("frontend", "i18n", "locales", locale, "docs.json")) + ); + + assert.ok(labels.every((label) => label.groups), "each docs.json namespace needs a `groups` object"); + + for (const group of groups) { + for (const label of labels) { + const text = label.groups[group]; + assert.ok(text, `the "${group}" group has no label in its docs.json`); + assert.notEqual(text, group, `the "${group}" label is untranslated`); + } + } +}); + +test("the pages only link to pages that are published", () => { + for (const page of docPages) { + for (const link of page.markdown.matchAll(/\]\((\/docs\/?[a-z0-9-]*)\)/g)) { + const target = link[1].replace("/docs/", ""); + if (!target) continue; // /docs itself + assert.ok(slugs.has(target), `${page.slug} links to ${link[1]}, which is not published`); + } + } +}); + +test("the three integrations each have their own page", () => { + for (const slug of ["discord", "foundry", "obsidian"]) { + assert.ok(pageAbout(slug), `${slug} has no documentation page`); + } + assert.ok(pageAbout("connecting-a-service"), "the shared way of connecting a service is undocumented"); +}); + +// --- The integrations pages describe what the integrations actually offer --- + +// discord-bot/src/commands.js builds the slash commands with discord.js, which the repository root +// does not install: the builder is stubbed by one that records the names it is given. +function loadSlashCommands() { + const registered = []; + + class Builder { + constructor() { + this.name = ""; + this.parent = null; + this.children = []; + this.optionNames = []; + } + + setName(name) { this.name = name; return this; } + setDescription() { return this; } + setContexts() { return this; } + setRequired() { return this; } + setMaxLength() { return this; } + setAutocomplete() { return this; } + addChoices() { return this; } + addStringOption(configure) { configure(new Builder()); return this; } + addBooleanOption(configure) { configure(new Builder()); return this; } + addSubcommand(configure) { + const sub = new Builder(); + sub.parent = this; + configure(sub); + this.children.push(sub); + return this; + } + } + + class SlashCommandBuilder extends Builder { + constructor() { + super(); + registered.push(this); + } + } + + const moduleStub = { exports: {} }; + vm.compileFunction(readRepoFile("discord-bot", "src", "commands.js"), ["require", "module", "exports"])( + (id) => { + if (id === "discord.js") return { InteractionContextType: { Guild: 0 }, SlashCommandBuilder }; + throw new Error(`require("${id}") is not stubbed`); + }, + moduleStub, + moduleStub.exports + ); + + const names = []; + for (const command of registered) { + names.push(command.name); + for (const sub of command.children) names.push(`${command.name} ${sub.name}`); + } + return names; +} + +test("the Discord page lists every command the bot declares", () => { + const about = pageAbout("discord"); + const commands = loadSlashCommands(); + + // Sanity check on the stub before it is trusted to list anything. + assert.ok(commands.includes("characters"), `expected the bot's commands, got ${commands.join(", ")}`); + assert.ok(commands.includes("dragonroll connect")); + + for (const command of commands) { + assert.ok( + about.markdown.includes("`/" + command), + `the Discord page does not document /${command}` + ); + } +}); + +// The Obsidian plugin registers each command palette entry with `this.addCommand({ id, name, … })`. +function loadObsidianCommands() { + const source = readRepoFile("obsidian-plugin", "main.js"); + const commands = [...source.matchAll( + /this\.addCommand\(\{\s*id:\s*["']([^"']+)["'],\s*name:\s*["']([^"']+)["']/g + )].map((match) => ({ id: match[1], name: match[2] })); + + // Sanity check on the extraction before it is trusted to list anything. + assert.ok(commands.length >= 2, `expected the plugin's commands, got ${commands.length}`); + + return commands; +} + +test("the Obsidian page lists the commands the plugin registers", () => { + const about = pageAbout("obsidian"); + + for (const command of loadObsidianCommands()) { + assert.ok( + about.markdown.includes(`**${command.name}**`), + `the Obsidian page does not document "${command.name}" (${command.id})` + ); + } +}); + +test("the Foundry page covers what the world and the campaign do with each other", () => { + const about = pageAbout("foundry").markdown; + + for (const topic of ["Auto-sync", "Force Sync", "item directory", "Pairing Status"]) { + assert.ok(about.includes(topic), `the Foundry page never mentions ${topic}`); + } +}); + +// --- The routes --- + +test("the app renders whichever page the address asks for", () => { + const root = readRepoFile("frontend", "app", "app.vue"); + assert.match(root, //, "app.vue has to render the matched page"); + assert.doesNotMatch(root, /CreateWindow/, "the window app boots from AppShell, not from app.vue"); +}); + +test("the documentation has a route of its own, and the app keeps the rest", () => { + const pages = path.join("frontend", "app", "pages"); + const docsRoutes = ["docs/index.vue", "docs/[slug].vue"]; + + for (const route of docsRoutes) { + assert.match( + readRepoFile(pages, route), + //, + `${route} has to render the documentation` + ); + } + + for (const route of ["index.vue", "[...all].vue"]) { + assert.match( + readRepoFile(pages, route), + //, + `${route} has to open the window app` + ); + } + + // The catch-all is what keeps /link/authorize, and every path a service already links to, alive. + const shell = readRepoFile("frontend", "app", "components", "views", "AppShell.vue"); + assert.ok(shell.includes("/link/authorize"), "the service link screen has to stay reachable"); + assert.ok(shell.includes("/discord/authorize"), "the legacy Discord link has to stay reachable"); +}); + +test("the main menu points at the documentation", () => { + const menu = readRepoFile("frontend", "app", "components", "windows", "MainMenuWindow.vue"); + assert.match(menu, /href="\/docs"/, "the main menu has to link to /docs"); + assert.match(menu, /main-menu\.documentation/); + + for (const locale of ["en", "es", "ca"]) { + const strings = JSON.parse(readRepoFile("frontend", "i18n", "locales", locale, "main-menu.json")); + assert.ok(strings.documentation, `${locale} has no label for the documentation link`); + } +});