Custom apps

Getting started

A complete custom app in one small resource: launcher entry, page, two server actions, theme and signal, a notification and a message from Lua.

#What this builds

This is the example that ships in fx-pocketbook/sdk/examples/fx-pocketbook-example: a traveller card. The app:

  • adds itself to the launcher and registers two server actions,
  • takes the notebook's ink colours and signal bars,
  • reads the player's own card (name, job, grade, whether the line works) from the server,
  • sends the player a notification,
  • receives a message sent from Lua,
  • cleans up when the page closes.

It writes nothing to the database and moves no money or items. The texts below are in English; the shipped copy is in Turkish.

To try it, copy the folder next to fx-pocketbook, keep Config.CustomApps.Enabled = true, and add ensure fx-pocketbook-example after ensure fx-pocketbook. With Config.CustomApps.RequireInstall = true, install the app from the App Store first. The /pocketcard command also opens it.

#fxmanifest.lua

luafx_version 'cerulean'
game 'rdr3'
rdr3_warning 'I acknowledge that this is a prerelease build of RedM, and I am aware my resources *will* become incompatible once RedM ships.'
author 'Fixitfy'
description 'Optional Pocketbook SDK example: personal traveller card'
version '1.0.0'
dependency 'fx-pocketbook'
shared_script 'config.lua'
client_script 'client.lua'
server_script 'server.lua'
files {
    'ui/index.html', 'ui/app.js', 'ui/style.css', 'ui/pocketbook.js',
    'ui/assets/*.svg', 'ui/assets/*.png', 'ui/assets/*.ttf'
}
-- No ui_page: Pocketbook owns the embedded frame and focus.

#config.lua

luaPocketExample = {
    Core = 'fx-pocketbook', AppId = 'traveller_card', Title = 'Traveller Card',
    JobLabels = { unemployed = 'Free', police = 'Lawman', doctor = 'Doctor' },
    NotificationCooldown = 10
}

If your notebook folder has another name, change Core and the dependency together.

#client.lua

The app is registered when this resource starts and again on fx-pocketbook:ready, so it comes back after a restart of the notebook.

lualocal registered = false
local function register()
    if registered or GetResourceState(PocketExample.Core) ~= 'started' then return end
    local ok, result = pcall(function()
        return exports[PocketExample.Core]:AddCustomApp({
            identifier = PocketExample.AppId,
            name = PocketExample.Title,
            ui = 'ui/index.html',
            icon = 'ui/assets/account-box-outline.svg',
        })
    end)
    registered = ok and result == true
end
AddEventHandler('onClientResourceStart', function(resource)
    if resource == GetCurrentResourceName() then SetTimeout(0, register) end
end)
AddEventHandler('fx-pocketbook:ready', register)
AddEventHandler('onClientResourceStop', function(resource)
    if resource == PocketExample.Core then registered = false end
end)

RegisterCommand('pocketcard', function()
    register()
    if registered then exports[PocketExample.Core]:OpenApp(PocketExample.AppId) end
end, false)

-- A message from this resource to its own page, while it is open.
RegisterCommand('pocketcardmessage', function()
    if registered then
        exports[PocketExample.Core]:SendCustomAppMessage(PocketExample.AppId, { kind = 'hint', text = 'Safe travels. Refresh your card any time.' })
    end
end, false)

#server.lua

Each action checks the player again with ValidateApplicationPlayer. The card is built from the character the core passes in, never from the payload.

lualocal registered = false
local notices = {}

local function allowed(src, char)
    local ok, result, reason = pcall(function()
        return exports[PocketExample.Core]:ValidateApplicationPlayer(PocketExample.AppId, src, char.id)
    end)
    if not ok then return false, 'Your card cannot be reached right now. Try again.' end
    return result, reason
end

local actions = {}
function actions.getCard(src, char)
    local ok, reason = allowed(src, char)
    if not ok then return { ok = false, error = reason or 'Your card is not available.' } end
    return { ok = true, card = {
        name = char.name,
        job = PocketExample.JobLabels[char.job] or char.job or 'Not set',
        grade = char.grade or 0,
        canSend = exports[PocketExample.Core]:CanUseOnline(src, 'send'),
        canReceive = exports[PocketExample.Core]:CanUseOnline(src, 'receive'),
    }, audit = { recordId = char.id, operation = 'readOwnCard' } }
end
function actions.remind(src, char)
    local ok, reason = allowed(src, char)
    if not ok then return { ok = false, error = reason or 'The notification cannot be sent.' } end
    local previous, now = notices[src], os.time()
    if previous and previous.character == char.id and now - previous.at < PocketExample.NotificationCooldown then
        return { ok = false, error = 'Wait a few seconds before the next reminder.' }
    end
    local sent = exports[PocketExample.Core]:Notify(src, { title = PocketExample.Title, message = 'Your traveller card is ready. Good journey.', offline = true })
    if not sent then return { ok = false, error = 'The notification could not be delivered. Refresh your card.' } end
    notices[src] = { character = char.id, at = now }
    return { ok = true, audit = { recordId = char.id, operation = 'selfReminder' } }
end

local function register()
    if registered or GetResourceState(PocketExample.Core) ~= 'started' then return end
    local ok, result = pcall(function()
        return exports[PocketExample.Core]:RegisterApplication(PocketExample.AppId, actions)
    end)
    registered = ok and result == true
end
AddEventHandler('onResourceStart', function(resource)
    if resource == GetCurrentResourceName() or resource == PocketExample.Core then SetTimeout(0, register) end
end)
AddEventHandler('onResourceStop', function(resource)
    if resource == PocketExample.Core then registered = false end
end)
AddEventHandler('playerDropped', function() notices[source] = nil end)

#ui/index.html

pocketbook.js is the file copied from fx-pocketbook/sdk/pocketbook.js. It loads before app.js.

html<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Traveller Card</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
<main>
  <div class="scroll">
    <h1 id="name">Opening your card…</h1>
    <dl id="card" hidden>
      <div><dt>Job</dt><dd id="job"></dd></div>
      <div><dt>Grade</dt><dd id="grade"></dd></div>
      <div><dt>Send telegrams</dt><dd id="send"></dd></div>
      <div><dt>Receive telegrams</dt><dd id="receive"></dd></div>
    </dl>
    <p id="signal" aria-live="polite"></p>
    <p id="hint" hidden></p>
  </div>
  <footer>
    <p id="status" role="status" aria-live="polite">Waiting for Pocketbook…</p>
    <button id="refresh" class="ink" disabled>Refresh my card</button>
    <button id="remind" class="secondary" disabled>Send a reminder</button>
    <button id="home" class="secondary" disabled>Back to home</button>
  </footer>
</main>
<script src="pocketbook.js"></script>
<script src="app.js"></script>
</body>
</html>

#ui/app.js

js(() => {
  'use strict';
  const $ = (id) => document.getElementById(id);
  const controller = new AbortController();
  let alive = true, ready = false, busy = false, loaded = false, sequence = 0;

  const status = (text, error = false) => { $('status').textContent = text; $('status').dataset.error = String(error); };
  function controls() {
    for (const id of ['refresh', 'remind']) $(id).disabled = !ready || busy || (id === 'remind' && !loaded);
    $('home').disabled = !ready;
  }

  async function request(action) {
    if (!ready || busy) return;
    busy = true; controls();
    const token = ++sequence;
    status(action === 'getCard' ? 'Refreshing your card…' : 'Sending a reminder…');
    try {
      const r = await Pocketbook.request(action, {});
      if (!alive || token !== sequence) return;
      if (!r?.ok) {
        status(r?.error || 'No connection. Try again.', true);
        if (action === 'getCard' && !loaded) $('name').textContent = 'Your card could not be loaded';
        return;
      }
      if (action === 'getCard') {
        const card = r.card; loaded = true;
        $('card').hidden = false;
        $('name').textContent = card.name;
        $('job').textContent = card.job;
        $('grade').textContent = String(card.grade);
        $('send').textContent = card.canSend ? 'Available' : 'Signal too weak';
        $('receive').textContent = card.canReceive ? 'Available' : 'Signal too weak';
        status('Your card is up to date.');
      } else status('Reminder sent to your notifications.');
    } catch {
      if (alive) status('No connection. Try again.', true);
    } finally {
      if (alive) { busy = false; controls(); }
    }
  }

  // Theme colours and signal; the first context also means "ready".
  const stopContext = Pocketbook.onContext((context) => {
    for (const key of ['ink', 'muted', 'accent']) {
      if (context.colors?.[key]) document.documentElement.style.setProperty('--' + key, context.colors[key]);
    }
    $('signal').textContent = `Line signal: ${Math.max(0, Math.min(5, Number(context.signal) || 0))} / 5`;
    if (!ready) { ready = true; controls(); request('getCard'); }
  });

  // Messages from SendCustomAppMessage.
  const stopMessage = Pocketbook.onMessage((data) => {
    if (data?.kind === 'hint' && typeof data.text === 'string') {
      $('hint').textContent = data.text.slice(0, 300);
      $('hint').hidden = false;
    }
  });

  $('refresh').addEventListener('click', () => request('getCard'), { signal: controller.signal });
  $('remind').addEventListener('click', () => request('remind'), { signal: controller.signal });
  $('home').addEventListener('click', () => Pocketbook.home(), { signal: controller.signal });

  // The frame is destroyed when the player leaves the app.
  window.addEventListener('pagehide', () => {
    alive = false; sequence++; controller.abort(); stopContext(); stopMessage();
  }, { once: true });
})();

#ui/style.css

The page is drawn on the notebook's paper, so keep the background transparent and take the ink colours from the context. A short start:

css:root { --ink: #3b3224; --muted: #66573d; --accent: #795a2e; }
html, body { height: 100%; margin: 0; background: transparent; color: var(--ink); font-family: serif; }
dl > div { display: flex; justify-content: space-between; border-bottom: 1px solid var(--muted); }
button { display: block; width: 100%; font: inherit; color: var(--ink); }

#Logs

The core logs traveller_card.getCard and traveller_card.remind with the server's log settings. To send them to their own webhook, add PocketServerConfig.Apps.traveller_card.Logs in the core's config_server.lua.