The ctx object
A plugin receives ctx as the argument of its onload function:
export default definePlugin({ onload(ctx) { ctx.log('info', 'The plugin has started');
// requires the `ui` permission ctx.ui.notice({ text: 'Hello from the plugin' }); },});ctx is an ordinary object whose properties give the plugin access to the app. In the example, ctx.log writes a line to the log of the plugin, and ctx.ui displays elements on the screen. These properties are the only way for a plugin to reach the app, because the code of a plugin runs in an isolated environment where nothing else is available, such as the page, the file system or the network.
Some properties require a permission. In the example, ctx.ui.notice requires the ui permission, so the manifest of the plugin must list it, and the person approves it when installing the plugin. When a plugin uses a property without holding the permission that it needs, the call throws an error named PermissionDenied.
This page lists every property of ctx, then shows how to use the most important ones for common tasks. The exact types and parameters of every property are documented in the reference. In the table, each property links to its page.
The properties of ctx
Section titled “The properties of ctx”| Property | What it is for | Permission |
|---|---|---|
ctx.state |
Reads the library as it is now: rows, outlines, areas, saved searches and friends. | read |
ctx.query |
Searches the library, and extends the search with new words, filters and lists. | read |
ctx.hooks |
Runs a function when a change is about to happen or has just happened, so that the plugin can allow it, refuse it, replace it or react to it. | read |
ctx.editing |
Examines the text that the person types in a title or a note before each change becomes final. | read |
ctx.normalize |
Repairs the data of the plugin after every change. | none |
ctx.facets |
Defines the extra information that the plugin stores on rows, outlines and the library. | none |
ctx.dispatch |
Makes a change. | write:rows, or write:outlines for the commands that create, modify, move, delete or rename outlines, areas and saved searches |
ctx.rows, ctx.outlines |
Ready-made changes to rows and to outlines. ctx.rows.reveal shows the person something other than what a row stores. |
write:rows, write:outlines, and read for reveal |
ctx.commands |
Registers actions that have a name, which the person can run from the command palette, from menus and with shortcuts. | none |
ctx.notifications |
Sends events and listens to events, between plugins and from the app. | notifications to send, read to listen |
ctx.topics |
The events that the app itself sends. | none |
ctx.observe |
Calls a function when a value changes. | read |
ctx.keys |
The values that ctx.observe can watch: the state of synchronization and the language of the app. |
none |
ctx.views |
The lists that the app already provides. | none |
ctx.ui |
Talks to the person and adds elements to the screen. | ui |
ctx.i18n |
Provides the texts of the plugin in several languages. | none |
ctx.crypto |
Locks and unlocks text, and signs it. | crypto, and crypto:friends for devices and friends |
ctx.audit |
Reads the signed record of the changes made to an outline, and writes notes in it. | audit to read, audit:write to write a note, and audit:grant to record who received a key |
ctx.net |
Fetches from a website. | net:<domain> |
ctx.jobs |
Runs slow work in the background. | jobs |
ctx.clock |
Provides the current time. | none |
ctx.platform |
States where the plugin runs and the version of the app. | none |
ctx.log |
Writes a line to the log of the plugin. | none |
Common tasks
Section titled “Common tasks”Reading rows and searching
Section titled “Reading rows and searching”ctx.state returns rows, outlines, saved searches and friends. Rows, outlines and searches are looked up by id. The rows are copies that the plugin cannot modify, and they do not update by themselves: to see later changes, ask again.
const row = ctx.state.row(rowId); // undefined when no row has this idif (row) { // the rows at the same level, including this one const level = ctx.state.children(row.outline, row.parent);
// the parent first, then the grandparent, and so on const path = ctx.state.ancestors(row.id); ctx.log('info', `"${row.title}" has ${path.length} ancestors`);}
const hits = ctx.query.run('#phone is:open'); // [{ outline, id }, …]
// the friends of the person, by name; a plugin that locks text for a friend asks the person to choose one of themconst friends = ctx.state.friends(); // [{ group: 'a1b2…', name: 'Ann' }, …]
// only the friends who are on the shared outline of a row ([] when it is not shared)const onIt = ctx.state.friends(row.outline);These calls require the read permission.
Refusing a change
Section titled “Refusing a change”A hook is a function that the app calls when a change is about to happen. A hook can allow the change, refuse it, replace it, or ask the app to wait. The page How a change goes through explains each hook. The following hook refuses to delete any row that carries the tag #keep:
ctx.hooks.shouldDelete({ on: 'row', onTimeout: 'veto' }, delta => { if (delta.kind !== 'deleted') return allow(); const tags = ctx.facets.core.tags.tags.of({ facets: delta.value.facets ?? {} }) ?? []; return tags.some(t => t.toLowerCase() === 'keep') ? veto('protected', 'Tagged #keep: it cannot be deleted') : allow();});Registering a hook requires the read permission, because a hook receives data from the library.
Storing information on rows
Section titled “Storing information on rows”A facet is a piece of extra information that a plugin attaches to a row, to an outline or to the library as a whole. ctx.facets.define creates one, and the handle that it returns reads and writes the value.
const sessions = ctx.facets.define<number>({ key: 'com.example.pomodoro/sessions', on: 'row', merge: 'counter', schema: { type: 'integer', minimum: 0 },});
const count = sessions.of(row); // the value on a row, or undefinedawait ctx.dispatch(sessions.set(row.id, 3)); // write the valueThe schema describes the values that are allowed, and the app checks every value that is written. The merge rule determines what happens when two devices change the value at the same time: counter adds up what each device added. The page The data model describes the other merge rules. Writing the value goes through ctx.dispatch, which requires write:rows, whatever the value is attached to.
Making a change
Section titled “Making a change”ctx.rows and ctx.outlines hold ready-made changes. Each one is called like a function, and it returns an Outcome, whose status tells what happened: committed, vetoed, unavailable, invalid, conflict, cancelled or failed.
const outcome = await ctx.rows.modify({ id: row.id, title: 'Buy milk' });if (outcome.status !== 'committed') { ctx.log('warn', `The title was not changed: ${outcome.status}`);}These calls require write:rows and write:outlines. A change that has no ready-made function is made by passing an intent to ctx.dispatch, as the previous section does with sessions.set.
Asking the person
Section titled “Asking the person”ctx.ui asks questions and returns the answer. Each question returns a promise, and a question never blocks a change that is in progress.
const answer = await ctx.ui.confirm({ title: 'Archive this outline?', message: 'You can restore it later.', action: 'Archive',});if (answer.confirmed) { await ctx.outlines.modify({ id: outlineId, archived: true });}This example requires the ui permission, and write:outlines for the change. The other properties of ctx.ui add elements to the screen: a message, a card with a progress bar, an entry in the sidebar, a panel, a new way of displaying an outline, an item in the / menu, and small marks on rows.
Fetching from a website
Section titled “Fetching from a website”ctx.net.fetch fetches over https from a single website. The manifest names the website in its permission, for example net:api.example.com, and the plugin can reach that website and no other.
const response = await ctx.net.fetch('https://api.example.com/rates');if (response.status === 200) { ctx.log('info', response.body.slice(0, 100));}Locking text with a password
Section titled “Locking text with a password”A plugin sometimes needs to store text that only the person can read, for example a note that is protected by a password. ctx.crypto does this in two steps. First it turns the password into a key. Then the key locks and unlocks text. This requires the crypto permission.
The following code makes a key and uses it to lock a text:
// The settings for a new key. They are made once and saved with the locked text.const params = ctx.crypto.newParams();
// The key, made from the password and the settings.const key = await ctx.crypto.deriveKey(password, params);
// Locks the text. The second argument names the row that the text belongs to.const locked = key.seal('my secret', 'row:' + row.id);locked is a string that cannot be read without the key. To read it later, for example after the app has restarted, the plugin asks for the password again and makes the key again from the same password and the same settings:
const key = await ctx.crypto.deriveKey(password, params);const text = key.open(locked, 'row:' + row.id); // 'my secret'When the password is wrong, or when the locked text was changed, open throws an error. The reason property of the error tells which case it is: wrong-key or not-sealed, the latter meaning that the text was never locked.
try { key.open(locked, 'row:' + row.id);} catch (error) { ctx.log('warn', 'The text could not be unlocked: ' + error.reason);}Three rules apply to this code:
- The settings (
params) contain a random value called a salt, which makes the same password produce a different key each timenewParamsis called. The settings are not secret, but the plugin must save them next to the locked text, because the same password gives a different key with different settings. deriveKeytakes about one second. This is intended: a person who tries to guess the password has to wait the same time for every guess. The app stays responsive while it runs. It throws an error when the settings ask for less work than the default, because someone may have lowered them.- The second argument of
sealandopennames the place that the text belongs to. A text opens only with the place that it was locked with, so a locked text that is copied to another row does not open there.
Locking text for other devices and friends
Section titled “Locking text for other devices and friends”A plugin can also lock a text so that only certain people can read it, without using a password. The app holds a pair of keys on each device and handles them itself, so the plugin never receives a key. It only says who may read the text. This requires the crypto permission and the crypto:friends permission.
The following code locks a text for all the devices of the person, and then opens it:
// Locks the text. The result is an envelope.const envelope = await ctx.crypto.sealTo({ me: true }, 'dinner at eight', { purpose: 'note' });
// An envelope is plain data. The plugin can save it, for example in a facet, or send it.// To read it, the plugin gives the same purpose again.const opened = await ctx.crypto.open(envelope, { purpose: 'note' });if (opened) { ctx.log('info', opened.text); // 'dinner at eight'}The first argument of sealTo says who can read the text:
| Value | Who can read the text |
|---|---|
{ me: true } |
all the devices of the person |
{ device: id } |
one device of the person, identified by its id |
{ friend: groupId } |
the devices of a friend, identified by the id of the friend’s group |
The purpose is a word that the plugin chooses to say what the text is for, such as note or invitation. An envelope opens only in the plugin that made it, and only with the same purpose.
open also tells who locked the text. The from property is { me: true } when one of the devices of the person locked it, and { friend, name } when a friend did, where friend is the id of the friend’s group:
if (opened) { if ('me' in opened.from) { ctx.log('info', 'Locked on one of my devices'); } else { ctx.log('info', 'Locked by ' + opened.from.name); }}To let the person choose a friend, list the friends with ctx.state.friends() (this requires read). The group of each one is what friend takes:
const friends = ctx.state.friends(); // [{ group: 'a1b2…', name: 'Ann' }, …]const answer = await ctx.ui.pick({ title: 'Lock this note for…', choices: friends.map(f => ({ id: f.group, label: f.name })),});if (!('cancelled' in answer)) { const envelope = await ctx.crypto.sealTo({ friend: answer.id }, 'dinner at eight', { purpose: 'note' });}A text can be locked more than once. The text of an envelope is a string, so a plugin can lock an envelope again for someone else. Then the first person opens the outer layer and finds an envelope that only the second person can open. The plugin gives each layer its own purpose, so that an envelope never opens as the other one:
// ann and bob are the group ids of two friends. The inner layer is for Bob, and the outer layer is for Ann.const inner = await ctx.crypto.sealTo({ friend: bob }, 'the letter', { purpose: 'inner' });const outer = await ctx.crypto.sealTo({ friend: ann }, JSON.stringify(inner), { purpose: 'outer' });
// On Ann's device: she opens the outer layer, and what she finds is still locked for Bob.const first = await ctx.crypto.open(outer, { purpose: 'outer' });const forBob = JSON.parse(first.text);
// On Bob's device, after the envelope reached it: he opens the letter. Ann cannot, and neither can the person who locked it.const letter = await ctx.crypto.open(forBob, { purpose: 'inner' });Such layers are opened in order: the second person has nothing to open before the first one has opened their layer. To let several people agree in any order, use a key cut in parts, as the next section shows.
open returns null instead of throwing an error when it cannot open the envelope. This happens when the envelope is for other devices, comes from another plugin, has another purpose, was changed, or was locked by someone whom the person does not know. sealTo throws an error when the friend is not a friend of the person, when the device is not in the group of the person, or when purpose is missing. A text can have at most 256 KiB.
A key that several people must give back
Section titled “A key that several people must give back”A plugin can also lock a text with a random key, and cut that key in parts that are all needed to open the text. This requires the crypto permission. Each part can be locked for one person with sealTo, so that the text opens only when every one of them gives their part back. This is how the plugin A letter that opens only when everyone agrees works.
// a new random key, and the text locked with it; no password, no waitconst key = ctx.crypto.newKey();const locked = ctx.crypto.keyOf(key).seal('the letter', 'row:' + row.id);
// the key cut in three parts: all three are needed, and two of them say nothing about the keyconst [a, b, c] = ctx.crypto.split(key, 3);
// later, with the three parts, in any order: the key again, and the textconst again = ctx.crypto.join([c, a, b]);const text = ctx.crypto.keyOf(again).open(locked, 'row:' + row.id); // 'the letter'With a part missing or changed, join returns another key, and open throws an error. The key and the parts are secrets: the plugin saves them only where the people who may read the text can read them, for example each part locked for its person with sealTo.
Signing a text
Section titled “Signing a text”A signature shows that a device of the person or of a friend wrote a text, and that the text has not changed since. Signing requires the crypto permission and the crypto:friends permission.
// Signs the text with this device.const signature = await ctx.crypto.sign('I agree', { purpose: 'deal' });
// Later, on any device that knows the signer, checks the signature against the text.const who = await ctx.crypto.verify(signature, 'I agree', { purpose: 'deal' });// { me: true }, or { friend, name }, or nullverify returns null when the signature does not belong to the text, as in the next call, where the text is different from the one that was signed. It also returns null for a signature that was made for another plugin or another purpose, and for a signer whom the person does not know. A signature is plain data, like an envelope, so the plugin can save it or send it.
const forged = await ctx.crypto.verify(signature, 'I agree to pay', { purpose: 'deal' });// nullWriting in the audit trail
Section titled “Writing in the audit trail”Every change that a plugin makes is already in the audit trail of the outline: the device that made the change signs an entry for it, with the person and the time, and the origin Plugin. That entry says what changed, not why. A plugin that wants the trail to say what the person did, for example that they agreed to open a letter, writes a note. This requires the audit:write permission.
// Writes a note in the trail of the outline of the row: the share's trail, or the person's own.await ctx.audit.record(row.outline, 'Agreed to open "' + row.title + '"');The device signs the note in its own list, like its changes, so the note cannot be changed or removed afterwards, and the other devices of the trail receive it. The note also appears in History, under the outline that it is about, with the person who wrote it and the plugin. The app writes the name of the plugin in the note: bundled/<id> for a plugin that ships with the app, <publisher>/<id> for a plugin that names its publisher, and the id alone otherwise. A plugin cannot write a note in the name of another. A note has from 1 to 500 characters.
ctx.audit.entries returns a note as an entry whose kind is note, with the plugin and the text in note:
const entries = await ctx.audit.entries(row.outline, device, { after: -1, limit: 100 });for (const entry of entries) { if (entry.kind === 'note') ctx.log('info', `${entry.note.plugin}: ${entry.note.text}`);}A note is written only once the device belongs to a group, because before that there is no trail. The call then changes nothing visible.
Speaking the language of the person
Section titled “Speaking the language of the person”ctx.i18n.define takes the texts of the plugin in each language, and it returns a function t that answers in the language that the app currently uses. When a language has no text for a key, the English text is used. No permission is needed.
A text that the plugin computed earlier does not change by itself when the person changes the language, so the plugin watches ctx.keys.app.language and computes the text again.
const words = ctx.i18n.define({ en: { done: 'Done' }, fr: { done: 'Terminé' },});
ctx.ui.notice({ text: words.t('done') });ctx.observe(ctx.keys.app.language, { new: true }, () => { ctx.ui.notice({ text: words.t('done') });});Each name is written once
Section titled “Each name is written once”The app never requires a name to be typed twice. Every event, value, view, facet and command is an object that carries its name, and the plugin uses that object, so a misspelled name is a compile error.
| What | The object | How it is used |
|---|---|---|
| an event | ctx.topics.deviceDidChange, or one created with ctx.notifications.declare<T>(name) |
post(topic, …) and subscribe({ topic }, …) |
| a value to watch | ctx.keys.net.sync, ctx.keys.app.language, or the handle.on(id) of a facet |
ctx.observe(key, …) |
| a view | ctx.views.outlines.header, or one created with ctx.query.declare<Args>(name) |
ctx.query.view(ref, …) |
| a facet | ctx.facets.core.tasks.status, or one created with ctx.facets.define<T>(…) |
ref.of(row) reads it, ref.set(id, value) and ref.clear(id) build the change, and handle.on(id) watches it |
| a command | ctx.commands.core.tasks.setTask, or one created with ctx.commands.register<Args>(…) |
ref({ id, on }) builds the request, and ref.command is its id |
