Skip to main content

Building for instant pages and live updates

Two things make Poly Community feel like an app. A move to another page draws it at once, with no page fetched from the server, and what a page shows changes by itself when something changes elsewhere. A part you build or change keeps both when it follows the same few rules as the parts of Poly Community itself. This page is the path through them. The pages it links to go into each step.

How a page is shown​

  1. The first page is drawn by the server, whole, as any WordPress page.
  2. A move to another page is drawn from that page file: a static file the site made earlier, the same for every reader of its kind (a visitor, a member, an administrator). The browser fills it with one request for its data: the lists, parts and numbers the page names. See Moving between pages.
  3. What a member sees stays current through events. A change on the server is told as an event on the channels of those who may see it. A member page hears it over the realtime connection where the site has one, or by asking every few seconds where it has not. The event carries the rows it changed, and the page writes them in place. A change by someone else never makes a page ask the server: what its event does not carry, a list growing or a row it does not bring, shows on the next page the member opens, so nothing shifts while they read. Only their own changes ask. A visitor page asks for no events: a visitor sees what changed on the next page they open. See Live updates in code.

Everything on a page is drawn from data in the page state: rows by type and id, lists of their ids, and parts. The same markup is drawn by the server on a whole load and by the browser after a move or an event. That is what lets both work.

All of it is the WordPress Interactivity API. The markup is blocks with directives, drawn on the server first (server-side rendering), the page state is the global state of the poly-community store, and a move is a client-side navigation of the Interactivity Router. The WordPress reference is the full reference for each, and Built on the Interactivity API maps them to what Poly Community adds.

The rules in short​

  • Draw from data, never from the moment. A block names its lists and parts by key and draws them from the state. On a whole load the server puts their data in the state. While a page file is drawn, the block names them unread, and the browser asks them in its one request. See Lists.
  • Who may do what is a fact, not a drawing. Draw the button for everyone and show it by a fact of the reader (state.reader). A page file is the same for every reader of a kind, so what differs by reader must come as data.
  • Tell every change as an event, on the channels of those who may see what changed, with the row it changed where it may go, and say which events a list follows and which change one of its rows.
  • Never fetch a page or draw HTML of your own in the browser. Ask data through the REST API and write it into the state. HTML a row shows is drawn by the server, kept by key, and drawn with data-wp-html.

Building a new part, step by step​

The example is a component with a page of rooms. Administrators add, rename and remove rooms on the page, and every member who has it open sees each change at once. Each room is drawn from its row, and a move to the page from anywhere in the community draws it from its page file.

Download the example plugin (Rooms for Poly Community, a zip to upload under Plugins → Add New Plugin → Upload Plugin). The code on this page is taken from it, some of it shortened, and the plugin tests install it as a site owner would and check each step of this page on it (examples/poly-community-rooms in the plugin, checked by tests/specs/instant-and-live.spec.ts). Read it beside this page, or start your own component from it.

The Rooms page as an administrator sees it: a field and Add a room, then four rooms, each with Rename and Remove
The Rooms page of the example, as an administrator

1. Make it part of a component​

Blocks drawn in page files are the community own blocks, named poly-community/…. Give yours to a component, so it comes and goes with the component and is checked as the others are. A plugin adds its component with poly_community_register_kits, as Building a component shows:

function poly_community_rooms_register( $kits ) {
$kits->add( __DIR__ . '/example-rooms' );
}
add_action( 'poly_community_register_kits', 'poly_community_rooms_register' );

The component (example-rooms/kit.json) declares one page, at rooms, puts it in the menu and asks for its own table. defaultOn switches it on once the plugin is active, and script: drawn loads its script only on a page that draws it:

{
"slug": "example-rooms",
"title": "Rooms",
"group": "content",
"defaultOn": true,
"script": "drawn",
"textDomain": "poly-community-rooms",
"tables": [ "example_rooms" ],
"views": { "example-rooms": { "path": "rooms", "width": "list", "title": "Rooms" } },
"nav": [ { "view": "example-rooms", "label": "Rooms", "icon": "key", "after": "members" } ]
}

Its table is made from schema.php the first time the plugin runs, named $wpdb->poly_example_rooms. The file runs again when it changes, and CREATE TABLE IF NOT EXISTS leaves a table that is there as it is, so a later version changes its table with statements of its own. Its page template (templates/example-rooms.html) holds its block, <!-- wp:poly-community/example-rooms /-->, declared in blocks/example-rooms/block.json with "supports": { "interactivity": true }, which tells WordPress it uses the Interactivity API and works with client-side navigation. Its class adds its hooks in boot():

final class Poly_Community_Kit_Example_Rooms extends Poly_Community_Kit {

public function boot() {
add_action( 'poly_community_register_row_types', array( $this, 'row_types' ) );
add_action( 'poly_community_register_lists', array( $this, 'lists' ) );
add_filter( 'poly_community_json_move_blocks', array( $this, 'move_blocks' ) );
add_filter( 'poly_community_viewer_facts', array( $this, 'facts' ), 10, 2 );
add_action( 'rest_api_init', array( $this, 'routes' ) );
}
}

It then has its page under Settings → Components, with its switch, and its data: the rooms in its table, counted and deleted there with the rest.

Rooms under Settings, Components: switched on, nothing to set up, and its data with Delete Rooms data
Settings → Components → Rooms

2. Register its rows​

A row is what the browser draws an object from. Register its type once:

public function row_types( $live ) {
$live->register_type( 'room', array(
// The object as it is now, by its id.
'find' => array( __CLASS__, 'get' ),
// Its row put in the state and returned, or null where it is not drawn from data.
'row' => array( $this, 'build_row' ),
// Its version: a newer one always wins in the browser.
'version' => array( $this, 'room_version' ),
// The events about it, each answering the room: they carry its row where it may go.
'events' => array(
'room.updated' => array( $this, 'room_of_event' ),
),
) );
}

// Every callback is a public method, never an anonymous function: the community calls it from outside the class,
// an error names it, and a hook takes off only a named one.
public function room_version( $room ) {
return (int) $room->updated_us;
}

public function room_of_event( $payload ) {
return (int) ( $payload['id'] ?? 0 );
}

public function build_row( $room, $form = 'reader' ) {
if ( ! $room ) {
return null;
}
$live = Poly_Community()->live_data;
$v = (int) $room->updated_us;
$html = $this->view( 'room', array( 'room' => $room ) ); // trusted HTML, escaped where it holds what members wrote
$row = array(
'id' => (int) $room->id,
'v' => $v,
'name' => (string) $room->name,
'html' => (object) array( 'row' => $live->html( 'room', (int) $room->id, 'row', $v, $html ) ),
);
$live->put( 'room', $row );

return $row;
}

The version must grow with every change: a row at the same version as the one a page holds is not taken. Keep the time of the change in microseconds when you save it ((int) floor( microtime( true ) * 1000000 )), not in seconds, or two changes in one second share a version and the second is lost.

$form says for whom the row is built: reader (the reader of this request) or shared (everyone the event reaches). Put nothing of one reader in a shared row. The Live updates in code page has every argument.

3. Register its list​

A list is the ids a part of the page draws in order. Register its kind, so the browser can ask it as JSON (GET lists/rooms) after a move or an event:

public function lists( $live ) {
$live->register_list( 'rooms', array(
'args' => array(
'page' => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1 ),
),
// The list's shape, its rows put for the reader.
'list' => array( $this, 'rooms_list' ),
// The arguments of a key after `rooms:` (a page file names its list by key).
'key' => array( $this, 'rooms_key' ),
// Rows read again by id (`GET lists/rooms?ids=`).
'rows' => array( $this, 'rooms_rows' ),
) );
}

public function rooms_key( $rest ) {
return array( 'page' => max( 1, (int) $rest ) );
}

public function rooms_rows( $ids ) {
foreach ( (array) $ids as $id ) {
$this->build_row( self::get( (int) $id ) );
}
}

public function rooms_list( $args ) {
$ids = $this->room_ids( $args ); // the rooms the reader may see, in order
foreach ( $ids as $id ) {
$this->build_row( self::get( $id ) );
}
// What shows while there is none, trusted HTML by key as a row has.
$empty = '<p class="example-rooms-empty">' . esc_html__( 'No rooms yet.', 'poly-community-rooms' ) . '</p>';

return array(
'ids' => $ids,
'type' => 'room',
'more' => false,
'page' => (int) ( $args['page'] ?? 1 ),
'args' => $args,
// The events it follows, and those that change one of its rows (Lists: whose events ask it again).
'events' => 'room.created room.deleted',
'reads' => array( 'room.updated' ),
'empty' => Poly_Community()->live_data->html( 'rooms', 0, 'empty', abs( crc32( $empty ) ), $empty ),
);
}

The Lists page has the shape of a list and how its events are written.

4. Draw the block from the state​

The block puts its list on a whole load and only names it while a page file is drawn. Its template draws the rows from the state either way. A component block named poly-community/example-rooms is drawn by its component class render_example_rooms():

public function render_example_rooms( $attributes, $content, $block ) {
$lists = Poly_Community_Address_Lists();
$slot = $lists->new_slot();
$key = 'rooms:1';
if ( ! $lists->is_skeleton() ) {
Poly_Community()->live_data->put_list( $key, $this->rooms_list( array( 'page' => 1 ) ) );
}
$lists->state();
wp_interactivity_state( 'poly-community', array( 'tileKeys' => array( $slot => $key ) ) );

return Poly_Community()->blocks->kit_block( $block, $this->view( 'rooms', array( 'slot' => $slot ) ) );
}

Its view, views/rooms.php, is plain Interactivity API markup: data-wp-each draws a list from its ids, data-wp-bind sets attributes from the state, data-wp-context holds the slot of the list, and data-wp-html draws the trusted HTML of each row:

<form class="example-rooms-add" data-wp-bind--hidden="!state.reader.exampleRoomsCanEdit">
<input class="poly-input" name="name" type="text" maxlength="80" required placeholder="Name of the new room">
<button class="poly-btn poly-btn-primary" type="submit">Add a room</button>
</form>
<div class="example-rooms" data-poly-tiles="<?php echo esc_attr( $slot ); ?>" data-poly-from-data
data-wp-context="<?php echo esc_attr( wp_json_encode( array( 'tileSlot' => $slot ) ) ); ?>"
data-wp-bind--data-poly-list="state.tileKey"
data-wp-bind--data-can-edit="state.reader.exampleRoomsCanEdit">
<template data-wp-each--item="state.partRows" data-wp-each-key="context.item.id">
<div data-wp-bind--data-poly-tile="context.item.id">
<div class="poly-tile-part" data-wp-bind--data-poly-html="state.rowPartKey" data-wp-html="state.rowPart"></div>
</div>
</template>
<div class="poly-tile-part" data-wp-bind--hidden="!state.tilesEmptyKey" data-wp-bind--data-poly-html="state.tilesEmptyKey" data-wp-html="state.tilesEmpty"></div>
</div>

These getters are the community own (state.partRows, state.rowPart, state.tilesEmpty), derived state of the poly-community store, so the list draws before any script of yours has loaded, as it has not yet after a move. Showing the rooms needs no script at all. Teaching in the courses component is drawn the same way (kits/courses/views/teaching-tiles.php).

A part that is not a list (a number, a short summary) is named the same way with Poly_Community_Parts: unread() while a file is drawn, put() otherwise. See Parts: name them unread.

5. List the block for page files​

public function move_blocks( $blocks ) {
$blocks[] = 'example-rooms'; // without poly-community/
return $blocks;
}

A page holding a block that is not listed has no file, and moves to it load its HTML. That is safe, only slower. Listing a block is a promise that it draws nothing of the moment and nothing of its reader in a file, on every page that holds it.

6. Say what the reader may do as a fact​

public function facts( $facts, $context ) {
if ( ! empty( $context['logged_in'] ) ) {
$facts['exampleRoomsCanEdit'] = ! empty( $context['is_admin'] );
}
return $facts;
}

The form of step 4 is in every drawing, so every file of a kind is the same, and it shows for the readers it is for (state.reader.exampleRoomsCanEdit). The browser reads the facts again when the access of its reader changes (the access.changed event).

A row is the same for every reader too, as an event takes it to all of them. So the Rename and Remove buttons of a room are in its HTML for everyone, and its styles show them where the list holding it says its reader may change rooms (data-can-edit, bound to the same fact):

.example-room-tools { display: none; }
.example-rooms[data-can-edit="true"] .example-room-tools { display: flex; }

The server never takes the fact on trust: each route asks the capability itself (step 8).

The Rooms page as a member sees it: the same four rooms, with no field and no buttons
The same page, as a member

7. Tell each change as an event​

public function save( $id, $name ) {
global $wpdb;

$now = (int) floor( microtime( true ) * 1000000 ); // its version, in microseconds

if ( $id && self::get( $id ) ) {
$wpdb->update( $wpdb->poly_example_rooms, array( 'name' => (string) $name, 'updated_us' => $now ), array( 'id' => (int) $id ) );
Poly_Community()->events->emit( array( 'site' ), 'room.updated', array( 'id' => (int) $id ) );
return (int) $id;
}

$wpdb->insert( $wpdb->poly_example_rooms, array( 'name' => (string) $name, 'updated_us' => $now, 'created_at' => current_time( 'mysql', true ) ) );
$id = (int) $wpdb->insert_id;
Poly_Community()->events->emit( array( 'site' ), 'room.created', array( 'id' => $id ) );
return $id;
}

Name the object id in the payload, as a list reads a row again by it. Emit after the change is saved, on the channels of those who may see the object: site for everyone, members for members, user:{id} for one account, or the core helpers Poly_Community()->access->item_channels( $item ), space_channels( $space ) and profile_channels( $profile ). Every member page showing the list hears it. room.updated carries the room row (the row type events in step 2), so each page writes it in place and asks nothing (the list reads). room.deleted takes the room out of the list at once. room.created shows on the next move of each reader, so the list never shifts while it is read (its events). A payload that names the profile id of the member who made the change, as author, by or profile, makes their own other tabs ask the list again (a user id there matches nobody). It follows with no reload, and with no code of yours in the browser.

8. Your routes and your script, where you need them​

What a reader changes goes through a REST route of the community API (poly-community/v1), which the component adds and which asks the capability itself, whatever a page shows. A route that changes a room answers with the room row, as a pack, so the page that asked draws it at once:

public function routes() {
register_rest_route( Poly_Community_Rest_Api::NAMESPACE_V1, '/example-rooms', array(
'methods' => 'POST',
'callback' => array( $this, 'rest_save' ),
'permission_callback' => array( $this, 'can_edit' ),
'args' => array( 'name' => array( 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ) ),
) );
// … and /example-rooms/(?P<id>\d+), POST to rename and DELETE to remove, with the same check.
}

public function can_edit() {
return current_user_can( 'manage_options' );
}

public function rest_save( WP_REST_Request $request ) {
// … the name checked, a WP_Error with a status for one refused …
$id = $this->save( (int) $request->get_param( 'id' ), $name );

// Built by build_row(), the row of its type, kept out of the page's state: the answer carries it.
return rest_ensure_response( array( 'id' => $id, 'data' => Poly_Community()->live_data->row_pack( 'room', self::get( $id ) ) ) );
}

row_pack( $type, $object ) builds the row of an object of a registered type as a pack. For anything else a write answers with, pack( $build, false, false, $args ) calls $build with $args and packs what it puts.

A component script is a script module that imports from the core module poly-community, and from @wordpress/interactivity where it needs store() or getContext(). A file at assets/<slug>.js is registered as @poly-community/kit-<slug> by itself. Without script in kit.json it loads on every community page. With script: drawn, as here, it loads only on a page that draws the component: on its first load, and on a move to it, from its page file or its HTML alike, as the WordPress router brings the modules of a page it shows. Its import … from 'poly-community' then gets the one copy of the core already running. The components of Poly Community build theirs from src/index.ts. The example is a plain module with no build:

import { api, toast, errorMessage, mergePack, listOf } from 'poly-community';

const KEY = 'rooms:1'; // the list this page draws

// The answer drawn: its row put into the state, the list told of a new id or one gone.
function drawn( answer, removed = 0 ) {
mergePack( answer?.data );
const list = listOf( KEY );
if ( ! list ) {
return;
}
const ids = ( list.ids || [] ).map( Number );
if ( removed ) {
const at = ids.indexOf( removed );
if ( at > -1 ) {
ids.splice( at, 1 );
list.ids = ids;
}
} else if ( answer?.id && ! ids.includes( Number( answer.id ) ) ) {
list.ids = [ ...ids, Number( answer.id ) ];
}
}

async function send( path, options, removed = 0 ) {
try {
drawn( await api( path, options ), removed );
return true;
} catch ( error ) {
toast( errorMessage( error ), true ); // the message of the WP_Error the route answered
return false;
}
}

// A room added from the form above the list.
async function addRoom( event ) {
const form = event.target instanceof Element ? event.target.closest( '.example-rooms-add' ) : null;
if ( ! form ) {
return;
}
event.preventDefault();
const field = form.elements.namedItem( 'name' );
if ( await send( 'example-rooms', { method: 'POST', body: { name: field.value.trim() } } ) ) {
field.value = '';
}
}
// … and changeRoom(), a click on Rename or Remove in a room, sent the same way (assets/example-rooms.js).

// On the document, so it holds on every page a move brings: the module runs once a page load. Named handlers, so
// they can be taken off again with removeEventListener().
document.addEventListener( 'submit', addRoom );
document.addEventListener( 'click', changeRoom );

api() calls a route under poly-community/v1/ with the reader session, so example-rooms is /wp-json/poly-community/v1/example-rooms. Every other page showing the rooms follows the event the save told, with no code of yours: a row the event carries is written in place, a room deleted leaves at once, and a new one shows on the next move of the reader. The page that made the change draws it from the answer, and the event that comes after finds the list as it is. Write state through rows, parts and lists like this, never into the page HTML, as a page drawn again from its file or an event draws over it.

An event of your own, beside what the lists do with theirs, is handled with onLive( type, listener ), as Live updates in code shows.

9. Check it​

  • Its page file is made. As an administrator, open /?poly_moves_made=1 on the site: every page, its kinds, and why a kind has no file (a block not listed, something of the moment read, two readers drawn otherwise, with where they part).
  • A move uses it. After a move, document.documentElement.dataset.polyMove is file where it came from the page file, and says why where it did not.
  • It stays current. Add a room as an administrator in one browser, and watch the page of a member in another follow with no reload.
  • Its tests. The specs of Poly Community check a page against a whole load of it with movesFromFile() (tests/fixtures/moves.ts), as tests/specs/instant-and-live.spec.ts does for this example: a file for each kind of reader, its script brought by a move from the file or from the HTML with the core loaded once, a member page following rooms changed on the server with no page asked, and an administrator page drawing its own writes while it hears none of their events.

Changing an existing part​

  • Its template in the Site Editor, or a view override in your theme: both are part of the page key, so the page files are made again from them. Keep the rules of this page in what you add: a block of your own listed, its data named and not read.
  • What a post row holds: a component adds its own values to the rows of its kinds with poly_community_item_row_data (under kit: a job pay, a listing price, an event date). It is told the form the row is built in (reader, shared, known), so nothing of one reader goes into a shared one. The row version moves at each change of the post. For a row of a core table you change yourself, call Poly_Community()->live_data->touch( $type, $id ) after the change.
  • A part of a post card: poly_community_card_part_html filters the HTML of each part of a card as it is drawn ($html, the part name, the block). Draw from the row, never from the reader.
  • The widgets beside a page type: poly_community_sidebar_blocks lists them (block names, attributes as JSON after a space). Each must be a block a file may hold.
  • A page that draws by something of your own (a setting of your plugin, a file it reads): add it to the page key with poly_community_json_move_key, so a change of it makes the files again. It is given the page id and, as a third argument, the tab page id (kit-events-calendar, whose key holds the month, so a new month draws its file again).
  • A link that draws the page again with another address (a tab, a sort): mark it data-poly-file, and it becomes a page file of its own. Its address must be the same for every reader. See Tabs that draw the page again.
  • Something only some readers see: a fact of the reader, as in step 6, not a test in the view.
  • A list that should follow more events: add them to its events, with what their payload must hold (room.deleted:space=12).

What stops a page file: a block not listed, a block that reads rows or parts while a file is drawn, another plugin that prints into the page or hooks an action its page type runs, and a classic widget in the widget area. Each is said on /?poly_moves_made=1, and the page still works, moved to by its HTML.

What is stable​

poly_community_register_kits, poly_community_register_row_types, poly_community_register_lists, poly_community_sidebar_blocks, register_type() and register_list() are on the stable list. The rest of this page is not on it yet: the events and their names, Poly_Community()->events->emit(), the poly-community script module and its functions, poly_community_viewer_facts, poly_community_item_row_data, poly_community_card_part_html, poly_community_json_move_blocks, poly_community_json_move_key and the page file rules.

See also Built on the Interactivity API, Moving between pages, Lists, Live updates in code and Building a component.