LaptopAdding apps

Adding apps

Put your own app on the Laptop in four files. Register it from your server, and build its page with the Laptop's SDK.

On this page

An app is a web page in your own resource and a few server functions. Players find it in the laptop's browser, download it from its website and open it in a window on the desktop. You don't change anything in tr_laptop.

your resource                                tr_laptop
───────────────────────────────────          ──────────────────────────────────────────
server: registerApp({ id, ui, calls, ... })  →  its website: found by searching, sells it, installs it
web/index.html (loads tr_laptop's SDK)       ←  shown in a window when the player opens it
  laptop.call('add', ...)                    →  routed to your calls.add(src, laptop, ...)
  laptop.on('found', fn)                     ←  exports.tr_laptop:sendApp(serial, id, 'found', data)

Before any of your code runs, the Laptop checks that the player has that laptop open and logged in, is still next to it, and has your app installed.

Your first app

A notes app: players write notes, and each laptop keeps its own.

Make a resource

A folder in your resources, with four files:

my_notes/
├── fxmanifest.lua
├── server.lua
└── web/
    ├── index.html
    └── icon.svg

icon.svg is the app's icon: any square SVG or PNG.

fxmanifest.lua

List the page and the icon in files, so the game can load them:

fxmanifest.lua
fx_version 'cerulean'
game 'gta5'
lua54 'yes'

server_script 'server.lua'

files {
    'web/index.html',
    'web/icon.svg',
}

server.lua

Register the app on the server. The Laptop may start before or after your resource, and may restart, so register now and whenever it says it's ready (the last two lines):

server.lua
local function register()
    exports.tr_laptop:registerApp({
        id = 'notes',
        label = 'Notes',
        description = 'Jot things down. They stay on this laptop.',
        icon = 'web/icon.svg',
        ui = 'web/index.html',
        window = { width = 34, height = 26 },

        -- What the page is shown. Sent again after every call.
        state = function(src, laptop)
            return { notes = exports.tr_laptop:getData(laptop.serial) or {} }
        end,

        -- What the page can ask for: true and a result, or false and a reason.
        calls = {
            add = function(src, laptop, text)
                if type(text) ~= 'string' or text == '' then
                    return false, 'Write something first.'
                end
                local notes = exports.tr_laptop:getData(laptop.serial) or {}
                notes[#notes + 1] = text:sub(1, 200)
                exports.tr_laptop:setData(laptop.serial, notes)
                return true
            end,
        },
    })
end

AddEventHandler('tr_laptop:ready', register)
if GetResourceState('tr_laptop') == 'started' then register() end

getData and setData keep one value per resource on each laptop, saved with it.

web/index.html

The page loads the Laptop's SDK (laptop.js) and its look (laptop.css). laptop.state is what your state returned, and laptop.call runs one of your calls:

web/index.html
<!doctype html>
<html class="lt-theme">
<head>
  <meta charset="utf-8" />
  <link rel="stylesheet" href="https://cfx-nui-tr_laptop/web/sdk/laptop.css" />
  <script src="https://cfx-nui-tr_laptop/web/sdk/laptop.js"></script>
</head>
<body>
  <form id="add">
    <input id="text" class="lt-input" placeholder="A new note" />
    <button class="lt-btn lt-btn-primary">Add</button>
  </form>
  <ul id="list"></ul>

  <script>
    const list = document.getElementById('list');
    const text = document.getElementById('text');

    function render(state) {
      list.innerHTML = '';
      for (const note of state.notes) {
        const item = document.createElement('li');
        item.textContent = note;
        list.append(item);
      }
    }

    laptop.ready(() => render(laptop.state));
    laptop.onState(render);

    document.getElementById('add').onsubmit = async (event) => {
      event.preventDefault();
      try {
        await laptop.call('add', text.value);
        text.value = '';
      } catch (err) {
        laptop.notify('Notes', err.message, true);
      }
    };
  </script>
</body>
</html>

Any web page works the same way: React, Vue or plain HTML. Build it, and list the built files in files.

Start it

Add it to server.cfg after tr_laptop, and start it (or restart the server):

server.cfg
ensure tr_laptop
ensure my_notes

Open a laptop, search for "notes" in its browser, download it from its website and open it from the desktop.

Everything an app can have

registerApp returns true, or false and what's wrong (also printed in the server console). Registering the same id again replaces it. When your resource stops, its apps' websites go; laptops keep them installed, and they come back when your resource starts again.

Its website

Every app gets a website made from its fields, at its name as an address (label 'Crypto Market' is cryptomarket.com). The browser's search finds it by its name, summary, description, developer, category and about. The website's download button pays for the app and installs it. To give it a website of your own instead, see Your app's own website.

An installed app is a file in Downloads (file, like notes.exe). Deleting it there uninstalls the app.

Off the web: the Terminal

Give an app a terminal address and the search doesn't find it, and it has no website. Players download it in the laptop's Terminal instead:

wget undernet.onion/undernet.exe

notes.txt in Documents lists every Terminal app's address, read from the server when it's opened. An address is a host with a dot in it, then a path: letters, digits, -, ., _, /, ~ and %.

Fields

Field
idrequiredLetters, digits and _. browser, store, files, terminal and settings are taken
labelrequiredIts name
iconrequiredA file in your resource (or an https:// address). Square, SVG or PNG
uirequiredIts page: a file in your resource (or an https:// address)
descriptionOne line, under its search result and on its website
summaryIts website's headline, and its search result's title
aboutParagraphs about it on its website
developerShown on its website
categoryprivacy, browsers, tools, games, business, social, utilities (default) or your own
priceDefault 0 (free)
accountcash, bank or dirty. Default: store.account in the config
installTimeSeconds. Installs carry on while the laptop is closed
window{ width, height, maximize }: size in rem (width 16–80, height 10–50, default 40×28), and whether it can be maximised
devicesDevice ids it needs plugged in to run, like { 'wifi_adapter' }
fileIts file in Downloads: letters, digits, ., - and _. Default: its label's letters and digits in lower case, and .exe
terminalAn address it's downloaded from in the Terminal, instead of a website. See Off the web
bannerTwo colours for its website (header, then the band at its foot), like { '#c88a12', '#6b4a06' }
sizeMB, shown on its website
ratings{ score = 4.5, count = 812, split = { 0.7, 0.18, 0.06, 0.02, 0.04 } } (5 stars first)
reviews{ { stars = 5, title = '...', name = '...', body = '...' }, ... }
screenshots{ { image = 'web/notes/shot1.png', caption = '...' }, ... }

Server functions

All are optional and run in your resource. laptop is { serial, coords }.

FunctionWhen
state(src, laptop)Returns what the page is shown (anything JSON can hold). Keep it small: it's sent with every update. A tray field, { label, status = 'on' | 'busy' | 'off' }, puts an icon in the laptop's top bar while the app runs
calls.<name>(src, laptop, ...)The page called laptop.call('<name>', ...). Return true, result or false, reason. A reason is shown to the player: your own text, or a key from the Laptop's locales/*.json error.*. An error in your function shows "try again" and is printed in the console
canInstall(src, laptop)The player is downloading it. Return false, reason to stop them before they pay
onOpen(src, laptop)The player opened the laptop and logged in (your app is installed)
onClose(src, laptop)The laptop closed, after onOpen
onUnplug(src, laptop, device)A device was pulled out of the laptop

Calls are rate limited, and only reach you while the player has that laptop open and logged in, stands next to it, and has your app installed. Check everything else yourself: arguments, money, cooldowns.

What your resource keeps on a laptop

exports.tr_laptop:getData(serial) and setData(serial, value) keep one value per resource on each laptop, saved with it. It goes wherever the laptop goes and stays when your app is uninstalled. It's for small things (settings, a list); keep anything big in your own tables, keyed by the serial.

The app's page

Any web page works: plain HTML, React, anything. Load the Laptop's SDK, and its stylesheet if you want the laptop's look:

html
<link rel="stylesheet" href="https://cfx-nui-tr_laptop/web/sdk/laptop.css" />
<script src="https://cfx-nui-tr_laptop/web/sdk/laptop.js"></script>
js
laptop.ready(() => render(laptop.state));
laptop.onState((state) => render(state));
laptop.on('shared', (text) => laptop.notify('Notes', text));

form.onsubmit = async (e) => {
  e.preventDefault();
  try {
    await laptop.call('add', input.value);
    input.value = '';
  } catch (err) {
    laptop.notify('Notes', err.message, true);
  }
};
laptop.ready(fn)Once the laptop has sent the first state: fn({ app, language, state, laptop, theme, sound, os })
laptop.stateYour app's state (what your state returned)
laptop.info{ serial, ports, devices, user }: the laptop and its player
laptop.onState(fn)Whenever either changes: fn(state, info). Returns a function that stops it
laptop.on(event, fn)Messages from your server or client (sendApp)
laptop.call(name, ...args)Runs one of your calls. Resolves to its result, or rejects with an Error whose .code is the reason and .message the text to show
laptop.notify(title, body?, error?)A notification on the laptop under your app's name
laptop.open('browser' | appId)Opens the browser or another installed app
laptop.close()Closes your window
laptop.refresh()Asks the server for your state again
laptop.theme'dark' or 'light': the windows' style the player chose in Settings
laptop.sound{ on, volume }: whether the player has the laptop's sounds on, and how loud to play yours, 0 to 1
laptop.onSettings(fn)Whenever the player changes either: fn({ theme, sound }). Returns a function that stops it
laptop.os'ifruitos' or 'leafos'. Changing it restarts the laptop, so it never changes while your page is open

Fitting in

  • Size everything in rem. The laptop scales with the player's screen, and 1rem on your page is the laptop's rem.
  • Escape on your page goes to the laptop (closing it) unless your page handles it.
  • The mouse. When the screen is drawn on the laptop in the world, the player uses it on their own page laid exactly over that screen, so your page gets the mouse and keyboard as it would anywhere. The SDK draws the cursors your CSS asks for (pointer, text, the resize cursors) the laptop's way.
  • Its look. laptop.css gives you the laptop's colours as --lt-* variables, its font, and a few classes: lt-btn (with lt-btn-primary, lt-btn-danger, lt-btn-sm), lt-input, lt-card, lt-muted, lt-secondary.
  • Light and dark. The SDK puts data-laptop-theme="dark" or "light" on your page's <html>. Style [data-laptop-theme="light"] yourself, or give <html> the class lt-theme and the --lt-* colours turn light with it. It also gets data-laptop-os, the system the laptop runs.
  • Sounds your page plays should follow laptop.sound: none when on is false, and at volume otherwise.
Was this page helpful?

Still stuck? Open a ticket on Discord.Privacy