# ![spFlea logo](https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/spflea.png) spFlea (Static Pages Flea)

A superdupertiny flea size zero config static site generator for static pages.

Start it and go — no configuration, no backend, no build pipeline required.

[![spFlea on npmjs.com](https://img.shields.io/npm/v/spflea?logo=npm&logoColor=white)](https://www.npmjs.com/package/spflea)
[![spFlea on Codeberg](https://img.shields.io/badge/dynamic/json?color=2185D0&logo=codeberg&logoColor=white&label=codeberg&query=%24.version&url=https%3A%2F%2Fcodeberg.org%2Fapi%2Fv1%2Frepos%2Fstefan25376%2Fspflea%2Fraw%2Fpackage.json)](https://codeberg.org/stefan25376/spflea)
[![spFlea on jsDelivr](https://data.jsdelivr.com/v1/package/npm/spflea/badge?style=rounded)](https://www.jsdelivr.com/package/npm/spflea)

---

## Table of contents

- [Introduction](#introduction)
- [Features](#features)
- [Limitations](#limitations)
- [Installation](#installation)
- [CLI options](#cli-options)
- [Project structure (skeleton)](#skeleton)
- [Howto/Step by step instructions](#howto)
  - [Quick start - your first site in 5 minutes](#quick-start)
  - [Conventions at a glance](#conventions)
  1. [Adding assets](#adding-assets)
  2. [Page header and footer](#global-html)
  3. [Providing CSS and JavaScript](#css-javascript)
  4. [Editing pages](#editing-pages)
  5. [Editing blog entries](#editing-blog-entries)
  6. [Linking to pages or blog entries](#editing-linking)
  7. [Using hashtags](#using-hashtags)
  8. [Using emojis](#using-emojis)
  9. [Adding syntax highlighting](#syntax-highlighting)
  10. [Blog pagination and lazy loading](#blog-pagination-lazy-loading)
  11. [Handlebars partials and helpers](#handlebars-partials-helpers)
  12. [BEM classes](#sass-bem)
- [Search](#search)
- [Development](#development)
- [Todos/Work in progress](#todos)
- [Technologies](#technologies)
- [License](#license)

---

## <a name="introduction"></a> Introduction

The purpose of spFlea is to provide the ability to create a static page with a minimum of boilerplate, setup, learning, practice and technically speaking also configuration and code.

All the user needs to know is how to install a node module, create folders and files, write Markdown or HTML, add CSS styling and publish the result to a simple and cheap static page server.

spFlea is a small helper which orchestrates a couple of well known third party libraries (see [Technologies](#technologies)) and combines them with a convention-over-configuration approach. The idea is to have a lot of power in a tiny package with zero configuration. The thought is: start and go.

Of course spFlea can be used with any cheap static hosting service. Even with Github pages. You can take the result in the `docs` folder and upload it anywhere you like (with FTP, SSH, SFTP, WebDAV or any other transfer method) or you can zip the folder content and send it somewhere. With `spflea --build` you can also generate the `docs` folder in a CI pipeline without starting any server.

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** Put your site project (the folder with the `src` and `docs` folders) into a git repository. The generated HTML, CSS and JSON are prettified, so they diff nicely and do not bloat the git history.

---

## <a name="features"></a> Features

- Zero config - **really zero!**
- Everything is done by convention. (See [Convention over configuration](https://en.wikipedia.org/wiki/Convention_over_configuration).)
- Written in [TypeScript](https://www.typescriptlang.org/) (ESM), compiled to `dist/`.
- Provides a blog on the homepage and unlimited nested pages.
- Pages and blog entries can be written in Markdown or - if more sophisticated things like custom CSS or JS are needed - also in HTML.
- The blog is paginated by 10 and numbered JSON files - each containing 10 entries - are provided for lazy loading.
- Blog entries can optionally contain a short version for the list and a long version for the details view.
- Finds hashtags and generates pages which show in which articles a hashtag is used.
- Finds emojis by unicode or GitHub notation (`:smile:`) and replaces them with **locally hosted** images - the used images are copied from the bundled [GitHub emoji collection](https://github.com/olivrichtea/github-emoji) into `docs/assets/emoji/` at build time. No external hotlinks.
- Does syntax highlighting in code blocks.
- Generates a search index in JSON and provides an AJAX and JavaScript based fuzzy search ([Levenshtein distance algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance)) with extended search patterns like `OR`, `AND` and `NOT`. A page or blog entry which becomes accessed by clicking on a search result has the search terms marked in it, so they can be highlighted by CSS. See [Search](#search).
- No login required.
- No backend needed.
- Everything is done on the file level.
- Creates a nice skeleton on the first run.
- Starts up an [express](https://github.com/expressjs/express) webserver (default port 3000).
- Watches on file changes, then rebuilds and reloads the page in the browser (livereload).
- Generates static pages with SEO friendly file names.
- Header, footer, navigation, pagination and blog entries, pages, hashtag pages and search results are generated from [Handlebars](https://handlebarsjs.com/) templates.
- All language specific data of spFlea is in the [Handlebars](https://handlebarsjs.com/) templates.
- Uses [Sass](https://sass-lang.com/) for providing CSS. (In the [Sass](https://sass-lang.com/) file pure CSS can be used, if someone is not familiar with [Sass](https://sass-lang.com/).)
- HTML, CSS and JSON are prettified so they work better with git diffing and do not bloat the git history.
- CSS from [Sass](https://sass-lang.com/) compilation contains autoprefixing for the recent 2 browser generations.
- [BEM](http://getbem.com/introduction/) classes are automatically added to the HTML.
- Resolution of links in the final static pages is done automatically.
- [Handlebars](https://handlebarsjs.com/) partials and helpers can be added (`math` and operators helpers are already provided).
- `--build` mode for CI pipelines: builds `docs/` and exits without starting server, watcher or browser.
- Completely tested with [Vitest](https://vitest.dev/): golden master snapshot tests (byte-identical output), feature tests, invariant/property tests, dev server tests and jsdom tests for the browser search - so future changes happen without unwanted side effects.

---

## <a name="limitations"></a> Limitations

- spFlea is a static site generator, not a CMS. There is no admin interface, no database and no user management.
- Pages and blog entries are single files. If you need thousands of entries or complex data relations, you might want to use a more fully featured generator.
- The dev server is intentionally simple (static file serving + livereload). It is meant for local development, not for production traffic.
- Raw HTML in Markdown is escaped (only `<time datetime>` is allowed through), because pages are rendered from Markdown by default. Write `.html` files if you need full control over the markup.

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/warning.png" alt="Important" width="50" height="60" align="left" /> **IMPORTANT!** Every page and every blog entry needs an `<h1>` headline - files without one are skipped. Blog entries additionally need a `<time datetime="...">` element, which is used for sorting and the URL.

---

## <a name="installation"></a> Installation

spFlea requires [node.js](https://nodejs.org/) >= 22.22.2.

If you wanna use it globally then do the following:

```sh
npm install spflea -g
cd my/static/pages/root/folder/
npx spflea
```

This copies the skeleton into the folder, builds the initial static page into `docs/` and starts the webserver and watcher. Open http://localhost:3000 in your browser (or press any key to open it automatically).

Alternatively, if you are working in a node project anyway, you can install spflea as a local dependency:

```sh
cd my/static/pages/root/folder/
npm install spflea --save
npx spflea
```

---

## <a name="cli-options"></a> CLI options

```
spflea [options]

Options:
  -b, --build              build the static site into ./docs and exit (no server/watcher) — for CI
      --port <n>           web server port (default: 3000)
      --livereload-port <n> livereload port (default: web port + 1)
  -h, --help               show this help
```

| Option | Meaning |
| ------ | ------- |
| `-b`, `--build` | Builds `docs/` once and exits with code 0. No dev server, no watcher, no livereload snippet in the generated HTML. Perfect for CI pipelines and static hosting. |
| `--port <n>` | Port of the dev webserver (default: `3000`). |
| `--livereload-port <n>` | Port of the livereload server (default: web port + 1). |
| `-h`, `--help` | Shows the help. |

Example for a CI pipeline (f.ex. Codeberg Pages / GitHub Pages workflow):

```sh
npx spflea --build
# the static site is now in ./docs — deploy that folder
```

---

## <a name="skeleton"></a> Project structure (skeleton)

On the first run, the skeleton becomes copied into the `./src` folder and the vendor script `handlebars.runtime.min.js` becomes copied from the installed dependency into `./src/assets/js/` (see `skeleton.json`). The `didyoumean.js` search bundle is already part of the skeleton (built from didyoumean2 with rollup at package build time, see [Development](#development)). The initial structure of the folder looks like this:

```
+ src
  + assets
    + js
      - scripts.js
      - search.js
      - handlebars.runtime.min.js
      - didyoumean.js
  + blog
    - 2022-03-17-first-post.md
    - 2022-03-18-second-post.html
  + global
    - footer.hbs
    - header.hbs
  + handlebars
    + helpers
      - math.js
      - operators.js
    + partials
      - navigation.hbs
      - pagination.hbs
  + pages
    + 03-projects
      - index.md
    - 01-about.md
    - 02-contact.html
  + scss
    - styles.scss
  - assets.json
  - blog.hbs
  - hashtag.hbs
  - page.hbs
  - search.hbs
  - search-results.hbs
+ docs            <- the generated static site goes here
```

This is not a lot of boilerplate!

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/warning.png" alt="Important" width="50" height="60" align="left" /> **IMPORTANT!** Be aware of the fact, that there is no styling at all in the skeleton. If you look at the initial data in the browser it is totally unstyled. Add your styles in `src/scss/styles.scss`.

---

## <a name="howto"></a> Howto/Step by step instructions

### <a name="quick-start"></a> Quick start - your first site in 5 minutes

1. Install spFlea and create an empty project folder:

   ```sh
   npm install spflea -g
   mkdir my-site && cd my-site
   npx spflea
   ```

2. On the first run spFlea copies the skeleton into `./src` (all your content lives there from now on), copies the two vendor scripts (`handlebars.runtime.min.js`, `didyoumean.js`) into `./src/assets/js/`, builds the site into `./docs` and starts the dev server. Open http://localhost:3000 in your browser (or press any key in the terminal to open it automatically).
3. You now see the blog homepage (intentionally unstyled - add your styles in `src/scss/styles.scss`). Every page and blog entry you add shows up automatically.
4. Try it: open `src/pages/01-about.md`, change the text, save the file. The watcher rebuilds and the browser reloads by itself. Then open http://localhost:3000/about.html.
5. Add a new page: create `src/pages/03-projects.md` with `# My projects` as the first line and some text below. Save - http://localhost:3000/my-projects.html now exists and "My projects" appears in the navigation.
6. Publish: upload the `docs/` folder to any static hoster (GitHub Pages, Codeberg Pages, Netlify, your own webspace via FTP/SCP/...). In a CI pipeline run `npx spflea --build` instead - it builds `docs/` and exits without starting a server.

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** Put the project folder into a git repository. Commit `src/` (your content) and let the generated `docs/` be committed as well (or build it in CI) - the generated HTML, CSS and JSON are prettified, so the diffs stay small and readable. Add `node_modules/` to your `.gitignore`.

### <a name="conventions"></a> Conventions at a glance

spFlea works by convention over configuration: **your folder and file structure is your website**. You never write a config file - you just create folders and files:

| You create in `src/` | spFlea generates in `docs/` | Navigation shows |
| -------------------- | --------------------------- | ---------------- |
| `pages/01-about.md` containing `# About` | `about.html` | "About" |
| `pages/02-contact.html` containing `<h1>Contact</h1>` | `contact.html` | "Contact" |
| `pages/03-projects/index.md` containing `# Projects` | `projects.html` | "Projects" |
| `pages/03-projects/01-web.md` containing `# Web` | `projects-web.html` | "Web", nested below "Projects" |
| `blog/2022-03-17-first-post.md` (see [blog entries](#editing-blog-entries)) | `2022-03-17-12-00-first-post.html` | in the blog list on the homepage and in the "latest" sidebar |

The rules behind this:

- **Number prefixes** (`01-`, `02-`, `03-...`) in file and folder names only control the **sort order** in the navigation. They are stripped and never shown or linked.
- The **first `<h1>` headline** of a file becomes the page title: it is used as the navigation label, in the `<title>` tag and - slugified - as the file name (`# About` becomes `about.html`, `# My projects` becomes `my-projects.html`).
- **Subfolders become nested pages**: the folder name is prepended to the URL (`pages/04-deep/nested-page.md` with `# Nested Page` becomes `deep-nested-page.html`, nested below "Deep" in the navigation).
- A folder **without** an `index.md`/`index.html` gets an auto-generated placeholder page ("Index missing in /..."), so the navigation never contains dead links.
- A file **without** an `<h1>` headline is skipped completely.
- A **blog entry** additionally needs a `<time datetime="...">` element - it is used for sorting and for the URL (see [blog entries](#editing-blog-entries)).

### <a name="adding-assets"></a> 1. Adding assets

Everything you put into `src/assets/` is copied as-is into `docs/assets/` - images, fonts, downloads, ... Reference them with absolute paths from your templates or content:

```html
<img src="/assets/img/my-logo.svg" alt="My logo" />
```

Additionally you can map **any file from your project** into the assets folder with `src/assets.json` - useful for files that live outside `src/` (f.ex. a PDF in a `downloads/` folder):

```json
{
    "./my-logo.svg": "img/my-logo.svg",
    "./downloads/my-cv.pdf": "downloads/my-cv.pdf"
}
```

The keys are paths relative to your project root, the values are paths below `docs/assets/`. Changes to `assets.json` are picked up on rebuild and the newly mapped files are watched as well.

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** The two vendor scripts `handlebars.runtime.min.js` and `didyoumean.js` are copied into `src/assets/js/` automatically on the first run (see `skeleton.json`) - do not edit or delete them, the search page needs them.

### <a name="global-html"></a> 2. Page header and footer

`src/global/header.hbs` and `src/global/footer.hbs` are Handlebars templates which wrap **every** generated page - they contain the `<!DOCTYPE html>`, the whole `<head>`, the opening `<body>` and the closing `</html>`. Put your header markup, the search form and the navigation there. The skeleton's header already shows how:

```hbs
<form class="search-form" action="/search.html" method="GET">
    <input class="search-form__q" type="text" name="q" value="" />
    <input class="search-form__submit" type="submit" value="Search" />
</form>
{{#if navigation.pages.nested}}
    <nav class="navigation">
        {{> navigation pages=navigation.pages.nested level=1}}
    </nav>
{{/if}}
```

Available data in every page: `navigation.pages` (the page tree, nested and flattened), `navigation.blog` (the latest blog entries) and `navigation.hashtags`, plus page specific data like `titles` (the headline path of the current page), `entry`/`entries` (blog) or `occurences` (hashtag pages).

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** All labels and texts of the generated site live in these Handlebars templates - if you want your site in another language or with your own wording, just edit the templates. The operator helpers (`if`, `eq`, `gt`, ...) are available everywhere (see [partials and helpers](#handlebars-partials-helpers)).

### <a name="css-javascript"></a> 3. Providing CSS and JavaScript

- **CSS**: write Sass in `src/scss/styles.scss` (plain CSS works too, if you are not familiar with Sass). It is compiled, autoprefixed for the last 2 browser generations and written to `docs/assets/css/styles.css`:

  ```scss
  .navigation__list__item__link {
      color: rebeccapurple;

      &:hover {
          text-decoration: underline;
      }
  }
  ```

- **JavaScript**: put your scripts into `src/assets/js/` - they are copied to `docs/assets/js/` and you reference them from `footer.hbs` with a `<script>` tag. The skeleton ships an empty `scripts.js` (your own code goes here) plus the `search.js` for the search page.

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** BEM classes are added automatically to all generated HTML (see [BEM classes](#sass-bem)), so you can style the generated content - headlines, paragraphs, lists, links, blog entries, search results - without touching any template.

### <a name="editing-pages"></a> 4. Editing pages

Create Markdown (`.md`) or HTML (`.html`) files in `src/pages/` - subfolders are allowed and become nested pages. This folder structure:

```
src/pages/
  01-about.md            ->  docs/about.html          nav: "About"
  02-contact.html        ->  docs/contact.html        nav: "Contact"
  03-projects/
    index.md             ->  docs/projects.html       nav: "Projects"
    01-web.md            ->  docs/projects-web.html   nav: "Web" (nested below "Projects")
```

A page file is as simple as it gets - the first `<h1>` is the title, everything below it is the content:

```md
# About

Hello, I am Jane and this is my **static site** built with spFlea.
I like #coding and :smile: emojis.
```

What happens to such a file:

- `.md` files are rendered as Markdown. Raw HTML inside Markdown is escaped (only `<time datetime>` is allowed through), because pages are rendered from Markdown by default - write `.html` files if you need full control over the markup.
- The `<h1>` text becomes the title, the navigation label and the URL slug: `# About` becomes `about.html`, `# My projects` becomes `my-projects.html`. Nested pages are joined with a dash: `# Nested Page` inside `04-deep/` becomes `deep-nested-page.html`.
- Number prefixes (`01-`, `02-`, ...) in the file or folder names only control the **order** in the navigation - they are stripped from labels and URLs.
- A folder without an `index.md`/`index.html` gets a generated placeholder page ("Index missing in /..."), so no dead navigation links occur.
- A file without an `<h1>` headline is skipped completely.

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** Umlauts and other non-ASCII characters in titles are stripped from the URL slug (f.ex. `Über uns` becomes `-ber-uns.html`). Use ASCII titles if you want clean URLs.

### <a name="editing-blog-entries"></a> 5. Editing blog entries

Create files in `src/blog/`. A blog entry is a Markdown or HTML file with an `<h1>` headline and a `<time datetime="YYYY-MM-DD hh:mm">` element:

```md
# My first post

## <time datetime="2022-03-17 12:00">March 17th 2022</time>

This is the **short teaser** shown in the blog list.

# The long version

Everything from the second `<h1>` on is only shown on the detail page of the entry.
```

- Entries are sorted by datetime **descending** (newest first) and the URL is built from datetime + title: the file above becomes `/2022-03-17-12-00-my-first-post.html`.
- The date in the **file name** is only a convention for your own overview in the folder - sorting and URL come from the `<time datetime>` inside the file.
- The human readable date (`March 17th 2022`) is used as `subtitle` in the blog list and in the "latest" sidebar.
- If an entry contains **two** `<h1>` headlines, the part before the second headline becomes the short teaser for the blog list and the part from the second headline on becomes the detail page. With a single `<h1>`, the whole entry is shown in both places.
- The homepage `index.html` is the blog list, paginated by 10 entries (see [pagination](#blog-pagination-lazy-loading)).

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** Use the two-`<h1>` trick for long reads: readers see the teaser in the blog list and can click through to the full text - no separate page files needed.

### <a name="editing-linking"></a> 6. Linking to pages or blog entries

Write normal links with the **source paths** in your Markdown - they are resolved automatically in the generated pages:

```md
See the [about page](/pages/01-about) or [post 02](/blog/2022-01-02-post-02.md).
```

This becomes `/about.html` and `/2022-01-02-12-00-post-02.html` in the output. External links (`https://...`) automatically get `target="_blank" rel="noopener"`.

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** Always link using the source path (f.ex. `/pages/01-about`), never a generated file name - if you rename a headline later, the generated URL changes and hardcoded links would break.

### <a name="using-hashtags"></a> 7. Using hashtags

Just write `#hashtag` in your content - in pages and blog entries alike:

```md
I like #coding and #photography.
```

- The hashtag is automatically linkified and a page `hashtag-<slug>.html` is generated which lists all pages and blog entries where the hashtag occurs (with occurrence counts, paginated by 20: `hashtag-coding.html`, `hashtag-coding-2.html`, ...).
- Hashtags also show up in the sidebar navigation with their counts.

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** Hashtags are a zero-effort tagging system: write `#project` in every project-related entry and readers get a filterable overview page for free.

### <a name="using-emojis"></a> 8. Using emojis

Write emojis either as unicode character (😄) or in GitHub notation (`:smile:`) - both work in pages and blog entries:

```md
Have a nice day :smile:
```

At build time the matching image from the bundled [GitHub emoji collection](https://github.com/olivrichtea/github-emoji) (npm package `github-emoji`) is copied into `docs/assets/emoji/` and the emoji is replaced with a local `<img class="image--emoji">` tag. Only the images actually used are copied - no external requests, no hotlinking.

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** The `:names:` are the GitHub emoji shortcodes (see the collection in the `github-emoji` npm package). Style the images with `.image--emoji { height: 1em; vertical-align: -0.1em; }` in your Sass so they behave like inline text.

### <a name="syntax-highlighting"></a> 9. Adding syntax highlighting

Use fenced code blocks with a language in Markdown:

````md
```js
const answer = 42;
console.log(answer);
```
````

Code blocks are highlighted with [highlight.js](https://highlightjs.org/) at build time - the `hljs` and language classes are added to the `<code>` element. Add a highlight.js theme or your own `.hljs` styles to `src/scss/styles.scss`.

### <a name="blog-pagination-lazy-loading"></a> 10. Blog pagination and lazy loading

The blog list on the homepage is paginated by 10 entries per page: `index.html` (entries 1-10), `blog-2.html` (entries 11-20), and so on. The pagination links are rendered from the `pagination` partial (see `blog.hbs`).

Additionally numbered JSON chunks (`blog-lazy-loading-1.json`, `blog-lazy-loading-2.json`, ... - 10 entries each) are generated. Every chunk contains the rendered HTML of its entries, so you can lazy load older entries with AJAX in your own `scripts.js`:

```js
const response = await fetch('/blog-lazy-loading-2.json');
const chunk = await response.json(); // { currentPage, entriesPerPage, totalEntries, totalPages, entries: [{ title, url, html, ... }] }
document.getElementById('blog').insertAdjacentHTML('beforeend', chunk.entries.map((e) => e.html).join(''));
```

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** The JSON chunks are also handy for a client side search or for building an archive page - the data is all static.

### <a name="handlebars-partials-helpers"></a> 11. Handlebars partials and helpers

- **Partials**: every `.hbs` file in `src/handlebars/partials/` is registered by its file name and can be used with `{{> navigation ...}}`. The skeleton ships `navigation.hbs` and `pagination.hbs`, which are used in `global/header.hbs` and `blog.hbs`. Add your own partials the same way - drop a `.hbs` file into the folder and use it.
- **Helpers**: every `.js` file in `src/handlebars/helpers/` is loaded at build time with the Handlebars instance (CommonJS style). The raw source of all helpers is also inlined into the search page, so they work in the browser as well. The `math` and `operators` (`eq`, `ne`, `lt`, `gt`, `lte`, `gte`, `and`, `or`) helpers are already provided, plus `getIndex` for pagination links.

Example - your own helper `src/handlebars/helpers/shout.js`:

```js
module.exports = function(Handlebars) {
    Handlebars.registerHelper('shout', function(text) {
        return String(text).toUpperCase();
    });
};
```

Then use it in any template: `{{shout "hello"}}` renders `HELLO`.

### <a name="sass-bem"></a> 12. BEM classes

[BEM](http://getbem.com/introduction/) classes are automatically added to the generated HTML, so you can style all generated content with BEM selectors in your Sass without touching the templates:

| HTML element | generated classes |
| ------------ | ----------------- |
| `<h1>` ... `<h6>` | `headline headline--level1` ... `headline--level6` |
| `<p>` | `paragraph` |
| `<a>` | `link` (hashtag links additionally `link--hashtag`) |
| `<ul>` / `<ol>` | `list list--unordered` / `list list--ordered` |
| `<li>` | `list__item` |
| `<img>` | `image` (emojis additionally `image--emoji`) |
| `<b>` / `<strong>`, `<i>` / `<em>` | `bold`, `italic` |
| `<blockquote>`, `<code>`, `<pre>`, `<hr>`, `<time>` | `blockquote`, `code`, `preformatted`, `line`, `time` (+ `time--datetime`) |

Example in `src/scss/styles.scss`:

```scss
.headline--level1 {
    font-size: 2rem;
}

.paragraph {
    line-height: 1.6;
}

.link {
    color: rebeccapurple;
}
```

---

## <a name="search"></a> Search

spFlea generates a static search index (`docs/search.json`) at build time and the search page (`docs/search.html`) loads it with AJAX and searches it in the browser with [didyoumean2](https://github.com/foray1010/didyoumean2) (fuzzy matching via [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance)) - no backend needed.

**How the algorithm works:** the index has the shape `{ b: [...blog entries...], p: [...pages...], t: { term: { c: totalCount, b: { docIndex: count }, p: { docIndex: count } } }, c: totalDocCount }`. The query in the `q` parameter is split on whitespace into terms; a leading `+` puts a term into the AND set, a leading `-` into the NOT set, everything else into the OR set, and surrounding quotes (`"foo"`) switch a term to literal (non-fuzzy) matching. The result base set is built from the OR terms (fuzzy-matched against all index terms plus substring matches); if there are no OR terms, the AND terms form the base (so `+foo` behaves exactly like `foo`); if there are only NOT terms, the base is every document (so `-foo` lists all documents that do not contain `foo`). The AND and NOT sets then filter that base set across all content types (blog entries and pages alike): a document must contain every AND term and no NOT term. If any AND term has zero hits overall, the result is empty. Results are sorted by hit count (descending), blog entries before pages on ties. The same patterns with examples are also listed on the search page itself (`src/search.hbs`).

Query syntax in the `q` parameter (case-insensitive, fuzzy by default - `fooo` also finds `foo`):

| Pattern | Meaning | Example result |
| ------- | ------- | -------------- |
| `foo` | all documents containing `foo` | every page and post with "foo" |
| `foo bar` | OR - documents containing `foo` or `bar` | union of both result sets |
| `foo +bar` | AND - only documents containing `foo` and `bar` | documents with both terms |
| `+foo` | same as `foo` (a leading `+` on a single term is equivalent) | every page and post with "foo" |
| `+foo +bar` | only documents containing both terms | intersection of both terms |
| `foo -bar` | documents containing `foo` but not `bar` | "foo" results without "bar" documents |
| `-foo` | all documents that do NOT contain `foo` | every page and post without "foo" |
| `"foo"` | literal match only - disables fuzzy matching | only documents with the exact term "foo" |

Examples: `post`, `post +lorem`, `post -lorem`, `+post`, `-post`, `pst` (fuzzy matches `post`), `"pst"` (literal - finds nothing, because there is no exact term "pst").

Search terms are words of 3+ letters, unicode-aware (umlauts like `straße` are indexed correctly). Terms containing other characters (e.g. `foo!` or `123`) are ignored; an empty query shows no results. Clicking a search result adds an `m` query parameter to the target URL and the terms get marked with `<span class="search-mark">` in the text, so you can highlight them with CSS.

> <img src="https://codeberg.org/stefan25376/spflea/raw/branch/main/assets/info.png" alt="Advice" width="50" height="60" align="left" /> **ADVICE!** Phrases like `"foo bar"` are not supported - a quoted multi-word string matches nothing. Use single-word terms and combine them with spaces (OR), `+` (AND) and `-` (NOT) instead. The full semantics (including the pure-AND and pure-NOT edge cases above) are pinned by tests in `test/search.cases.test.ts`.

---

## <a name="development"></a> Development

Development happens in this repository:

- Clone this repository.
- Install node.js (>= 22.22.2) if necessary.
- Run `npm install`.
- `npm run build` - compiles the TypeScript sources from `src/` into `dist/` and rebuilds the minified didyoumean2 browser bundle into `skeleton/assets/js/didyoumean.js` (`scripts/build-vendor.mjs`, rollup + terser). If you update `didyoumean2`, the bundle changes too - `test/vendor.test.ts` fails until you rebuild and commit it.
- `npm test` - builds (`pretest`) and runs the Vitest test suite: golden master snapshot tests (the generated `docs/` output must stay byte-identical to the approved snapshot in `test/golden/docs/`), feature tests, invariant tests, dev server tests and jsdom tests for the browser search. Approved deviations from the snapshot are listed in `test/approved-deviations.md` and `test/golden.deviations.json`.
- `npm run golden` - regenerates the golden snapshot with the current implementation (only do this when an output change is intended and approved).
- `npm run test:watch` - runs the tests in watch mode.

The source is organized as:

```
+ src
  - cli.ts            CLI entry (parseArgs: --build, --port, --livereload-port, --help)
  - Spflea.ts         orchestrator: skeleton kickstart, build, dev server, watcher
  - config.ts         tunables (pagination sizes, default ports, package paths)
  - util.ts           file helpers, glob, url slugs, ConcurrentQueue
  - log.ts            logging
  + core
    - Builder.ts      the build pipeline (pages, blog, hashtags, search index, assets, CSS)
    - Navigation.ts   nested/flattened navigation
    - Renderer.ts     Handlebars setup, writeFile, livereload/generator injection
    - model.ts        types
  + pipeline          dom, markdown, hashtags, searchIndex, bem, highlight, emojis, links
  + server            DevServer (express), Watcher (chokidar), LiveReload (ws)
+ test                Vitest suite, fixture site, golden snapshot
```

---

## <a name="todos"></a> Todos/Work in progress

- Examples with [Disqus](https://disqus.com/) integration (and similar services) into the blog.

---

## <a name="technologies"></a> Technologies

- [markdown-it](https://github.com/markdown-it/markdown-it) - Markdown to HTML conversion
- [sanitize-html](https://github.com/apostrophecms/sanitize-html) - escaping of raw HTML in Markdown (only `<time datetime>` is allowed)
- [jsdom](https://github.com/jsdom/jsdom) - HTML parsing and DOM manipulation at build time
- [handlebars](https://github.com/handlebars-lang/handlebars.js/) - templating
- [highlight.js](https://github.com/highlightjs/highlight.js/) - syntax highlighting for code blocks
- [linkify-html](https://github.com/soapbox/linkify-html) + [linkifyjs](https://github.com/nfrasser/linkifyjs) - hashtag linkification
- [express](https://github.com/expressjs/express) - serving webpages with a minimum of boilerplate (dev server)
- [chokidar](https://github.com/paulmillr/chokidar) - watching for changes in the file system
- [ws](https://github.com/websockets/ws) - tiny livereload server (reloads the browser after rebuilds)
- [sass](https://github.com/sass/sass) - modularizing and nesting CSS
- [postcss](https://github.com/postcss/postcss) + [autoprefixer](https://github.com/postcss/autoprefixer) - autoprefixing the compiled CSS
- [didyoumean2](https://github.com/foray1010/didyoumean2) - fuzzy matching with the [Levenshtein distance algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance) in the browser search (bundled to a minified IIFE via [rollup](https://rollupjs.org/) at package build time)
- [prettier](https://github.com/prettier/prettier) - prettifying HTML, CSS and JSON so it works better with git diffing
- [github-emoji](https://github.com/olivrichtea/github-emoji) - the GitHub emoji image collection, copied locally at build time (self-hosted emojis)
- [glob](https://github.com/isaacs/node-glob) - finding pages, blog entries, helpers and partials
- [fs-extra](https://github.com/jprichardson/node-fs-extra) - file system helpers
- [typescript](https://www.typescriptlang.org/) + [vitest](https://vitest.dev/) - language and test runner for development

Feel free to check the `package.json`, if you want to take a further look into the used technologies.

---

## <a name="license"></a> License

This software is brought to you with :heart: **love** :heart: from Dortmund and offered and distributed under the ISC license. See `LICENSE.txt` and [Wikipedia](https://en.wikipedia.org/wiki/ISC_license) for more information.
