Skip to main content

Nui Basics

Nui projects are split in two parts:

  • Frontend: The user interface which is compiled to WASM and displayed in a browser window.
  • Backend: The backend allows native system interaction and communication with the browser context.

Therefore your project is always build twice: once for the frontend target and once for the backend target. It is possible to only produce a frontend for web applications but that is not the primary focus for Nui.

The Nui Template

The template already provides an example structure for your project, as well as the minimal CMake needed to get going.

Backend

The backend directory contains the backend that constructs the browser window. The main function looks like this and is fairly straightforward:

#include <nui/core.hpp>
#include <nui/window.hpp>

// This file is generated by nui. It contains the frontend index:
#include <index.hpp>

int main() {
using namespace Nui;

Window window{{.title = "Nui", .debug = true /* may open dev tools */}};
window.setSize(480, 320, WebViewHint::WEBVIEW_HINT_NONE);

// Loads the index:
window.setHtml(index());
window.run();
}

Frontend

The frontend also defines a main function, but not as we know it from regular C++ programs. The frontend main function is later called when the page is loaded. It is responsible for creating the document.

#include <nui/core.hpp>
#include <nui/window.hpp>
#include <nui/frontend.hpp>

#include <memory>

static std::unique_ptr<Nui::Dom::Dom> dom{};

extern "C" void frontendMain() {
dom = std::make_unique<Nui::Dom::Dom>();
dom->setBody(body{}("Hello World!"));
}

EMSCRIPTEN_BINDINGS(nui_example_frontend) {
emscripten::function("main", &frontendMain);
}
#include <nui/frontend/bindings.hpp>

Note that the Dom is a global static variable. The variable has to survive the frontend main function. All UI related functions may not be used in parallel. This restriction is forwarded by Nui from emscripten.

The dom.setBody function replaces the document root with your own page. In this case a body element with textContent.