FotobogenDocumentation

Writing a module

A module is a small folder of plain JavaScript that changes how photographs look. There is nothing to compile, no package to publish, and no admin code to write. This page takes you from an empty folder to a working, tested module.

What you are making

A module is a folder with two files:

data/modules/sepia/
├── module.json     what the module is called
└── index.mjs       what settings it has, and what it does to a picture

It contributes one or more transforms. A transform takes a photograph, and a few settings, and returns a changed photograph. Fotobogen does the rest:

The whole of the image library sharp is available to you, without installing or importing anything.

What a module cannot do

And two things it must not do, though nothing stops it: read or write files, and use the network. A module runs inside the server with the server's permissions.

Step 1: start one

You need a copy of Fotobogen's source with its packages installed (how). From that folder:

pnpm fotobogen module new my-module

This writes data/modules/my-module/ with a module.json and an index.mjs holding one working transform with three settings. It is a real module: you can test and install it as it is, then change it.

The name is lowercase letters, digits, and hyphens, starting with a letter, up to 40 characters. It becomes the folder's name and the module's.

You can also make the folder and the two files by hand. The command only saves typing.

Step 2: module.json

{
  "name": "sepia",
  "version": "1.0.0",
  "label": "Sepia",
  "description": "A warm brown tone.",
  "entry": "index.mjs"
}
FieldRequiredRules
nameYesLowercase letters, digits, and hyphens, starting with a letter; 40 characters at most. It must be the folder's name exactly.
versionYesAny text that is not empty. 1.0.0 is the convention. Shown in the admin.
labelYesThe name people see in the admin.
descriptionNoA sentence shown under the label.
entryYesThe file name of your code: a .mjs or .js file in the same folder.

Step 3: the code file

The entry file exports one object, with a list of transforms:

// data/modules/sepia/index.mjs
export default {
  transforms: [
    {
      id: 'tone',
      label: 'Sepia tone',
      description: 'Black and white, tinted warm.',
      params: {
        warmth: { type: 'range', label: 'Warmth', min: 0, max: 100, step: 5, default: 60 },
        fade: { type: 'boolean', label: 'Faded blacks', default: false },
      },
      apply(image, params) {
        const amount = params.warmth / 100
        let toned = image.removeAlpha().tint({ r: 128 + 40 * amount, g: 128 - 6 * amount, b: 128 - 60 * amount })
        if (params.fade) toned = toned.linear(0.9, 20)
        return toned
      },
    },
  ],
}

That is a complete module. Each transform has:

FieldRequiredRules
idYesLowercase letters, digits, and hyphens, starting with a letter. Unique within the module. Do not change it later: photos remember the transform by this id.
labelYesWhat people see in the admin.
descriptionNoA sentence about what it does.
paramsNoThe settings, by name. Leave it out for a transform with none.
applyYesThe function that changes the picture.

A module can hold several transforms: add more objects to the list. Each appears separately in the admin.

Step 4: settings

Each setting has a name (letters and digits, starting with a letter) and one of four types. Every type takes an optional label; without one, the name is shown.

range: a slider

warmth: { type: 'range', label: 'Warmth', min: 0, max: 100, step: 5, default: 60 }

select: a menu

colour: { type: 'select', label: 'Colour', options: ['white', 'black'], default: 'white' }

boolean: a checkbox

fade: { type: 'boolean', label: 'Faded blacks', default: false }

text: a one-line text field

words: { type: 'text', label: 'Your name', default: '', maxLength: 60 }

Step 5: the apply function

apply(image, params, context)
ArgumentWhat it is
imageThe photograph, as a sharp pipeline. It is already the right way up, in sRGB, 8 bits a channel, and at most 2560 pixels on its long side when yours is the first step. A step before yours may have changed its size.
paramsYour settings, by name, already checked.
context.width, context.heightThe size of image, in pixels.
context.sharpThe sharp function itself, for making a new picture from a buffer: an SVG you have written, or raw pixels. You need it only if you build something around or over the photo.

Return a sharp pipeline, or a promise of one (so apply may be async). The result may be a different size from what came in. Do not call .toFile(); Fotobogen writes the files.

Four rules

  1. Work in proportions, not pixels. The same settings are run on a 240-pixel preview and on a 2560-pixel copy. A border of "6 percent of the shorter side" looks the same on both; a border of "40 pixels" does not. Use context.width and context.height.
  2. The same input must give the same output. Never use Math.random() or the time. If you need randomness (grain, specks, a ragged edge), make it from a seed built from the photo's size and your settings, as in the example below. Otherwise the picture changes each time it is rendered, and the preview does not match the result.
  3. Do not rely on the order you call sharp's methods in. Within one pipeline, sharp applies its operations in its own fixed order, whatever order you wrote them. If step two must come after step one, finish step one into pixels and start a new pipeline from them. Example below.
  4. Do nothing but change the picture. No files, no network, nothing kept between calls.

Worked examples

Each of these is a complete index.mjs that has been run through module test. Give each its own folder and module.json.

Adjusting the photo

The sepia module above is this kind: it calls sharp's methods on image and returns the result. Anything in sharp's colour and operation pages works the same way: modulate, tint, linear, recomb, greyscale, blur, sharpen, gamma, negate.

Making the picture larger: a border

Draw a bigger picture as an SVG, open it with context.sharp, and lay the photo on top.

export default {
  transforms: [
    {
      id: 'plain',
      label: 'Plain border',
      description: 'A white or black border, like a print with a margin.',
      params: {
        colour: { type: 'select', label: 'Colour', options: ['white', 'black'], default: 'white' },
        width: { type: 'range', label: 'Width (percent of the shorter side)', min: 1, max: 20, step: 1, default: 6 },
      },
      async apply(image, params, { width, height, sharp }) {
        // A share of the photo's size, so it looks the same on a small copy and a large one.
        const border = Math.max(1, Math.round(Math.min(width, height) * params.width / 100))
        const canvasWidth = width + border * 2
        const canvasHeight = height + border * 2
        const fill = params.colour === 'black' ? '#000000' : '#ffffff'
        // A new, larger picture: a filled rectangle, drawn as SVG.
        const canvas = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${canvasWidth}" height="${canvasHeight}"><rect width="100%" height="100%" fill="${fill}"/></svg>`)
        // The photo as it stands, to be laid on top.
        const photo = await image.png().toBuffer()
        return sharp(canvas).composite([{ input: photo, left: border, top: border }])
      },
    },
  ],
}

Because colour is a select and comes first, the strip under each photo in the admin shows the white and the black border side by side.

Laying something over the photo: darker corners

Draw an SVG the same size as the photo, mostly transparent, and composite it on top. This one needs no await and no context.sharp.

export default {
  transforms: [
    {
      id: 'corners',
      label: 'Darker corners',
      params: {
        strength: { type: 'range', label: 'Strength', min: 0, max: 100, step: 5, default: 40 },
      },
      apply(image, params, { width, height }) {
        if (params.strength === 0) return image
        // A picture the same size as the photo: clear in the middle, dark at the edges.
        const overlay = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">
          <defs><radialGradient id="v" cx="50%" cy="50%" r="75%">
            <stop offset="55%" stop-color="#000" stop-opacity="0"/>
            <stop offset="100%" stop-color="#000" stop-opacity="${params.strength / 100}"/>
          </radialGradient></defs>
          <rect width="100%" height="100%" fill="url(#v)"/></svg>`)
        return image.composite([{ input: overlay, blend: 'over' }])
      },
    },
  ],
}

Randomness that repeats: specks of dust

A small generator that gives the same numbers for the same seed, and a seed made from the photo's size and the setting.

/** A small repeatable random-number generator: the same seed always gives the same numbers. */
function randomFrom(seed) {
  let state = seed >>> 0
  return () => {
    state = (state + 0x6d2b79f5) >>> 0
    let t = state
    t = Math.imul(t ^ (t >>> 15), t | 1)
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296
  }
}

export default {
  transforms: [
    {
      id: 'specks',
      label: 'Specks',
      params: {
        amount: { type: 'range', label: 'How many', min: 0, max: 200, step: 10, default: 60 },
      },
      apply(image, params, { width, height }) {
        // Seeded from the photo's size and the setting, never from the clock,
        // so the same photo always gets the same specks.
        const random = randomFrom(width * 73856093 ^ height * 19349663 ^ params.amount * 83492791)
        const size = Math.max(1, Math.min(width, height) / 400)
        let specks = ''
        for (let i = 0; i < params.amount; i++) {
          specks += `<circle cx="${(random() * width).toFixed(1)}" cy="${(random() * height).toFixed(1)}" r="${(size * (0.5 + random())).toFixed(2)}" fill="#fff" opacity="${(0.3 + random() * 0.5).toFixed(2)}"/>`
        }
        const overlay = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">${specks}</svg>`)
        return image.composite([{ input: overlay }])
      },
    },
  ],
}

The seed includes the size on purpose: the preview and the full-size copy get different specks, each in proportion, and each the same every time.

Two steps in a fixed order

To be sure the toning happens before the border is added, finish the toning into raw pixels, then begin again from those pixels.

export default {
  transforms: [
    {
      id: 'toned-print',
      label: 'Toned print',
      params: {
        border: { type: 'range', label: 'Border (percent)', min: 0, max: 15, step: 1, default: 5 },
      },
      async apply(image, params, { width, height, sharp }) {
        // Step one: tone. Finish it, as raw pixels, before going on.
        const { data, info } = await image.removeAlpha().greyscale().linear(1.15, -12).raw().toBuffer({ resolveWithObject: true })
        // Step two starts from those pixels, so it happens after step one, whatever sharp's own order is.
        const toned = sharp(data, { raw: { width: info.width, height: info.height, channels: info.channels } })
        const border = Math.round(Math.min(width, height) * params.border / 100)
        return border === 0 ? toned : toned.extend({ top: border, bottom: border, left: border, right: border, background: '#ffffff' })
      },
    },
  ],
}

Step 6: test it

pnpm fotobogen module test my-module

This loads the module exactly as the server would and runs every transform with its default settings, at a large size (2560 pixels) and a small one (240), twice each. For each it prints a line:

  ok   module.json: "Border", version 1.0.0
  ok   index.mjs: 1 transform (plain)
  ok   plain at 2560 px: 1296 x 896
  ok   plain at 2560 px: the same result twice
  ok   plain at 240 px: 260 x 180
  ok   plain at 240 px: the same result twice

Look at the results:
  module-test/border-plain-2560.webp
  module-test/border-plain-240.webp

The module works. Copy its folder into data/modules/ on a site and restart to install it.

The sizes printed are of the result. The built-in test picture is 1200 by 800 and is never enlarged, so the "2560" run of a border module shows 1296 by 896: the picture plus its border.

The test uses default settings only. Try the ends of your sliders in the admin, with its live preview, before you call it done.

Step 7: install it and switch it on

  1. Copy the folder into data/modules/ on the site, so that you have data/modules/<name>/module.json. (If you made it with module new in the same copy of Fotobogen, it is already there.)
  2. Restart Fotobogen.
  3. Open Admin, Modules. Your module is listed, switched off. Switch it on.
  4. Set it for all photos on that page, or for one photo on its page in the Library, where the strip of previews shows it.

Nothing is rebuilt. The controls appear because the admin reads your declarations from the server when the page loads.

Changing a module that is already installed

Removing one

Switch it off, delete its folder, and restart. Photos that used it go back to how they would look without it.

How yours works with the others

When something goes wrong

A module that cannot be loaded never stops the site. It is listed under Admin, Modules with the reason, and the same line is in the server's log. module test prints it too.

MessageWhat to fix
The folder is called "x" but module.json names the module "y". They must match.Rename the folder, or change name.
module.json must be a JSON object. / Parameter "x" must be an object. / Each transform must be an object. / Transform "x": "params" must be an object.Something that should be written in braces, { … }, is a list, a string, or a number.
module.json needs a "name" of lowercase letters, digits, and hyphens.No capitals, spaces, or underscores; start with a letter.
module.json needs a "version". / a "label".Add the missing field.
module.json needs an "entry": the file name of a .mjs or .js file in the module folder.Name your code file, and keep it in the same folder.
The entry file index.mjs must be a file in the module's folder, not a link.The file named by entry is a link to somewhere else. Put the file itself in the folder.
The entry file index.mjs is missing.The file named by entry is not there.
The module must export { transforms: [...] } with at least one transform.Use export default { transforms: [ … ] }.
Each transform needs an "id" of lowercase letters, digits, and hyphens.Add or correct id.
Two transforms share the id "x".Give each its own.
Transform "x" needs a "label". / an "apply" function.Add it.
Transform "x": parameter names are letters and digits, starting with a letter.No hyphens or underscores in a setting's name: edgeWidth, not edge-width.
Range parameter "x" needs numeric min, max, and default, with min below max.All three as numbers, not text.
Select parameter "x" needs a list of text options and a default that is one of them.The default must appear in options, spelt the same.
Boolean parameter "x" needs a true or false default.true or false, without quotation marks.
Text parameter "x" needs a text default (it may be empty).Use default: ''.
Parameter "x" has an unknown type. Use "range", "select", "boolean", or "text".One of those four, spelt exactly.
The "x" transform produced a picture that is too large.The result was over 40 megapixels. Make the border or the enlargement smaller.

If apply throws while a photo is being made, that photo is marked failed with the error, in the Library, and can be tried again once the module is fixed or switched off. Other photos are not affected.

Before you share it

Read the ones that come with Fotobogen

The three bundled modules are written to be read, with comments on every part:

A module is trusted code, like a WordPress plugin: whoever installs yours is trusting it with their server. Keep it small enough to read in one sitting, and say plainly what it does.

Back: Modules Next: Questions