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 admin draws the controls from the settings you declare: a slider, a menu, a checkbox, or a text field for each. You write no interface code.
- The server checks every value before your code sees it, so your code can trust its inputs.
- Your transform is run once for every photo that uses it, in the background, on a working copy at most 2560 pixels on its long side; every size shown on the site is then made from the result. It is also run on small previews in the admin.
- The uploaded file is never touched. Every copy is made from the original plus the list of transforms, so switching yours off always gets the photo back exactly.
The whole of the image library sharp is available to you, without installing or importing anything.
What a module cannot do
- Add screens, pages, or its own kind of control to the admin.
- Read or change a photo's title, description, or other details.
- Change the uploaded file.
- Produce a picture larger than 40 megapixels.
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"
}
| Field | Required | Rules |
|---|---|---|
name | Yes | Lowercase letters, digits, and hyphens, starting with a letter; 40 characters at most. It must be the folder's name exactly. |
version | Yes | Any text that is not empty. 1.0.0 is the convention. Shown in the admin. |
label | Yes | The name people see in the admin. |
description | No | A sentence shown under the label. |
entry | Yes | The 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:
| Field | Required | Rules |
|---|---|---|
id | Yes | Lowercase letters, digits, and hyphens, starting with a letter. Unique within the module. Do not change it later: photos remember the transform by this id. |
label | Yes | What people see in the admin. |
description | No | A sentence about what it does. |
params | No | The settings, by name. Leave it out for a transform with none. |
apply | Yes | The 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 }
min,max, anddefaultare required numbers, withminbelowmax.stepis optional.- Your code receives a number between
minandmax. A value outside is pulled to the nearest end; anything that is not a number becomes the default.
select: a menu
colour: { type: 'select', label: 'Colour', options: ['white', 'black'], default: 'white' }
optionsis a list of texts;defaultmust be one of them.- Your code receives exactly one of the options. Anything else becomes the default.
- Put a
selectfirst if it defines the look. Under each photo in the admin is a strip of small previews. If a transform's first setting is aselect, the strip shows one preview for every option, side by side. That is how the film looks appear there.
boolean: a checkbox
fade: { type: 'boolean', label: 'Faded blacks', default: false }
- Your code receives
trueorfalse.
text: a one-line text field
words: { type: 'text', label: 'Your name', default: '', maxLength: 60 }
defaultis required and may be empty.maxLengthis optional: 80 unless you say, and never more than 200.- Your code receives a text of at most that length, with line breaks and control characters replaced by spaces.
- Drawing text is your job, and the server has no fonts you can rely on. A font named in an SVG may not exist on the server. The bundled watermark draws its letters as dots for exactly this reason; read
modules/watermark/index.mjsbefore attempting text. - If you put the text into an SVG, escape
&,<, and>first.
Step 5: the apply function
apply(image, params, context)
| Argument | What it is |
|---|---|
image | The 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. |
params | Your settings, by name, already checked. |
context.width, context.height | The size of image, in pixels. |
context.sharp | The 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
- 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.widthandcontext.height. - 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. - 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.
- 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.
- Look at the pictures. They are written to
./module-test. Compare the large and the small one: they should look alike. If the small one's border is enormous or its grain coarse, you have used pixels where you needed proportions. - "A different result the second time" means something is not repeatable:
Math.random(), the time, or state kept between calls. --image photo.jpgtries it on a photograph of your own, in place of the built-in test picture.--out some/folderwrites the results somewhere else.- A name means the module in
data/modules. Anything else is taken as a path, so a module kept elsewhere can be tested:pnpm fotobogen module test ../my-modules/border.
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
- Copy the folder into
data/modules/on the site, so that you havedata/modules/<name>/module.json. (If you made it withmodule newin the same copy of Fotobogen, it is already there.) - Restart Fotobogen.
- Open Admin, Modules. Your module is listed, switched off. Switch it on.
- 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
- Edit the files and restart. Modules are read once, at start.
- Photos already made keep their old look until they are made again. Switch the module off and on again under Admin, Modules, and every photo that uses it is made again in the background.
- You may add settings: photos saved without them get the new setting's default.
- Do not rename a transform's
idor the module'sname. Photos refer to them, and a photo whose transform has gone simply skips it.
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
- A photo's look is a list of transforms, up to eight, run one after another. Yours receives whatever the one before it produced, which may already be black and white, or larger than the photo.
- A look made in the admin runs in the order the modules are listed there. (One saved through the API, or named by a skin, runs in the order it is written.) The modules that come with Fotobogen go first: film looks, then the film frame, then the watermark. Installed modules follow, in name order.
- A skin can name your transform as its look for every photo.
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.
| Message | What 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
pnpm fotobogen module testsays "The module works."- The large and small test pictures look alike.
- Every slider has been tried at both ends in the admin.
- It works on an upright photo, a wide one, and a small one (under 500 pixels).
- It works after another transform: switch on Film frame with it and check the result.
- Labels say what a setting does in plain words, with its unit: "Width (percent of the shorter side)".
- It reads no files and uses no network.
Read the ones that come with Fotobogen
The three bundled modules are written to be read, with comments on every part:
modules/filmlooks: tone and grain. Adjusting colour, a seeded grain layer, and two steps kept in order.modules/filmframe: a border drawn round the photo. Making the picture larger, drawing with SVG, a ragged edge from seeded randomness.modules/watermark: text on the photo. Atextsetting, and drawing letters without a font.
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.