Plugins and components
Plugins in the plugins/ folder, PLUGINS, UI bundles from COMPONENTATOR(), server components with NEWCOMPONENT(), and NPMINSTALL(), REQUIRE() and IMPORT().
On this page
A plugin is a folder in plugins/ that packs one feature of the application: its own controllers, actions, schemas, public files and views. Total.js loads every plugin at start, together with the files of the application, so a plugin works like a small application inside the main one.
This page also covers components: UI component bundles downloaded from Componentator with COMPONENTATOR(), server components compiled with NEWCOMPONENT(), and the helpers that load code at run time: NPMINSTALL(), REQUIRE() and IMPORT(). The full list of methods is in the reference Plugins and components.
Structure of a plugin
plugins/
shop/
index.js <- required: the plugin definition
controllers/ <- routes of the plugin
actions/
schemas/
models/
definitions/
extensions/
middleware/
public/ <- static files, served as /_shop/...
views/ <- views, rendered as #shop/views/...The name of the folder is the id of the plugin. A folder without an index.js file is skipped, together with all its subfolders. Folders whose name contains -bk or _bk are skipped too, so you can switch a plugin off by renaming shop to shop-bk.
index.js
index.js is an ordinary Node.js module. Total.js requires it, stores it in PLUGINS under the id of the plugin and calls its install() function.
// plugins/shop/index.js
exports.icon = 'ti ti-shopping-cart';
exports.name = 'Shop';
exports.position = 3;
exports.permissions = [{ id: 'shop', name: 'Shop' }, { id: 'shop_orders', name: 'Orders' }];
exports.visible = user => user.sa || user.permissions.includes('shop');
exports.install = function() {
ROUTE('+API ? shop_orders --> Shop/orders');
ON('ready', function() {
// the whole application is loaded
});
};The framework itself reads only these properties:
| Property | What Total.js does with it |
|---|---|
exports.install | Called once, when the plugin is loaded |
exports.id | Set to the folder name when you do not define it |
exports.name | Written with the id and the permissions to the source map of the application (debug mode) |
exports.permissions | An array of strings or objects with id; the ids are written to the source map |
Any other property, such as icon, position or visible, is yours: your administration UI reads it from PLUGINS to build a menu or to hide items the user may not open.
Files inside a plugin
These subfolders of a plugin are loaded exactly like the folders of the same name in the root of the application: every .js file is required and its install() is called.
| Folder | Content |
|---|---|
controllers/ | Routes, see Routing |
actions/ | NEWACTION() definitions, see Actions |
schemas/ | Schemas and actions, see JSON schemas |
models/, definitions/, extensions/ | Shared code, delegates, prototypes |
middleware/ | NEWMIDDLEWARE() definitions, see Middleware |
All plugins and all application files share one global space: a route, an action or a schema declared in a plugin is available everywhere. Use the plugin id as a prefix of names (Shop/orders, /admin/shop/) to avoid conflicts.
// plugins/shop/controllers/api.js
exports.install = function() {
ROUTE('+API ? shop_products --> Shop/products');
ROUTE('+GET /admin/shop/', function($) {
$.view('#shop/views/index');
});
};Public files, views and templates
- Public files: a URL that starts with
/_and the plugin id is served from thepublic/folder of the plugin./_shop/css/shop.cssreadsplugins/shop/public/css/shop.css(see Static files). - Views: a view name that starts with
#is relative to theplugins/folder:$.view('#shop/views/index')rendersplugins/shop/views/index.html(see Views). - Templates:
TEMPLATE('#shop/templates/order.html', model)readsplugins/shop/templates/order.html..htmlis added when the name does not contain it. - Paths:
PATH.plugins('shop/data.json')returns the absolute path of a file in the plugins folder.
In debug mode the plugins/ folder is watched like controllers/: a change of a script restarts the application.
Configuration of a plugin
A plugin can have a config file next to its index.js. It has the same format as the main config file (see Configuration) and is read before the scripts of the application and the plugins run, after the main config. Its keys are merged into CONF, so a plugin can bring its own defaults, and a key with the same name overrides the value from the main file.
// plugins/shop/config
shop_currency : EUR
shop_pagesize : 20// plugins/shop/actions/products.js
NEWACTION('Shop/products', {
action: function($) {
var take = CONF.shop_pagesize;
// ...
$.success();
}
});FlowStream in a plugin
When a plugin contains an index.flow file (a FlowStream export in JSON), Total.js reads it and starts the FlowStream right after the index.js of the plugin, before the other files of the plugin; the FlowStream is created asynchronously, so PLUGINS[id].flowstream is set once it is ready. The FlowStream gets the plugin id as its id, the plugin name (translated) as its name and the plugin folder as its directory. The running instance is stored in PLUGINS[id].flowstream. See FlowStream.
// plugins/iot/index.js
exports.name = 'IoT';
exports.install = function() {
ON('ready', function() {
setTimeout(function() {
var flow = PLUGINS.iot.flowstream;
flow && console.log('IoT FlowStream is running');
}, 1000);
});
};PLUGINS
PLUGINS is an object with all loaded plugins, by id. Each value is the module.exports object of the plugin index.js.
// a menu for an admin panel
ROUTE('+GET /admin/plugins/', function($) {
var user = $.user;
var arr = [];
for (var id in PLUGINS) {
var plugin = PLUGINS[id];
if (plugin.visible && !plugin.visible(user))
continue;
arr.push({ id: id, name: plugin.name, icon: plugin.icon, position: plugin.position });
}
arr.quicksort('position');
$.json(arr);
});UI components (COMPONENTATOR)
COMPONENTATOR(name, components, [removeprev], [attrs]) downloads one minified bundle of jComponent UI components from https://componentator.com into public/. The file is downloaded only when it does not exist yet, so call it in a definition file and keep it in the code.
// definitions/ui.js
COMPONENTATOR('ui', 'exec,locale,aselected,page,viewbox,input,box,validate,loading,notify,message,errorhandler,empty,menu,colorpicker,icons,directory,miniform,preview,datagrid', true);The bundle is saved as public/ui-<name>-<hash>.min.js (public/ui-<hash>.min.js when removeprev is false); the hash comes from the list of components, so a different list gives a new file and (with removeprev, the default) the old bundle of the same name is deleted. The URL of the file is stored in REPO[name], so a layout can load it:
<script src="@{REPO.ui}"></script>Server components (NEWCOMPONENT)
A server component is an HTML file with a <script total> (or <script node>) block that holds the server code, optionally with <settings>, <style>, <script>, <body>, <readme>, <schema> and <template> parts for a UI. NEWCOMPONENT() compiles it into a component object; you create instances of it and send them data.
<!-- components/uppercase.html -->
<script total>
exports.name = 'Uppercase';
exports.config = { prefix: '' };
exports.inputs = [{ id: 'input', name: 'Text' }];
exports.outputs = [{ id: 'output', name: 'Result' }];
exports.make = function(instance, config) {
instance.message = function(msg) {
msg.send('output', config.prefix + String(msg.data).toUpperCase());
};
};
</script>
<readme>
Converts the text to upper case.
</readme>var com = await NEWCOMPONENT('uppercase'); // reads components/uppercase.html
com.debugger = false; // do not print outputs to the console
var instance = com.create({ prefix: '> ' });
instance.input('input', 'hello', function(msg) {
console.log(msg.output, msg.data); // output > HELLO
});NEWCOMPONENT() accepts the name of a file in components/, the HTML itself, or an https:// URL. Packages listed in exports.npm are installed with NPMINSTALL() before exports.install() runs. An instance can also emit data on its own with instance.send(output, data), for example from a timer, and report progress with instance.activity(key, name, value). An input with a schema (a schema string such as 'name:String, age:Number') validates the data: the cleaned data is in msg.data and errors in msg.error.
NPM packages and remote modules
NPMINSTALL(name, [callback])installs an NPM package intoCONF.$nodemodules(thenode_modulesfolder of the application) withnpm install. It does nothing when the package is already there (and has the version fromname@version).REQUIRE(name)loads a module: Node.js built-in modules directly, other packages withrequire()and, when that fails, fromCONF.$nodemodules.IMPORT(url, [callback])downloads a JavaScript file into the temporary folder and requires it. A second call with the same URL in the same process returns the loaded module without downloading. An error page (status400or more) or a file that is not a module gives an error.
// plugins/pdf/index.js
exports.install = async function() {
await NPMINSTALL('pdfkit@0.15.0');
var PDFDocument = REQUIRE('pdfkit');
// ...
};IMPORT('https://cdn.example.com/helpers.js', function(err, module) {
if (!err)
module.hello();
});