Creating a theme

Note

You need version 1.4.0 or newer.

There are various ways to create a theme. A theme can be written in CommonJS (with require() statements) or as an ES module (with import statements). It can also be written in TypeScript of course, but it would have to be built to ESM/CommonJS first.

Then there is also the question where to place the theme. The main options are directly linking to the path, which is great for a one-time use theme (if it's just for your personal site, for example), or by creating it for use as a module, which can eventually be published to npm. We'll go over both ways!

Creating the basics

In the same place

First, we'll need to create a directory where we want to put our theme. For this example, we'll use a layout like the following:

.
├── theme/
│   └── theme.ume.js
├── content/
│   └── index.md
├── index.js
└── package.json

The contents of theme/theme.ume.js isn't important right now, we'll create the contents for it later.

Assuming you already know to set up a webserver with umejs, as can be found inside the quick start guide for example, we'll need our ume config to look something like the following:

const ume = require('@dantenl/umejs');

ume({
    themes: ['./theme/theme.ume.js']

    contentDir: path.join(__dirname, 'content')
});

This will load your theme to umejs from this directory. A setup is great for decluttering your work environment if your theme is large. However, it's not great for publishing it later and/or reusing it easily.

As a local package

For this, we can create a new project somewhere else entirely. We'll be creating it as an npm module, allowing you to use it elsewhere with greater ease. You'll also be able to publish it.

First, you should create a new directory and run npm init -y. This will create a package.json. You should then create the main endpoint that umejs will run. You could call this something like theme.ume.js. This will give you a file structure like this:

.
└── projects/
    ├── my-ume-theme/
    │   ├── package.json
    │   └── theme.ume.js
    └── my-ume-site/
        ├── content/
        │   └── index.md
        ├── package.json
        └── index.js

Next, you'll need to make some modifications to your package.json. Please make sure you have the key main pointing to your theme.ume.js file. This is crucial for your theme to work! (if you're feeling fancy, the exports key would work as well, but the best would be a combination of the two!). Also make sure you have a memorable name set. You'll be needing that.

Once you've done that, run npm link in your theme directory. This will make it available elsewhere on your device. Then, go back to your site directory and run npm link <theme name>. You've now linked the two together and you can use your theme inside your site! Inside your site's index.js ume config object, you can then import your theme easily:

const ume = require('@dantenl/umejs');

ume({
    themes: ['<theme name>']

    contentDir: path.join(__dirname, 'content')
});

Designing your theme

Well, now that you've got your entry point layed out in theory, we'll also need to make your theme actually work! It requires a bit of code writing to define it to umejs, but it essentially boils down to a slightly more complicated JSON.

When writing a CommonJS module, you'll want your theme.ume.js to look something like this:

// theme.ume.js
const themeConfig = {
    name: 'example-theme',
};

module.exports = themeConfig;

If you're writing with ECMAScript, please ensure that you've got type set to module in your package.json. Writing the module isn't that much more complicated:

// theme.ume.js
const themeConfig = {
    name: 'example-theme',
};

export default themeConfig;

Congrats! That's all you need for a theme. Granted, it doesn't do anything, but it technically is a theme!

What is there to be customised?

Quite a lot, actually! For example, here's the manifest for a theme that is currently being worked on. What each key does, can be found below.

{
    name: 'umejs-red-maple',
    // simplified format to semver; what version can be used for umejs
    uneVersion: '^1.4.0',
    // the theme's version
    version: '0.0.1',

    entryTemplate: 'layout.ume.html',
    templatesDir: path.join(__dirname, 'templates'),
    partialsDir: path.join(__dirname, 'partials'),
    assetsDir: path.join(__dirname, 'assets'),


    // define default styles for the user
    config: {
        siteTitle: 'umejs-red-maple',
        colors: {
            light: {
                primary: '#f1414d;',
                accent: '#e95d67;',
            },
            dark: {
                primary: '#be0e1a',
                accent: '#a2161f',
            },
        },
    },

    // register the builder
    builders: [pageBuilder],

    helpers: {
        // helper to show the current year
        year: () => new Date().getFullYear(),
        themeStyles: {
            helper: (slug, config) => {
                // load the custom user defined theme overrides
                const colors = config.colors || {};
                let css = '<style>';
                let hasColors = false;

                // override light-mode specifics
                if (colors.light) {
                    hasColors = true;
                    css += ':root[data-theme="light"] {';
                    for (const [key, value] of Object.entries(colors.light)) {
                        css += `--${key}: ${value};`;
                    }
                    css += '}';
                }

                // override dark mode specifics
                if (colors.dark) {
                    hasColors = true;
                    css += ':root[data-theme="dark"] {';
                    for (const [key, value] of Object.entries(colors.dark)) {
                        css += `--${key}: ${value};`;
                    }
                    css += '}';
                }

                css += '</style>';
                return hasColors ? css : '';
            },
            // cache this, as it's unlikely to change
            cache: true,
        },
        // load the content on the top bar, if the user has any
        // this shows links to other pages in, well, the top bar
        topbarContent: {
            helper: (slug, config) => {
                if (!config.topbarLinks) return '';

                let topbarLinksHTML = '';

                config.topbarLinks.forEach((linkObject) => {
                    topbarLinksHTML += `<a href="${linkObject.link}">${linkObject.title}</a>`;
                });
                return topbarLinksHTML;
            },
            cache: true,
        },
    },

    // seperate api thing for more advanced control
    setup(api) {
        // cache config for builder
        themeConfig = api.config;

        // get the contentDir from the _ume namespace inside the config
        const contentDir = api.config._ume?.contentDir;

        if (contentDir && fs.existsSync(contentDir)) {
            const { sidebarTree, searchIndex, metaCache } = buildTree(contentDir);

            api.registerHelper('sidebarMenu', () => renderSidebar(sidebarTree));
            api.registerHelper('searchIndexJson', () => JSON.stringify(searchIndex));

            // store metadata for the builder
            pageMetadata = metaCache;
        }
    }
}

name

The name of your theme. As of version 1.4.0, this is not really used.

version

The current version of your theme. As of version 1.4.0, this is not really used much.

umeVersion

The compatibility with umejs. It's a simplified format to semver; the thing npm uses. Here's a table illustrating the possible operations. It ignores checking build numbers and pre-release tags.

This key is optional. If it's not included, all versions will be allowed.

Symbol Rule Example
* / (none) Any version allowed *: all versions
^ Allows changes that do not modify the left most digit ^1.4.0: 1.4.1, 1.5.6 NOT: 1.3.0, 2.0.0
~ Allows changes to right most digit only ~1.4.0: 1.4.1 NOT: 1.3.0, 1.5.6, 2.0.0
>= Anything greater or equal to digit >=1.4.0: 1.4.1, 1.5.6, 2.0.0 NOT: 1.3.0

entryTemplate

But that's a very boring theme. Let's make have an actual design! Similarly to regular umejs projects, themes can define a templatePath via the form of the entryTemplate key. You don't have to this at all though! Themes can be more than just show you some pretty pages, they might do stuff like adding highlight.js code highlighting to your page, or they might minify all your code files. In such cases, there's no need for an entryTemplate.

The entry template shows where umejs where to put the Markdown. If umejs can't find one, it can't load the website. If multiple entryTemplates are defined, the first theme in the themes array wins, as long as the user doesn't have their own template defined.

Here's a very simple example of an entryTemplate:

<!-- templates/layout.ume.html -->
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>My umejs theme</title>
    </head>
    <body>
        {_BODY}
    </body>
</html>

You can use any variables, partials and helpers that you'd be able to use in a regular templatePath template.

Here's how we'd define it in our themeConfig object we defined earlier:

// theme.ume.js

// for commonjs:
const path = require('path');
// for esm:
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));

// ---

const themeConfig = {
    entryTemplate = path.join(__dirname, 'templates', 'layout.ume.html'),

    name: 'example-theme',
};

/* ...export */

Here's our themes' current folder structure:

.
└── theme/
    ├── templates/
    │   └── layout.ume.html
    ├── theme.ume.js
    └── (package.json)

package.json is between brackets () because your projects may not include it, if it's in the same place as the rest of your site.

extends

If your theme requires another theme to function, you can add this here. This will ensure that your theme is run after any other themes that it requires. Meaning, you can overwrite just the files, helpers and builders you need to overwrite. Or simply add some extra features on top of it. The extends key works the same way as the themes key in the config:

const themeConfig = {
    extends: ["@example/umejs-base-theme"]
    name: 'example-theme',
};

setup(api)

Allows you to more dynamically register helpers, builders, includes and parsers. It also allows you to resolve partials and templates.

Other options

The rest of the keys mirror the ume configuration exactly. Any key available there is also available for themes, in the same capacity, with some exceptions. The following keys are unavailable to themes:

  • contentDir
  • themes (if you require another theme, use the extends key)
  • cachePath
  • parallel
  • mode
  • quiet
  • verbose
  • notFoundPath
  • nextUsage